[英]Python While Loop Syntax
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
您好,我在理解上述while循环时遇到了一些困难,AFAIK您需要使用while循环来满足条件,因此:
while (stuff) == True:
但是上面的代码有:
while current:
是否与以下内容相同:
while current == head:
谢谢
while current:
语法的字面意思是while bool(current) == True:
该值将首先转换为bool,然后与True
相比较。 在python中,除非是None
, False
,零或空集合,否则转换为bool的Everyting均为True
。
请参阅真值测试部分以供参考。
您的循环可视为
while current is not None:
因为解析器将尝试将current解释为布尔值(并且None,空列表/元组/ dict / string和0的计算结果为False)
可变current
的值就是条件。 如果是事实,则循环继续;如果是事实,则循环停止。 期望在链接列表的最后一个元素中, next
将包含一个伪造的值。 我假设值是None
,在这种情况下,循环等效于:
while Current is not None:
相反,如果链接列表使用false
作为结束标记,则等效于:
while Current != false:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.