用户选项和验证



我试图让用户输入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.')

如果您希望您的输入是在range(1, 4),它需要是int,而不是str(这是由input()返回的:

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

您必须检查相同类型的值。你的代码比较string和int。您还需要处理基本语句的语法:if <condition>: except:是不合法的。保持简洁:

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

最新更新