Simple raw_input and conditions

孤街醉人 提交于 2019-12-24 11:44:07

问题


I created the simple code:

name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")

if age >= 21
    print "Margaritas for everyone!!!"
else:
    print "NO alcohol for you, young one!!!"

raw_input("\nPress enter to exit.")

It works great until I get to the 'if' statement... it tells me that I am using invalid syntax.

I am trying to learn how to use Python, and have messed around with the code quite a bit, but I can't figure out what I did wrong (probably something very basic).


回答1:


It should be something like this:

name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
age = int(age)

if age >= 21:
    print "Margaritas for everyone!!!"
else:
    print "NO alcohol for you, young one!!!"

raw_input("\nPress enter to exit.")

You were missing the colon. Also, you should cast age from string to int.

Hope this helps!




回答2:


With python, indentation is very important. You have to use the correct indentation or it won't work. Also, you need a : after the if and else

try:

if age >= 21:
    print #string
else:
    print #other string



回答3:


Firstly raw_input returns a string not integer, so use int(). Otherwise the if-condition if age >= 21 is always going to be False.:

>>> 21 > ''
False
>>> 21 > '1'
False

Code:

name = raw_input("Hi. What's your name? \nType name: ")
age = int(raw_input("How old are you " + name + "? \nType age: "))

The syntax error is there because you forgot a : on the if line.

if age >= 21
            ^
            |
       colon missing


来源:https://stackoverflow.com/questions/17572736/simple-raw-input-and-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!