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.