[英]While loop running even after condition is False
我希望用户输入 1、2 或 3。但是当我测试它并输入 1,2 或 3 时,它仍然运行,即使条件为 False。 我不断地从 and 和 or 改变条件,但我似乎无法解决它。 任何帮助将不胜感激。
def get_input():
user_input = input("Enter a number 1,2 or 3: ")
while (user_input != 1) and (user_input != 2) and (user_input != 3) :
print('Invaild input!')
user_input = input("Enter a number 1,2 or 3 : ")
您正在阅读字符串,您应该转换它或使用字符串。 所以条件应该是
(user_input != "1") and (user_input != "2") and (user_input != "3")
因为input()
返回的值是一个字符串(用引号括起来),而不是一个整数。
IE。
"1"
与1
不是一回事
要修复它,请更改此行。
while (user_input != "1") and (user_input != "2") and (user_input != "3") :
您可以尝试将输入数据类型从字符串更改为整数,或者在代码中使用“2”而不是 2
在不改变数据类型的情况下使用它:
def get_input():
user_input = input("Enter a number 1,2 or 3: ")
while (user_input != "1") and (user_input != "2") and (user_input != "3") :
print('Invaild input!')
user_input = input("Enter a number 1,2 or 3 : ")
要将数据类型更改为 int:
def get_input():
user_input = int(input("Enter a number 1,2 or 3: "))
while (user_input != 1) and (user_input != 2) and (user_input != 3) :
print('Invaild input!')
user_input = int(input("Enter a number 1,2 or 3 : "))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.