Multiple conditions with if/elif statements

22,012

Solution 1

What you're trying to do is

if user_input == "look" or user_input == "look around":
    print description

Another option if you have a lot of possibilities:

if user_input in ("look", "look around"):
    print description

Since you're using 2.7, you could also write it like this (which works in 2.7 or 3+, but not in 2.6 or below):

if user_input in {"look", "look around"}:
    print description

which makes a set of your elements, which is very slightly faster to search over (though that only matters if the number of elements you're checking is much larger than 2).


The reason your first attempt always went through is this. Most things in Python evaluate to True (other than False, None, or empty strings, lists, dicts, ...). or takes two things and evaluates them as booleans. So user_input == "look" or "look around" is treated like (user_input == "look") or "look_around"; if the first one is false, it's like you wrote if "look_around":, which will always go through.

Solution 2

You could use regular expressions to match the strings if they follow a pattern with optional sections or you could do an array lookup:

if user_input in ["look", "look around"]:
    print description

The boolean operator or only works with boolean values, it evaluates the expressions on both sides and returns True if one of the expressions evaluates to True. It has nothing to do with the natural language '

Share:
22,012
Blaine
Author by

Blaine

Updated on July 05, 2022

Comments

  • Blaine
    Blaine almost 2 years

    I'm trying to get an if statement to trigger from more than one condition without rewriting the statement multiple times with different triggers. e.g.:

    if user_input == "look":  
        print description
    
    
    if user_input == "look around":
        print description
    

    How would you condense those into one statement?

    I've tried using 'or' and it caused any raw_input at all to trigger the statement regardless of whether the input matched either of the conditions.

    if user_input == "look" or "look around":  
        print description