我遇到的问题是,当用户输入类文件时,它会一直说它是无效的输入。知道为什么会这样吗
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.
python3中的
input
返回一个字符串。while语句将此字符串与整数进行比较。这是行不通的,因为字符串从不与整数比较您可以通过将输入强制转换为整数或将其与字符串进行比较来解决此问题。我更喜欢后者,因为这样在非整数输入上就不会出现异常
因此,将while语句更改为以下内容,代码将正常工作:
相关问题 更多 >
编程相关推荐