Skip to main content Link Menu Expand (external link) Left Arrow Right Arrow Document Search Copy Copied

Lesson 1 - Using Python as a Calculator

The simplest thing we can do with Python is use it as a calculator. Addition, subtraction, multiplication - you name it!

Table of Contents

Lesson Objectives

  • Learn about some of the mathematical operations Python supports.
  • Use the math library to get access to more math functions.

Math Operations

Using Python as a calculator works exactly as you think it should.

Input

5 + 7

Output

12

By default, Python supports addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floored division (//).

If there are multiple operations in the same line, they follow the order of operations outlined in the table below. Operations at the top have higher precedence. Rows with multiple operations have equal precedence and are evaluated from left to right in the expression.

Operation Symbol
Parentheses ( )
Exponents **
Multiplication, Division, Floor Division, and Modulus *, /, //, %
Addition and Subtraction +, -

Input

5 + 2 * (2**3 / 2)

Output

13

Although we’ve only been using integers for our math, Python supports decimal numbers as well as complex numbers. We’ll briefly talk about complex numbers later in Lesson 3a.

Input

3.2 * 5 + 0.102

Output

16.102

Other Math Functions

Other math functions, such as log, sin, and cos, are supported in some of Python’s math libraries. A library is a package of functions or values. To gain access to these functions, we need to add an extra line of code at the top.

Input

import math

math.cos(0)

Output

1.0

The first line, import math, tells Python to include some math functions that are not included by default.

In the second line, we’re using the cos() function from the math library. Since cos() only needs one input value, we put it inside the brackets.

A full list of functions and values that the math library provides can be found here: https://www.w3schools.com/python/module_math.asp.

Key Points / Summary

  • You can use Python as a calculator.
  • To get access to more math functions, you have to import the math library.