When using IF statements in Python, you have to do the following to make the "cascade" work correctly.
if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
Is there a way to make Python accept multiple values when checking for "equals to"? For example,
if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
if job in ("mechanic", "tech"):
print "awesome"
elif job in ("tool", "rock"):
print "dolt"
The values in parentheses are a tuple. The in
operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.
Note that when Python searches a tuple or list using the in
operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a frozenset
:
AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])
def func():
if job in AwesomeJobs:
print "awesome"
The use of frozenset
over set
is preferred if the list of awesome jobs does not need to be changed during the operation of your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With