Using modulo and floor division in while loop


#1

Hi,

I have a hard time understanding how this function returns 10 (when digit_sum(1234)). Can any you please break it down for me?

Thanks,
Torben


#2

Hi @tfsn,

Let’s focus on these two lines …

        total += x % 10
        x = x // 10

What do you think each one of them does?


#3

Hi @appylpye ,

As far as I know ‘total’ will add/reassign the result of x % 10. The remainder of 1234 % 10 is 123.
123 = 123 // 10 is 12.
Is this correct? If it is, how can the function return 10 and not 12?


#4

See Python Syntax: Arithmetic for a review of the % operator. The result of 1234 % 10 is actually 4, which is the value of the final digit of the number. During each iteration of the while loop, you are adding the value of the final digit of x to total.

Also see Python Syntax: Two Types of Division. The // operator, which is not explicitly discussed there, performs floor division, which discards the remainder. Therefore, when it is used to divide x by 10, it gets rid of the final digit instead of yielding a float number.

In effect, each iteration of your while loop adds one of the digits of the number to total.

EDITED on April 8, 2018 for clarification


#5

Now it makes sense. Thanks for the explanation! :slight_smile:


#6