Calculating with numbers

Lesson 7 of 54 · Python Foundations

An expression combines values and operations to produce a result. Operators include + for addition, - for subtraction, * for multiplication, and / for division. A minus sign can make a number negative.

morning = 14
change = -3
evening = morning + change
average = (morning + evening) / 2
print(evening)
print(average)
11
12.5

The change reduces 14 to 11. Parentheses group the readings before division; without them, division takes priority over addition. Multiplication and division are evaluated before addition and subtraction. In Python 3, / returns a float even when the result is whole: 8 / 2 produces 4.0. Dividing by zero raises ZeroDivisionError.

A decimal fraction can represent a proportion: 80 * 0.25 produces 20.0, one quarter of 80. Floating-point numbers approximate many decimal fractions; 0.1 + 0.2 may not display the exact decimal expected. For money, a decimal-specific representation may be appropriate.

Chapter index