In this post, we will go over the basics of numbers in Python and explore the various built-in functionalities available to us. Each section comes with a brief description and some sample code.
Table of Contents
Order of Operations
Whenever there are multiple operators, Python follows the same order of procedure as usual mathematical expressions. More precisely, the operator precedence is defined as follows:
- Parentheses
()
- Exponents
**
- Multiplication
*
, Division/
, Floor//
, Modulo%
- Addition
+
, Substration-
Operators with equivalent precedence are evaluated from left to right, with the exception of exponents. Given the properties of right-associativity, exponents are evaluated from right to left instead. For instance, given the equation \(x^{y^{z}}\), \(y^{z}\) would be computed first and not \(x^{y}\).
# Order of operations left to right
2 * 3 + 1
> 7
# Using parentheses
2 * (3 + 1)
> 8
# Right-associtivity for exponents
(2 ** 3 ** 4) == (2 ** (3 ** 4))
> True
(2 ** 3 ** 4) == ((2 ** 3) ** 4)
> False
Incrementing Values
Updating the value of a variable is a very common action in many programming languages, and it's no different in Python. There are two main ways of incrementing a numeric variable: the first consists of applying an operation (ie. +
, -
, *
, etc.) on a given variable and reassigning it to itself, whereas the second technique involves a special command (ie. +=
, -=
, *=
, etc.) which accomplishes the same thing.
count = 0
# Option 1, apply operation on variable and reassign to variable
count = count + 1
print(count)
> 1
# Option 2, use special syntax to achieve the same thing
count += 1
print(count)
> 2
Built-in Functions
Although the majority of math related function are found in the math
module, there are still a few built-in math functions that are quite commonly used. The following math functions does not required the import of any additional modules.
# Absolute value
abs(-9)
> 9
# Exponent 2 to the power 5
pow(2, 5)
> 32
# Rounding to 2 decimal places
round(3.14159, 2)
> 3.14
math
Module
The math
module contains the bulk of math related functions. Only a few of them are presented below, but there is documentation covering the extensive list of functions from this module1.
# Import math module
import math
# Ceiling
math.ceil(2.43)
> 3
# Greatest Common Divisor
math.gcd(24, 42)
> 6
# Logarithm
math.log2(8)
> 3.0
Casting
Casting allows us to convert a variable from one data type to another. For instance, in order to use math related functions, we would first need to convert any variable involved into the approriate data type.
# Multiplying a string
'10' * 2
> '1010'
# Casting string to integer, then multiplying integer
int('10') * 2
> 20
# Casting string to float to preserve decimals
float('5.5') / 2
> 2.75