简体   繁体   English

Python While 循环中的海象运算符

[英]Python Walrus Operator in While Loops

I'm trying to understand the walrus assignment operator.我试图了解海象赋值运算符。

Classic while loop breaks when condition is reassigned to False within the loop.当条件在循环中重新分配给 False 时,经典的 while 循环会中断。

x = True
while x:
    print('hello')
    x = False

Why doesn't this work using the walrus operator?为什么这不能使用海象运算符? It ignores the reassignment of x producing an infinite loop.它忽略了 x 的重新分配,从而产生无限循环。

while x := True:
    print('hello')
    x = False

You seem to be under the impression that that assignment happens once before the loop is entered, but that isn't the case.您似乎认为该赋值在进入循环之前发生一次,但事实并非如此。 The reassignment happens before the condition is checked, and that happens on every iteration .重新分配发生在检查条件之前,并且发生在每次迭代中。

x:= True will always be true, regardless of any other code, which means the condition will always evaluate to true. x:= True将始终为真,无论任何其他代码如何,这意味着条件将始终计算为真。

Let's assume we have a code:假设我们有一段代码:

>>> a = 'suhail'
>>> while len(a) < 10:
...   print(f"too small {len(a)} elements expected at least 10")
...   a += '1'

The assignment expression helps avoid calling len twice:赋值表达式有助于避免调用len两次:

>>> a = 'suhail'
>>> while (n := len(a)) < 10:
...   print(f"too small {n} elements expected at least 10")
...   a += '1'
... 
too small 6 elements expected at least 10
too small 7 elements expected at least 10
too small 8 elements expected at least 10
too small 9 elements expected at least 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM