我正在尝试了解海象赋值运算符。
当在循环中将条件重新分配为 False 时,经典的 while 循环会中断。
x = True
while x:
print('hello')
x = False
为什么这不能使用海象运算符?它忽略了 x 的重新分配,从而产生了一个无限循环。
while x := True:
print('hello')
x = False
我正在尝试了解海象赋值运算符。
当在循环中将条件重新分配为 False 时,经典的 while 循环会中断。
x = True
while x:
print('hello')
x = False
为什么这不能使用海象运算符?它忽略了 x 的重新分配,从而产生了一个无限循环。
while x := True:
print('hello')
x = False
您似乎认为该分配在进入循环之前发生了一次,但事实并非如此。重新分配发生在检查条件之前,并且发生在每次迭代中。
x := True
无论任何其他代码如何,都将始终为真,这意味着条件将始终评估为真。
假设我们有一个代码:
>>> a = 'suhail'
>>> while len(a)<10:
... print(f"too small {len(a)} elements expected atleast 10")
... a+='1'
赋值表达式有助于避免调用len()
两次:
>>> a='suhail'
>>> while (n:=len(a))<10:
... print(f"too small {n} elements expected atleast 10")
... a+='1'
...
too small 6 elements expected atleast 10
too small 7 elements expected atleast 10
too small 8 elements expected atleast 10
too small 9 elements expected atleast 10