1

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?

Medak_
  • 23
  • 4

2 Answers2

1

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.

kxrosene
  • 63
  • 8
  • 1
    Please don't re-answer FAQs. There's a reason close-as-duplicate exists: so we can use existing, maximally-canonical answers for commonly asked questions. – Charles Duffy May 20 '23 at 23:28
  • @CharlesDuffy sorry about that. I wasn't aware that this question was a duplicate. – kxrosene May 20 '23 at 23:30
0

You've misunderstood the or syntax

In python all empty strings, lists, dicts, etc, evaluate to False:

x = []
if x: # Evaluates to False
   pass

In this example, x, being empty is False. According to this behavior any non-empty list, string, etc, evaluates to True:

x = [1, 2, 3]
if x: # Evaluates to True!
   print("This will print!")

Your code is asking is inp equal to "s", or is the string "stand" non-empty. The string "stand" is non-empty and thus the statement evaluates to True. To fix this, try asking is inp equal to "s", or is inp equal to "stand":

inp = "h"
if inp == "s" or inp == "stand": # Note the edit... This will evaluate to False.
    print("stand")
elif inp == "h":
    print("hit")
else:
    print("else")