Yes, the code contained inside an
if or an
elif block will only run if the condition is met - i.e. it is
True once fully resolved.
As a real-world analogy, let’s say you’re doing a lunch run to Subway* and your colleague Bob wants you to pick him up a sandwich.
Bob says: “I’d like a foot-long Subway Melt on Hearty Italian bread, or regular Italian if they’re out of that. 9-grain wheat is OK, but it’s not my favourite. Lettuce, onion, tomato and peppers as well, oh and honey mustard sauce please. Mayo is fine if they don’t have that sauce.”
Bob’s order can be expressed using
sandwich = "Subway Club"
bread = ""
sauce = ""
if they_have_hearty_italian_bread == True:
bread = "Hearty Italian"
elif they_have_italian_bread == True:
bread = "Italian"
bread = "9-Grain Wheat"
if they_have_honey_mustard_sauce == True:
sauce = "Honey Mustard"
elif they_have_mayo == True:
sauce = "Mayo"
sauce = None
Let’s not forget about the
not operator. For example:
am_i_hungry = False
while not am_i_hungry:
not am_i_hungry here resolves to
not False, which is
True so the
while loop runs. If we become hungry, and flip the value of
True, the while loop condition is no longer met and we run the
else block of
Does that help at all? Hopefully it does. Now, if you’ll excuse me, I need to go buy a sandwich…
(* other food vendors are available.)