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 arithmetic 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|
The order in which Python processes the operators and numbers, called Operator precedence, is the same as in math. For example, multiplication and division come before addition and subtraction. If you’re in doubt about operator precedence, you can always use parentheses. Alternatively, you can 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
Now that we’re getting more and more advanced, here’s a little trick I’d like to show you that can save you time.
You can obtain the result of the last expression in a Python REPL with the underscore operator, e.g. in the Python REPL this looks like:
>>> 3 * 3 9 >>> _ + 3 12
Have you noticed that Python keeps a history of commands too? You can go back and forth between previous commands by pressing the up and down arrows. Python keeps this history in a file (on most OSes in
~/.python_history), so it even persists between sessions.
Terrific, we can do some math in Python already, and we can even access previous results and commands. But it would be even more awesome if we could store the results of our calculations. Python allows us to define variables exactly for that purpose, which is the subject of our next lesson.