-4

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?

2 Answers2

4

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You already got useful answers, but I just wanted to answer your question in a way that can be easily understood by someone who is a beginner in Python. You could rewrite your code as:

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

'while t' is equivalent to 'while t!=0', meaning that the loop will end when t is equal to 0.

In your for loop, 't //= 10' is equivalent to 't = t // 10' ('//' is a floor division operator and returns an integer). So the value of t becomes smaller each time the loop is executed, until it eventually reaches the value of 0. At this point, the 'while t' condition is False and the loop ends.

simon.sim
  • 149
  • 4