0

So Im just wondering why my code below is not functioning as expected,i want it to keep adding odd values to the odd count when given an odd number, likewise with the evens. but no matter what i put, it just adds it to the odd count. suggestions?

odd_value = 0
even_value = 0

x = int(input('enter'))
while x != 0:
    if x == 3 or 5 or 7 or 9:
        odd_value += x
    elif x == 2 or 4 or 6 or 8:
        even_value += x
    x = int(input('enter'))

print('The sum of the odds is ',odd_value)
print('The sum of the evens is' ,even_value)    
Bob Smith
  • 45
  • 3
  • possible duplicate of [Always true when testing if string == various OR'ed alternatives](http://stackoverflow.com/questions/24159301/always-true-when-testing-if-string-various-ored-alternatives) – wwii May 27 '15 at 02:15

1 Answers1

0

You've created an infinite loop. x will never equal to 0, and hence your loop will always keep going. It doesn't have an exit point. You can use a break statement anywhere to get out of the loop when you want.

Also, your logic is wrong:

if x in (3, 5, 7, 9):
    odd_value += x
elif x in (2, 4, 6, 8):
    even_value += x

or...

if x == 3 or x == 5 or x == 7 or x == 9:
    odd_value += x
elif x == 2 or x == 4 or x == 6 or x == 8:
    even_value += x

Now it evaluates each individual statement properly, instead of just seeing something that is implicitly True.

Here's why your original statements don't work:

>>> if x == 3 or 5 or 7 or 9:
...     print "Oh Darn!"

Oh Darn!

Let's see this in english:

if x is equal to 3 # Nope!
if 5 # That's True so let's go on!
Execute the if code block
Forget the elif code block
Zizouz212
  • 4,908
  • 5
  • 42
  • 66
  • more specifically, why when i enter an even number, it just adds it to the odd value. – Bob Smith May 27 '15 at 02:16
  • ok im following so far, but why when i enter an even number, say '2', the first if statement that only contains odd numbers gives your "That's true so let's go on!" and adds it to the odd count? – Bob Smith May 27 '15 at 02:23
  • It's because it doesn't do x == 2, instead it sees 5 and that evaluates to `True` right away. So it continues with that particular code block. I'll show you another way which is more straightforward. – Zizouz212 May 27 '15 at 02:25