Difference between Sums of Odd and Even Digits in Python (original) (raw)

Last Updated : 31 Oct, 2025

Given a number, the task is to find whether the difference between the sum of digits at odd positions and the sum of digits at even positions is zero or not. If the difference is 0, print “Yes”, otherwise print “No”. The digits are counted from left to right, starting from index 0.

**For Example:

**Input: 1212112
**Output: Yes

**Explanation:
Odd-position digits -> 2 + 2 + 1 = 5
Even-position digits -> 1 + 1 + 1 + 2 = 5
Difference -> 5 − 5 = 0 -> **Yes

Let's explore different methods to find the difference between the sums of odd and even digits in Python.

Using List Comprehension and Slicing

This compact method uses list slicing to separate digits at odd and even indices directly from a string.

Python `

n = 1212112 digits = list(map(int, str(n))) odd_sum = sum(digits[1::2]) even_sum = sum(digits[0::2])

if abs(odd_sum - even_sum) == 0: print("Yes") else: print("No")

`

**Explanation:

Using String Conversion and Indexing

This method converts the number into a string so we can easily access each digit’s index and decide if it’s in an odd or even position.

Python `

n = 1212112 num_str = str(n) odd_sum = 0 even_sum = 0

for i in range(len(num_str)): digit = int(num_str[i]) if i % 2 == 0: even_sum += digit else: odd_sum += digit

if abs(odd_sum - even_sum) == 0: print("Yes") else: print("No")

`

**Explanation:

Using Modulus and Integer Division

This method extracts digits from right to left using % and // operators. A flag alternates between True and False to track even and odd positions.

Python `

n = 1243 odd_sum = 0 even_sum = 0 flag = True

while n > 0: digit = n % 10 if flag: odd_sum += digit else: even_sum += digit flag = not flag n //= 10

if abs(odd_sum - even_sum) == 0: print("Yes") else: print("No")

`

**Explanation:

**Note: This method processes digits from right to left, but since both sums are compared at the end, the result remains the same.

Please refer complete article on Difference between sums of odd and even digits for more details!