We’ll start our Python learning journey in something called the Python REPL. It’s an interactive shell that allows you to enter Python commands and directly see the results. It’s a great way to tinker and learn! We’ll use the REPL as a calculator and explore Python’s operators.
Exploring The Python REPL
We’ll start inside the Python REPL. With your terminal open and the Python interactive shell started, you’ll see a command prompt consisting of three arrows (
>>>). 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, which is short for Read-Evaluate-Print-Loop:
- Read: Python reads 10
- Evaluate: Python evaluates this input and decides it is a number
- Print: it prints out what was evaluated
- Loop: and it’s ready for the next input
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.
OK, so Python is great at doing math. In fact, it can replace your calculator easily. A little confession: I use the Python REPL as a calculator all the time!
We’ve seen how to use the + operator. It’s just like regular math. Let’s go over some of the other operators you can use. Some will look familiar; others might look a bit odd. You’ll get used to it quickly, and most of the operators are the same in other programming languages, so it pays to learn them well.
Go ahead a play around with this in the REPL:
|+||Addition||2 + 2|
|–||Subtraction||3 – 1|
|*||Multiplication||5 * 3|
|/||Division||5 / 2|
If you know your math, you might also want to try:
|%||Modulus||5 % 2|
|//||Floor division||9 // 2|
|**||Exponential||2 ** 4|
Operator precedence, the order in which Python processes the operators and numbers, is the same as math. For example, multiplication and division come before addition and subtraction. If you doubt, you can always use parentheses or try it in the REPL and see what happens.
Let’s try some examples:
>>> 2 + 3 * 3 11 >>> (2 + 3) * 3 15 >>> 1 + 2 ** 2 5 >>> 2 / 2 * 8 8.0