Menu

Arithmetic Operators

Arithmetic Expressions

An arithmetic expression is a combination of values, variables, constants and operators that works out a result. The result can be stored in a variable using assignment (=) or displayed with print().

For example, if score = 18 and bonus = 4, then score + bonus is an expression. Its result, 22, can be assigned with total = score + bonus or displayed directly.

Arithmetic operators work on whole numbers, real numbers, variables and constants. A constant is a named value that stays the same, such as ITEM_PRICE = 2.5, and it can be used in an expression just like a variable. Several operators can appear in one expression, for example number_of_items * ITEM_PRICE.

Whole numbers and real numbers

An expression that uses only integers produces an integer result, unless it uses division with /. In Python 3, / always produces a real number, even when both values are whole numbers, so 20 / 4 gives 5.0, not 5.

If an expression mixes an integer and a real number, the result is a real number. The integer is treated as a real value for that calculation. For example, 7 + 2.5 gives 9.5, because 7 is treated as 7.0 during the addition.

ExpressionTypes involvedResult
9 + 5two integers14 (integer)
9 + 5.0integer and real14.0 (real)
12 / 3two integers, / used4.0 (real)
12 + 0.5integer and real12.5 (real)

Expressions in a program

This program stores two values, combines them in an expression and displays the result. The expression weekday_hours + weekend_hours mixes an integer and a real number, so the output is real.

weekday_hours = 3
weekend_hours = 2.5
total_hours = weekday_hours + weekend_hours
print(total_hours)
print(weekday_hours * 2)

Output:

5.5
6

The second expression, weekday_hours * 2, uses only integers, so its result is an integer.

Practise this