# Control Flows

#Basic#Control Flow

We have learned how to use Python as a "calculator", i.e., creating variables, assigning values, and writing formulas to get an outcome. In this lesson, we will work on control flows to make Python handle more situations and write more complex programs.

# if statements

In case we want to execute a block of codes only if a condition is met, if statements come in handy for this purpose.

Let's take a look at the following example.

a, b = 10, 100
if b > a:
    print("a is less than b")
1
2
3

An if statement consists of at least two parts:

  • a condition
  • a block (or body) of codes to execute if condition satisfies

In the previous example,

  • the condition is whether b > a
  • the code to run is to display "a is less than b"

Notice that

  • the condition is a statement with comparison operators. In fact, we can use any form of statement as long as that statement returns a boolean. Thus, logical operators would also work. Or simply placing a True or False as the condition.
  • the condition ends with a :. This is the structure of an if statement. The Python interpreter knows it would expect some codes to fill the body
  • the code in body is indented. Python always uses indentation to control the flow of codes, unlike other languages that may use a pair of {}. The best practice is to use 4 spaces as indentation.
  • Indentation can be nested if we choose to use nested structures.

Here's another example.

x, y, z = 10, 20, 30
if x > 0:
    print(x)
    if y < 100:
        print(y)
        print(z)
1
2
3
4
5
6

The first print(x) is within the body of if x > 0. It is indented by 4 spaces. However, the second print(y) and third print(z) are within the body of if y < 100. They are both indented by 8 spaces.

These statements are to display value of x if x is greater than zero and further to display value of y and z if y is less than one hundred.

What if the indentation of the third print(z) changes.






 

x, y, z = 10, 200, 30
if x > 0:
    print(x)
    if y < 100:
        print(y)
    print(z)
1
2
3
4
5
6

Now value of z will display as long as x is greater than zero, regardless of y.

# elif

An if statement can chain with zero or more elif, which reads as "else if". An 'elif` branch works as additional steps to evaluate the conditions and run codes accordingly.

x = -10

if x > 0:
    print("x is greater than 0")
elif x == 0:
    print("x is 0")
elif x < 0:
    print("x is less than 0")
1
2
3
4
5
6
7
8

# else

An else branch is the catch-all situation for an if statement, it runs if all the previous conditions return False

x = -10

if x > 0:
    print("x is greater than 0")
elif x == 0:
    print("x is 0")
elif x > -10:
    print("x is less than 0 but somehow greater than -10")
else:
    print("x is not greater than -10")
1
2
3
4
5
6
7
8
9
10

# Assignment 3

Create a Python script named bmi_calculator.py that prompts for weight in pounds and height in inches. The script will then calculate and display the body mass index (BMI). It will also prompt the BMI classification.

BMI = (Weight in Pounds / (Height in inches x Height in inches)) x 703

The BMI classification is as follows.

BMI BMI Classification
18.5 or less Underweight
18.5 to 24.99 Normal Weight
25 to 29.99 Overweight
30 to 34.99 Obesity (Class 1)
35 to 39.99 Obesity (Class 2)
40 or greater Morbid Obesity

A sample run of the script would look like

python bmi_calculator.py
Enter weight in pounds: 200
Enter height in inches: 69
BMI = 29.531611006091154
BMI Classification = Overweight
1
2
3
4
5
Sample Solution
weight_in_pounds = float(input("Enter weight in pounds: "))
height_in_inches = float(input("Enter height in inches: "))

bmi = weight_in_pounds / (height_in_inches * height_in_inches) * 703

print("BMI =", bmi)

if bmi <= 18.5:
    classification = "Underweight"
elif bmi <= 25:
    classification = "Normal Weight"
elif bmi <= 30:
    classification = "Overweight"
elif bmi <= 35:
    classification = "Obesity (Class 1)"
elif bmi <= 40:
    classification = "Obesity (Class 2)"
else:
    classification = "Morbid Obesity"

print("BMI Classification =", classification)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# while statements

With the while loop we can execute a set of statements as long as a condition is met.

Let's take a look at the following example.

i = 0
while i < 10:
    print(i)
    i += 1
1
2
3
4

Notice that

  • the condition to control the while loop is i < 10
  • the body of the while loop is also indented

In plain language, the while loop tries to display the value of i as long as i is less than ten. And within each iteration of the loop, i increments by 1.

TIP

It's important to change the value of some variable that has impact on the condition eventually. Otherwise the while statements would never end and become an infinite loop.

Use while loop when we are not sure about how many times the loop shall run but we know the condition to continue.

For example, a simple guessing game

to_play = True
secret = "hello"
while to_play:
    guess = input("what is the secret? ")
    if secret == guess:
        to_play = False
        print("You've got it!")
    else:
        print("Wrong guess :(")
1
2
3
4
5
6
7
8
9

# break

We can use break to stop and escape the loop.



 
 



i = 0
while i < 10:
    if i == 5:
        break
    print(i)
    i += 1
1
2
3
4
5
6

The loop above would only display 0 to 4 since when i equals 5, the loop terminates.

# continue

We can use continue to skip and continue on with the next iteration of the loop.




 
 


i = 0
while i < 10:
    i += 1
    if i == 5:
        continue
    print(i)
1
2
3
4
5
6

The loop above would only display all the integers from 1 to 10 except for 5 (notice the increment of i is moved to the beginning of the body). The reason is that when i equals 5, the loop jumps out current iteration (not displaying the value) and then continue on to the next, until i is no less than ten.

# Assignment 4

Create a Python script named square.py that prompts for length of a square. The script will then display a square of the given length in the terminal.

You can use any character to represent the side of a square. A sample run would look like the following

python square.py
Enter length: 5
*****
*   *
*   *
*   *
*****
1
2
3
4
5
6
7

TIP

The terminal only draws character row by row. To generate a square in terminal, we need to put ourself in the shoe of a terminal. Think of these questions:

  1. How do I draw the first row?
  2. How do I draw the next row?
  3. How do I draw the last row?

By the way, the * operator can be applied on strings. It would duplicate that string multiple times, depending on the value from the right hand side of *.

Say, print("=" * 3) would display ===

print("Hello" * 2) would display HelloHello

Sample Solution
length = int(input("Enter length: "))

line_number = 0

while line_number < length:
    if line_number == 0 or line_number == length - 1:
        print("*" * length)
    else:
        print("*" + " " * (length - 2) + "*")

    line_number += 1
1
2
3
4
5
6
7
8
9
10
11

# for statements

for is another primitive loop statement in Python. It's used to iterate over a sequence (we will talk about more date types, such as list and dictionary, in the next lesson.)

First, let's see how to use for in a string (a string is sequence of characters).

for character in "calgary":
    print(character)
1
2

It iterates all the characters in the string "calgary" and display them line by line.

We usually use the range() (opens new window) function to loop through a body of codes for a specific number of times.

for i in range(5):
    print("doing something for the", i, "time")
1
2

range() would return a sequence of numbers (loop counters). If not specified otherwise, it always starts at 0.

range(5) from above returns numbers 0, 1, 2, 3, 4 particularly.

We can also specify the start/stop/step values of the sequence.

print(list(range(10)))
print(list(range(3, 10)))
print(list(range(3, 10, 2)))
print(list(range(10, -1, -1)))
1
2
3
4

# break and continue

break and continue also works in for loop

for j in range(1, 10):
    if j % 2:
        odd_or_even = "odd"
    else:
        odd_or_even = "even"
    if j == 5:
        print("skipping 5")
        continue
    elif j == 7:
        print("leaving early at 7")
        break
    print(j, "is", odd_or_even)
1
2
3
4
5
6
7
8
9
10
11
12

# Assignment 5

Create a Python script named diamond.py that prompts for rows of a diamond, where the number of rows shall be odd. The script will then display a diamond with the given number of rows in the terminal.

A sample run looks like the following.

python diamond.py
Enter number of rows: 21
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
*********************
 *******************
  *****************
   ***************
    *************
     ***********
      *********
       *******
        *****
         ***
          *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Sample Solution
while True:
    rows = int(input("Enter number of rows: "))
    if rows % 2:
        break

for i in range(0, rows // 2):
    print(" " * (rows // 2 - i) + "*" * (2 * i + 1))

print("*" * rows)

for i in range(rows // 2 - 1, -1, -1):
    print(" " * (rows // 2 - i) + "*" * (2 * i + 1))

# or
# for i in range(rows // 2 + 1, rows):
#     print(" " * (i - rows // 2) + "*" * (2 * (rows - i) - 1))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# Quote

practice-makes-perfect

# Assignment 6

Create a Python script named triangle.py that prompts for rows of a triangle. The script will then display a triangle with the given number of rows in the terminal.

A sample run looks like the following.

python triangle.py
Enter number of rows for the triangle: 7
      *
     **
    ***
   ****
  *****
 ******
*******
1
2
3
4
5
6
7
8
9
Sample Solution
rows = int(input("Enter number of rows for the triangle: "))

for i in range(rows):
    print(" " * (rows - i - 1) + "*" * (i + 1))
1
2
3
4

# Assignment 7

Create a Python script named plus.py that prompts for rows of a plus sign. The script will then display a plus sign with the given number of rows in the terminal.

A sample run looks like the following.

python plus.py
Enter number of rows for the plus: 11
     *
     *
     *
     *
     *
***********
     *
     *
     *
     *
     *
1
2
3
4
5
6
7
8
9
10
11
12
13
Sample Solution
while True:
    rows = int(input("Enter number of rows for the plus: "))
    if rows % 2:
        break

i = 0
while i < rows:
    if i != rows // 2:
        print(" " * (rows // 2) + "*")
    else:
        print("*" * rows)
    i += 1
1
2
3
4
5
6
7
8
9
10
11
12

# Assignment 8

Create a Python script name grades.py that prompts for a percentage grade and turns it into a letter grade and 4.0 scale.

You can use the following conversion table

Percent Grade Letter Grade 4.0 Scale
97-100 A+ 4.0
93-96 A 4.0
90-92 A- 3.7
87-89 B+ 3.3
83-86 B 3.0
80-82 B- 2.7
77-79 C+ 2.3
73-76 C 2.0
70-72 C- 1.7
67-69 D+ 1.3
65-66 D 1.0
Below 65 F 0.0

A sample run looks like the following.

python grades.py
Enter a percentage grade: 98
Letter Grade = A+
4.0 Scale = 4.0
1
2
3
4
Sample Solution
percentage_grade = int(input("Enter a percentage grade: "))

if percentage_grade < 65:
    letter_grade = "F"
    scale = 0.0
elif percentage_grade < 67:
    letter_grade = "D"
    scale = 1.0
elif percentage_grade < 70:
    letter_grade = "D+"
    scale = 1.3
elif percentage_grade < 73:
    letter_grade = "C-"
    scale = 1.7
elif percentage_grade < 77:
    letter_grade = "C"
    scale = 2.0
elif percentage_grade < 80:
    letter_grade = "C+"
    scale = 2.3
elif percentage_grade < 83:
    letter_grade = "B-"
    scale = 2.7
elif percentage_grade < 87:
    letter_grade = "B"
    scale = 3.0
elif percentage_grade < 90:
    letter_grade = "B+"
    scale = 3.3
elif percentage_grade < 93:
    letter_grade = "A-"
    scale = 3.7
elif percentage_grade < 97:
    letter_grade = "A"
    scale = 4.0
else:
    letter_grade = "A+"
    scale = 4.0

print("Letter Grade =", letter_grade)
print("4.0 Scale =", scale)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# Assignment 9

Create a Python script named odd_or_even.py that would keep prompting for a number and tell if that number is odd or even. The script exists if the user enters a negative number.

A sample run looks like the following.

python odd_or_even.py
Enter a number: 3
Odd number
Enter a number: 2
Even Number
Enter a number: 1
Odd number
Enter a number: 0
Even Number
Enter a number: -1
See you later!
1
2
3
4
5
6
7
8
9
10
11
Sample Solution
while True:
    number = int(input("Enter a number: "))
    if number < 0:
        print("See you later!")
        break
    elif number % 2:
        print("Odd number")
    else:
        print("Even Number")
1
2
3
4
5
6
7
8
9