【问题标题】:How to end a while Loop when a desired input is given?给出所需输入时如何结束while循环?
【发布时间】: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")

【问题讨论】:

标签: python while-loop


【解决方案1】:
  1. 使用布尔变量(keep_adding 用于下面的代码)来决定 while 循环的终止条件。它将被设置为False iff add_more == "n"

  2. 如果用户输入既不是“y”也不是“n”,则使用raise TypeErrorraise error

  3. 如果输入无效,您应该从 except TypeError 中删除 break,以便继续询问“您想添加更多项目吗?(y/n):”。

elif user_input == "a":
    keep_adding = True
    while keep_adding:
        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":
                        keep_adding = False
                        break
                    else:
                        raise TypeError
                except TypeError:
                    print("ERROR: Expected y or n in return! Try again!.\n")
        except ValueError:
            print("\nERROR: Amount must be an integer! Try adding an item again!\n")

【讨论】:

  • 这太完美了,非常感谢您的解释!
猜你喜欢
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
相关资源
最近更新 更多