Example 11: Sum up the digits in an integer

Given an integer, say 287591, we want to calculate the sum of all its digits. The result would be 32 = 2+8+7+5+9+1.  This problem was already considered in the while-loop section (example 6). Now we are solving it with a for-loop.

How do we proceed with a for-loop?  We change the integer into a string! Python allows us to iterate over the characters in the string and while doing so we add up “the digits.” Note that in the for-loop we need to convert the character “5” into digit 5 before making the addition.

# 02Loops example_11 SumDigits2.py
# add up the digits in an integer using a for loop

n = int(raw_input("Please input an integer:")) 	

sum = 0
for i in str(n): 	   #Convert integer sum into a string
	#Convert the string reresenting a single digit into an integer and add
    sum = sum + int(i) 

print(sum) 		

The following video uses this problem in a nested loop setting.  Video Length: 4:33