0

I am a new programmer learning python, but I am having trouble with a challenge I came up with recently. The challenge is to have the console recognize odd and even numbers through numeric variables (24-32 in this case). It all seems to be functioning but when I run it it immediately skips to the else statement. I am writing in 3.8.2. Thanks for your help!

x = int(input("Enter a number between 24-32: "))
even = (24, 26, 28, 30, 32)
odd = (25, 27, 29, 31)

if x is (even):
  print("true")
  pass
elif x is (odd):
  print("false")
  pass
else:
  print("Please try again with a number between 24-32")
  pass
  • You need to by a loop around it. Likely a `while` loop – dawg Oct 14 '20 at 01:33
  • 2
    ```if x in even```. Do the same for the rest of elif. – andondraif Oct 14 '20 at 01:33
  • @andondraif is right. `is` is for object identity and `x` and `(even)` are *not* the same object. If you want membership checks, you should use `in`. – paxdiablo Oct 14 '20 at 01:35
  • Does this answer your question? [Testing user input against a list in python](https://stackoverflow.com/questions/3944655/testing-user-input-against-a-list-in-python) – akane Oct 14 '20 at 01:43

2 Answers2

1

Wrong syntax. To check if variable is in a tuple or a list, it should be:

if var in tuple:

or

if var in list:

Your code should be like this:

x = int(input("Enter a number between 24-32: "))
even = (24, 26, 28, 30, 32)
odd = (25, 27, 29, 31)

if x in even:
  print("true")
  pass
elif x in odd:
  print("false")
  pass
else:
  print("Please try again with a number between 24-32")
  pass
hung3a8
  • 21
  • 1
0

How about you try this instead:

x = int(input("Enter a number between 24-32: "))
if x not in range(24, 33):
    print("Please try again with a number between 24-32")
else:
    if x % 2 == 0:
      print("true -> x is even")
    else:
      print("false -> x is odd")
Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Dev
  • 665
  • 1
  • 4
  • 12
  • Wow that seems so much easier. I wish I could ask how it works on a deeper level but thanks for your submission! – abracadabra Oct 14 '20 at 01:43
  • @chatt - please mark this as solution, and don't forget to upvote! Thanks for your lovely feedback! – Dev Oct 14 '20 at 01:44