Home > Net >  Write a python program to input an integer n and print sum of all its even and odd digits separately
Write a python program to input an integer n and print sum of all its even and odd digits separately

Time:11-12

Digits mean numbers not places

I tried but the logic is wrong I know

N=input()
L=len(N)
N=int(N)
sum_e=0
sum_o=0
for i in range(0,L 1):
    if i%2==0:
        sum_e=sum_e i
    else:
        sum_o=sum_o i
print(sum_e, sum_o)

CodePudding user response:

You can implement this more succinctly by modulating the input value as follows:

N = abs(int(input('Enter a number: ')))

eo = [0, 0]

while N != 0:
    v = N % 10
    eo[v & 1]  = v
    N //= 10

print(*eo)

Sample:

Enter a number: 1234567
12 16

CodePudding user response:

N=input()

sum_e=0
sum_o=0

for i in N:
    if int(i)%2==0:
        sum_e  = int(i)
    else:
        sum_o  = int(i)

print(sum_e, sum_o)

Let it remain string so we can iterate the digits and later convert it to Integer

CodePudding user response:

Using a dictionary:

N = input()
# N = '1234567'

out = {}
for c in N:
    c = int(c)
    key = 'odd' if c%2 else 'even'
    out[key] = out.get(key, 0)   c

print(out['even'], out['odd'])
# 12 16

Or with a method similar to @Cobra's:

N = int(input())
# N = 1234567

out = [0, 0]

while N>0:
    N, n = divmod(N, 10)
    out[n%2]  = n

print(*out)
# 12 16
  • Related