a program that takes an integer and finds the sum of even and odd numbers

Asked 1 years ago, Updated 1 years ago, 366 views

odd_sum = 0
even_sum = 0

while True :
        num_str = input ("Enter an integer")

        if num_str == "99" :
            break

        num = int(num_str)

        if num % 2 == 0 :
            even_sum += num
        else :
            odd_sum += num

print("Odd number sum:",odd_sum)
print("even sum:",even_sum)

I wrote the code above to receive an arbitrary integer and divide it into the sum of odd and even numbers.

Enter
integer.5 56
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10208/1013878919.py in <module>
     14             break
     15 
---> 16         num = int(num_str)
     17 
     18         if num % 2 == 0 :

ValueError: invalid literal for int() with base 10: '5 56'

The above error occurred.

Which part is wrong?

python

2023-04-20 04:18

1 Answers

"Enter an integer" and you entered 556 right? So,

num = int('5 56')

That's the error because it ran. (Try pressing "Execute Code.")

Just in case, let me add... 556 is not an integer. It might be a string that connects two integers with one space.


2023-04-20 15:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.