Functions in Modules

M3-R5.1 · Chapter 6: Functions · 3 min read

2. Functions in Module

 1. What is a Module?

A module is a file containing Python definitions (functions, classes, variables) that can be imported and reused in other programs. Python ships with a rich standard library of built-in modules, and you can also install third-party modules via pip.

Key benefits:

  •  Code reusability — write once, use anywhere

  •  Organisation — split large programs into logical files

  •  Namespace management — avoids name conflicts

  •  Access to Python's standard library (~200+ built-in modules)

2.  Ways to Import a Module

Syntax

Meaning

Example usage

import module

Import whole module

import math
math.sqrt(9)

from module import name

Import specific item

from math import sqrt
sqrt(9)

from module import *

Import everything (avoid in big projects)

from math import *
sqrt(9)

import module as alias

Give module a short alias

import math as m
m.sqrt(9)

3.  math Module — Complete Function Reference

Provides mathematical functions and constants for numerical computations. Always use import math before calling any function.

Usage:  import math    then call math.sqrt(25)

Function / Constant

Description

Example

Result

math.pi

Value of π (constant)

math.pi

3.14159…

math.e

Euler's number (constant)

math.e

2.71828…

math.sqrt(x)

Square root of x

math.sqrt(25)

5.0

math.pow(x, y)

x raised to power y

math.pow(2, 8)

256.0

math.floor(x)

Largest integer ≤ x

math.floor(4.9)

4

math.ceil(x)

Smallest integer ≥ x

math.ceil(4.1)

5

math.fabs(x)

Absolute value (float)

math.fabs(-7)

7.0

math.factorial(n)

n! factorial

math.factorial(5)

120

math.gcd(a, b)

Greatest common divisor

math.gcd(12, 8)

4

math.log(x)

Natural log (base e)

math.log(math.e)

1.0

math.exp(x)

e raised to power x

math.exp(1)

2.718…

math.hypot(x, y)

Hypotenuse √(x²+y²)

math.hypot(3, 4)

5.0

math.isnan(x)

True if x is NaN

math.isnan(float('nan'))

True

math.trunc(x)

Truncate to integer

math.trunc(3.99)

3

4.  random Module — Complete Function Reference

Generates pseudo-random numbers, selections, and shuffles. Uses the Mersenne Twister algorithm internally. Set a seed for reproducible results.

Usage:  import random    then call random.randint(1, 10)

Function

Description

Example

Result

random.random()

Float in [0.0, 1.0)

random.random()

0.7342…

random.randint(a, b)

Integer in [a, b] inclusive

random.randint(1, 6)

4

random.randrange(start, stop, step)

Random from range

random.randrange(0, 10, 2)

6

random.choice(seq)

Random element from sequence

random.choice([1,2,3])

2

random.choices(seq, k=n)

k random choices with replacement

random.choices('abc', k=3)

['b','a','b']

random.shuffle(lst)

Shuffle list in-place

random.shuffle([1,2,3])

[3,1,2]