Python is designed as a simple programming language with a small core language that can be greatly extended through modules. Think of Python like a house with a small living room, but with many additional rooms that you can open as needed. Modules are those additional rooms that contain special functions and constants.
A module is a unit of Python code organization that is loaded through the import process. When you need special mathematical functions, you don't need to create them from scratch, but simply import a module that already provides those functions.
The math module provides mathematical functions that are useful for int and data types. Meanwhile, for calculations involving complex numbers, Python provides the module that supports , , and data types.
The most basic way to import a module is using the import math command. This way, all function and constant names remain bound to the math namespace.
import_basic.py
import math# Using sqrt function with math prefixprint(math.sqrt(9)) # Output: 3.0# Accessing pi constantprint(math.pi) # Output: 3.141592653589793# If trying without prefix, an error will occur# sqrt(9) # NameError: name 'sqrt' is not defined
To make code more concise, you can give an alias to the imported module. This is very useful when the module name is long or frequently used.
import_alias.py
import math as m# Using alias 'm' instead of 'math'print(m.sqrt(9)) # Output: 3.0print(m.pi) # Output: 3.141592653589793# Original name 'math' is no longer available# math.sqrt(9) # NameError: name 'math' is not defined
This method imports all names from the math module to the global namespace so they can be accessed directly without a prefix. Although practical for interactive sessions, this method is not recommended for complex Python programs.
import_all.py
from math import *# Functions can be called directly without prefixprint(sqrt(9)) # Output: 3.0print(pi) # Output: 3.141592653589793# Name 'math' is not available because it wasn't imported# math.sqrt(9) # NameError: name 'math' is not defined
Using from math import * has several drawbacks that you need to understand. First, there's a risk of name conflicts if you import multiple modules that have functions with the same name. Second, it's difficult to trace the origin of specific functions when reading code. Third, code becomes more difficult to maintain in the long term.
A more selective approach is to import only the specific functions needed. This provides direct access without a prefix while maintaining code clarity.
import_specific.py
from math import sqrt# sqrt function can be called directlyprint(sqrt(9)) # Output: 3.0# pi constant is not available because it wasn't imported# print(pi) # NameError: name 'pi' is not defined# Name 'math' is also not available# math.sqrt(9) # NameError: name 'math' is not defined
You can also give an alias to specific functions when importing them. This is useful for making function names more concise or avoiding name conflicts.
import_function_alias.py
from math import factorial as fac# Using alias 'fac' for factorial functionprint(fac(5)) # Output: 120# Original name 'factorial' is not available# factorial(5) # NameError: name 'factorial' is not defined# Same with 'math'# math.factorial(5) # NameError: name 'math' is not defined
Python provides several basic mathematical functions as built-in functions that can be used directly without import. Examples are abs() and round(). These built-in functions demonstrate the concept of function overloading, where one function name can handle various data types.
The abs() function returns the absolute value of a number. This function can handle integers, floats, and even complex numbers.
abs_function.py
# Absolute value for negative integerprint(abs(-5)) # Output: 5# Absolute value for negative floatprint(abs(-1.4)) # Output: 1.4# Absolute value for complex number (modulus)print(abs(4 + 3j)) # Output: 5.0
For complex numbers, the abs() function calculates the modulus or distance from the origin point in the complex plane. The result for 4 + 3j is 5.0 because 42+32=16+9=25=5.
The round() function rounds floating-point numbers to the nearest integer using the Banker's rounding system. In this system, numbers that are exactly in the middle (like 0.5) are rounded to the nearest even number.
round_function.py
# Standard roundingprint(round(-3.8)) # Output: -4print(round(3.5)) # Output: 4print(round(4.5)) # Output: 4 (not 5!)# Rounding with specific precisionprint(round(3.141592653589793, 3)) # Output: 3.142print(round(1234.4321, -2)) # Output: 1200.0
Note that round(4.5) produces 4, not 5. This is because Python uses Banker's rounding which rounds to the nearest even number for cases exactly in the middle. The round() function also accepts a second parameter to determine the number of decimal digits or rounding position.
The math module also provides important mathematical constants that are frequently used in calculations.
math_constants.py
import math# Pi constant (π ≈ 3.141592...)print(f"Value of π: {math.pi}")# e constant (Euler's number ≈ 2.718281...)print(f"Value of e: {math.e}")# Infinity (positive infinity)print(f"Infinity: {math.inf}")# Not a Numberprint(f"NaN: {math.nan}")# Example usage of constantscircle_radius = 5circle_area = math.pi * circle_radius ** 2print(f"Circle area with radius {circle_radius}: {circle_area}")
import mathdef calculate_euclidean_distance(x1, y1, x2, y2): """Calculate Euclidean distance between two points""" return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)def calculate_triangle_area(a, b, c): """Calculate triangle area using Heron's formula""" # Calculate semi-perimeter s = (a + b + c) / 2 # Heron's formula area = math.sqrt(s * (s - a) * (s - b) * (s - c)) return area# Usage examplepoint1 = (0, 0)point2 = (3, 4)distance = calculate_euclidean_distance(*point1, *point2)print(f"Distance between {point1} and {point2}: {distance}")# Calculate triangle area with sides 3, 4, 5area = calculate_triangle_area(3, 4, 5)print(f"Triangle area with sides 3, 4, 5: {area}")
After learning the import methods and functions in the math module, such as sqrt(), round(), trigonometry functions, and the pi constant, you can write calculations with clearer code. The import method you choose will affect how easy your code is to read and maintain in the long term.