in this post, we are going to discuss how to find the sum of all even digits of a given number in Python using a while loop.
The program takes a number as input from the user and finds the sum of all its even digits using a while loop.
Here is a program in Python to find the sum of all even digits of a given number using a while loop.
Simple Code:
num = int(input("Enter a number: "))
sum_even = 0
while num > 0:
digit = num % 10
if digit % 2 == 0:
sum_even += digit
num //= 10
print("Sum of even digits of the given number is", sum_even)
Output:
Enter a number: 258
Sum of even digits of the given number is 10
Enter a number: -546462145
Sum of even digits of the given number is 0
Enter a number: 00
Sum of even digits of the given number is 0
Explanation with comments:
# Taking input from user
num = int(input("Enter a number: "))
# Initializing variables
sum_even = 0
# Finding the sum of even digits
while num > 0:
digit = num % 10 # Extract the last digit of the number
if digit % 2 == 0: # Check if the digit is even
sum_even += digit # Add the even digit to the sum
num //= 10 # Remove the last digit from the number
# Printing the result
print("Sum of even digits of the given number is", sum_even)
Explanation:
The program takes a number as input from the user and initializes a variable ‘sum_even’ to 0.
It then uses a while loop to extract the last digit of the number and checks if it is even.
If it is even, it adds the digit to ‘sum_even’.
It then removes the last digit from the number and repeats the process until all the digits have been processed.
Finally, it prints the sum of even digits of the given number.
Note: The program assumes that the input number is positive. If the input number is negative, the program can be modified to take its absolute value before processing. Also, if the input number is 0, the program will output 0 as the sum of even digits.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.