Introduction to Modules and Types

Python tutorial · PySpark.in

What is a Module?

A module is a single Python file (.py) that contains code such as:

You can import modules and use their functionality in any Python program.

Module means reusable code written in a single Python file

Why Do We Use Modules?

Code reuse Better organization
Avoid rewriting functions again
Easy maintenance
Useful for large projects

Example benefits:

Types of Modules

Python modules are divided into two categories:

A. Built-in Modules

These modules come pre-installed with Python. No installation is needed.

Examples:

Module

Purpose

math

mathematical functions

random

random number generation

datetime

date and time

os

operating system functions

sys

system-level operations

statistics

statistical calculations

json

JSON handling

Built-in Module Example: math

```

import math

print(math.sqrt(25)) # square root

print(math.pi) # pi value

print(math.factorial(5)) # factorial

print(math.sin(0)) # sine

```

Built-in Module Example: datetime

```

import datetime

now = datetime.datetime.now()

print(now)

print(now.year)

print(now.month)

print(now.day)

```

Built-in Module Example: random

```

import random

print(random.randint(1, 100))

print(random.choice([10, 20, 30, 40]))

```

B. User-Defined Modules

These are modules created by the programmer. You create a .py file and reuse it in other Python files.

Example 1: Creating a User-Defined Module

File: mymodule.py

```

Hide

def greet():

return "Hello from module!"

def add(a, b):

return a + b

```

File: main.py

```

hide

import mymodule

print(mymodule.greet())

print(mymodule.add(10, 20))

```

Example 2: Importing specific functions

mymath.py

```

Hide

def square(x):

return x * x

def cube(x):

return x * x * x

```

main.py

```

hide

from mymath import square, cube

print(square(4))

print(cube(2))

```

How to Import Modules

Method 1: import module_name

```

import math

print(math.sqrt(9))

```

Method 2: import module as alias

```

import math as m

print(m.sqrt(16))

```

Method 3: from module import function

```

import math

from math import sqrt

print(sqrt(25))

```

Method 4: from module import * (import all)

```

from math import *

print(pi)

print(sqrt(36))

```

Not recommended for large programs
(Easy to create conflicts)

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges