Expressions, values and types
An expression is a piece of code that Python can work out to get a value. 2 + 3 is an expression, and its value is 5. Working out the value is called evaluating the expression. A single number or a variable on its own is an expression too: the value of score is whatever the variable holds at that moment.
An expression can go anywhere Python expects a value: on the right side of =, inside the parentheses of print, inside the braces of an f-string, or as the condition of an if. That's the difference from a statement: a statement does something, and an expression has a value. total = 5 is a statement, while total + 5 is an expression.
Python's interactive interpreter shows this well. It runs one line at a time, and when you type an expression after its >>> prompt, it shows the expression's value. Here is what it prints for a few expressions:
>>> 7 + 8 * 2
23
>>> 9 / 4
2.25
>>> "rain" + "bow"
'rainbow'
>>> 20 - 6 < 10
FalseThe interpreter shows a string in quotes, so you can see that 'rainbow' is text. The last expression is a comparison, and its value is False.
Step by step
Small expressions combine into bigger ones, and Python evaluates a big one piece by piece, each time putting a value in place of a part. With price = 4 and count = 3, the condition price * count + 5 > 20 goes like this:
price * count + 5 > 20
4 * 3 + 5 > 20
12 + 5 > 20
17 > 20
False
Multiplication comes before addition, as in mathematics, and the comparison comes after the arithmetic.
Every expression has a type
Since an expression has a value, it also has a type: its data type. You met the function type in part 1. Give it any expression, and it tells the type of the expression's value:
print(type(42))
print(type(3.5 * 2))
print(type("4" + "2"))
print(type(42 > 7))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>These are the four types you know: int for whole numbers, float for numbers with a decimal point, str for strings and bool for the truth values True and False. A comparison is an expression of the type bool, which is why it can be the condition of an if, or be printed:
price = 4
count = 3
total = price * count + 5
print(f"Total: {total}, over 20: {total > 20}")
Total: 17, over 20: False