简体   繁体   中英

How to compare a user input against multiple OR conditions PYTHON 3.x

Apologies if this is a dumb question. I've done a bit of searching, and haven't been able to find the info I need though. I'm very new to python. Currently in the middle of the Learn Python 3 The Hard Way course.

I'm trying to write an IF statement that takes a user generated string, and compares it against a list, and then evaluates to True, if there is a match.

I have been able to do this successfully using:

if input in list:
    print("That was in the list.")

but what I'm trying to do now is swap this around and use a one off list that's part of the IF statement. I'm doing a ZORK style game where there are rooms with doors in different walls etc, so in this case it didn't make sense to me to have a bunch of permanent lists with different configurations of 'n', 's', 'e', 'w' in them that I'd have to reference depending on which walls have doors. But I don't want to write out three separate elif evaluations that all do the exact same thing either (if I wrote one for each 'no go' direction in each room.) Hope that all makes sense.

I read somewhere that you could put a list into an IF statement like this {'up', 'down', 'left'} But when I try that it says that I don't have a string in my "in" evaluation:

choice = input("> ")

if {'up', 'down', 'left', 'right'} in choice:
    print("You wrote a direction!")
else:
    print("Oh bummer.")

All you need to do is use a list [] square brackets, instead of curly ones (those are for sets) and you need to move the choice variable ahead. ( You want to see that the choice is in the list, and not the other way around. )

Your code should be :

choice = input("> ")

if choice in ['up', 'down', 'left', 'right']:
    print("You wrote a direction!")
else:
    print("Oh bummer.")

Wrong order

if choice in {'up', 'down', 'left', 'right'}:
    print("You wrote a direction!")
else:
    print("Oh bummer.")

EDIT: Use sets for existence-checking is usually more efficient than lists

You can use any() to check if any of 'up' , 'down' , 'left' , 'right' string exists in your choice variable:

choice = input("> ")

if any(x in choice for x in {'up', 'down', 'left', 'right'}):
    print("You wrote a direction!")
else:
    print("Oh bummer.")

The input format is usually pre-determined by the program though, so you could probably doing something like this:

choice = input("> ")

# assuming the input is always in the format of "go <direction>"
direction = choice.split()[1]

if direction in {'up', 'down', 'left', 'right'}:
    print("You wrote a direction!")
else:
    print("Oh bummer.")

Or maybe you could use regex (but that's rather more complicated)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM