Mathematical Operations#

Performing mathematical operations is somewhat intuitive in the Python programming languages. The code you’ll write will mostly look like how you would write the operations on a piece of paper or in a graphing calculator. Try typing some of the operations below into a Code cell in your own Jupyter Notebook, and running the cell.

By default, a Jupyter Notebook will display whatever the last result of code cell directly underneath it. If a cell has multiple calculations, it will only show the last unless you specifically ask it to show the others using the print() function. You’ll also notice that spacing between the numbers and the operators is not important. The numbers can be directly up against the operator symbols or separated with a space or two. It’s good practice to find a style that works for you and be consistent.

2+2
4
3 * 2

print(5 *   100)

7*3
500
21
24/6
4.0

If you were to use improper syntax when writing your code cell, Python will let you know by returning an error, specifically a SyntaxError.

5 +
  File "<ipython-input-4-4f4744a157be>", line 1
    5 +
       ^
SyntaxError: invalid syntax

You’ll notice this error message provides some information as to why your code produced an error.

  • SyntaxError: invalid syntax indicates that the error was caused by your code being written in a format Python did not understand. In this case, Python knows that the + symbol should have numerical objects on either side of it, and since there was no number on the right-hand side, did not know how to proceed.

  • File "<ipython-input-4-4f4744a157be>", line 1 indicates that the error was found in line 1 of the cell.

  • The ^ symbol indicates the location in the code that started the error.

Tracking down errors in your code will be a time-consuming part of your work when programming, so learning to read the error messages for hints about the nature of the error will be very helpful!

Common Operators#

You can use many of the common math operations in Python.

Expression Type

Operator

Example

Value

Addition

+

2 + 3

5

Subtraction

-

2 - 3

-1

Multiplication

*

2 * 3

6

Division

/

7 / 3

2.33334

Floor Division

//

7 // 3

2

Remainder (or Modulo)

%

7 % 3

1

Exponentiation

**

2 ** 0.5

1.41421

Order of Operations#

Python expressions obey the same familiar rules of precedence as in algebra: multiplication and division occur before addition and subtraction. Parentheses can be used to group together smaller expressions within a larger expression.

1 + 2 * 3 * 4 * 5 / 6 ** 3 + 7 + 8 - 9 + 10
17.555555555555557
1 + 2 * (3 * 4 * 5 / 6) ** 3 + 7 + 8 - 9 + 10
2017.0

Explore some calculations that you can perform to get comfortable with the syntax and operators. See what kind of error you get when using operators to divide by 0 or perform other complex calculations. You won’t break your computer or the internet by trying out something that produces an error message!