Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 4

Operators and Expressions

This lesson goes with Episode 4 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

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

Practice 4.1

Multiple choice

In the Python shell you type the statement total = 6 * 7 and press Enter. What does the shell show?

Choose one answer

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 = 17
b = 5
print(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.

Practice 4.2

Predict the output

What does it print?

first = 19
second = 4
print(first + second, first * second)
print(first / second)
print(first // second, first % second)

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

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":

   -4    -3.5    -3     ...     3     3.5     4
    ◄─────┘                       ◄─────┘
  floor(-3.5) = -4              floor(3.5) = 3

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)

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

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 = 472
print(n % 10)         # last digit
print(n // 10)        # everything except the last digit
print(n // 10 % 10)   # the middle digit
print(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 = 22
later = (now + 5) % 24
print(later)

Output

3

Splitting into units. How many hours, minutes and seconds are in 4000 seconds?

total_seconds = 4000
hours = total_seconds // 3600
minutes = total_seconds % 3600 // 60
seconds = total_seconds % 60
print(hours, "h", minutes, "min", seconds, "s")

Output

1 h 6 min 40 s

// 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 = 50
print("Left over:", pencils  8)

The finished program prints:

Target

Left over: 2

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
  1. number = number // 10
  2. last = number % 10
  3. number = 472
  4. print(middle, last)
  5. middle = number % 10

Write code

Weeks and days. A course lasts 100 days. Store days = 100. Print two lines: first the number of full weeks, then the number of days left over.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Full weeks: 14
Days left: 2

4.5 Powers: **

a ** b means a to the power b, or a multiplied by itself b times:

print(2 ** 10)
print(10 ** 3)
print(5 ** 0)
print(10 ** -2)
print(2 ** 0.5)

Output

1024
1000
1
0.01
1.4142135623730951

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.

Practice 4.5

Predict the output

What does it print?

print(-2 ** 2)
print(2 ** 3 ** 2)
print(10 ** -1)
print(16 ** 0.5)

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

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:

Expression Result type Example
int + - * // % ** int int 7 // 2 → 3
int / int float, always 6 / 2 → 3.0
int ** negative int float 2 ** -2 → 0.25
anything with a float float 7.0 // 2 → 3.0
bool with int int (True counts as 1) True + 1 → 2
print(type(7 // 2), type(7.0 // 2))
print(type(2 ** 3), type(2 ** -3), type(2 ** 0.5))
print(type(True + 1), type(6 / 2))

Output

<class 'int'> <class 'float'>
<class 'int'> <class 'float'> <class 'float'>
<class 'int'> <class 'float'>

The type depends only on what goes in, never on whether the answer happens to be whole: 6 / 2 is 3.0, a float, even though 3 is whole.

Practice 4.6

Multiple choice

Which of these expressions gives an int?

Choose one answer

Predict the output

What does it print?

print(6 / 2, 7 // 2, 7.0 // 2)
print(True + True, 2 ** -1)

4.7 Built-in number functions

Python has several built-in functions for working with numbers. They're always available, with no setup.

Function What it does Example Result
abs(x) distance from zero abs(-7.5) 7.5
round(x) nearest whole number round(3.7) 4
round(x, n) round to n decimal places round(3.14159, 2) 3.14
pow(a, b) same as a ** b pow(3, 4) 81
pow(a, b, m) a ** b % m, but much faster pow(3, 4, 5) 1
divmod(a, b) (a // b, a % b) divmod(17, 5) (3, 2)
max(a, b, ...) the largest argument max(3, 9, 4) 9
min(a, b, ...) the smallest argument min(3, 9, 4) 3

max and min take as many arguments as you like. They'll also work on whole lists of values → Chapter 25.

round has two surprises

Surprise 1: halves round to the even neighbour.

print(round(0.5), round(1.5), round(2.5), round(3.5))

Output

0 2 2 4

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.

Practice 4.7

Predict the output

What does it print?

print(round(2.5), round(3.5))
print(round(3.14159, 3), abs(-8))
print(max(2, 7, 5) - min(2, 7, 5))

Fill in the blank

Fill in the name of the built-in function that gives the quotient and the remainder at once.

boxes, left = (47, 6)
print(boxes, "boxes,", left, "left over")

The finished program prints:

Target

7 boxes, 5 left over

Put the lines in order

Put the lines in order. Eggs are packed into boxes of 12, and the program prints how many eggs are inside the full boxes.

The program in the right order prints:

Target

48 eggs in 4 boxes
  1. boxes, left = divmod(eggs, 12)
  2. eggs = 53
  3. eggs = boxes * 12
  4. print(eggs, "eggs in", boxes, "boxes")

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

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 = 10
x *= 2 + 3
print(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 = 20
x -= 2 + 3
print(x)
x //= 4
x *= x
print(x)

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
  1. score += 5
  2. score -= 4
  3. print(score)
  4. score *= 2
  5. score = 10

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, ...):

  place value:   8   4   2   1
  12 in binary:  1   1   0   0     = 8 + 4         = 12
  10 in binary:  1   0   1   0     = 8 + 2         = 10

bin() shows any integer in binary, with the 0b prefix from Chapter 2:

print(bin(12))
print(bin(10))

Output

0b1100
0b1010

The six bitwise operators

Bitwise operators work on the individual bits of integers, comparing them place by place:

Operator Name Each result bit is 1 when... 12 and 10 Result
& AND both bits are 1 1100 & 1010 1000 = 8
| OR at least one bit is 1 1100 | 1010 1110 = 14
^ XOR (exclusive or) the bits are different 1100 ^ 1010 0110 = 6
~ NOT (flips every bit; see below) ~12 −13
<< left shift (moves bits left) 12 << 2 110000 = 48
>> right shift (moves bits right) 12 >> 2 11 = 3
print(12 & 10, 12 | 10, 12 ^ 10)
print(~12)
print(12 << 2, 12 >> 2)

Output

8 14 6
-13
48 3

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)
Choose one answer

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(12  10)

The finished program prints:

Target

8

Predict the output

What does it print?

print(bin(5))
print(6 | 3, 6 & 3)
print(~7, 1 << 4)

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
2 x[i], x[i:j], f(...), x.attr indexing, slicing, calls, attributes
3 await x waiting in async code → Chapter 64
4 ** power
5 +x, -x, ~x unary plus, minus, bitwise NOT
6 *, @, /, //, % multiply, matrix multiply, divide, floor divide, remainder
7 +, - add, subtract
8 <<, >> shifts
9 & bitwise AND
10 ^ bitwise XOR
11 | bitwise OR
12 in, not in, is, is not, <, <=, >, >=, !=, == comparisons, membership, identity → Chapter 5
13 not x logical NOT → Chapter 5
14 and logical AND → Chapter 5
15 or logical OR → Chapter 5
16 x if c else y conditional expression → Chapter 11
17 lambda anonymous function → Chapter 23
18 (lowest) := assignment expression

You don't need to memorise all of it. The part you'll use daily is the middle:

**, then unary minus, then * / // %, then + -, then comparisons, then not, and, or.

Associativity: same level, which first?

When two operators have the same precedence, associativity decides. All Python operators work left to right, except **, which works right to left:

print(10 - 4 - 3)        # (10 - 4) - 3
print(100 / 10 / 5)      # (100 / 10) / 5
print(2 * 3 ** 2)        # 2 * (3 ** 2): ** is higher than *
print(2 ** 3 ** 2)       # 2 ** (3 ** 2): right to left

Output

3
2.0
18
512

Comparisons are a special case again: they don't group left to right, they chain, so 1 < x < 10 means what it does in maths → Chapter 5.

Working through a long expression

Here's how Python evaluates 15 - 3 * 2 ** 2 // 5 % 3, one step at a time:

15 - 3 * 2 ** 2 // 5 % 3
15 - 3 * 4 // 5 % 3          ** first (highest)
15 - 12 // 5 % 3             then * // % from left to right: 3 * 4 = 12
15 - 2 % 3                   12 // 5 = 2
15 - 2                       2 % 3 = 2
13                           finally -
print(15 - 3 * 2 ** 2 // 5 % 3)

Output

13

Surprising precedence

A few combinations catch even experienced programmers:

print(1 << 2 + 1)     # + is higher than <<, so this is 1 << 3
print((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

Multiple choice

What does this line print?

print(10 - 4 - 3 * 2 ** 2)
Choose one answer

4.11 Operators on text

Some operators work on strings too, with a different meaning:

print("Core" + " " + "Python")
print("ab" * 3)
print("-" * 10 + ">")

Output

Core Python
ababab
---------->

+ 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!
============

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?

Choose one answer

+ 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.

Predict the output

Predict the output

print(23 // 4, 23 % 4)
print(-23 // 4, -23 % 4)
print(23.0 // 4)

Predict the output

print(2 + 3 * 4 ** 2)
print((2 + 3) * 4 ** 2)
print(100 - 10 - 5 * 2)

Predict the output

x = 7
x += 3
x //= 4
x **= 3
print(x)

Predict the output

print(round(3.5), round(4.5), round(-1.5))
print(max(4, 9, -2), min(4, 9, -2), abs(-9))

Fix the bug

Fix the bug

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

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

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

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

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

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

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

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.

Example run

Hundreds: 3
Fifties: 1
Twenties: 1
Tens: 1
Fives: 1
Ones: 2

Write code · Medium

Digit sum. Store a three-digit number, such as 583. Print its three digits separately and their sum, using only // and %.

Print the three digits first (hundreds, tens, ones), then their sum.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

5 8 3
Sum: 16

Write code · Medium

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

Write code · Hard

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

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

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

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:

  1. the number of buses that are completely full
  2. the number of students in the last bus, which is not full
  3. the number of buses needed in total
  4. the cost for one student in dollars, rounded to 2 decimal places: the cost of all the buses, shared equally among the students
  5. 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