04. Conditionals


In this lab, we’ll introduce a new concept: conditionals. This allows change the behavior of our code based on context.

[0] Conditional behavior

There are many situations where you change your behavior based on the environment. For example, if it is raining outside, you wear rain boots. Otherwise, you might wear a different kind of shoe like tennis shoes.

You probably have even more complicated environmental responses as well.

For example, if you are ordering bubble tea, your order might go like this:

  • If the shop has taro,
    • you get taro in your tea
  • If the shop doesn’t have taro but has pearl
    • you get pearl in your tea
  • Finally, in the case that the shop doesn’t have taro or pearl
    • you don’t order any bubble tea.

In computer science, we call this kind of behavior conditional: your code runs only in the case that some condition is satisfied.

[1] Set up

Due to an issue with the mwc tool, you will clone this lab manually.

๐Ÿ’ป Start by going into your unit00_drawing folder.

cd ~/desktop/making_with_code/cs9/unit00_drawing/
๐Ÿ’ป Then clone the lab
git clone https://github.com/the-isf-academy/lab_conditionals.git
๐Ÿ’ป Now that you have the lab, go into its folder.
cd lab_conditionals

๐Ÿ’ป Enter the Poetry Shell to start the lab. As a reminder, we will run this command at the start of each lab, but only when we are inside a lab folder.

poetry shell
๐Ÿ‘พ ๐Ÿ’ฌ Exiting the poetry shell
When you want to exit the shell, you can type exit or ^D

๐Ÿ’ป Take a look at the files inside with: ls

  • conditionals_example.py
  • conditionals_modulo.py
  • conditionals_pattern.py
  • conditionals_rainbow.py
  • conditionals_user_input.py

[2] Writing Conditionals

Using the conditions generated by comparison operators, you can conditionally execute pieces of your code. This is useful for changing what your code does to respond to different conditions of the program.

[if statements]

if statements are the beginning to every conditional code block. The code written inside the code block that follows only runs if the condition after the if evaluates to True.

for i in range(20):
    if i < 10:
        print("Smaller than 10")

[else statements]

else statements can be paired with if statements to create an alternative block of code to execute if the condition after the if evaluates to False.

What is the difference between the following two programs?

# [else: example 1]
for i in range(20):
    if i < 10:
        print("Smaller than 10")
    print("Greater than or equal to 10")
# [else: example 2]
for i in range(20):
    if i < 10:
        print("Smaller than 10")
        print("Greater than or equal to 10")

[elif statements]

Finally, elif statements (“else if”) can be used to create multiple branches of a conditional. These statements add another condition to check if the condition above them does not pass.

The following program creates three branches of execution:

for i in range(20):
    if i < 10:
        print("Smaller than 10")
    elif i < 15:
        print("Greater than 9 but less than 15")
        print("Greater than or equal to 15")

This conditional creates the following cases for the variable i:

  • i < 10
  • 10 <= i < 15
  • 15 <= i

๐Ÿ’ป Run the following file to see this conditional statement in action: conditionals_example.py.

python conditionals_example.py

๐Ÿ’ป Open the code in: conditionals_example.py.

atom conditionals_example.py

๐Ÿ’ป Experiment with changing the conditional statements. Then run your code to see how your changes affect what it prints.

[3] Conditionals: User Input

Now, let’s explore how we can use conditionals in conjunction with user input.

๐Ÿ’ป Start by running the file: conditionals_user_input.py. One way to use conditionals in our drawings is to use them to respond to user input.

Try asking the program to draw a square.

python conditionals_user_input.py
๐Ÿ’ป Now, let's open up the code.
atom conditionals_user_input.py
# Unit 0 Lab 4
# conditionals_user_input.py

from turtle import *

while True:

    drawing = input("What would you like me to draw? ")
    size = int(input("How big should I draw it? "))
    if drawing == "square":
        for i in range(4):
    elif drawing == "quit":
        print("Sorry, I don't know how to draw that...")


while True: just prevents the program from ending after one loop

This program has a lot of potential, but so far it can only generate one drawing.

๐Ÿ’ป Add at least two more branches to the conditional so that the program can draw more than just a square. An elif statement will probably be useful here.

For example, your program could draw a square, a triangle, and a circle.

[4] Modulo

Python has many operators that allow you to perform calculations with values. You’ve probably seen and used the basic ones like +(add), - (subtract), * (multiply), and / (divide).

However, Python has some other less common opertors that can be really helpful.

One such operator is the modulo operator (%). This operator takes two values, divides them, and returns the remainder of the division.

For example:

5/2 has a remainder of 1

5%2 = 1

๐Ÿ’ป Open and run the file conditionals_modulo.py to experiment with the modulo operator. Does it output what you expected?


[Even/Odd Pattern]

Conditionals can also be paired with the modulo operator to cause your code to run in repeated patterns.

๐Ÿ’ป Start by running conditional_pattern.py. You should see a series of red boxes.

python conditionals_pattern.py
๐Ÿ’ป Edit the code so uses the modulo operator to create an alternating pattern of red and blue boxes.

One common use of the modulo operator, is to determine if a number is even or odd. Use that in conjunction with conditional statements to create an alternating color pattern.

[5] Deliverables

Once you’ve successfully completed the pattern be sure to fill out this Google form.

[6] Extension: Rainbow

๐Ÿ’ป Start by running conditionals_rainbow.py. You should see a series of colored boxes in a rainbow - very similar to the previous program.

python conditionals_rainbow.py

๐Ÿ’ป Open up the code and see how it works conditionals_rainbow.py. As you can see the code is over 80 lines long!

atom conditionals_rainbow.py

Although this code is really really long, there is a pattern to the rainbow that we could use to simplify the code!

๐Ÿ’ป Simplify this code using conditional statements and the modulo operator. Your file should be less than 40 lines of code when successfully simplified.