Basic Math¶
Let’s start by using Python like a calculator. Python has an interactive mode called the REPL (Read Evaluate Print Loop).
You can invoke the REPL from the command line by simply typing:
> python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Now whatever you type after the new prompt (>>>) will be executed interactivately by the Python interpreter. We will use this triple bracket prompt (>>>) in the code examples in the book to indicate that the example was executed in the REPL environment. A single bracket (>) indicates that we executed the command from the command line.
Type in 2 + 2 and enter:
>>> 2 + 2
4
More examples:
>>> 999 * 999
998001
>>> 1234 - 4321
-3087
>>> 1 / 3
0.3333333333333333
For exponentiation use ** like this:
>>> 2 ** 10
1024
>>> 2 ** (-3)
0.125
For floor division (drops the fractional part):
>>> 20 // 3
6
>>> 1 // 3
0
An interesting feature of Python is that integer operations have arbitrary precision:
>>> 2 ** 200
1606938044258990275541962092341162602522202993782792835301376
If you divide by zero, you will get an error that looks like this:
>>> 10 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
For modular arthmetic, use the % symbol:
>>> 27 % 12
3
>>> 11 % 2
1
>>> 91 % 13
0