I ran into an issue while trying to make aliases for an input.
inp = "h" #the input
if inp == "s":
print("stand")
elif inp == "h":
print("hit")
else:
print("else")
This code behaves exactly as expected s makes it take the first branch h second and anything else the third. But when i add or into the if statement
inp = "h"
if inp == "s" or "stand":
print("stand")
elif inp == "h":
print("hit")
else:
print("else")
the first branch gets picked regardless on the input provided. What I expected to happen was to get the same logic as before. Am I misusing OR or this should work but doesnt?
>Solution :
You’re not quite using or correctly. I made the same mistake with my first time using logic, so I wouldn’t stress it too much. The correct usage isn’t much different:
inp = "h"
if inp == "s" or inp == "stand":
print("stand")
elif inp == "h":
print("hit")
...
The way conditions work is that for each condition, python basically puts on is True
at the end. So if inp == "s"
would basically be if inp == "s" is True
. That would explain why inputting stand
wouldn’t work, since it would be checking if "stand" was equal to True.
Edit: sorry, my above statement is incorrect. What the program is checking for is if "stand" is a "valid" item. That might not be the correct terminology, but something that wouldn’t be valid would be an empty list, empty string, or the keyword None
. Since "stand" is valid, it counts as being True, and thus the first branch is always taken.