用户选项和验证

问题描述

我试图让用户输入 1、2 或 3。如果没有输入任何数字,将显示一条错误消息,程序将再次要求输入。

我如何确定用户输入的是 1,2 还是 3?

这是我目前拥有的。

while True:
    try:
        userInput = input("Enter a number: ")
        if userInput not in range(1,4):
    except:
        print('Sorry,invalid entry. Please enter a choice from 1 to 3.')
    elif userInput.isdigit('1'):
        print('1')
    elif userInput.isdigit('2'):
        print('2')
    else:
        print('Thank you for using the Small Business Delivery Program! Goodbye.')

解决方法

您必须检查相同类型的值。您的代码比较字符串和整数。您还需要处理基本语句的语法:if <condition>: except: 是不合法的。保持简单:

userInput = None

while userInput not in ['1','2','3']:
    userInput = input("Enter a number: ")
,

如果您希望输入在 fileName 中,则它需要是 range(1,4),而不是 int(这是 str 返回的内容:

input()