There are a few things wrong here:
You check for age < 21
and age > 21
, but what happens if I'm exactly 21 years old? You'll want to change the >
to >=
in order to catch this case (assuming you're in America where the drinking age is 21 and over).
Another thing I noticed. What happens if I'm not over 21?
Traceback (most recent call last):
File "beer.py", line 8, in <module>
if beer is "union":
NameError: name 'beer' is not defined
Oops. You've defined beer
, but this condition is never reached if you're not over 21. Therefore when you reference beer
in your last if
statement, the interpreter has no idea what you're talking about. You'll want to move the last if
inside the second one:
if age > 21:
print("what beer do you like?")
beer = input()
if beer is "union":
print("this is water")
Lastly, it's not a wise idea to use is
as a substitute for the ==
operator, because they are not equivalent. In this case, beer is "union"
evaluates to False, whereas beer == "union"
does not, but there are some cases where the two statements are functionally equivalent. For example:
$ python -i
>>> x = 3
>>> if x is 3:
... print('x is 3!')
...
x is 3!
Therefore, your final code would look like this:
print("enter your age")
age = int(input())
if age < 21:
print("no beer")
if age >= 21:
print("what beer do you like?")
beer = input()
if beer == "union":
print("this is water")
Edit: see this answer for why they are not equivalent. is
checks that they are the same object, whereas ==
checks that the values are equivalent (which is what you want).