Sum of even and odd | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Sum of even and odd

Write a program to input an integer N and print the sum of all its even digits and sum of all its odd digits separately. Digits mean numbers, not the places! That is, if the given integer is "13245", even digits are 2 & 4 and odd digits are 1, 3 & 5.

1st Jul 2021, 7:55 PM
Student
Student - avatar
9 Answers
+ 6
N=input() print(sum([int(c) for c in N if c in "02468"])) Analogue to odds
1st Jul 2021, 8:01 PM
Oma Falk
Oma Falk - avatar
+ 4
You could get the total of all the digits and then just find the total of all of either the evens or the odds. The other will just be the total minus whichever you find. Example (just finding evens): N = input() total = 0 evens = 0 for c in N: c = int(c) total += c if c % 2 == 0: evens += c odds = total - evens print(f"{evens=} {odds=}") Or a more advanced way; https://code.sololearn.com/cII4B1PpyFi1/?ref=app
2nd Jul 2021, 3:15 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
If N=12345 then str(N) will return it's string form "12345". (defaultly input is string type, no need convertion there) Then use a loop to extract each charecter and in if block, if condition of even is true , Add to even sum ( use int equivalent- int(char)) else : Add to odd sum Print even sum Print odd sum. These are steps you can follow. Hope you can know it how to convert to code as you already completed python beginner course. If not yet tried, then try now. If something went wrong then post your try here... someone help you to find errors... Hope it helps..
1st Jul 2021, 8:48 PM
Jayakrishna 🇮🇳
+ 2
odds=0 evens =0 for c in N: if c .... evens += int(c) else: .... print(odds, evens)
1st Jul 2021, 8:48 PM
Oma Falk
Oma Falk - avatar
+ 2
You can do it mathematically if you convert the input to an int, and using the modulo operator to get the digit in the ones place (N % 10), then check that digit to see if it is even/odd Then use floor division to drop the digit from the ones place (N //= 10) and repeat until N is 0. https://code.sololearn.com/cJI650Vm5aNg/?ref=app
2nd Jul 2021, 5:21 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
If I have to run the code using decision and conditional statements how can I do this?
1st Jul 2021, 8:17 PM
Student
Student - avatar
+ 1
In hint it is mentioned ## You can follow this syntax for printing values of two variables val1 and val2 separaetd by space - ## print(val1, " ", val2) Instance if N=81346 N=N%10 = 6 --- check odd and even N=N/10=4----again check odd and even and have form a loop. Means here we need to use while. Please answer it using while loop.
2nd Jul 2021, 5:06 AM
Student
Student - avatar
0
N = input("enter an integer: ") even_sum =0 odd_sum =0 for i in N: if i%2=0 even_sum += i else: odd_sum += i print(even_sum) print(odd_sum)
2nd Jul 2021, 6:47 AM
Thisal Rasindu
Thisal Rasindu - avatar
3rd Jul 2021, 1:59 AM
Abhishek Kumar
Abhishek Kumar - avatar