Dremendo Tag Line

Input number and find sum of all odd and even digits in it using for loop in Python

for Loop - Question 12

In this question, we will see how to input a number and find the sum of all odd digits and even digits present in the number separately in Python programming using for loop. To know more about for loop click on the for loop lesson.

Q12) Write a program in Python to input a number and find the sum of all odd digits and even digits present in the number separately using for loop.

Program

import itertools

even=0; odd=0
n=int(input('Enter a number '))

for i in itertools.repeat(1):
    if n>0:
        d=n%10
        if d%2==0:
            even=even+d
        else:
            odd=odd+d

        n=n//10     # removing the last digit from the number using floor division

    else:
        break

print("Sum of even digits = %d" %(even));
print("Sum of odd digits = %d" %(odd));

Output

Enter a number 45612
Sum of even digits = 12
Sum of odd digits = 6
video-poster