使用Python实现一个循环输入
实现此目的的最简单方法是将input方法放在while循环中。当你输入错误时使用continue,break当你满意时使用break。
当您的输入可能会引发异常时
使用try和catch检测用户何时输入无法解析的数据。
while True:代码地址:codingdict.com/article/22038
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
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.")
实现自己的验证规则
如果要拒绝Python可以成功解析的值,可以添加自己的验证逻辑。
while True:
data = input("Please enter a loud message (must be a