import sandbox_widget, steps_widget, puzzle_widget15 Precedence
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.
The order of things
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\)
%%sandbox
2 / 4 * 2The following one first reduces to \(1 * 4\) and then to \(4\):
%%sandbox
2 / 2 * 4If you want Python to order the operations in any other way, you need to use parentheses (E.g., 2 / (2 * 4)).
Exercise 15-1
Look at each expression in the exercises below and use the table above to decide if it evaluates to True or False. Then, run the code and test if you were right. If not, figure out why.
%%sandbox
2 + 4 * 7 == 2 + (4 * 7) Exercise 15-2
Does this reduce to True or False?
%%sandbox
4 > 3 and 2 < 1 or 7 > 2Exercise 15-3
Does this reduce to True or False?
%%sandbox
4 > 3 and (2 < 1 or 7 > 2)Exercise 15-4
Does this reduce to True or False?
%%sandbox
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.
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 * 7is an expression, and so arey * 7 + 14 - xand4 > 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 15-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:
%%sandbox
x = 5
y = 20
z = (x + y) / 2 + 20
print(z * 2 + 1)
h = 2 * x - 9 * 48
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 15-6
Consider the following code:
%%sandbox
greeting = 'Hello' + ' my '
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:
x = 4
y = 3
z = x * y + 8Here, 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.
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 15-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.
%%steps
x = 7
y = 4 + x
2 + x * x**2 + y - xExercise 15-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.
%%steps
a = 4
b = a
c = 2
c = a + b + cExercise 15-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.
%%steps
x = 1
x = xExercise 15-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.
%%steps
microsatellite = "GTC" * 41Surprised?
Exercise 15-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.
%%steps
mini_gene = "ATG" + "GCG" + "TAA"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 15-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.
%%steps
number = 1 / 1 * 4In what order are reductions made? Does the order of operations matter, and in what order does Python do the reductions?
Exercise 15-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.
%%steps
x = 4
y = x + xExercise 15-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.
%%steps
x = 4
x = x + 1Exercise 15-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.
%%steps
x = 4
x += 1Compare the final value of x to that in Section 15.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. 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 15-16
Consider this code:
%%sandbox
1.2 * 3 + 4 / 5.2What does that expression evaluate to? Try to explicitly make all the reductions on paper before you run the code.
Exercise 15-17
Consider this code:
%%sandbox
1.2 * (3 + 4) / 5.2What does that expression evaluate to? Try to explicitly make all the reductions on paper before you run the code.
Exercise 15-18
Consider this code:
%%sandbox
10 % 3 - 2What does that expression evaluate to? Try to explicitly make all the reductions on paper before you run the code.
Exercise 15-19
Consider this code:
%%sandbox
11 % (7 - 5)**2What does that expression evaluate to? Try to explicitly make all the reductions on paper before you run the code.
Exercise 15-20
Consider this code:
%%sandbox
a = 5
x = 9
banana = 7
x + 4 * a > bananaWhat does the last expression evaluate to? Try to explicitly make all the substitutions and reductions on paper before running the code. What happens if you run the code? Why?
Exercise 15-21
Consider this code:
%%sandbox
dance = 'can'
dance = dance + dance
print("Do the", dance)What is printed? Try to explicitly make all the substitutions and reductions on paper before running the code. What happens if you run the code? Why?
Exercise 15-22
Consider this code:
%%sandbox
foo = 30
bar = 50
baz = bar + foo
print(baz)
bar = 10
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 15-23
Consider this code:
%%sandbox
1 == '1'and this:
%%sandbox
1 == 1.0What 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 15-24
Consider this code:
%%sandbox
a = '1'
b = '2'
c = a + b
print(a, b, c)
print(a + b == 3)What is printed here? Run the code and see for yourself once you think you know. If you were wrong, make sure you understand why.
Exercise 15-25
Consider this code:
%%sandbox
a = 1
b = 2
c = a + b
print(a, b, c)
print(a + b == 3)What is printed here? Compare to Section 15.0.0.24. Run the code and see for yourself once you think you know. If you were wrong, make sure you understand why.
Exercise 15-26
Consider this code:
%%sandbox
x = 4
print(x + 2 and 7)
print(x + 2 or 7)
x = -2
print(x + 2 and 7)
print(x + 2 or 7)What is printed here? Run the code and see for yourself once you think you know. If you were wrong, make sure you understand why.
Exercise 15-27
I have shuffled the statements in the code below. Put them in the right order to make the code print 100.
%%puzzle 100
x = x * x
x = x * 5
x
x = 4
x = x + 4Exercise 15-28
I have shuffled the statements in the code below. Put them in the right order to make the code print the string 'Banana'.
%%puzzle 'Banana'
y = (x + y) * 2
x
x = 'a'
x = 'B' + y + x
y = 'n'Exercise 15-29
Make a puzzle exercise, like the two previous ones, for a fellow student.
Exercise 15-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 15-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):
%%sandbox
result = x * y
result
x = 4
y = 2Now 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 15-32
In Section 15.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 15-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 15-34
What does this expression reduce to, and what type of value is it?
%%sandbox
3 > 2Exercise 15-35
What does this expression reduce to, and what type of value is it? Do all the reduction steps in your head.
%%sandbox
2 - 4 * 5 - 2 * 1/3Exercise 15-36
What does this expression reduce to, and what type of value is it? Do all the reduction steps in your head.
%%sandbox
3 > 2 and 2 - 4 * 5 - 2 * 9Exercise 15-37
What is printed here and why? Decide, then run it:
%%sandbox
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 13.0.0.14 again.
Exercise 15-38
What does this expression reduce to? Do all the reduction steps in your head.
%%sandbox
0 and 1 or 2Exercise 15-39
What does this expression reduce to? Do all the reduction steps in your head.
%%sandbox
4 and 1 or 2Exercise 15-40
If you understood Section 15.0.0.37, then you should also understand this one. Run it:
%%sandbox
weather = 'rain'
what_to_do = weather == 'rain' and 'watch movies' or 'go swimming'
print(what_to_do)What happens if you change 'rain' in the first line to something else (like 'sun')?
Exercise 15-41
What is the value of result once the code below has run? Do the substitutions, reductions, and assignments in your head before you run the code.
%%sandbox
x = 7
y = 13
z = x + y
x = 0
result = x + y + zExercise 15-42
What is the value of result once the code below has run? Do the substitutions, reductions, and assignments in your head before you run the code.
%%sandbox
x = 5
y = x + 1
x = y + 1
y = x + 1
result = x + yExercise 15-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.
%%puzzle 9
y
y = 5
y = y - 1
x = x + 1
y = y * x
x = 1Exercise 15-44
In the code below, I have shuffled the statements. Put them in the right order to make the code print 'Mogens'
%%puzzle 'Mogens'
a = b + a
b = c + a
a = 'ens'
c
c = 'M'
c = b
b = 'og'Exercise 15-45
Make three exercises that require the knowledge of programming so far. Have your fellow students solve them.
Fitting it all in there
With all the stuff you need to learn and remember, it is worth considering how to best go about it. The two Youtube videos below describe how retrieval rather than re-reading is often the best way to remember what you learn.