'The if statement isn't working correctly, and I don't know why [duplicate]
The if statement isn't working! Write when I type in 4, the first part gets triggered even though this if statement part is false, because the number is 4, and not 1, 3, 5 or something.
Here's the entire code:
number = input("Choose number between 0 and 20 (you can use 0 and 20, too) ")
int(number)
if number == 1 or 3 or 5 or 7 or 9 or 11 or 13 or 15 or 17 or 19:
number = int(number) * 3 + 1
print(number)
elif number == 0 or 2 or 4 or 6 or 8 or 10 or 12 or 14 or 16 or 18 or 20:
number = int(number) / 2
print(number)
else:
print("Run Code Again")
Solution 1:[1]
Your conditional statements need to be separated:
if number == 1 or number == 3 or number == 5, ... or number == 19:
It might be easier to use modulo to check for odd numbers:
if number % 2 == 1:
Solution 2:[2]
You are misusing the 'or' operator.
For instance:
print (1==2 or 3 or 5)
gives 3, not False.
print (1==(2 or 3 or 5))
would be closer to what you want, but this really just evaluates to 1==2 and would still be false even if 1 was in the or list as long as it wasn't the first non-zero item.
Solution 3:[3]
It is because conditions
3 or 5 or 7 or 9 or 11 or 13 or 15 or 17 or 19
is always true because you are not checking this with the number.
What you should do to make it logically correct is to compare them with your number like Martin's answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gray-lab |
| Solution 2 | user10489 |
| Solution 3 | holydragon |
