Link Search Menu Expand Document (external link)

How to do basic mathematical computations (in Python)

See all solutions.

Task

How do we write the most common mathematical operations in a given piece of software? For example, how do we write multiplication, or exponentiation, or logarithms, in Python vs. R vs. Excel, and so on?

Solution

For those expressions that need the Python math package, use the code import math beforehand to ensure that package is loaded. Alternatively, you can write from math import * and thus drop the math prefixes in the table below.

Mathematical notation Python code Requires math package?
x+y x+y no
xy x-y no
xy x*y no
xy x/y no
xy x//y no
remainder of x÷y x%y no
xy x**y no
|x| abs(x) no
lnx math.log(x) yes
logab math.log(b,a) yes
ex math.exp(x) yes
π math.pi yes
sinx math.sin(x) yes
sin1x math.asin(x) yes
x x**0.5 no
x math.sqrt(x) yes

Other trigonometric functions are also available besides just math.sin, including math.cos, math.tan, etc.

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)