我刚刚在一个月前开始学习python,并且一直想创建一个“选择故事”提示。
看起来像这样
while True:
try:
party = int(input("How many people joined the party "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
我注意到了几件事,不知道该如何解决
while True:
try:
party = int(input("How many people joined the party (1-5)?:"))
except ValueError:
print("\nSorry, I didn't understand that.")
continue
if 0 < party <= 5:
print(f"{party} people joined")
break
print(f"\nInvalid answer, please insert a number between 1 and 5")
验证数字是您必须在之外进行的操作int(input(...))
。在我的情况下,我验证最终答案是否在0到5之间。如果是,我将打破while循环。如果答案不在该范围内,我会显示一条消息,要求他们在正确的范围内插入一个值。
How many people joined the party (1-5)?: 0
Invalid answer, please insert a number between 1 and 5
How many people joined the party (1-5)?: I and my best friend
Sorry, I didn't understand that.
How many people joined the party (1-5)?: 3
3 people joined
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句