Python18 min read

Python Modules

Learn imports, aliases, and how to create your own module so projects stay clean and reusable.

Michael Brown
September 7, 2025
5.8k258

As soon as your code grows, one file becomes messy. Modules let you split code into multiple files and reuse functions cleanly.

## Import built-in modules

```python
import math

print(math.sqrt(16))
print(round(math.pi, 4))
```

Expected output:

```
4.0
3.1416
```

## Import specific items

```python
from math import sqrt, pi

print(sqrt(25))
print(pi)
```

Expected output:

```
5.0
3.141592653589793
```

## Aliases (common in real projects)

```python
import datetime as dt

now = dt.datetime.now()
print(now)
```

Expected output example:

```
2025-12-18 14:20:33.123456
```

## Create your own module

Create `mymodule.py`:

```python
def greet(name: str) -> str:
    return f"Hello {name} from Seattle!"

def add(a: int, b: int) -> int:
    return a + b
```

Create `main.py`:

```python
import mymodule

print(mymodule.greet("Tom"))
print(mymodule.add(5, 3))
```

Expected output:

```
Hello Tom from Seattle!
8
```

## Graph: import flow

```mermaid
flowchart LR
  A[main.py] --> B[import mymodule]
  B --> C[Python loads mymodule.py]
  C --> D[Functions ready]
  D --> E[Call functions]
```

In the next lesson, you will learn packages and virtual environments so each project can keep dependencies clean and avoid conflicts.
#Python#Intermediate#Modules