break语句用于退出循环,而不是程序。使用sys.exit()退出程序,还需要导入sys。在
编辑:
对于你的评论,我可能会这样做:while True:
inputted_name = input("Please enter your name:")
try:
name = str(inputted_name)
except ValueError:
print("Please enter a valid name")
else:
break
while True:
inputted_age = input("Please enter your age:")
try:
age = int(inputted_age)
except ValueError:
print("Please enter a valid age")
else:
break
while True:
inputted_height = input("Please enter your height:")
try:
height = float(inputted_height)
except ValueError:
print("Please enter a valid height")
else:
break
if age >= 18 and height >= 148:
print("You're able to drive a car {}".format(inputted_name))
if age < 18 and height > 148:
print("You're not able to drive a car {}".format(inputted_name))
所以有一些变化:
用户输入的每个阶段都在自己的循环中。我使用了try/except/else语句尝试将输入转换为正确的类型,但ValueErrors(如果不能转换,则抛出,例如,如果用户将文本答案放入input age则会发生这种情况)。如果它成功地强制转换为正确的类型,则循环将中断,脚本将移动到下一个类型。每个循环都有单独的循环意味着如果用户为其中一个输入了错误的值,他们就不必重做整个操作。在
我还使用format()将name插入到最后的字符串中,以避免必须进行字符串连接。在
另外,简单地说一下,我假设您使用的是python3。但是,如果您使用python2,input()应该替换为raw_input()。在python2中,input()将尝试将用户输入作为表达式进行计算,而raw_input()将返回一个字符串。在