操作符与条件和返回语句的关系



根据我对运算符语句的理解,当给定"statement x" and "statement y"时,假设两个语句x和y都是True。鉴于此,所表示的and操作符将检查statement x是否为True,然后将移动到statement y并执行相同的操作。但是,一旦它完成了检查最终语句(y),当试图检查(换句话说,"引用"语句)"statement x" and "statement y"中的语句时,我们只能检查最终语句,IEstatement y

根据这个逻辑,第一个片段的输出确实是正确的,这证实了我的理解。

variable1 = "this is variable 1" 
variable2="this is variable 2" 
def returning(var1,var2):
return var1 and var2 
print(returning(variable1,variable2))

根据我的逻辑,对于第二个代码片段,循环不应该停止,因为and操作符只检查y语句。但是,循环停止了,这与我的逻辑相矛盾。为什么会有这样的矛盾?换句话说在我对运算符的理解中什么是无效的?

x = 3
y = 2
while(x and y):
print("iteration has been made")
x=x-1
user_input = input("Enter something (type 'quit' to exit): ")
if user_input == "quit":
break

在Python中andor是惰性的,例如是短路运算符。
一旦x求值为False,语句x and y就不能再求值为True,那么y求值为什么就无关紧要了。
同样,当python计算x为False时,x == 0

查看此StackOverflow post

当= 0 (x = x - 1)时,x变为False,这就是为什么循环停止的原因:

x = 3
y = 2
while(x and y):
print(f'Loop x={x}')
x = x - 1
print(f'Last x={x})

输出:

Loop x=3  # x and y is True
Loop x=2  # x and y is True
Loop x=1  # x and y is True
Loop x=0  # x and y is False, because x=0

读真值检验