Intro to Python, Chapter 3 – Conditional Statements

This post was originally published here


Emerging from the sewer, Baldric found himself in the basin of a dry fountain. In its center was a marble statue of a massive fist which appeared to be composed of many entangled bodies. Employees, by how they were dressed. There were holes in various mouths and eyes that were apparently meant to be channeling water. “I’ve got a bad feeling about this,” Baldric muttered. Shaking off his fear along with the sewage, he climbed out of the fountain and proceeded across the polished granite floors of the otherwise empty, high-ceilinged room towards a particular pair of iron-reinforced doors. They were unlocked, and with a heave, he pulled one open and started down the dim rock-wall passage. It seemed to be sloping downward.

Chamber 1

After a time the passage opened up into a small, unadorned stone chamber, the first of six according to Cassandra. Two arched doorways leading out of the chamber stood in front of Baldric. Carved into the rock above the leftmost doorway was the expression 157 * 211. Above the other doorway was carved 37 * 919. On the ceiling of the chamber was the “greater than” symbol >.

“Based on what Cassandra said, I need to take the doorway with the greater result. I’ll bet I can weave some magic to figure that out.”

>>> 157 * 211 > 37 * 919
False

“So Door 1 is not greater than Door 2, which means that Door 2 is in fact the greater door, and so I should take Door 2. But what is this new thing I’ve produced? Is False a string?”

>>> type(False)
<class 'bool'>

# 'bool' is short for boolean,
# a data type that has only two possible values,
# True and False

>>> type(True)
<class 'bool'>

>>> type(1  

“That’s right, comparisons become booleans, which can take the form of either True or False. Interesting. Anyways, these comparisons are supposed to get more difficult, and Cassandra mentioned that death and worse lurks in the incorrect passages, so I’d better see if I can weave Magic that’s a little easier to read and understand.”

>>> door1 = 157 * 211
>>> door2 = 37 * 919
>>> door1 > door2
False

“That’s more readable, but I wish I could have it just tell me which door to go down so I don’t even have to think about it…oh yeah, I forgot! That Book of Magic had a section on conditional statements.”

# notice the code's structure here, how it is indented
# try using a single tab (equivalent in length to 4 spaces) as your standard indentation

if 1 > 2:
    print("It's True!")
else:
    print("It's False!")
It's False!

“I remember now, conditional statements use booleans to determine which branch of code gets executed. 1 is not greater than 2, so that first if branch’s condition is False. Therefore, the else branch gets executed. Let’s see if I can get them to work in the case of this little puzzle…”

# note that the code is now written in 'script mode'
# and the result of the code is shown in a separate window

door1 = 157 * 211
door2 = 37 * 919

if door1 > door2:
    print('Proceed through Door 1')
else:
    print('Proceed through Door 2')

Proceed through Door 2

“There we go, much harder to mix up.” Baldric happily strolled through Door 2 and once again proceeded down a dimly-lit passage before arriving at a second chamber.

Chamber 2

In this chamber were a total of three arched doorways.

  • Above Doorway 1:     661 * 691
  • Above Doorway 2:     61 * 7331
  • Above Doorway 3:     41 * 83 * 131
  • On the Ceiling:           == 445793

“I see there’s a third branch to our decision now with that third door. And I have to find the result that equals 445793. Shouldn’t be a problem. elif statements can be used to fill in extra branches between the initial if and ending else. The first branch with a True boolean gets executed, and the rest of the branches are then ignored. If none of the other conditions are True, then the else branch gets executed.”

door1 = 661 * 691
door2 = 61 * 7331
door3 = 41 * 83 * 131

# notice that = is used for variable assignment
# while == (two equals signs) is used to test for equality

if door1 == 445793:
    print('Take Door 1')
elif door2 == 445793:
    print('Take Door 2')
else:
    print('Take Door 3')
Take Door 3

Baldric took a step towards Door 3, then stopped in thought.

“Wait a second, I didn’t actually check to make sure that the calculation for Door 3 equals 445793. I just assumed it did if the other two doors weren’t equal to 445793. It’s probably a pretty safe bet, but I’d better make a little change to my Magic just to make sure I didn’t make a mistake.”

door1 = 661 * 691
door2 = 61 * 7331
door3 = 41 * 83 * 131

if door1 == 445793:
    print('Take Door 1')
elif door2 == 445793:
    print('Take Door 2')
elif door3 == 445793:
    print('Take Door 3')
else:
    print('Is there a mistake?')
Take Door 3

“Same result, excellent. I’m very curious about these booleans though. Are they similar to numbers? Or strings? Or lists?”

>>> True + True
2

>>> True + False
1

>>> False + False
0

>>> True == 1
True

>>> False == 0
True

# True and False can behave like 1 and 0, and vice versa

>>> True[0]
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: 'bool' object is not subscriptable

# they can't, however, behave like strings or lists

“So True and False are very closely related to the integers 1 and 0. Intriguing.”

Chamber 3

Baldric soon came to a third chamber, similar to the others, though this time it had five doors, and the following jibberish text on the ceiling:

  • Doorway 1:     “laksjdflf”
  • Doorway 2:     “aowiejflk”
  • Doorway 3:     “wopidnsks”
  • Doorway 4:     “ufkasidhu”
  • Doorway 5:     “paoiwmqnk”
  • Ceiling:            in “aiuhmxijfhmsioduyweniahuewiauehrnuaghfjskalfhwiaeunhsdfhksjaueyrukasenfhkdjsfhasneuinakheiuarsdgnfudhlfauneyhuiasgnfkdhuauerhnasihafsuiehnsdjfhmauefhnyuhnkausdkfhmskaldfhmaskdufkasidhufiuwoeumopasienroiaweuroiawenruiaweynroiafuioshfnouisdgbuiozfhmniozsuerynosuihnfrsdioufhosiaueyhnasduifhnsuiafbyioausenyrunsaerbuaysdbni”

“Looks like I have to determine which of the shorter strings appears in the longer one. I think I know just the trick.”

text = """
aiuhmxijfhmsioduyweniahuewiauehrnuaghfjskalfhwiaeunhsdfhksjaueyrukasenfhkdjsfha
sneuinakheiuarsdgnfudhlfauneyhuiasgnfkdhuauerhnasihafsuiehnsdjfhmauefhnyuhnkaus
dkfhmskaldfhmaskdufkasidhufiuwoeumopasienroiaweuroiawenruiaweynroiafuioshfnouis
dgbuiozfhmniozsuerynosuihnfrsdioufhosiaueyhnasduifhnsuiafbyioausenyrunsaerbuays
"""

subtext1 = "laksjdflf"
subtext2 = "aowiejflk"
subtext3 = "wopidnsks"
subtext4 = "ufkasidhu"
subtext5 = "paoiwmqnk"

# in statements are simple and very useful
# they can be used to test for substrings (i.e. >>> "fire" in "fireball")
# and they can also be used to test for membership in lists (i.e. >>> 2 in [1,2,3])

if subtext1 in text:
    print("Door 1")
elif subtext2 in text:
    print("Door 2")
elif subtext3 in text:
    print("Door 3")
elif subtext4 in text:
    print("Door 4")
elif subtext5 in text:
    print("Door 5")
else:
    print("Was there a mistake?")
Door 4

“Door 4 it is.”

“Ah, Door 4, I never would have guessed,” said a deep, hearty voice from behind Baldric.

Baldric spun around to see a hulking figure emerge from the shadows. A Human, tall even by Human standards. He was wrapped in a dark gray cloak, beneath which Baldric could make out white plated armor. Despite his snow-white hair and beard, the man gave the impression of a boulder, powerful and implacable. As he approached, his armor clinking, Baldric’s mind raced with what he should do. “This guy could rip me in half with his bare hands,” thought Baldric. “Maybe it’s time to try out some more Fire magic, or maybe just make a run for it, or…”

Baldric almost sighed with relief when he saw the man smile and offer his hand. He shook it, grimacing from the man’s iron grip.

“The name’s Bill, Bill Johnson from Maintenance. The team got a message about a leaky faucet in the HR Manager’s office, but I’ll be damned if I can find it!” he said, throwing back his head and roaring with laughter.

“Maintenance? Pardon me for asking, but where are your tools?”

“Tools? I’ve got my trusty hammer right here,” said Bill, motioning behind his back. For the first time, Baldric noticed a shape resembling the head of a massive hammer bulging beneath Bill’s cloak, and a thick metal haft sticking up over his shoulder.

“That’s quite the hammer Bill. I’d hate to be the leaky faucet.”

Throwing back his head in laughter once again, Bill roared, “Well said Master Dwarf, well said! I think we’re going to get along just fine. What did you say your name was?”

“Baldric Hightower, under-clerk of the Most Glorious Empire, may it be busy forever, ID# 61837…”

“Baldric! A fine name for a fine fellow. Well lead on Master Baldric. You seem to know what you’re about, and I assume you’re heading towards the HR Manager’s office like myself. Let’s not dawdle now, my hammer and I are eager to get this problem solved.”

The two proceeded through Door 4.

Chamber 4

The fourth chamber had nothing on the ceiling, just the following text above 4 different doorways:

  • Doorway 1:     2 > 1 and 3
  • Doorway 2:     2 > 1 and 3 > 4
  • Doorway 3:     2 and 3
  • Doorway 4:     2 and 3 > 4

“Gah, more accursed puzzles. Which way this time?”

Baldric, thinking back to the Book of Magic, remembered that the and operator requires the expressions on both of its sides to be true for the whole thing to evaluate to true. If one or both expressions are false, then the whole thing evaluates to false.

>>> True and True
True

>>> True and False
False

>>> False and True
False

>>> False and False
False

This was a simple enough puzzle, but he wove some Magic just to be sure of himself.

if 2 > 1 and 3 < 4:
    print("Door 1")
elif 2 > 1 and 3 > 4:
    print("Door 2")
elif 2 < 1 and 3 < 4:
    print("Door 3")
elif 2 < 1 and 3 > 4:
    print("Door 4")
else:
    print("Error?")
Door 1

“Looks like Door 1 this time, Bill.”

Walking along the passageway to the fifth chamber, Baldric noticed that part of Bill’s cloak had been torn, and it appeared as if a portion of it had been burned away. From glimpses beneath the cloak, the head of Bill’s hammer seemed to be coated in a dark-reddish substance.

“Bill? Eh hem…Bill?”

Bill looked at Baldric in confusion, then said, “Oh yes, excuse me, I was uhh…deep in thought. What is it, Master Baldric?”

“I couldn’t help but notice that your cloak has seen better days.”

“Oh, this? Yes, I made the mistake of wandering through one of these doorways at random. They’ve got some nasty critters down here to take care of any trespassers. But don’t you worry, if we take a wrong turn I know just the trick to dealing with them.” Baldric decided not to inquire any further.

Chamber 5

They arrived in the fifth chamber, and Baldric noticed that it was now noticeably warmer, hot even. This chamber had four doorways again, above which were the following statements:

  • Doorway 1:     2 > 1 or 3
  • Doorway 2:     2 > 1 or 3 > 4
  • Doorway 3:     2 or 3
  • Doorway 4:     2 or 3 > 4
  • Ceiling:            not

Baldric thought he remembered that the “or” operator required just one of its expressions to be true for the whole thing to be true. He quickly ran a test to verify this.

>>> True or True
True

>>> True or False
True

>>> False or True
True

>>> False or False
False

Just as he suspected. This was similar to the previous chamber, but he also needed to take into account the not operator stated on the ceiling. “That not operator should reverse the results, and so the not needs to apply to the entire expression. If I enclose the main expression in parentheses it will get evaluated first, and then the not should appropriately reverse the truth value of that expression.”

if not (1 < 2 or 3 < 4):
    print("Door 1")
elif not (1 < 2 or 3 > 4):
    print("Door 2")
elif not (1 > 2 or 3 < 4):
    print("Door 3")
elif not (1 > 2 or 3 > 4):
    print("Door 4")
else:
    print("Error?")
Door 4

“Door 4 this time, Bill. Bill?”

Bill was muttering to himself, seemingly lost in thought. “…doesn’t make sense…adding cabbage to gibberish…but if they were somehow all converted to numbers…”

“Bill, you all right?”

“Huh? Oh! Yes, forgive me. Just thinking about a dream I had. Lead the way, Master Baldric. I trust we’re almost there.”

“I hope so, I’m sweating like an elf in a goblin cookpot.”

Chamber 6

They arrived in the sixth and final chamber to find a cloaked and hooded figure seated behind a desk.

“Good evening gentlemen, how can I help you?” said a voice like a sword unsheathing.

Bill whispered to Baldric, “Quick man, figure out which door’s the one.” Then turning back toward the hooded figure, he said, “Hi there, I’m Bill Johnson with Maintenance, and we got a report about some water leakage in the HR Manager’s office. Would you mind pointing us in the right direction?”

After a moment of silently studying Baldric and Bill, the figure said, “Why certainly, the second doorway from the left is where you want to go.”

Despite the hooded figure’s foreboding aura, Baldric got the feeling that under its hood was a smile.

Turning his attention back to the doorways and ceiling, Baldric saw the following.

  • Doorway 1:     99
  • Doorway 2:     77
  • Doorway 3:     66
  • Doorway 4:     55
  • Doorway 5:     33
  • Ceiling:            in and a divisor of 998877665544

“Hmm, which door is it this time…”

nmain = 998877665544
n1 = 99
n2 = 77
n3 = 66
n4 = 55
n5 = 33

if (str(n1) in str(nmain)) and (nmain % n1 == 0):
    print("Door 1")
elif (str(n2) in str(nmain)) and (nmain % n2 == 0):
    print("Door 2")
elif (str(n3) in str(nmain)) and (nmain % n3 == 0):
    print("Door 3")
elif (str(n4) in str(nmain)) and (nmain % n4 == 0):
    print("Door 4")
elif (str(n5) in str(nmain)) and (nmain % n5 == 0):
    print("Door 5")
else:
    print("No matches?")

# if this structure seems repetitive and inefficient, that's because it is
# you will see how to do this more efficiently in future chapters
Door 3

“Bill, it’s Door 3,” whispered Baldric. Bill turned to look at him.

“You’re sure about that?”

“By my father’s axe, I swear it.”

After frowning for a moment, a big smile suddenly split Bill’s face. “Door 2 huh? You know what pal, I’ve got a better idea.” In one fluid motion Bill drew his warhammer and cast off his cloak, revealing a heavy set of gleaming white plate mail. He handled the massive hammer as if it was light as air.

Startled, the hooded figure jumped up from its seat. Its hood fell back to reveal a demonic face filled with far too many mouths and beady black eyes, all of them burning with hate. After a moment of surprise the demon began weaving Magic, and though Baldric didn’t recognize the patterns, he got the feeling it was something nasty.

But charging forward with unnatural speed, Bill suddenly leapt through the air and with a roar brought his hammer down on the demon before it could finish its spell, and it disappeared in a shockwave of dust and desk fragments. Bill stood up, brushed the dust off his armor, and walked back to Baldric.

“Thank you for your guidance Master Baldric, but I’ve got an appointment with the HR Manager now, so regardless of your plans I recommend you clear out, and fast. May you find peace in the Light.”

And with that, Bill set off charging through Door 3.

“Oh, shave my beard and dull my axe, what have I gotten myself into now?” Baldric looked longingly back at the way he had come. But, reminding himself of his mission, he turned around and ran through the door after Bill.


Congratulations, you earned 245 experience and 87 gold! You are now a Level 3 Dwarven Journeyman! (cue victory music)

Here are the Python topics you covered (and may want to DuckDuckGo for further inquiry):

  • conditional statements
  • booleans (True, False)
  • if, elif, else
  • equality comparisons (>, =,
  • in
  • and, or
  • testing for divisibility (x % y == 0)
  • multi-line strings


Chapter 4 – Functions >>>

Related Posts

Intro to Python, Epilogue – Only the Beginning Congratulations, dear reader, on completing your quest. But be warned, opening the Door was but the first step of your journey. You now have an under...
Intro to Python, Chapter 8 – Opening the Door Baldric was suddenly standing in a crowd of soldiers. Not Imperial soldiers thankfully. These were more ragtag, wearing random bits of armor here and...
Intro to Python, Chapter 7 – Imports and Nesting Baldric had been a town guard for years, breaking up fights and catching thieves and helping the elderly cross the street. When the Empire arose and ...
Intro to Python, Chapter 6 – Built-in Functions and Methods Magic-wielding escapees were desperately deflecting the Imperial attacks on the fortress’ supports as best they could. Ranks of longbowmen rain...

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz