+ 2
Can I use if/and/or in defining a variable?
Code coach exercise for printing child, teen or adult depending on 6 different ages that are input. age = int(input()) Child = age <11 Teen = age >11 and <18 Adult = age>17 if Child: print("Child") elif Teen: print("Teen") else: print("Adult") Whenever I attempt to use and/ if/ or in the variable teen it always gives syntax error as if it cant be there. However I need teen to consider more than & less than, otherwise a 19y/o is named as a teen. I have solved with another method bt cn this be done?
14 Respuestas
+ 4
age = int(input())
Child = age <11
Teen = age >11 and age<18
Adult = age>17
if Child:
print("Child")
elif Teen:
print("Teen")
else:
print("Adult")
# try this.. your mistake is in 3rd #line .. age> 11 and age <18
+ 3
Boolean True and False are just 1 and 0 respectively. If child and teen are both False (0), then you get not (0+0) which equals True (1).
Your If Else setup also allows for ODLNT's answer of Teen = age<18 to work as well since you evaluate child first, then Teen then adult.
You also have the option of only checking for two cases and defaulting to the third. If Child = False and Adult = False then Teen = True.
age = int(input())
Child = age<11
Adult = age>17
if Child:
print("Child")
elif Adult:
print("Adult")
else:
print("Teen")
+ 1
Try either
Teen = age >=11 and age<18
or
Teen = age<18
+ 1
Interesting. Thanks for explaining it. I learned something today.
+ 1
child = age < 11
if child:
print('child')
is same like:
if age < 11:
print ('child')
-------------
if a > b:
return True
else:
return False
is like:
return a > b
0
I like where you were going with that, perhaps you would like this option:
Child = age <11
Adult = age>17
Teen = not (Child+Adult)
The + in that equation is equivalent to an OR in boolean logic.
0
Because the expression after your ”and” is not correct. age >11 is a correct expression, but < 18 is not. < takes two parameters and you are currently not comparing 18 to anything. You probably meant to write age < 18
- 1
Brandon that does look interesting but how do you get it work with the if and print?
- 1
Chris Coder Child Teen and Adult already have boolean values (true or false), no need to compare them to anything. The only problem is that Teen has a syntax error
- 1
Brandon when working with boolean expressions it’s cleaner in my opinion to work with logical operators directly and not intermediately type juggle to integers.
So you could write
Teen= not ( Child or Adult ).
Also possible would be
Teen = (not Child) and (not Adult)
- 2
What language?
- 2
Python, sorry.
- 2
Thanks John Doe I understood brandons example. I like that this can be done in different ways.
I was just going in this direction.
age = int(input())
if age < 11:
print("child")
elif age <=19 and age >= 11:
print("teen")
else:
print("adult")
- 2
Javascript warm message implementation