while 循环不能正常工作?
While loop isn't working correctly?
我正在为 python 编程练习创建一个数学测验,但我遇到了一个问题。我正在尝试创建一个 while
循环以将其用作验证以确保用户输入了 1、2 或 3。当我使用此循环时,它只是继续循环而不退出。
cl = int(input("Please enter your class (1, 2 or, 3): "))
while cl != 1 or cl != 2 or cl != 3 :
cl = int(input("Please enter your class (1, 2 or, 3): "))
我有代码将其他信息保存到文本文件(我知道 csv 文件可能更容易),并且不会继续到此代码。
我该如何解决这个问题,或者有更好的方法来完成我正在尝试的事情吗? cl
是一个变量,它将以整数形式作为用户的输入。该整数将用于 select if 和 elif 语句之间。
这个条件总是正确的!要使其工作,您需要使用 and
代替:
while cl != 1 and cl != 2 and cl != 3:
^^^ ^^^
以基本案例为例:c1 != 1 or c1 != 2
看看逻辑如何适用于您的 while
条件和我建议的条件:
c1 c1 != 1 c1 != 2 (c1 != 1 or c1 != 2) (c1 != 1 and c1 != 2)
1 false true true false
2 true false true false
!1,2 true true true true
我正在为 python 编程练习创建一个数学测验,但我遇到了一个问题。我正在尝试创建一个 while
循环以将其用作验证以确保用户输入了 1、2 或 3。当我使用此循环时,它只是继续循环而不退出。
cl = int(input("Please enter your class (1, 2 or, 3): "))
while cl != 1 or cl != 2 or cl != 3 :
cl = int(input("Please enter your class (1, 2 or, 3): "))
我有代码将其他信息保存到文本文件(我知道 csv 文件可能更容易),并且不会继续到此代码。
我该如何解决这个问题,或者有更好的方法来完成我正在尝试的事情吗? cl
是一个变量,它将以整数形式作为用户的输入。该整数将用于 select if 和 elif 语句之间。
这个条件总是正确的!要使其工作,您需要使用 and
代替:
while cl != 1 and cl != 2 and cl != 3:
^^^ ^^^
以基本案例为例:c1 != 1 or c1 != 2
看看逻辑如何适用于您的 while
条件和我建议的条件:
c1 c1 != 1 c1 != 2 (c1 != 1 or c1 != 2) (c1 != 1 and c1 != 2)
1 false true true false
2 true false true false
!1,2 true true true true