You've been writing calculations since Chapter 1: 2 * 15 + 3 * 12, celsius * 9 / 5 + 32. This chapter looks at the machinery behind them. By the end you'll know every arithmetic operator, exactly how Python decides what to calculate first, and some tricks with // and % that solve a surprising number of real problems.
4.1 Expressions
An expression is any piece of code that Python can work out to get a value. Here are some:
42 a literal
price a variable
price * 3 an operator with two operands
(price * 3) + delivery expressions built from smaller expressions
type(price) a function call
In price * 3, the * is an operator: a symbol that performs an operation. price and 3 are its operands: the values it works on. Working out an expression to get its value is called evaluating it.
Most operators are binary: they take two operands, one on each side (a + b). A few are unary: they take one operand (-a). Operators combine into bigger expressions, and every expression, however big, ends up as a single value with a single type.
An expression is different from a statement. A statement is a complete instruction, like total = price * 3 (an assignment) or del total. An expression produces a value; a statement does something. The shell shows this nicely: type an expression and it shows the value; type a statement and it shows nothing.
>>> 6*7
42
>>> answer=6*7>>> answer
42
Output
Practice 4.1
Multiple choice
In the Python shell you type the statement total = 6 * 7 and press Enter. What does the shell show?
An expression produces a value. A statement does something.
An assignment is a statement. Does a statement produce a value for the shell to show?
The answer is: It shows nothing
An assignment is a statement, so the shell has no value to show. Typing the expression total on the next line would show the value.
4.2 Arithmetic operators
Python has seven arithmetic operators, plus unary minus and plus:
Operator
Name
Example
Result
+
addition
17 + 5
22
-
subtraction
17 - 5
12
*
multiplication
17 * 5
85
/
division
17 / 5
3.4
//
floor division
17 // 5
3
%
remainder (modulo)
17 % 5
2
**
power (exponent)
17 ** 5
1419857
-x
negation
-17
-17
+x
unary plus
+17
17
a=17b=5print(a+b,a-b,a*b,a/b)print(a//b,a%b,a**b)
Output
22 12 85 3.4
3 2 1419857
The first four you know from school. The other three need a closer look.
4 fits into 19 four whole times. How much is left over after that?
It prints
23 76
4.75
4 3
/ gives the exact float, // gives the whole number of times 4 fits into 19, and % gives what is left over.
Fill in the blank
Fill in the operator so that the line prints 3 to the power 4.
print(3 4)
The finished program prints:
Target
81
Look at the table of the seven arithmetic operators.
The power operator is written with two symbols that are the same.
print(3**4)
** is the power operator. 3 ** 4 is 3 multiplied by itself 4 times.
4.3 Two kinds of division
Python has two division operators, because "17 divided by 5" can mean two different things.
True division, /, gives the exact answer as a float: 17 / 5 is 3.4. It always gives a float, even when the answer is whole (10 / 5 is 2.0).
Floor division, //, divides and then rounds down to a whole number: 17 // 5 is 3. Think of it as "how many whole times does 5 fit into 17?" If 17 students are put into teams of 5, you get 3 full teams.
print(17/5)print(17//5)print(20//5)print(4//5)
Output
3.4
3
4
0
The type of a // result follows the usual mixing rule: two ints give an int, and if either operand is a float, the result is a float, though still rounded down to a whole value:
print(7//2)print(7.0//2)print(7.5//2)
Output
3
3.0
3.0
"Down" means towards minus infinity
Floor means "round down to the next whole number below". For positive numbers that's the same as chopping off the decimal part. For negative numbers it isn't:
print(7//2)print(-7//2)
Output
3
-4
7 / 2 is 3.5; the whole number below it is 3. -7 / 2 is -3.5; the whole number below it is -4, not -3. On a number line, "down" always means "to the left":
Some other languages (C, Java) chop towards zero instead and would give -3. Python's choice keeps a very useful rule true, as you'll see next.
Practice 4.3
Predict the output
What does it print?
print(9//2,-9//2)print(9.0//2)print(3//8)
// rounds down. On a number line, down always means to the left.
If one operand is a float, the result is a float. How many whole times does 8 fit into 3?
It prints
4 -5
4.0
0
Floor division rounds towards minus infinity, so the negative result moves away from zero. A float operand gives a float result.
Fix the bug
A coach puts 23 players into teams of 5. This program should print the number of full teams as a whole number. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
Full teams: 4
Output
/ gives the exact result as a float. A number of teams is a whole number.
Which division operator rounds down to a whole number?
players=23print("Full teams:",players//5)
// answers the question: how many whole times does 5 fit into 23? Two ints with // give an int.
4.4 The remainder operator: %
% gives the remainder after floor division. 17 % 5 is 2, because 5 goes into 17 three times (making 15), with 2 left over. In programming, the remainder operation is usually called modulo or mod, so 17 % 5 is read "17 mod 5".
print(17%5)print(20%5)print(3%5)
Output
2
0
3
20 % 5 is 0 because 5 divides 20 exactly. 3 % 5 is 3 because 5 goes into 3 zero times, leaving all 3.
// and % are partners. For any numbers a and b (with b not zero), this is always true:
a == (a // b) * b + (a % b)
"Quotient times divisor, plus remainder, gives back the original number." For 17 and 5: 3 × 5 + 2 = 17. Python even has a built-in that gives you both at once:
print(divmod(17,5))print(17//5*5+17%5)
Output
(3, 2)
17
divmod gives back a pair of values in brackets, called a tuple→ Chapter 30. You can unpack the pair straight into two variables, just like in Chapter 3: teams, left_over = divmod(17, 5).
Remainders with negative numbers
Because // rounds towards minus infinity, % has to adjust to keep the rule true. The result is that the remainder always has the same sign as the divisor (the number on the right):
print(-17//5,-17%5)print(17//-5,17%-5)
Output
-4 3
-4 -3
Check the rule for the first line: (−4) × 5 + 3 = −17. ✓
This is actually what you want most of the time. When the divisor is positive, n % 5 is always between 0 and 4, whatever n is. That makes % perfect for anything that wraps around, like a clock.
What % is good for
% looks like a minor operator, but it solves a whole family of problems:
Even or odd. A number is even when it divides by 2 with nothing left over:
print(14%2)print(15%2)
Output
0
1
Divisibility. In general, n % d is 0 exactly when d divides n. A year divisible by 4 gives year % 4 equal to 0.
Picking out digits.% 10 gives the last digit; // 10 removes it:
n=472print(n%10)# last digitprint(n//10)# everything except the last digitprint(n//10%10)# the middle digitprint(n//100)# the first digit
Output
2
47
7
4
Wrapping around. A 24-hour clock wraps from 23 back to 0. What time is it 5 hours after 22:00?
now=22later=(now+5)%24print(later)
Output
3
Splitting into units. How many hours, minutes and seconds are in 4000 seconds?
// 3600 counts the whole hours. % 3600 is what's left after removing them (400 seconds), and // 60 turns that into whole minutes. % 60 is the leftover seconds.
Dividing by zero
All three division operators refuse to divide by zero:
print(10%0)
Output
Traceback (most recent call last):
File "operators.py", line 1, in <module>
print(10 % 0)
~~~^~~
ZeroDivisionError: division by zero
The same ZeroDivisionError comes from 10 / 0 and 10 // 0, with ints or floats.
Practice 4.4
Fill in the blank
A teacher shares 50 pencils equally among 8 children. Fill in the operator that gives the number of pencils left over.
pencils=50print("Left over:",pencils 8)
The finished program prints:
Target
Left over: 2
Each child gets 50 // 8 pencils. You need the other half of that pair of operators.
The remainder operator is one symbol. It is also called modulo.
pencils=50print("Left over:",pencils%8)
% gives the remainder after floor division. 8 fits into 50 six times, which uses 48 pencils.
Put the lines in order
Put the lines in order. The program prints the middle digit of 472 first, then its last digit.
The program in the right order prints:
Target
7 2
number=number//10
last=number%10
number=472
print(middle,last)
middle=number%10
% 10 gives the last digit of the number as it is at that moment.
Take the last digit first. Then remove it with // 10, so that the middle digit becomes the last one.
A negative power means "one over": 10 ** -2 is 1/10² = 0.01. A fractional power is a root: ** 0.5 is the square root, ** (1/3) the cube root. Any number to the power 0 is 1.
Powers go right to left
Most operators work left to right: 10 - 4 - 3 is (10 - 4) - 3. ** is the exception. It works right to left:
print(2**3**2)print((2**3)**2)
Output
512
64
2 ** 3 ** 2 means 2 ** (3 ** 2), which is 2 ** 9, which is 512. This matches maths too, where 2³² means 2 to the 9th, not 8².
Big powers
Because integers have no size limit, you can raise them to huge powers exactly. 2 ** 10000 has 3011 digits, and Python calculates it instantly. There's one surprising limit, though: Python refuses to display an integer with more than 4300 digits:
print(2**20000)
Output
Traceback (most recent call last):
File "operators.py", line 1, in <module>
print(2 ** 20000)
~~~~~^^^^^^^^^^^^
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
The calculation itself worked. Only turning the 6021-digit result into text was refused. This limit protects programs, such as websites, from attackers who send gigantic numbers that take a long time to convert. As the message says, you can raise the limit if you really need to.
** is done before the minus sign on its left, and a chain of ** works from right to left.
A negative power means one over. The power 0.5 is the square root, and the result is a float.
It prints
-4
512
0.1
4.0
-2 ** 2 means -(2 ** 2), and 2 ** 3 ** 2 means 2 ** (3 ** 2). A negative or fractional power gives a float.
Fix the bug
This should print the square root of 81. It prints a different number. Fix it.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
9.0
Output
Which is done first on this line: ** or /?
The power must be one half. Put brackets around the fraction, or write the half as a decimal number.
print(81**(1/2))
** is higher than /, so the starting line works out 81 ** 1 and then divides by 2. Brackets make the power one half.
4.6 The type of an expression
Every expression has a type, decided by the operator and the types of its operands. Chapter 2 gave the mixing rule; here it is again with all the operators:
At school you learned to round halves up, so 2.5 → 3. Python instead rounds a value that's exactly halfway to the nearest even number: 0.5 → 0, 2.5 → 2, but 1.5 → 2 and 3.5 → 4. This is called banker's rounding. When you round thousands of numbers, always rounding halves up pushes the total upwards; rounding to even sends half of them up and half down, so the errors cancel out. It's the standard rule in science and finance.
Surprise 2: floats aren't what they look like.
print(round(2.675,2))
Output
2.67
You'd expect 2.68. But as you learned in Chapter 2, the float written 2.675 is stored as a binary number very slightly less than 2.675, so it isn't really halfway, and it rounds down. When exact decimal rounding matters, as with money, use the decimal module → Chapter 17.
round with a negative number of places rounds to tens, hundreds and so on: round(1234, -2) is 1200.
divmod needs the starting number of eggs. Only then can the program work out how many eggs the full boxes hold.
Write code
Warm and cold. Three temperatures were measured: -4, 9 and 3 degrees. The starting code stores them. Print three lines: first the highest temperature, then the lowest, then the difference between the highest and the lowest.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Highest: 9
Lowest: -4
Difference: 13
Output
max and min take as many arguments as you like.
Store the two results in variables. The difference is the highest minus the lowest.
max and min pick the largest and the smallest argument. Subtracting a negative number makes the difference larger than the highest value.
4.8 Assignment operators
You met the augmented assignment operators in Chapter 3. Here they are again, now that you know every arithmetic operator:
Operator
Example
Same as
=
x = 5
+=
x += 5
x = x + 5
-=
x -= 5
x = x - 5
*=
x *= 5
x = x * 5
/=
x /= 5
x = x / 5
//=
x //= 5
x = x // 5
%=
x %= 5
x = x % 5
**=
x **= 5
x = x ** 5
There are also &=, |=, ^=, <<= and >>= for the bitwise operators in the next section, and @= for matrix multiplication (used by libraries like NumPy).
The right side is always worked out completely first. So x *= 2 + 3 means x = x * (2 + 3), not x = x * 2 + 3:
x=10x*=2+3print(x)
Output
50
The walrus operator: :=
Normal assignment is a statement: it does something but doesn't produce a value. Python also has an assignment expression, written :=, which assigns and gives back the value, so you can use it in the middle of a bigger expression. It's nicknamed the walrus operator, because := looks like a walrus's eyes and tusks.
print(total:=40+2)print(total)
Output
42
42
The first line works out 40 + 2, assigns it to total, and passes the same value on to print. The walrus is really useful in loops and conditions, which you'll see in → Chapter 13. For ordinary assignments, always use plain =. Python won't even let you write x := 5 on a line by itself; it has to be inside something else, such as brackets.
Practice 4.8
Predict the output
What does it print?
x=20x-=2+3print(x)x//=4x*=xprint(x)
The right side is worked out completely first. So the second line subtracts 5.
x //= 4 means x = x // 4. On the line after it, x *= x multiplies the new value by itself.
It prints
15
9
An augmented assignment works out its whole right side first, then uses the old value of the variable with the operator.
Put the lines in order
Put the lines in order so that the program prints the target number.
The program in the right order prints:
Target
26
score+=5
score-=4
print(score)
score*=2
score=10
The variable must be created first, and print goes last.
Try the three middle lines in different orders in your head. Doubling after the bonus gives more than doubling before it.
score=10score+=5score*=2score-=4print(score)
Each line changes the value left by the line before, so the order matters: 10, then 15, then 30, then 26.
4.9 Bitwise operators
This section is a little more technical. You won't need bitwise operators often in everyday programs, but they appear in low-level code, graphics, networking and puzzles, and they're part of the precedence table in section 4.10, so it's worth understanding them.
Integers in binary
Every integer is stored in binary: a string of bits (binary digits), each 0 or 1. In decimal, each place is worth ten times the place to its right (1, 10, 100, ...). In binary, each place is worth twice the place to its right (1, 2, 4, 8, 16, ...):
Shifts multiply and divide by powers of two. Moving every bit one place left doubles the number, just as adding a 0 on the right in decimal multiplies by ten. So x << n is x * 2 ** n, and x >> n is x // 2 ** n.
~x is always -x - 1. Python integers behave as if they had an endless row of sign bits on the left, using a system called two's complement. Flipping all the bits of 12 gives −13. You don't need the details now; just remember the rule ~x == -x - 1.
A few things people do with bitwise operators:
n & 1 is 1 for odd numbers and 0 for even ones (it looks at the last bit).
1 << n is 2 to the power n, very quickly.
Several on/off settings can be packed into one integer, one bit each (these are called flags), and combined with |.
Practice 4.9
Multiple choice
What does this line print?
print(5<<2)
<< moves the bits to the left. Each place to the left doubles the number.
x << n is the same as x * 2 ** n.
The answer is: 20
A left shift by 2 places doubles the number two times, so it multiplies by 4.
Fill in the blank
In binary, 12 is 1100 and 10 is 1010. Fill in the bitwise operator that keeps only the bits that are 1 in both numbers.
print(1210)
The finished program prints:
Target
8
Three operators compare the bits place by place: AND, OR and XOR.
You need AND: a result bit is 1 only when both bits are 1.
print(12&10)
& is bitwise AND. Only the place worth 8 has a 1 in both numbers, so the result is 1000 in binary.
Predict the output
What does it print?
print(bin(5))print(6|3,6&3)print(~7,1<<4)
bin() shows the bits with the prefix 0b. In binary, 6 is 110 and 3 is 011.
~x is always -x - 1. 1 << n is 2 to the power n.
It prints
0b101
7 2
-8 16
OR keeps a bit that is 1 in at least one number, AND keeps a bit that is 1 in both, ~x is -x - 1, and a left shift doubles.
4.10 Precedence: what's done first
What is 2 + 3 * 4? Python follows the same rule as school maths: multiplication before addition, so 3 * 4 first, giving 14. Every operator has a precedence (priority) level, and higher-precedence operators are done first. Brackets override everything:
print(2+3*4)print((2+3)*4)
Output
14
20
Here is Python's complete precedence table, from the highest (done first) to the lowest (done last). Operators on the same row have the same precedence. Several of these you haven't met yet; they're included so you have one complete table to come back to.
Precedence
Operators
Meaning
1 (highest)
(...), [...], {...}
brackets, and building lists, dicts and sets → Chapter 25
A few combinations catch even experienced programmers:
print(1<<2+1)# + is higher than <<, so this is 1 << 3print((1<<2)+1)
Output
8
5
On the other hand, Python gets one thing more sensibly than C does: bitwise operators are higher than comparisons, so n & 1 == 0 means (n & 1) == 0, which is what you'd expect.
Evaluation order
Precedence decides how an expression is grouped. A separate rule decides the order in which the pieces are worked out: Python evaluates operands from left to right. In a() + b() * c(), the calls happen in the order a, b, c, even though the multiplication is grouped first. This only matters once operands have side effects, such as functions that print something → Chapter 19.
Practice 4.10
Fix the bug
This should change 68 degrees Fahrenheit into degrees Celsius. The rule is: subtract 32 first, then multiply by 5 and divide by 9. The program prints a wrong number. Fix it.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
20.0
Output
* and / are higher than -, so Python works out 32 * 5 / 9 first.
Brackets override the table. Put them around the part that must be done first.
fahrenheit=68print((fahrenheit-32)*5/9)
Without brackets, only 32 is multiplied and divided. Brackets make the subtraction happen first.
Multiple choice
What does this line print?
print(10-4-3*2**2)
The order is: ** first, then *, then -.
After the power and the multiplication, two subtractions are left. They work from left to right.
The answer is: -6
2 ** 2 is done first, then 3 * 4. The line is then 10 - 4 - 12, worked out from left to right.
4.11 Operators on text
Some operators work on strings too, with a different meaning:
+ joins strings (concatenation) and * repeats a string. The other arithmetic operators make no sense for text, so they raise a TypeError:
print("banana"-"ana")
Output
Traceback (most recent call last):
File "operators.py", line 1, in <module>
print("banana" - "ana")
~~~~~~~~~^~~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'str'
The same operator doing different things for different types is called operator overloading. It's why + adds numbers but joins strings. String operations are covered fully in → Chapter 7.
Practice 4.11
Write code
Banner. The starting code stores a word. Print three lines: first a line of twelve = characters; then the word three times with nothing in between, followed by one !; then a line of twelve = characters once more. Build the lines with * and +.
The program prints the lines below. Your program must print exactly these lines.
Example run
============
GoGoGo!
============
Output
A string times a number repeats the string.
+ joins two strings. * is done before +, so the word is repeated first and the ! is joined after that.
With strings, * repeats and + joins. The precedence is the same as with numbers: * goes before +.
4.12 What Python does with an operator
Practice 4.12
Multiple choice
Which special method of an int does Python call for 5 + 3?
Every operator has a special name with two underscores on each side.
The name comes from the word for the operation + performs on numbers: addition.
The answer is: __add__
5 + 3 is the same as (5).__add__(3). Operators are method calls in disguise.
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
In total = price * 3, identify the operator, the operands, the expression and the statement.
Show the answer
* is the operator; price and 3 are the operands; price * 3 is the expression; the whole line total = price * 3 is a statement (an assignment).
Check yourself
What's the difference between / and //? Give an example where they give different answers.
Show the answer
/ gives the exact answer as a float; // rounds down to a whole number. 7 / 2 is 3.5 but 7 // 2 is 3.
Check yourself
Why is -7 // 2 equal to -4 and not -3?
Show the answer
-7 / 2 is −3.5, and // always rounds down (towards minus infinity). The whole number below −3.5 is −4.
Check yourself
What is -7 % 3? Show that it fits the rule a == (a // b) * b + a % b.
Show the answer
-7 % 3 is 2. -7 // 3 is -3, and (−3) × 3 + 2 = −7. ✓
Check yourself
How can you use % to check whether a number is divisible by 7?
Show the answer
If n % 7 is 0, then n is divisible by 7.
Check yourself
Why is -2 ** 4 negative? How do you get +16?
Show the answer
** is done before the unary minus, so -2 ** 4 is -(2 ** 4) = −16. Write (-2) ** 4 to get 16.
Check yourself
What does round(4.5) give, and why isn't it 5?
Show the answer
4. Python uses banker's rounding: a value exactly halfway rounds to the nearest even number, and 4 is even.
Check yourself
What's the type of 9 // 2? Of 9.0 // 2? Of 2 ** -1?
Show the answer
int, float, float.
Check yourself
Put these in the order Python does them in a + b * c ** d: +, *, **.
Show the answer
** first, then *, then +: it's a + (b * (c ** d)).
Check yourself
What's the difference between 2 ^ 3 and 2 ** 3?
Show the answer
2 ^ 3 is bitwise XOR, which gives 1 (10 XOR 11 = 01). 2 ** 3 is power, which gives 8.
This should print the average of 80, 90 and 70 (which is 80).
The program prints the lines below. Your program must print exactly these lines.
Example run
80.0
Output
Which operator on this line does Python do first: + or /?
Only 70 is divided by 3 now. Put brackets around the whole sum.
print((80+90+70)/3)
Only 70 was being divided by 3, because / is done before +. Add brackets.
print((80+90+70)/3)
Output
80.0
Fix the bug
This should print 2 to the power 8 (256).
The program prints the lines below. Your program must print exactly these lines.
Example run
256
Output
In Python, ^ is a bitwise operator. It is not the power operator.
Power is written with two stars.
print(2**8)
^ is XOR. Power is **.
print(2**8)
Output
256
Fix the bug
This should print the area of a circle with radius 7, using 3.14 for π (the formula is π × r²).
The program prints the lines below. Your program must print exactly these lines.
Example run
153.86
Output
The formula needs the radius squared: the radius times itself.
radius * 2 doubles the radius. Use the power operator with 2.
radius=7print(3.14*radius**2)
radius * 2 doubles the radius; the formula needs the radius squared.
radius=7print(3.14*radius**2)
Output
153.86
Fix the bug
This should print how many full boxes of 12 eggs can be made from 100 eggs, and how many eggs are left over. It prints 8.333333333333334 4.
The program prints the lines below. Your program must print exactly these lines.
Example run
8 4
Output
/ always gives a float with the exact result. Which division gives whole boxes only?
Change / into the floor division operator.
eggs=100print(eggs//12,eggs%12)
Use floor division for whole boxes.
eggs=100print(eggs//12,eggs%12)
Output
8 4
Coding problems
Write code · Easy
Calculator. Store a = 29 and b = 6. Print the result of every arithmetic operator (+ - * / // % **) on them, each with a label.
Print one line for each operator, in this order: +, -, *, /, //, %, **.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
a + b = 35
a - b = 23
a * b = 174
a / b = 4.833333333333333
a // b = 4
a % b = 5
a ** b = 594823321
Output
Each line is one print with a label in quotes, a comma, and the expression.
The seven expressions are a + b, a - b, a * b, a / b, a // b, a % b and a ** b.
a=29b=6print("a + b =",a+b)print("a - b =",a-b)print("a * b =",a*b)print("a / b =",a/b)print("a // b =",a//b)print("a % b =",a%b)print("a ** b =",a**b)
a=29b=6print("a + b =",a+b)print("a - b =",a-b)print("a * b =",a*b)print("a / b =",a/b)print("a // b =",a//b)print("a % b =",a%b)print("a ** b =",a**b)
Output
a + b = 35
a - b = 23
a * b = 174
a / b = 4.833333333333333
a // b = 4
a % b = 5
a ** b = 594823321
Write code · Easy
Odd one out. For each of the numbers 18, 27 and 0, print the number and its remainder when divided by 2. (0 means even, 1 means odd.)
Print three lines, for 18, 27 and 0 in this order. On each line print the number first, then its remainder.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
18 0
27 1
0 0
Output
The remainder when a number is divided by 2 is number % 2.
One line can be print(18, 18 % 2). Write the same for the other two numbers.
print(18,18%2)print(27,27%2)print(0,0%2)
print(18,18%2)print(27,27%2)print(0,0%2)
Output
18 0
27 1
0 0
Zero is even: it divides by 2 with nothing left over.
Write code · Easy
Minutes to hours. A movie lasts 157 minutes. Print it as hours and minutes, like 2 h 37 min.
Print the hours first, then the minutes.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
2 h 37 min
Output
One hour is 60 minutes. How many whole times does 60 fit into 157?
// with 60 gives the whole hours, and % with 60 gives the minutes that are left.
movie=157print(movie//60,"h",movie%60,"min")
movie=157print(movie//60,"h",movie%60,"min")
Output
2 h 37 min
Write code · Medium
Cash counter. An ATM must pay out $387 using as few bills as possible, from $100, $50, $20, $10, $5 and $1 bills. Print how many of each bill to give. Use // and % (or divmod) at every step.
Print six lines with the number of bills: $100 first, then $50, $20, $10, $5 and $1.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Clock maths. It's 21:45 now. Print the time 3 hours and 50 minutes later, in 24-hour form, as hours and minutes. Hint: convert everything to minutes since midnight first.
Print the hours first, then the minutes.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
1 h 35 min
Output
A day has 24 * 60 minutes. Use % with that number to wrap past midnight, then split the result with // 60 and % 60.
Bracket puzzles. Add brackets (and nothing else) so that each line prints the number on the right. Then run your answers to check.
Keep the four lines in the same order. Your program must print the four wanted numbers, one on each line.
The program prints the lines below. Your program must print exactly these lines.
Example run
15
11
64
4
Output
Brackets are done first. Ask which operation must happen first to reach the wanted number.
For the first line, both the sum and the difference must be worked out before the multiplication. For the last two lines, think about what ** does before anything else.
A tempting wrong answer for the first one is (2 + 3) * 4 - 1, which gives 19: the - 1 still happens last. This is exactly why you run your answers; a quick test catches the mistake your head missed.
Write code · Hard
XOR swap. Swap the values of two integer variables a = 5 and b = 9 using only ^=, with no third variable and no multiple assignment. Print them before and after. (This is a famous trick; in Python, a, b = b, a is clearer, so use this only as a puzzle.)
Print both values on one line before the swap, then both values on one line after the swap.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
5 9
9 5
Output
a ^= b means a = a ^ b. Using XOR with the same value two times cancels it out.
You need three lines with ^=. They change a, then b, then a once more.
a=5b=9print(a,b)a^=bb^=aa^=bprint(a,b)
Each ^= mixes in the other value; XOR-ing the same value twice cancels it out.
a=5b=9print(a,b)a^=bb^=aa^=bprint(a,b)
Output
5 9
9 5
Write code · Hard
Day of the week.Zeller's congruence calculates the day of the week for any date. For day q, month m and year y, where January and February count as months 13 and 14 of the previous year:
Print the value of h for 20 July 1969 first, then for 1 January 2000. Use labels that contain no digits.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Moon landing: 1
First day of the year: 0
Output
Every ⌊…⌋ in the formula becomes //, and mod becomes %. Store K and J in variables first.
January counts as month 13 of the year before. So 1 January 2000 uses the month 13 and the year 1999.
q,m,y=20,7,1969K=y%100J=y//100h=(q+13*(m+1)//5+K+K//4+J//4+5*J)%7print("Moon landing:",h)q,m,y=1,13,1999K=y%100J=y//100h=(q+13*(m+1)//5+K+K//4+J//4+5*J)%7print("First day of the year:",h)
July is month 7 of 1969. January is treated as month 13 of the previous year, so 1 January 2000 uses m = 13 and y = 1999.
q,m,y=20,7,1969K=y%100J=y//100h=(q+13*(m+1)//5+K+K//4+J//4+5*J)%7print("20 July 1969:",h)q,m,y=1,13,1999K=y%100J=y//100h=(q+13*(m+1)//5+K+K//4+J//4+5*J)%7print("1 January 2000:",h)
Output
20 July 1969: 1
1 January 2000: 0
1 is Sunday and 0 is Saturday: the first Moon landing was on a Sunday, and the year 2000 began on a Saturday. Notice 13 * (m + 1) // 5 works correctly without extra brackets: * and // have the same precedence, so they go left to right, multiplying first. Copying the formula twice is clumsy; a function would let you write it once → Chapter 19.
Chapter project: School trip planner
Project
Plan a school trip. A school takes 137 students to a museum. One bus has 40 seats and costs 285 dollars. The buses leave at 22:15 and the trip takes 505 minutes. The starting code stores these values.
Print five lines, in this order:
the number of buses that are completely full
the number of students in the last bus, which is not full
the number of buses needed in total
the cost for one student in dollars, rounded to 2 decimal places: the cost of all the buses, shared equally among the students
the time when the trip ends, in 24-hour form: the hour first, then the minute
Use the variables in your calculations, not numbers that you worked out in your head. Your labels are free, but put no digits in them.
The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Full buses: 3
Students in the last bus: 17
Buses needed: 4
Cost for one student: 8.32
Trip ends: 6 h 40 min
Output
// with the number of seats gives the full buses, and % gives the students who are left for the last bus.
For the buses needed, add seats - 1 to the number of students before the floor division. Then every bus that is started counts as one more bus. Here the last bus is not empty, so full buses plus one gives the same number.
For the end time, change the start time to minutes since midnight, add the trip, and wrap with % (24 * 60). Then split the result with // 60 and % 60.
students=137seats=40bus_cost=285start_hour=22start_minute=15trip_minutes=505full=students//seatslast=students%seatsbuses=(students+seats-1)//seatseach=buses*bus_cost/studentsend=(start_hour*60+start_minute+trip_minutes)%(24*60)print("Full buses:",full)print("Students in the last bus:",last)print("Buses needed:",buses)print("Cost for one student:",round(each,2))print("Trip ends:",end//60,"h",end%60,"min")
The project uses the partners // and % three times: to fill buses, to wrap a clock past midnight, and to split minutes into hours and minutes. round is used only when the cost is printed.