【发布时间】:2020-09-20 18:12:11
【问题描述】:
我的程序接受用户关于他们想要添加的内容的输入。这很好用,但是当它归结为嵌套的 while 循环时就会出现问题,该循环会提示用户是否希望添加更多项目 (y/n)。我希望 y 从头开始循环, n 退出循环并继续程序,以及任何其他输入在重新启动 y/n 提示时给出错误。 我似乎无法弄清楚如何摆脱嵌套的 while 循环,如果输入既不是 y 也不是 n,我也无法弄清楚如何抛出错误。我该如何解决这个问题?
elif user_input == "a":
while True:
try:
add_item = input("What item would you like to add? ").lower()
if not re.match("^[a-z, A-Z]*$", add_item):
print("ERROR: Only letters A-Z are allowed!")
continue
elif len(add_item) < 1 or len(add_item) > 20:
print("Item name is too long, only a maximum of 20 characters are allowed!")
continue
else:
item_amount = int(input("How many of these would you like to add? "))
shopping_list[add_item] = item_amount
print(f"{item_amount}x {add_item.title()} added to the shopping list.\n")
while True:
try:
add_more = input("Would you like to add more items? (y/n): ").lower()
if add_more == "y":
break
elif add_more == "n":
break
except TypeError:
print("ERROR: Expected y or n in return! Try again!.\n")
break
except ValueError:
print("\nERROR: Amount must be an integer! Try adding an item again!\n")
【问题讨论】:
-
您可以将第一个 while True 替换为 while someVar 并在嵌套循环内更改 someVar
标签: python while-loop