Example 6: Summing up the digits in many integers

The “sum up the digits in an integer” problem was discussed in Loops in Python where it illustrated the use of a while loop and a for-loop.  Now we want to solve this problem repeatedly. The user provides an integer and the program prints the sum of the digits in that integer; this process is repeated until the user enters -1 as input.

The program below wraps a while loop around the for-loop code (see Example 11 in Loops – Python). We could have also used the while loop code (Example 6 in Loops – Python).

# 03Loops example_06_summing up digits.py

n = int(raw_input('Please input an integer: '))  #To get the first integer

while n != -1:
    sum = 0    			        #Use variable sum to store the sum of all the digits
    for i in str(n): 			#Convert the integer into a string
        sum = sum + int(i) 		#Convert the string into an integer and add
    print sum
    n = int(input('Please input an integer: ')) #Use input function to get another integer
print('The loop ends! Bye!')   		  #Program ends

This nested loop example is discussed in the following video.  Video Length: 4:33