- 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.
9 Antworten
+ 6
N=input()
print(sum([int(c) for c in N if c in "02468"]))
Analogue to odds
+ 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
+ 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..
+ 2
odds=0
evens =0
for c in N:
if c ....
evens += int(c)
else:
....
print(odds, evens)
+ 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
+ 1
If I have to run the code using decision and conditional statements
how can I do this?
+ 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.
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)
0
https://code.sololearn.com/cA200a22a24A
answer in link