Python Forum
2 if statements happening at the same time - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: 2 if statements happening at the same time (/thread-38752.html)



2 if statements happening at the same time - M0TH - Nov-19-2022

hi I'm looking at all these other forum posts and they seem a lot more complex so sorry if this is a waste of time

im really new to python but i cant put my finger on exactly why the /cash condition happens when i input /chop ik its gunna be really obvious but i honestly have no idea why this happens
import time

cash = 15
logs = 5
rocks = 5
bricks = 0
planks = 0
a = True

while a:
  action = input("")
  if action == "/cash" or "/money":
    print("\n")
    print(cash, "$")
  if action == "/chop":
    print("\n")
    print("chopping...")
    time.sleep(5)
    logs += 1
    print("you chopped a tree. you now have", logs, "logs")
result:
Output:
/chop 15 $ chopping... you chopped a tree. you now have 6 logs
please help me


RE: 2 if statements happening at the same time - bowlofred - Nov-19-2022

Please use python tags to protect your code when posting code. Otherwise the formatting is lost.

Your if statement is parsed this way:
if (action == "/cash") or ("/money"):
Non-empty strings (like "/money") are always true, so this conditional will always evaluate to true.

You probably intend something like one of the below:
if action == "/cash" or action == "/money":

if action in ["/cash", "/money"]:



RE: 2 if statements happening at the same time - deanhystad - Nov-19-2022

You don't understand how "or" works in Python.

You think the statement "if action == "/cash" or "/money":' is True if action is either "/cash" or "/money". But Python evaluates this statement in a very different way. Python thinks the value of the statement is True if action == "/cash", otherwise the value of the statement is "/money". This seen if you print the value of the or statement.
action = "/cash"
print(action == "/cash" or "/money")
action = "/money"
print(action == "/cash" or "/money")
action = "something else"
print(action == "/cash" or "/money")
Output:
True /money /money
The reason for this is that Python evaluates "a or b" in this way:

If a is truthy, return a
otherwise return b

For your particular or statement, the "a" part is action == "/cash" and the "b" part is "/money". action == "/cash" will be either True or False. If it is True, the value of the or statement is True (the value of "a"). If it is not True, the value of the if statement is "/money" (the value of "b").


RE: 2 if statements happening at the same time - M0TH - Nov-19-2022

thanks i got it immediately! thanks for the fast responses