The operator table in the Calculations chapter ends with two operators that
you will not find on a calculator keyboard: % and **. This chapter is about
those two, and about the kind of problem each one solves.
| Operator | Name | What it does | Example | Result |
|---|---|---|---|---|
// |
floor division | how many times one number fits into another | 17 // 5 |
3 |
% |
modulo | what is left over after that | 17 % 5 |
2 |
** |
exponentiation | raising a number to a power | 4 ** 2 |
16 |
% is called modulo, or mod for short. It divides the first number by
the second and gives you the remainder: the part that is left over once the
second number has gone in as many whole times as it can.
Share 17 sweets between 5 people. Everybody gets 3, which uses up 15, and there are 2 left over. Floor division answers the first half of that, and modulo answers the second half:
print(17 // 5)
print(17 % 5)
3
2
The % sign has nothing to do with percentages here. In Python it always means
the remainder.
A number is even when it divides by 2 with nothing left over, so number % 2
is 0 for every even number and 1 for every odd one:
print(8 % 2)
print(7 % 2)
0
1
The same trick works for any number. If number % 3 is 0, the number is in the
three times table.
Floor division and modulo are a pair: one says how many whole groups there are, the other says how much is left over. Used together, they split an amount into two units. 130 seconds is 2 whole minutes, with 10 seconds left over:
total_seconds = 130 minutes = total_seconds // 60 seconds = total_seconds % 60 print(str(minutes) + " minutes and " + str(seconds) + " seconds")
Change total_seconds and run it again. Try 60, 59 and 3600, and predict each
answer before you run it.
** is called exponentiation. It raises the first number to the power of
the second: 4 ** 2 is 4 squared, which is 4 times 4, and 4 ** 3 is 4 cubed,
which is 4 times 4 times 4.
print(4 ** 2)
print(4 ** 3)
print(2 ** 10)
16
64
1024
On paper you would write the power small and raised: 4². There is no way to type that into code, so Python writes it as two stars. One star multiplies, two stars raise to a power.
The area of a square is its side squared and the volume of a cube is its side
cubed, which makes ** the natural operator for both:
side_length = 3
area = side_length ** 2
volume = side_length ** 3
print("Area is " + str(area))
print("Volume is " + str(volume))
Powers work on floats as well. 2.5 ** 2 is 6.25, and a float to a power is
always a float, so 4.0 ** 2 is 16.0, not 16.
Make sure that you check for the following things:
** are written next to each other, with no space between
them.% gives the remainder, not a percentage, and // gives the number of whole
times. Check which of the two the question is asking for.int() or float() before you
calculate with it.print is wrapped in str().