如何检查用户输入 (Python)

How to check user input (Python)

我已经看到很多关于这个问题的答案,但我正在寻找一些非常具体的答案。我需要完成的(伪代码)是:

> FOR every ITEM in DICTIONARY, DO:
>           PROMPT user for input
>           IF input is integer
>                 SET unique-variable to user input

我是 Python 的新手,所以代码可能不正确,但这是我所拥有的:

def enter_quantity():
  for q in menu:
      quantities[q] = int(input("How many orders of " + str(q) + "?: "))

所以除了评估用户输入之外,这一切都完成了。我遇到的问题是,如果输入不正确,我需要在顶层 for 循环中重新提示他们输入相同的项目。因此,如果它询问 "How many slices of pizza?" 并且用户输入 "ten",我希望它再次对 "How many slices of pizza?".[=14= 的提示说 "Sorry that's not a number" 和 return ]

Any/all 想法表示赞赏。谢谢!


我的最终解决方案:

def enter_quantity():
for q in menu:
    booltest = False
    while booltest == False:
        inp = input("How many orders of " + str(q) + "?: ")
        try:
            int(inp)
            booltest = True
        except ValueError:
            print (inp + " is not a number. Please enter a nermic quantity.")
    quantities[q] = int(inp)

您需要一个带有 try/except 的 while 循环来验证输入:

def enter_quantity():
    for q in menu:
        while True:
            inp = input("How many orders of {} ?: ".format(q))
            try:
               inp = int(inp) # try cast to int
               break
            except ValueError:
                # if we get here user entered invalid input so print message and ask again
                print("{} is not a number".format(inp))
                continue
        # out of while so inp is good, update dict
        quantities[q] = inp

如果添加菜单,这段代码会更有用,否则它会在第一个障碍处崩溃。我还添加了一个字典来存储输入值。

menu = 'pizza', 'pasta', 'vino'
quantities = {}
def enter_quantity():

    for q in menu:
        while True:
            if q == 'pizza':
                inp = input(f"How many slices of {q} ?: ")
            elif q == 'pasta':
                inp = input(f"How many plates of {q} ?: ")
            elif q == 'vino':
                inp = input(f"How many glasses of {q} ?: ")
            try:
               inp = int(inp) # try cast to int
               break
            except ValueError:
                # exception is triggered if invalid input is entered. Print message and ask again
                print("{} is not a number".format(inp))
                continue
        # while loop is OK, update the dictionary
        quantities[q] = inp

    print(quantities) 

然后 运行 来自此命令的代码:

enter_quantity()