How to Sum of even digits of a number in Python

Published on Aug. 22, 2023, 12:16 p.m.

To find the sum of even digits in a number in Python, you can convert the number to a string and iterate through its digits. For each digit, you can convert it back to an integer and check if it is even. If it is even, you can add it to a running sum. Here’s an example code:

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

for digit in str(num):
    if int(digit) % 2 == 0:
        even_sum += int(digit)

print("The sum of even digits in", num, "is", even_sum)

In this code, we first ask the user to input a number. We then initialize a variable called even_sum to 0, which we will use to keep track of the running sum of even digits. We convert the number to a string using str(), and then use a for loop to iterate through each digit in the string. For each digit, we convert it back to an integer using int() and then check if it is even by taking the modulus with 2. If the remainder is 0, the digit is even, and we add it to the running sum using the += operator. Finally, we print out the sum of even digits using the print() function.

Note that this code assumes that the user inputs an integer. You may want to add additional input validation code to ensure that the user inputs only valid integer values.

Tags:

related content