我遇到的问题是,当用户输入类文件时,它会保持说它是无效输入。知道为什么会这样吗?
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.
答案 0 :(得分:2)
input
返回一个字符串。您的while语句将此字符串与整数进行比较。这不起作用,因为字符串从不比较等于整数。
您可以通过将输入转换为整数或将其与字符串进行比较来解决此问题。我更喜欢后者,因为那样你就不会在非整数输入上得到异常。
因此,将while语句更改为以下内容,您的代码将起作用:
while classfile not in ['1', '2', '3']: