0

I'm new to python and was looking around for a code for a function where the user inputs and integer and the function adds and returns the sum of the digits of the number.

The code looked like this:

def sum_digits(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s

So I know how a while loop works, but I can't wrap my head around (nor am able to find anything on Google) about how this works. I thought While loops always have a condition such as 'while n<10' or the sort.

What exactly is 'while n:' saying? How does this code work exactly? How does the code know how to stop running, and how exactly does it even return the sum of the digits (all I see it doing is returning the remainder of s/n).

Thanks for the help and sorry for any stupid questions.

Coding thermodynamist
  • 1,340
  • 1
  • 10
  • 18
rexorsist
  • 97
  • 5
  • https://docs.python.org/3/reference/expressions.html#boolean-operations – Josh Lee Sep 26 '17 at 19:40
  • See [the docs](https://docs.python.org/3/library/stdtypes.html#truth-value-testing). Objects can be "truthy" or "falsey". For example, non-zero `float` objects are "truthy", empty containers (`[], (), {})` are *falsey* – juanpa.arrivillaga Sep 26 '17 at 19:42
  • Possible duplicate of [Truth value of a string in python](https://stackoverflow.com/questions/18491777/truth-value-of-a-string-in-python) . From the answer to that question: `A numerical value of 0 is considered false (although a string value of '0' is considered true). All other expressions are considered True. ` – Davy M Sep 26 '17 at 19:45

2 Answers2

0

while n: is equivalent to while n!=0: (in this case, when you're dealing with numbers). Since each value in python has a Boolean value, for any number that is different from zero, bool(n) == True, if n equals zero, bool(n) == False.

That function can be written like (Thanks to @Jean-FrançoisFabre for suggesting the use of divmod):

def sum_digits(n):
    s = 0
    while n != 0:
        n, t = divmod(n, 10)  # to not use division and modulo separately
        # n has the value of n//10, t has the value of n%10
        s += t
    return s

print(sum_digits(154)) # => 10
print(sum_digits(134)) # => 8
print(sum_digits(987)) # => 24
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

while implicitly calls bool on the argument. So as long as bool(n) in your example is True the while loop continues.

And Pythons documentation for builtin types states that any number except zero is considered True:

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)

So basically the while n loop will continue until n becomes zero (or you break or return or raise...)

Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352