Programs and expressions 0/5

Lesson 5 of 21

Operators

Comparisons, integer division, modulo, rounding up and pulling digits out of a number.

Part 1 of 8 Arithmetic

Operators and operands

Since your first program you have been writing + and * between numbers. These symbols are called operators, and the values an operator works on are its operands: in hours * rate, the operator is * and its operands are hours and rate. This lesson goes through the operators you will use in almost every program, from arithmetic to comparisons that answer true or false.

Most of them work the way they do in school arithmetic. The two that need the most attention are // and %, which split a whole-number division into how many times one number fits into another and what is left over. Here is a job that needs both. A contest starts at 21:00, and a program has to print the time 63 minutes later. 63 minutes is one hour and 3 minutes, so the answer is 22:03, and the program gets the 1 with 63 // 60 and the 3 with 63 % 60.

When a line has several operators, as 2 + 3 * 4 does, a rule decides which one is worked out first. The last part of the lesson gives those rules.

Definition

An operator is a symbol such as + or % written between or before its operands, the values it works on. Like a function call, an expression built with operators has a value.

Arithmetic operators

/ divides and gives a float, and // divides and rounds down. This program applies them and the other arithmetic operators to 17 and 5:

Sign up to run
a = 17
b = 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** 2)
Python details

/ always gives a float, even when the division is exact: 10 / 5 is 2.0. // divides and rounds down to a whole number. ** raises a number to a power.

Each arithmetic operator also has an assignment form. x //= 5 is short for x = x // 5, so with x = 17 it leaves 3 in x; +=, -=, *= and %= work the same way.

Arithmetic in each language, with a = 17 and b = 5
OperationPythonC++Value
adda + ba + b22
subtracta - ba - b12
multiplya * ba * b85
divide, keeping the fractiona / ba / 5.0 (a double operand)3.4
integer quotienta // ba / b (both int)3
remaindera % ba % b2
squarea ** 2a * a289