Python Program for the Difference between Sums of Odd and Even Digits
Introduction
In this blog post, we will explore a Python program that calculates the difference between the sums of odd and even digits in a given integer. The program extracts individual digits from the number, categorizes them as odd or even, and computes the required difference.
Problem Statement
Given an integer, we want to find the absolute difference between the sum of its odd digits and the sum of its even digits.
For example:
- If the input number is 5472, the odd digits are 5 and 7, and the even digits are 4 and 2. The sum of odd digits is 12, and the sum of even digits is 6. Therefore, the output should be |12 – 6| = 6.
Python Program
def digit_sum_difference(number):
odd_sum = 0
even_sum = 0
# Iterate through each digit in the number
while number > 0:
digit = number % 10
# Categorize the digit as odd or even
if digit % 2 == 0:
even_sum += digit
else:
odd_sum += digit
# Remove the last digit from the number
number //= 10
# Calculate the absolute difference
difference = abs(odd_sum - even_sum)
return difference
# Example Usage
input_number = 5472
result = digit_sum_difference(input_number)
print(f"The absolute difference between sums of odd and even digits is: {result}")
Program Explanation
The program initializes two variables,
odd_sum
andeven_sum
, to keep track of the sums of odd and even digits.Using a
while
loop, the program iterates through each digit of the input number by repeatedly dividing it by 10 and extracting the last digit using the modulus operator.Each digit is categorized as odd or even, and the corresponding sum is updated.
After processing all digits, the absolute difference between the sums is calculated.
The result is then printed.
Example Output
For the example with input_number = 5472
, the output will be:
The absolute difference between sums of odd and even digits is: 6
Conclusion
This Python program efficiently calculates the absolute difference between the sums of odd and even digits in a given integer. It provides insights into handling individual digits of a number and performing categorization based on whether a digit is odd or even.
As an extension, readers can explore variations of this program, such as handling negative numbers or incorporating additional conditions for digit categorization. Experimenting with different input values will enhance your understanding of the program’s behavior. Happy coding!