OK — let’s go! With your terminal open, and the Python interactive shell started, you’ll see a command prompt consisting of three arrows (>>>
). If you use repl.it, the command prompt looks a bit different. Just to be absolutely clear, you don’t type in the three arrows, only what follows after it.
Now type in the number 10:
>>> 10
10
What happened? Remember we are in a REPL, short for read-evaluate-print-loop:
Let’s give it something more challenging:
>>> 10 + 10
20
This time, Python recognized two numbers and a so-called operator, the plus sign, and evaluates this to 20. Yup, Python can be used as a calculator.
In fact, Python is great at doing math. Let's go over the basic operators you can use. Go ahead a play around with this in the REPL:
Operator | Name |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
If you know your math, you might also want to try:
Operator | Name | Example |
---|---|---|
% | Modulus | 5 % 2 == 1 |
// | Floor division | 10 // 6 == 1 |
** | Exponential | 2 ** 4 == 16 |
Operator precedence, the order in which Python processes the operators and numbers, is the same as in math. Multiplication and division come before addition and subtraction. In case of doubt, you can always use parentheses. Let’s try some examples:
>>> 2 + 3 * 3
11
>>> (2 + 3) * 3
15
>>> 1 + 2 ** 2
5
>>> 2 / 2 * 8
8.0
If you liked this page, please share it with a fellow learner: