我正在编写一个必须接受用户输入的程序。#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.")如果用户输入合理数据,这将按预期工作。C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!但如果他们犯了错误,那就崩溃了:C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in <module>
age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'而不是崩溃,我希望它再次尝试获取输入。像这样:C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!我怎么能做到这一点?如果我还想拒绝像这样的上下文中-1的有效int但无意义的值,该怎么办?
4 回答
动漫人物
TA贡献1815条经验 获得超10个赞
虽然接受的答案是惊人的。我还想分享这个问题的快速入侵。(这也解决了负面年龄问题。)
f=lambda age: (age.isdigit() and ((int(age)>=18 and "Can vote" ) or "Cannot vote")) or \ f(input("invalid input. Try again\nPlease enter your age: "))print(f(input("Please enter your age: ")))
PS此代码适用于python 3.x.
添加回答
举报
0/150
提交
取消