我希望用户输入一个介于1000到25000之间的整数,但是我不希望用户输入一个通过25000的整数,同时希望用户无需重新启动程序即可再次尝试输入它。
while True:
try:
loan_amount= int(input("How much do you want to borrow?(1000-25000)"))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
break
if loan_amount > 25000:
print("Sorry, We only lend up to $25,000. Please try again!")
我希望当用户输入一个大于25,000的整数时,他们会被告知“我们不能再提供那么多的尝试”,然后再次重复该问题。
答案 0 :(得分:3)
您应该尝试在try
语句中将if else语句包含在break
语句中,以在输入正确的数量时退出while循环。
while True:
try:
loan_amount= int(input("How much do you want to borrow?(1000-25000) "))
if loan_amount > 25000:
print("Sorry, We only lend up to $25,000. Please try again!")
else:
print ("Amount loaned")
break
except ValueError:
print("Sorry, I didn't understand that. Please try again")
输出
尝试1
How much do you want to borrow?(1000-25000) 24999
Amount loaned
尝试2
How much do you want to borrow?(1000-25000) Donald Trump
Sorry, I didn't understand that. Please try again
How much do you want to borrow?(1000-25000) 23000
Amount loaned
尝试3
How much do you want to borrow?(1000-25000) 27000
Sorry, We only lend up to $25,000. Please try again!
How much do you want to borrow?(1000-25000) 23000
Amount loaned