Values, types and expressions
Evaluate a Python arithmetic expression, including //, % and **, and say its value and its type.
It opens on
The third line on the board adds "7" and "2", both in quotes. Will Python show 9, 72 or an error?
Why it matters
Every program, from a payroll to a game, is built from expressions, and a wrong operator, a wrong order or a wrong type gives a wrong answer with no warning, so reading an expression exactly as Python does is the first skill of programming.
Good to know first
- High-school algebra: arithmetic with whole numbers and decimals, powers such as 2³, and the order of operations, multiplication before addition, brackets first
Step by step
Values and their types
Say the value and the type, int, float, str or bool, of a line typed in the Python shell.
Each line is an expression, a piece of code that Python evaluates to a single value. The first one, 7 + 2, has the value 9.
A common mix-up
Digits in quotes are still numbers, so "7" + "2" is 9.
In fact: Quotes make a str, and plus on two strings joins them, giving '72'.
Whole division, remainder and power
Use //, % and ** to split a number of minutes into whole hours and minutes left, and to raise a number to a power.
Plain division, 135 / 60, gives 2.25, a float. That is right as a number of hours, but it is not 2 hours and some minutes.
A common mix-up
The percent sign gives a percentage, so 135 % 60 is some percent of 135.
In fact: It gives the remainder after // , the 15 minutes left over.
Which operator goes first
Evaluate an expression with several operators by the order Python follows, writing each step.
In 2 + 3 * 4, Python does 3 * 4 first, which is 12, and then 2 + 12 is 14; with brackets, (2 + 3) * 4 does 2 + 3 first, which is 5, and 5 * 4 is 20.
A common mix-up
Python reads left to right, so 2 + 3 * 4 is 20 and 2 ** 3 ** 2 is 64.
In fact: Multiplication comes before addition, and the power goes right to left, giving 14 and 512.
The type of a result
Say the value and the type of an expression that mixes int and float, and say when Python gives a TypeError.
So 7 + 2.0 is 9.0, a float, even though the value is a whole number, and 2 ** 3 is the int 8; the one exception is a power with a negative exponent, as 2 ** -1 is 0.5.
three lines with their results
A common mix-up
Equal numbers have equal types, so 135 / 60 * 60 is the int 135.
In fact: a slash gives a float, so the result is 135.0, a float.
Try it
What are the value and the type of "4" + "5", and of 4 + 5?Answer
'45', a str; and 9, an int
Hint: Quotes make text, and plus joins text
A video is 1000 seconds long. What are 1000 // 60 and 1000 % 60, as whole minutes and seconds left?Answer
16 and 40
Hint: 16 times 60 is 960
What does 8 // 3 * 3 + 8 % 3 give?Answer
8
Hint: 8 // 3 is 2, 2 * 3 is 6, 8 % 3 is 2
What are the value and the type of 5 * 2.0 + 1?Answer
11.0, a float
Hint: 5 * 2.0 is 10.0
By that rule, what does 6 / 3 give?Answer
2.0, a float, because the slash always gives a float.
