Skip to content Skip to sidebar Skip to footer

Python While Loop Syntax

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

Solution 1:

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.

Solution 2:

Your loop can be considered as

while current isnotNone:

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

Solution 3:

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 isnotNone:

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

while Current != false:

Post a Comment for "Python While Loop Syntax"