UnderscoreZero UnderscoreZero - 5 months ago 8
Python Question

Why does using an integer value as a 'while' loop condition work in Python?

The following code will output infinite lines of "test".

foo = 5
while foo:
print("bar")


The other day I came across an answer here about digit sums. This was the code shown in the answer:

def digit_sum(t):
s = 0
while t:
s += t % 10
t //= 10
return s


The part I'm focusing on is the "while t:" part. How and why does this work?

Answer

The while condition tests for truth. Any non-zero numeric value is considered true. See the Truth Value Testing section in the Python documentation:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.

Bold emphasis mine.

In your sample while loop, t trends to 0 (integer division by 10), so eventually while t: ends because t is considered false.

Comments