Getting started
Basic concepts: taking our first steps
Using an IDE
Objects and classes
Loops, ranges, and iterators
Working with files
Exception handling
Python data types
Course project: building a TODO application
And now what?


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!

Arithmetic operators

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 operators are the same in other programming languages, so it pays to learn them well.

Go ahead and play around with this in the REPL:

+Addition2 + 2
Subtraction3 – 1
*Multiplication5 * 3
/Division5 / 2
The basic operators most of you will know

If you know your math, you might also want to try:

%Modulus5 % 2
//Floor division9 // 2
**Exponential2 ** 4
Some more advanced operators

Operator precedence

Operator precedence, the order in which Python processes the operators and numbers, is somewhat similar to regular math. For example, multiplication and division come before addition and subtraction. Multiplication and division have the same precedence, so the order matters. Like in math, we work from left to right. E.g., 2 * 2 / 8 = 0.5 , while 2 / 2 * 8 = 8.0.

If in doubt, 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
>>> (2 + 3) * 3
>>> 1 + 2 ** 2
>>> 2 / 2 * 8

Using the underscore to get the previous result

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 this:

>>> 3 * 3
>>> _ + 3

Using the history

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.

Storing results

Terrific! We can do some math in Python and 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 precisely for that purpose, which is the subject of our next lesson.