Control Structures#

There are three basic types of control structures; sequential, selection and iteration. They can be combined in any way to solve specified problems.

  • Sequential These are commands which are run after each other in the order presented in the script. We will not cover this in detail here as it’s self-explanatory. An example would be:

print('I'm first!')
print('I'm second...')
  • Selection This determines whether something should happen by asking a question. The most basic and common way to achieve this is the “if” statement. The “if” and “if/else” statements can be nested.

  • Iteration The iteration or repetition of code repeatedly executing a series of statements as long as the condition is true. The condition may be predefined or open-ended.

Selection Structures#

Also known as a conditional structure, a selection structure is a programming feature that performs different processes based on whether a boolean condition is true or false. Selection structures use relational operators to test conditions. There are different types of selection structures that can be used to achieve different outcomes.

  • If you want your program to do something if a condition is true, but do nothing if that condition is false, then you should use an if structure.

  • If you want your program to do something if a condition is true and do something different if it is false, then you should use an if-else structure.

  • If you want to test multiple conditions, then you can include an if-elif structure within an if or if-else structure.

If#

In if structures, a process will be only performed if the boolean condition is true. They have the following form:

if some_condition:
    do_something

An example would be to print Hello if x is greater than 10:

x = 12
if x > 10:
    print("Hello")
Hello

If-else#

In if-else structures, a specific action will be performed if the boolean condition is true and another action, if the condition is false. They have the following form:

if some_condition:
    do_something_on_true
else:
    do_something_on_false

An example would be to print Hello if x is greater than 10 or World otherwise:

x = 12
if x > 10:
    print("Hello")
else:
    print("World")
Hello

if-elif#

if-elif structures are a way to combine multiple boolean conditions into a single selection structure. They have the form:

if some_condition:
    do_something_on_true
elif some_other_condition:
    do_something_else_on_true
else:
    do_something_on_false

An example would be:

x = 10
y = 12
if x > y:
    print("x > y")
elif x < y:
    print("x < y")
else:
    print("x = y")
x < y

If statements inside an if statement or if-elif or if-else are called nested if statements. For example:

x = 10
y = 12
if x > y:
    print("x > y")
elif x < y:
    print("x < y")
    if x == 10:
        print("x = 10")
    else:
        print("Invalid")
else:
    print("x = y")
x < y
x = 10

Iteration Structures#

Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. The sequence will approach some end point or end value. Each repetition of the process is a single iteration.

For#

A for loop has the ability to iterate over the items of any sequence, such as a list or a string. It has the structure:

for iterating_var in sequence:
   do_something

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statement block is executed. Each item in the list is assigned to iterating_var, and the do_something block is executed until the entire sequence is exhausted.

For example, printing all numbers between 0 and 4:

for i in range(5):
    print(i)
0
1
2
3
4

In the above example, i iterates over the 0,1,2,3,4. Every time it takes each value and executes the statement inside the loop. It is also possible to iterate over a nested list illustrated below:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list1 in list_of_lists:
    print(list1)
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

A use case of nested for loops in this case would be:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list1 in list_of_lists:
    for x in list1:
        print(x)
1
2
3
4
5
6
7
8
9

While#

while loops are useful when programming for scenarios where it is unknown how many times the code should execute. The conditions within while loops are tested using relational operators. They have the form:

while some_condition:    
    do_something

It is important to define the condition correctly and it most likely should be dependent from a value set within the loop. A wrong condition can result in an endless loop or the loop not executed at all

An example would be:

i = 1
while i < 3:
    print(i**2)
    i = i + 1
print("Bye")
1
4
Bye

Iteration control#

Break#

As the name says. It is used to break out of a loop when a condition becomes true when executing the loop. For example:

for i in range(100):
    print(i)
    if i >= 7:
        break
0
1
2
3
4
5
6
7

Continue#

The continue statement skips the rest of the current iteration of the loop and jumps to the next iteration. For example:

for i in range(10):
    if i > 4:
        print("Skip")
        continue
    print(i)
0
1
2
3
4
Skip
Skip
Skip
Skip
Skip

List Comprehensions#

Python makes it simple to generate a list with a single line of code using list comprehensions. For example, to generate multiples of 27, we could write:

res = []
for i in range(1, 11):
    x = 27 * i
    res.append(x)
res
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]

List comprehensions are a more concise way of expressing the same thing:

[27 * i for i in range(1, 11)]
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]

List comprehensions consist of three parts enclosed in square brackets. For example, in the following, we have

  • An expression to produce values (27 * i).

  • A looping construct (for i in range(1, 20)).

  • And a condition (if x <= 10). This is optional as shown above.

[27 * i for i in range(1, 20) if i <= 10]
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]

It is also possible to have multiple looping constructs. This corresponds to nested loops:

[27 * z for i in range(50) if i == 27 for z in range(1, 11)]
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]

Questions#

Selection Structures#

  • We have a thermometer which reports the temperature. Write an if selection structure to tell us to put a coat on if it’s below 10.

Solution:

Hide code cell content
temperature = 2

if temperature < 10:
    print("Please wear a coat.")
Please wear a coat.
  • Now add to this code to suggest it’s t-shirt weather if the temperature is more than 24 using an if-elif structure

Solution:

Hide code cell content
if temperature < 10:
    print("Please wear a coat.")
elif temperature > 24:
    print("Please wear a T-shirt.")
Please wear a coat.
  • Now convert this to an if-elif-else to tell us we can wear what we want if the temperature is greater than 10 and less than 25

Solution:

Hide code cell content
if temperature < 10:
    print("Please wear a coat.")
elif temperature > 24:
    print("Please wear a T-shirt.")
else:
    print("You can wear what you want.")
Please wear a coat.

Iteration Structures#

  • Use the built in range function to generate a list from 1-12 which will be the months of the year

Solution:

Hide code cell content
months = list(range(1, 13))
months
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  • Use a for loop to iterate over the months of the year printing It is month month

Solution:

Hide code cell content
for month in months:
    print("It is month", month)
It is month 1
It is month 2
It is month 3
It is month 4
It is month 5
It is month 6
It is month 7
It is month 8
It is month 9
It is month 10
It is month 11
It is month 12

The average monthly temperatures in Lund for 2019 were:

temperatures = [-1, 0, 0, 5, 11, 16, 17, 16, 13, 8, 4, 0]

Python has a built-in function zip which allows you to iterate over two lists at once giving the corresponding item at a position in both iterators. It has the form:

for item1, item2 in zip(list1, list2):
  • Use zip to iterate over months and temperatures to print It is month month and temperature temperature

Solution:

Hide code cell content
for temp, month in zip(temperatures, months):
    print("It is month", month, "and temperature", temp)
It is month 1 and temperature -1
It is month 2 and temperature 0
It is month 3 and temperature 0
It is month 4 and temperature 5
It is month 5 and temperature 11
It is month 6 and temperature 16
It is month 7 and temperature 17
It is month 8 and temperature 16
It is month 9 and temperature 13
It is month 10 and temperature 8
It is month 11 and temperature 4
It is month 12 and temperature 0

Combining Iteration structures and selection structures#

Use your final code for the selection structure questions and insert it into the final code for the iteration questions.

You will have to:

  • Modify the t-shirt temperature to fit to the Lund climate. You want each iteration of months to produce the statement:

It is month month and temperature temperature. Wear this item of clothes

Solution:

Hide code cell content
for temp, month in zip(temperatures, months):
    if temp < 10:
        advice = "Please wear a coat."
    elif temperature > 24:
        advice = "Please wear a T-shirt."
    else:
        advice = "You can wear what you want."
    print(f"It is month {month} and temperature {temp}. {advice}")
It is month 1 and temperature -1. Please wear a coat.
It is month 2 and temperature 0. Please wear a coat.
It is month 3 and temperature 0. Please wear a coat.
It is month 4 and temperature 5. Please wear a coat.
It is month 5 and temperature 11. You can wear what you want.
It is month 6 and temperature 16. You can wear what you want.
It is month 7 and temperature 17. You can wear what you want.
It is month 8 and temperature 16. You can wear what you want.
It is month 9 and temperature 13. You can wear what you want.
It is month 10 and temperature 8. Please wear a coat.
It is month 11 and temperature 4. Please wear a coat.
It is month 12 and temperature 0. Please wear a coat.