Python Program to Find Sum of all Odd Digits of Given Number Using While Loop

In this post, we are going to discuss how to write Python code to find the sum of all odd digits of a given number using a while loop.

Here is a Python program to find the sum of all odd digits of a given number using a while loop.

Simple code:

num = int(input("Enter a number: "))

sum = 0

while num > 0:
    digit = num % 10
    if digit % 2 != 0:
        sum += digit
    num //= 10

print("The sum of all odd digits of the given number is", sum)

Output:

Enter a number: 4568212
The sum of all odd digits of the given number is 6

Explanation in form of comments:

# Program description: Write a program to find the sum of all odd digits of a given number using a while loop.

# Taking input from user
num = int(input("Enter a number: "))

# Initializing variables
sum = 0

# Finding the sum of all odd digits using a while loop
while num > 0:
    digit = num % 10
    if digit % 2 != 0:
        sum += digit
    num //= 10

# Printing the result
print("The sum of all odd digits of the given number is", sum)

Explanation:

The program takes a number as input from the user and initializes a variable ‘sum’ to 0.

It then uses a while loop to find the sum of all odd digits of the given number.

Inside the while loop, it gets the last digit of the number using the modulus operator and checks if it is odd or not.

If it is odd, it adds it to the ‘sum’ variable.

It then removes the last digit from the number using the integer division operator.

This process continues until the number becomes 0.

Finally, it prints the result, which is the sum of all odd digits of the given number.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading