3. Control statements
Learning outcomes
At the end of this lesson, you will be able to:
- Understand the conditional statement
- Understand the loop statement
- Understand the concept of variable scope
- Utilise loop statement to draw impressive structures with the turtle
More on operators: logical operators and, or, not
These three logical operators operate on boolean expressions to result in boolean values. The meaning of these operators is just what the words mean. a and b will give True only if both a and b are True, otherwise it gives False. a or b will give False only if both a and b are False, otherwise it gives True. not a will give False if a is True, and vice versa.
The in operator
This operator tests if an value belongs to a list or a set. The situation with dictionaries is different: in will return whether a value belongs to the list of keys, not values, of a dictionary.
The conditional statement
So far, we have been dealing with simple python statements. Each statement could be written in a single line of code, and they instructed the computer to perform a single task. For example, a = 4 instructs the computer to put 4 into a and that's it.
Serious programming starts when we let the computer make decisions after it tests certain conditions. Instead of just printing a name, how about we get the computer to print the name only if it starts with letter A?
I just said if, which means: some condition should be tested before the print statement is executed. Now let me introduce the if statement in python. This statement has the following syntax:
if boolean_expression:
some_statements
The boolean_expression evaluates to either True or False. The if statement will only execute the statements if boolean_expression evaluates to True. Otherwise, these statements will not be executed.
So, to solve the above problem, here is the code:
s = 'Ahmed'
if s[0] == 'A':
print(s)
Result:
Ahmed
Indentation and blocks in python
Not the syntax here: the if keyword must be followed by the expression, then a colon :. In the next line, the some_statements has been indented. Indentation means: typing space, or tabs, before the statetment. Here, you can notice that print(s) has some space before it. By doing this, you are telling the compiler: if the condition is met, only execute the line of code that are indented. The indented statements form a block.
How much space? Well, you can add as much as you want, as long as you are consistent within the block. For example, the code below indents two print statements by 1 tab character.
s = 'Ahmed'
if s[0] == 'A':
print(s)
print('Done')
and the code below indents the two statements by 10 space characters.
s = 'Ahmed'
if s[0] == 'A':
print(s)
print('Done')
However, the code below will give an error.
s = 'Ahmed'
if s[0] == 'A':
print(s)
print('Done')
Now, as a matter of convention: follow the same indentation style in your entire code. It is better to use a single tab indentation, since that it is the most commonly used in python.
The else clause
In python, we can also specify what the code will do if the condition was not met. If the boolean expression evaluate to False (that is, if the first letter of the string is not A), we add the else statement:
if boolean_expression:
some_statements
else:
some_other_statements
So we can apply this to our example above as follows:
s = 'Brent'
if s[0] == 'A':
print(s)
else:
print('The string does not start with A')
Result:
The string does not start with A
The elif clause
Sometimes the condition we are testing might evaluate to more than two possible outcomes. For a simple demonstration: I will decide to put on a jacket if it's very cold outside. But if it's fair, maybe just a jumper. Otherwise, a t-shirt. So here we have three possible outcomes for the condition testing. The testing will check the temperature, and decide accordingly.
temperature = 15
if temperature < 15:
print('I am wearing a jacket')
elif temperature < 20:
print('I am wearing a jumper')
else:
print('I am wearing a t-shirt')
Result:
I am wearing a jumper
A useful example is to check the type of a variable:
x=True
if type(x) is list:
print('x is a list')
elif type(x) is set:
print('x is a set')
elif type(x) is tuple:
print('x is a tuple')
elif type(x) is int:
print('x is an integer')
elif type(x) is str:
print('x is a string')
elif type(x) is float:
print('x is a float')
elif type(x) is bool:
print('x is a boolean')
else:
print('I dont know what x is!')
Result:
x is an boolean
The loop statements
Python has two loop statements: the for and the while loop statements. The loop is a very important programming construct. It enables you to repetitively run a block of statements as long as a given condition is correct. Loops let us start write complex code that can solve complex problems; it is actually the starting point for doing serious programming!
The for loop
The syntax of the for loop is:
for x in collection:
statement1
statement2
...
statementN
Here collection could be any of the four collection types in python that we covered in Class 3. Note the in operator here.
In the for statement, x is called the index of the loop.
For example, the following loop will print out the elements from a list:
for k in [1,2,3]:
print(k)
Result:
1
2
3
A useful function in python is the range() function:
#You can passs 3 parameters:
range(start,end,step)
#or 2 parameters:
range(start,end)
#or 1 parameter:
range(end)
This function takes 1, 2 or 3 parameters. It creates a list starting from start. If start is not there, it assumes that 0 is the starting point. The last element is end - 1. If you give it a step parameter, it will only include numbers start, start+step, start+2*step, etc. up to the number less than or equal to end-1.
For example:
for x in range(2,20,3):
print(x)
Result:
2
5
8
11
14
17
You can also let the index run from a dictionary:
a = {('a',4):1,'b':2,'c':3}
for k in a:
print(k)
if type(k)==tuple:
print('It is a tuple')
Result:
('a', 4)
It is a tuple
b
c
Note that this only prints out the keys. What about the values?
a = {'a':1,'b':2,'c':3}
for k in a:
print(a[k])
Result:
1
2
3
The while loop
The syntax of the while loop is:
while x: statement1
statement2
...
statementN
The while loop keeps running the statement block as long as x is True. So x here is a boolean expression. For example:
a = 10
while a > 0:
print(a)
a-=1
Result:
10
9
8
7
6
5
4
3
2
1
The break statement
The statement breaks the execution of the loop.
The continue statement
When you call this statement, it breaks execution of the current loop, and enters the next loop..
The pass statement
This statement does nothing. When you call pass, it's like you called nothing at all. Not sure why they put it in python!
The else statement in the loop
The else in loops will run its block after the loop finishes.
The turtle
The turtle is a fun way to learn programming: instead of doing math or string operations, we move a turtle around a canvas, which will make the turtle draw geometry shapes.
We are going to use the online python interpreter called Trinket to program the turtle. This is because Colab doesn't let us draw on a canvas.
Let's start with the most basic turtle code:
from turtle import *
Then to start drawing, you call the goto() function:
goto(0,100)
goto(100,100)
goto(100,0)
goto(0,0)
Here, goto(x,y) takes you to the x and y coordinate on the screen.
Alternatively, you can move the turtle using the forward(), backward(), right() and left() functions:
for x in range(10):
forward(200)
left(170)
To learn more about the turtle, check out the documentation here.
