我正在编写一个必须接受用户输入的程序.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Run Code Online (Sandbox Code Playgroud)
如果用户输入合理数据,这将按预期工作.
C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
Run Code Online (Sandbox Code Playgroud)
但如果他们犯了错误,那就崩溃了:
C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in …Run Code Online (Sandbox Code Playgroud) 这里的Python新手,尝试将测验输入限制为仅限1,2或3.
如果键入文本,程序崩溃(因为文本输入无法识别)
这是对我所拥有的改编:欢迎任何帮助.
choice = input("Enter Choice 1,2 or 3:")
if choice == 1:
print "Your Choice is 1"
elif choice == 2:
print "Your Choice is 2"
elif choice == 3:
print "Your Choice is 3"
elif choice > 3 or choice < 1:
print "Invalid Option, you needed to type a 1, 2 or 3...."
Run Code Online (Sandbox Code Playgroud) 我试图允许用户输入我的程序,但是当他们输入一个字符串我的程序失败.这是一个更大的计划,但试图纠正这个问题,我到目前为止:
data = raw_input('Enter a number: ')
number = eval(data)
if type(number) != int:
print"I am afraid",number,"is not a number"
elif type(number) == int:
if data > 0:
print "The",number,"is a good number"
else:
print "Please enter a positive integer"
Run Code Online (Sandbox Code Playgroud)
当用户输入字符串时,它返回:
number = eval(data)
File "<string>", line 1, in <module>
NameError: name 'hel' is not defined
Run Code Online (Sandbox Code Playgroud)
非常感激任何的帮助.