Given a positive integer n, say 287591, we want to determine the sum of all its digits. The result for 287591 would be 2+8+7+5+9+1 = 32. To solve this problem, we need to determine the individual digits in integer n.

Our program works as follows:

- Use the remainder operator % to obtain the last digit of the integer and add the digit to the variable sum.
- Then, use the floor division operator // to produce the integer without the last digit.
- Repeat these steps until there are no digits left.

# 02Loops example_06 SumDigits1.py # add up the digits in an integer using a while loop n = int(raw_input("Please input an integer:")) sum = 0 while n != 0: #While there are still digits left in n, the loop continues last_digit = n % 10 #Obtain the last digit of n sum = sum + last_digit #Add the last digit to sum n = n // 10 #Remove the last digit of n with Floor Division operator print(sum)

Comments

- Video03NestedLoops2.mp4 uses this problem in a nested loop setting.
- The above program “destroys” integer n. If for some reason we need n later, we would need to store it in another variable.
- If students have already seen for-loops in Python, ask them to try computing the sum of the digits with a for-loop. We will consider the for-loop version of this problem in Example 11.