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:
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.
| Operation | Python | C++ | Value |
|---|---|---|---|
| add | a + b | a + b | 22 |
| subtract | a - b | a - b | 12 |
| multiply | a * b | a * b | 85 |
| divide, keeping the fraction | a / b | a / 5.0 (a double operand) | 3.4 |
| integer quotient | a // b | a / b (both int) | 3 |
| remainder | a % b | a % b | 2 |
| square | a ** 2 | a * a | 289 |
Integer division and remainder
Dividing 17 by 5 in whole numbers gives two answers. The quotient 3 counts how many whole fives fit into 17, and the remainder 2 is what is left over. // gives the quotient and % gives the remainder. The two always satisfy one equation, where is the number divided, the number it is divided by, the quotient and the remainder:
For positive numbers the remainder is at least 0 and less than . Dividing by 5 leaves 0, 1, 2, 3 or 4, never 5, since then another five would fit. The remainder also answers questions that are not about division. n % 2 is 0 exactly when is even. n % 10 is the last digit of , and n // 10 is without it: 1234 % 10 is 4 and 1234 // 10 is 123. When you need both numbers, divmod(17, 5) returns them together as (3, 2).
A division by 0 has no quotient, since no number of zeros adds up to 17. Python stops the program with ZeroDivisionError for /, // and % alike.
Turning minutes into hours and minutes
The contest clock from the start of this lesson is a quotient and a remainder: the full hours in K minutes, and the minutes left over.
A contest starts at 21:00. Given an integer K, print the time K minutes after 21:00 as HH:MM on the 24-hour clock, writing both the hour and the minute with two digits.
Constraints
- K is an integer.
Sample 1 · Input
63
Output
22:03
Sample 2 · Input
45
Output
21:45
Sample 3 · Input
100
Output
22:40
In the first sample, 63 minutes is one full hour and 3 minutes more, so the time is 22:03:
The output has one more requirement: 3 minutes prints as 03, padded with a zero to two digits.
k = int(input())
hour = 21 + k // 60
minute = k % 60
print(f"{hour:02d}:{minute:02d}")Python details
An f-string, written with f before the opening quote, prints its text with each {…} replaced by a value. {minute:02d} prints minute as a whole number (d) at least 2 characters wide, and 0 fills the gap with zeros.
In the second sample, 45 minutes is less than an hour, so the quotient is 0 and the time stays in hour 21. The program never asks whether K has passed an hour: the quotient is 0 when it has not and 1 when it has, so the same two lines handle every K from 0 to 100.
Dividing negative numbers
So far every division has used positive numbers. With a negative number, the exact answer often falls between two integers, and Python and C++ pick different ones. Take −17 divided by 5. The exact answer is −3.4, so the integer answer has to be −4 or −3. Python's // rounds down, to −4. C++'s / drops the fraction, which rounds toward zero, and gives −3. Python's int() also drops the fraction, so int(-17 / 5) is −3.
print(-17 // 5)
print(int(-17 / 5))
print(-17 % 5)
print((1 - 3) % 24)
print(-3 % 2)The remainder changes along with the quotient. In both languages, % gives the r that makes −17 = 5 × q + r true for that language's quotient q. Python's quotient is −4, so its remainder is 3. C++'s quotient is −3, so its remainder is −2. As a result, a Python remainder by a positive number is never negative, while a nonzero C++ remainder has the same sign as the number being divided.
You'll notice the sign of the remainder when you use % to keep a number inside a range, as with hours on a clock. Three hours before 1:00 on a 24-hour clock should be 22:00. Python's (1 - 3) % 24 gives 22. C++ gives −2 for the same expression, so C++ code adds the modulus back: ((1 - 3) % 24 + 24) % 24 is 22.
The same sign rule affects a test you'll write often: checking whether a number is odd. In Python, -3 % 2 is 1, so x % 2 == 1 works. In C++, -3 % 2 is −1, so the same test says −3 is not odd. Writing x % 2 != 0 works for negative numbers in both languages.
Step through a division
The program computes a quotient and a remainder, then prints them with b * q + r, which gives back a. The four inputs are an ordinary division, an exact one, a number smaller than the divisor and a negative number.
With , the division is exact and the remainder is 0, which is how a program tests whether one number divides another. With , no five fits into 3, so the quotient is 0 and the remainder is 3 itself.
Only gives a different answer in C++: −3 and −2 instead of −4 and 3. The other three exact quotients are positive, and for a positive number rounding down and rounding toward zero give the same integer.
Integer division that rounds up
Integer division of positive numbers rounds down, and some problems need the quotient rounded up. Theatre Square divided a side length by the stone size and needed the result rounded up, and its program got it by adding the stone size minus 1 before dividing. With quotient and remainder you can now see why that works.
Divide by , so that with the remainder between 0 and . If is 0, the division is exact and the answer rounded up is itself. If is more than 0, part of another is needed, and the answer rounded up is . Adding to gives
When , the extra is less than , so no further fits and the quotient stays . When is at least 1, is at least and less than , so exactly one more fits and the quotient becomes . Here it is with for , which leaves a remainder of 1, and for , which 3 divides exactly. The brackets mean rounded down, which is what integer division does:
This problem is practice for that step, on numbers up to :
An enemy has stamina A, and each attack lowers it by B. Print the smallest number of attacks that brings its stamina to 0 or below.
Constraints
- A and B are integers.
Sample 1 · Input
7 3
Output
3
Sample 2 · Input
123456789123456789 987654321
Output
124999999
Sample 3 · Input
999999999999999998 2
Output
499999999999999999
In the first sample the stamina is 7 and each attack removes 3. Two attacks bring it to 1, which is above 0, and a third brings it to , so the answer is 3. In general the answer is the smallest with , which is rounded up, so the program prints (a + b - 1) // b.
a, b = map(int, input().split())
print((a + b - 1) // b)Python details
Python integers grow as large as memory allows, so a + b - 1 is exact even near .
The listing's input is the third sample. Dividing with / and rounding up with math.ceil looks simpler, but for this sample it prints 500000000000000000, one more than the answer. The Deeper read below shows where the extra 1 comes from.
Deeper read: why float division loses large integers
Python's / always produces a float, and a float stores every whole number exactly only up to :
Past that, the stored values have gaps between them, and the gaps grow with the size of the number. / on two integers returns the stored value nearest the exact quotient. Here the exact quotient 499,999,999,999,999,999 lies between and , where stored values are apart, so / returns the nearest one, , and math.ceil leaves it there.
Integer division never passes through a float, so // stays exact at any size.
Comparison and boolean operators
Every operator so far has produced a number. A comparison operator produces a boolean instead: 7 > 5 asks whether 7 is greater than 5, and its value is true; 7 == 4 asks whether 7 equals 4, and its value is false. == asks whether two values are equal, which is a different operation from the single = that gives a name a value.
Boolean operators combine booleans. and is true when both sides are true, or is true when at least one side is, and not turns true into false and false into true. The program checks whether one of 1, 4 and 3 is the sum of the other two, then compares two floats:
a = 1
b = 4
c = 3
print(a < b)
print(a == b + c)
print(a == b + c or b == a + c or c == a + b)
print(not a == 1)
print(0.1 + 0.2 == 0.3)
print(abs((0.1 + 0.2) - 0.3) < 1e-9)Python details
and, or and not are written as words, and booleans print as True and False.
In the third line, a == b + c is false, since , but b == a + c is true, since , and one true side is enough for or.
The last two lines compare floats. 0.1 + 0.2 is stored as 0.30000000000000004, a different float from the one stored for 0.3, so == gives false. When two floats should be equal, ask whether they are close: whether the distance between them, abs(x - y), is below a small tolerance such as , written 1e-9.
Precedence and associativity
2 + 3 * 4 from the first part is 14, not 20, because multiplication comes before addition, as in school arithmetic. Each operator has a precedence, its rank in the table below, and higher-ranked operators are worked out first. Parentheses override the ranks: (2 + 3) * 4 is 20.
Operators of equal rank are worked out from left to right, so 20 - 6 - 4 is 14 - 4, which is 10. The rule for equal ranks is called associativity.
| Rank | Python | C++ |
|---|---|---|
| 1 | ( … ) | ( … ) |
| 2 | ** | no power operator |
| 3 | -x | -x, !x |
| 4 | *, /, //, % | *, /, % |
| 5 | +, - | +, - |
| 6 | <<, >> (bit shifts) | <<, >> (bit shifts, and cout <<) |
| 7 | <, <=, >, >=, ==, != | <, <=, >, >=, then ==, != |
| 8 | not | (! is at rank 3) |
| 9 | and | && |
| 10 | or | || |
not ranks below the comparisons, so not a == 1 means not (a == 1), and and ranks above or, so a or b and c means a or (b and c).
Deeper read: writing a power
** is the one operator in the table that works from right to left. 2 ** 3 ** 2 is 2 ** 9, which is 512, not 8 ** 2, which is 64. Powers stack this way in mathematics too: means .
** also ranks above the minus sign in front of a number, so -2 ** 2 is -(2 ** 2), which is -4. To square , write (-2) ** 2, which is 4.
Step through an expression
The diagram evaluates one expression an operator at a time and binds x once a single value is left. Python always works out the left operand of an operator before the right one.
In the last preset, 5 > 9 is false, so and is false whatever its right side is, and 7 % 2 == 1 is never worked out. This is called short-circuit evaluation, and or does the same when its left side is true.
Common mistakes
Using
/when the answer must be a whole number (Python).- Where it breaks
- For K = 63,
21 + k / 60is the float 22.05, and{hour:02d}stops the program withValueError, becausedformats only integers. - The fix
- Use
//for the quotient and%for the remainder.
Writing
^for a power.- Where it breaks
2 ^ 3is 1 in both languages, not 8:^combines the two numbers bit by bit (exclusive or), an operation for a later lesson.- The fix
- Write
2 ** 3in Python. In C++, multiply:a * a * a.
Chaining comparisons (C++).
- Where it breaks
- With x = 20,
1 < x < 10is true in C++:1 < 20is true, which counts as 1, and1 < 10is true. Python reads the same text as1 < x and x < 10and givesFalse. - The fix
- In C++, write
1 < x && x < 10.
Recall What are the quotient and remainder of $-7$ divided by 2 in Python, and in C++?
In Python, -7 // 2 is -4 and -7 % 2 is 1, since . In C++, -7 / 2 is -3 and -7 % 2 is -1, since . Python rounds the quotient down; C++ rounds it toward zero.
Recall What is `10 - 2 * 3 + 1`, and in what order are its operators worked out?
5. * ranks above - and +, so 2 * 3 goes first and gives 10 - 6 + 1. - and + share a rank, so they go from left to right: 10 - 6 is 4, and 4 + 1 is 5.
Key terms
| Term | Meaning |
|---|---|
| operator | A symbol that combines values into a new value: +, %, ==, and. |
| operand | A value an operator works on: hours and rate in hours * rate. |
| quotient | How many whole times fits into : 3 for 17 and 5. |
| remainder | What is left after taking out the quotient: 2 for 17 and 5. |
| rounding down | Python's rule for //: becomes . |
| rounding toward zero | C++'s rule for / on integers, also called truncation: becomes . |
| comparison operator | An operator that compares two values and gives a boolean: <, ==, !=. |
| boolean operator | An operator that combines booleans: and, or, not in Python, &&, ||, ! in C++. |
| precedence | An operator's rank, which decides what is worked out first. |
| associativity | The direction binary operators of equal rank are worked out: left to right, except Python's **, which goes right to left. |
| short-circuit evaluation | and and or skipping their right side once the left side decides the result. |
