的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進入決賽的字符串,以避免做字符串連接。
而且,只是一個快速的注意,我假設你使用Python 3本。但,如果你使用Python 2 input()應替換爲raw_input()。在Python 2中,input()將嘗試將用戶輸入評估爲表達式,而raw_input()將返回一個字符串。