Operators I

Arithmetic Operators in Python

In this lesson you will learn how to do mathematical operations using arithmetic operators in Python.


We already know how to create variables and assign them a numerical value:

revenue = 10
Python

In Python programming we often have to do mathemtical operations with these values.

Let's say that we have a company and we want to calculate our revenue.

Our revenue is the result of quantity (e.g number of sold items) times the price (of some product). We can calculate this using the multiplication operator *:

price = 10 quantity = 5 revenue = price * quantity print(revenue)
Python
Output

And our profit is revenue minus costs. We can calculate this using the subtraction operator -:

revenue = 50 costs = 35 profit = revenue - costs print(profit)
Python
Output

The most common arithmetic operators in Python are:

# Addition print(3 + 5) # Subtraction print(3 - 5) # Multiplication print(3 * 5) # Division print(3 / 5)
Python
Output

Another arithmetic operator is the Power (exponent) operator **. It is used to perform an exponential calculation:

# raise 3 to the power of 5 print(3**5) # 3*3*3*3*3
Python
Output

Just like any other programming language, Python follows mathematical conventions and has an order of operation for arithmetic expressions.

If mathematical expressions are combined, Python evaluates these according to the following hierarchical order (from highest to lowest):

 1. Parentheses ()

 2. Exponents **

 3. Multiplication & Division */

 4. Addition and Subtraction +-

Here we have a combination of addition and multiplication expressions. Because multiplication has higher precedence, it is evaluated before the addition:

print(2 + 10 * 5)
Python
Output

However, if we wrap the addition in parentheses, it gets a higher precedence than the multiplication:

print((2 + 10) * 5)
Python
Output

What will be the output?

print(3 + 2 * 6)
Python

What will be the output?

print((5 + 5) * 2 ** 3)
Python