6 The order of events
This chapter is about how Python interprets (or evaluates) the code you write. It has a few fancy long words that may seem foreign to you. Do not let that throw you off. They are all just fancy names for something straightforward.
Precedence of Operators
Fear not. Precedence is just a nasty word for something we have already talked about. Precedence just means that some things are done before others or, more correctly, that some operations are performed before others. You already know that multiplication is done before addition. Another way of saying that is that multiplication takes precedence over addition. The expression below obviously reduces to 7 in two steps:
\[ 1 + 3 * 2 \]
First, \(3 * 2\) reduces to 6, and then \(1 + 6\) reduces to 7. If we wanted to add 1 and 3 first, we would need to enforce this by adding parentheses:
\[ (1 + 3) * 2 \]
This is because the multiplication operator (*
) has higher precedence than the addition operator (+
). Here is the list of the most common operators and their precedence in Python:
Level | Category | Operators |
---|---|---|
Highest | exponent | ** |
positive / negative | +x , -x |
|
multiplication | * , / , // , % |
|
addition | + , - |
|
relational | != , == , <= , >= , < , > , in , not in |
|
logical | not |
|
logical | and |
|
Lowest | logical | or |
Sometimes, a statement contains adjacent operators with the same precedence. In this case, Python evaluates the expression from left to right. I.e., This following expression first reduces to \(0.5 * 2\) and then to \(1\)
2 / 4 * 2
The following one first reduces to \(1 * 4\) and then to \(4\):
2 / 2 * 4
If you want Python to order the operations in any other way, you need to use parentheses (E.g., 2 / (2 * 4)
).
Exercise 6-1
Look at each expression in the exercises below and use the table above to decide if it evaluates to True
or False
. Then, write the code and test if you were right. If not, figure out why.
2 + 4 * 7 == 2 + (4 * 7)
Exercise 6-2
Does this reduce to True
or False
?
4 > 3 and 2 < 1 or 7 > 2
Exercise 6-3
Does this reduce to True
or False
?
4 > 3 and (2 < 1 or 7 > 2)
Exercise 6-4
Does this reduce to True
or False
?
2 * 4 ** 4 + 1 == (2 * 4) ** (4 + 1)
Statements and Expressions
To talk concisely about programming (and to receive more useful help from your instructors), you need to have a bit of vocabulary. Statements and expressions are two words you need to know. Distinguishing between statements and expressions will help us discuss our code.
A statement is a line of code that performs an action. Python evaluates each statement until it reaches the end of the file (remember oath 2?).
print(y * 7)
is a statement, and so isx = 14
. They each represent a full line of code and perform an action.An expression is any code that reduces to one value.
y * 7
is an expression, and so arey * 7 + 14 - x
and4 > 5
.
We will talk more about how Python handles expressions in the next section, but right now, you must understand that statements do something while expressions are things that reduce to a value. Hopefully, this distinction will be more clear after completing the following exercises.
Exercise 6-5
Did you notice in the above examples that print(y * 7)
is a statement and y * 7
is an expression? Yes, expressions can be part of statements. In fact, they most often are. Similarly, expressions are often made up of other smaller expressions. E.g., y * 7
is part of the longer expression y * 7 + 14 - x
.
Take a look at this code:
= 5
x = 20
y = (x + y) / 2 + 20
z print(z * 2 + 1)
= 2 * x - 9 * 48
h print(h)
Write down the code on a piece of paper. Now, mark all statements and all expressions. Remember that expressions are often made up of smaller expressions so that you can find a lot of them. E.g. (x + y)
, 2 + 20
, and (x + y) / 2 + 20
are all expressions. A single variable (like x
) is also a small expression. Discuss with a fellow student. Do you agree on what to find?
Exercise 6-6
Consider the following code:
= 'Hello' + ' my '
greeting print(greeting + 'friend')
How many statements are there in this piece of code? How many expressions?
Substitution and Reduction
Although substitution and reduction may not sound like your new best friends, they truly are! If you remember to think about your Python code in terms of substitution and reduction, then programming will make a lot of sense. Understanding and using these simple rules will allow you to read and understand any code. If you do not, you may get by for a while - only to find yourself in big trouble later when things become more complicated.
You should remember, from the section on variables in the previous chapter, that variables in Python are either assigned a value or substituted for the value they represent.
In the first two lines of code below, the variables x
and y
are each assigned a value. Now consider the last line in the example:
= 4
x = 3
y = x * y + 8 z
Here, x
is substituted by the value 4
, and y
is substituted by the value 3
. So now the expression after the equals sign reads 4 * 3 + 8
. Because we multiply before we add, 4 * 3
reduces to 12
so that the expression now reads 12 + 8
. Finally, this reduces to the value 20
. The very last thing that happens is that the variable z
is assigned the value 20
.
You should do these steps every time you see an expression. You may think this is overdoing things a bit, but it is not. This kind of explicit thinking is what programming is all about, and it will become increasingly important as the course progresses. So make sure you make it a habit while it still seems trivial. Then, over time, it will become second nature.
Now raise your right hand and read the third and last oath out loud:
Oath 3: I now solemnly swear to consciously consider every single substitution and reduction in every Python expression that I read or write from this moment on.
This was the last of the three oaths, but it is by far the most important one. You can take your hand down now.
NB: You may not realize this at this point, but the last two subsections are the most important ones in the book. Go back and read them many times as you proceed through the course. If you explicitly think in terms of substitution and reduction, you will be fine. If you do not, you are entering a minefield with snowshoes on.
Exercise 6-7
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= 7
x = 4 + x
y 2 + x * x**2 + y - x
Exercise 6-8
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= 4
a = a
b = 2
c = a + b + c c
Exercise 6-9
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= 1
x = x x
Exercise 6-10
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= "GTC" * 41 microsatellite
Surprised?
Exercise 6-11
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= "ATG" + "GCG" + "TAA" mini_gene
What did you do first here? Does the order of additions matter? What operations does Python perform first when operators have the same precedence? (left to right or right to left)
Exercise 6-12
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= 1 / 1 * 4 number
In what order are reductions made? Does the order of operations matter, and in what order does Python do the reductions?
Exercise 6-13
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= 4
x = x + x y
Exercise 6-14
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= 4
x = x + 1 x
Exercise 6-15
Do the substitution and reduction steps with pen and paper, then run it to check yourself by inserting a print
statement at the end.
= 4
x += 1 x
Compare the final value of x
to that in Section 6.0.0.14. Can you see what +=
is a shorthand for? Nifty, right?
General exercises
The following exercises are meant to train your familiarity with the topics we have treated so far – in this case especially:
- Substitution
- Reduction
- Assignment
- Simple precedence rules
- Comparison operators
- Logical operators
- Distinction between text and numbers
Read each exercise and think hard about the questions before you code anything. Then write the code and try it out. Remember that it is crucial that you type it in – as super dull as it may be (remember oath one). This trains your accuracy and attention to detail, and it builds programming into your brain. Play around with each bit of code. Make small changes and see how it behaves.
There is a reason why there are lots of questions in this exercise but no answers. You are supposed to find them yourself if it takes you quite a while. That is the way you build understanding. Some of the questions may seem trivial, but do them anyway. If you only understand these concepts superficially, they will come back and bite you in the ass when things get more complicated.
Exercise 6-16
Consider this code:
1.2 * 3 + 4 / 5.2
What does that expression evaluate to? Try to explicitly make all the reductions on paper before you write and run the code.
Exercise 6-17
Consider this code:
1.2 * (3 + 4) / 5.2
What does that expression evaluate to? Try to explicitly make all the reductions on paper before you write and run the code.
Exercise 6-18
Consider this code:
10 % 3 - 2
What does that expression evaluate to? Try to explicitly make all the reductions on paper before you write and run the code.
Exercise 6-19
Consider this code:
11 % (7 - 5)**2
What does that expression evaluate to? Try to explicitly make all the reductions on paper before you write and run the code.
Exercise 6-20
Consider this code:
= 5
a = 9
x = 7
banana + 4 * a > banana x
What does the last expression evaluate to? Try to explicitly make all the substitutions and reductions on paper before writing the code. What happens if you write and run the code? Why?
Exercise 6-21
Consider this code:
= 'can'
dance = dance + dance
dance print("Do the", dance)
What is printed? Try to explicitly make all the substitutions and reductions on paper before writing the code. What happens if you write and run the code? Why?
Exercise 6-22
Consider this code:
= 30
foo = 50
bar = bar + foo
baz print(baz)
= 10
bar print(baz)
There are two print statements. The first print statement prints 80
. But what about the second print statement? Does that print 80
or 40
? Find out and make sure you understand why it prints what it prints. If not, reread the section on substitution.
Exercise 6-23
Consider this code:
1 == '1'
and this:
1 == 1.0
What does this reduce to? Try printing it and seeing once you think you know. If you were wrong, make sure you figure out why.
Exercise 6-24
Consider this code:
= '1'
a = '2'
b = a + b
c print(a, b, c)
print(a + b == 3)
What is printed here? Write the code and see for yourself once you think you know. If you were wrong, make sure you understand why.
Exercise 6-25
Consider this code:
= 1
a = 2
b = a + b
c print(a, b, c)
print(a + b == 3)
What is printed here? Compare to Section 6.0.0.24. Write the code and see for yourself once you think you know. If you were wrong, make sure you understand why.
Exercise 6-26
Consider this code:
= 4
x print(x + 2 and 7)
print(x + 2 or 7)
= -2
x print(x + 2 and 7)
print(x + 2 or 7)
What is printed here? Write the code and see for yourself once you think you know. If you were wrong, make sure you understand why.
Exercise 6-27
I have shuffled the statements in the code below. Put them in the right order to make the code print 100
.
= x + 4
x print(x)
= x * 5
x = x * x
x = 4 x
Exercise 6-28
I have shuffled the statements in the code below. Put them in the right order to make the code print the string `“Banana.”
= 'n'
y = 'B' + y + x
x print(x)
= 'a'
x = (x + y) * 2 y
Exercise 6-29
Make a puzzle exercise, like the two previous ones, for a fellow student.
Exercise 6-30
Remind yourself of the different types of Python values you know. For example, one of them is an integer (int
). Make a list.
Exercise 6-31
You already know about several types of data values in Python. Two are integers called int
, and decimal numbers (or floating points) called float
. When you use an operator like +
or >
it produces a value. No matter what you put on either side of >
it produces a boolean value (bool
), True
or False
. For other operators, the type of value produced depends on which values the operator works on. Try this and see if you print an integer or a float (8
or 8.0
):
= 4
x = 2
y = x * y
result print(result)
Now try to replace 4
with 4.0
. What type is the result now? Try to also replace 2
with 2.0
. What type is the result now? Can you extract a rule for what the *
operator produces depending on what types the two values have?
Exercise 6-32
In Section 6.0.0.31, you investigated what types of values the *
operator produces. Redo that exercise with the operators: +
, -
, /
, **
, //
, and %
. What are the rules for what is returned if both values are integers, one value is a float, or both values are floats?
Exercise 6-33
Make a list of all the operators you know so far in order of precedence (without looking in the notes). Then check yourself.
Exercise 6-34
What does his expression reduce to, and what type of value is it?
3 > 2
Exercise 6-35
What does his expression reduce to, and what type of value is it? Do all the reduction steps in your head.
2 - 4 * 5 - 2 * 1/3
Exercise 6-36
What does his expression reduce to, and what type of value is it? Do all the reduction steps in your head.
3 > 2 and 2 - 4 * 5 - 2 * 9
Exercise 6-37
What is printed here and why?:
print(True and "banana" or "orange")
Try to change the True
value to False
and see what happens. Can you explain it? If not, look at Section 5.0.0.14 again.
Exercise 6-38
What does his expression reduce to? Do all the reduction steps in your head.
0 and 1 or 2
Exercise 6-39
What does his expression reduce to? Do all the reduction steps in your head.
4 and 1 or 2
Exercise 6-40
If you understood Section 6.0.0.37, then you should also understand this one:
= 'rain'
weather = weather == 'rain' and 'watch movies' or 'go swimming'
what_to_do print(what_to_do)
What happens if you change 'rain'
in the first line to something else (like 'sun'
)?
Exercise 6-41
What is the value of results
once the code below has run? Do the substitutions, reductions, and assignments in your head before you run the code.
= 7
x = 13
y = x + y
z = 0
x = x + y + z result
Exercise 6-42
What is the value of results
once the code below has run? Do the substitutions, reductions, and assignments in your head before you run the code.
= 5
x = x + 1
y = y + 1
x = x + 1
y = x + y result
Exercise 6-43
In the code below I have shuffled the statements. Put them in the right order to make the code print 9
. To do that you must think about which values each variable will in each statement depending on the how you order the statements.
= x + 1
x = 5
y = y - 1
y print(y)
= 1
x = y * x y
Exercise 6-44
In the code below, I have shuffled the statements. Put them in the right order to make the code print 'Mogens'
= b
c print(c)
= b + a
a = 'og'
b = c + a
b = 'M'
c = 'ens' a
Exercise 6-45
Make three exercises that require the knowledge of programming so far. Have your fellow students solve them.