使用或在while循环中(Python)

Zim*_*ano 0 python logic loops while-loop

variable1 = 0
while variable1 != "1" or variable1 != "2" or variable1 != "3":
    variable1 = input ("Enter variable1: ")
print("Succes")
Run Code Online (Sandbox Code Playgroud)

即使为变量分配了1或2或3,我的代码也永远不会退出while循环。我从未读过任何有关Python的文档,这些文档说或语句在while循环中不起作用。根据命题演算,这应该是正确的,因为True或False或False = True

我知道我并没有使用整数。

提前致谢!

iCo*_*dez 5

您的while循环的条件将始终评估为True,因为variable1总是会不等于"1"或不等于"2"

相反,您将要在not in这里使用:

variable1 = 0
while variable1 not in ("1", "2", "3"):
    varible1 = input("Enter variable1: ")
print("Succes")
Run Code Online (Sandbox Code Playgroud)

但是,从您的代码结构来看,我认为您想variable1成为整数,而不是字符串。

如果是这样,则可以在Python 3.x上使用它:

variable1 = 0
while variable1 not in (1, 2, 3):
    varible1 = int(input("Enter variable1: "))
print("Succes")
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的是Python 2.x,则可以使用以下命令:

variable1 = 0
while variable1 not in (1, 2, 3):
    varible1 = int(raw_input("Enter variable1: "))
print "Succes"
Run Code Online (Sandbox Code Playgroud)