简体   繁体   中英

Python While Loop Syntax

class Solution: 
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

Hello, I am having some difficulties understanding the above while loop, AFAIK you need to have a condition with a while loop, so:

while (stuff) == True:

But the above code has:

while current:

Is this the same as:

while current == head:

Thanks

The while current: syntax literally means while bool(current) == True: . The value will be converted to bool first and than compared to True . In python everyting converted to bool is True unless it's None , False , zero or an empty collection.

See the truth value testing section for reference.

Your loop can be considered as

while current is not None:

because the parser will try to interpret current as a boolean (and None, empty list/tuple/dict/string and 0 evaluate to False)

The value of the variable current is the condition. If it's truthy, the loop continues, if it's falsy the loop stops. The expectation is that in the last element in the linked list, next will contain a falsy value. I assume that value is None , and in that case the loop is equivalent to:

while Current is not None:

If, instead, the linked list uses false as the end marker, it's equivalent to:

while Current != false:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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