Search code examples
pythonloopsuser-input

Python: How to code 2 different inputs


I'm trying to make a game to learn how to code with python. I've reached a part where I want a while loop to keep asking for input if the user input is not valid. But I also want two different inputs to give different outputs. However, I've coded it so that any user input is not valid.

action4 = input()
while action4 != ("left") or action4 != ("right"):                           
    print ("Left or right?")
    action4 = input()
if action4 == ("left"):
    print ("You turn left and proceed down this hallway")
    left = True
elif action4 == ("right"):
    print ("You turn right and proceed down this hallway")
    left = False

I'm trying to get it so that both left and right are both valid outputs. But keep the while loop so that if any other input is not valid.


Solution

  • let us consider the conditional in the while loop:

    action4 != ("left") or action4 != ("right")
    

    we need this to evaluate as False to break out of the while loop, so what values would make this False? We can break the conditional down like this:

    action4 = ...
    cond1 = action4 != ("left")
    cond2 = action4 != ("right")
    result = cond1 or cond2
    print(cond1,cond2,result)
    

    so what if action4 = "left"? Well then cond1 -> False but cond2 -> True so because one of them is True, cond1 or cond2 is True.

    what if action4 = "right"? Well then cond1 -> True but cond2 -> False so because one of them is True, cond1 or cond2 is True.

    I think what you need to change is the or to and, so if action4 is not either of left or right then it will break:

    while action4 != ("left") and action4 != ("right"):
    

    or you can use the not in operator:

    while action4 not in ("left","right"):
    

    which is a bit easier to understand.