Python有效输入测试无效

2024-03-28 19:00:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到的问题是,当用户输入类文件时,它会一直说它是无效的输入。知道为什么会这样吗

classfile = input("Which class would you like to display: ") #Prompts the user to find out which wile to open
while classfile not in [1, 2, 3]: #Ensures the input it valid
    print("There are only classes 1, 2 and 3 available.")
    classfile = input("Which class would you like to display: ") #If input is not valid it will ask them to input it again.

Tags: 文件theto用户youwhichinputdisplay
1条回答
网友
1楼 · 发布于 2024-03-28 19:00:30

python3中的input返回一个字符串。while语句将此字符串与整数进行比较。这是行不通的,因为字符串从不与整数比较

您可以通过将输入强制转换为整数或将其与字符串进行比较来解决此问题。我更喜欢后者,因为这样在非整数输入上就不会出现异常

因此,将while语句更改为以下内容,代码将正常工作:

while classfile not in ['1', '2', '3']:

相关问题 更多 >