Saturday 12 January 2019

python - Multiple conditions with if/elif statements




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


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...