Python5 min read

Python Modules

Organize code using modules and imports.

Michael Brown
December 18, 2025
0.0k0

Organize code better.

Import Module

```python import math

print(math.sqrt(16)) # 4.0 print(math.pi) # 3.14159... ```

Import Specific Items

```python from math import sqrt, pi

print(sqrt(25)) # 5.0 print(pi) # 3.14159... ```

Import with Alias

```python import datetime as dt

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

Create Your Own Module

```python # File: mymodule.py def greet(name): return f"Hello {name} from Seattle!"

def add(a, b): return a + b

File: main.py import mymodule

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

Popular Built-in Modules

```python import random print(random.randint(1, 10))

import datetime print(datetime.date.today())

import os print(os.getcwd()) ```

Remember

- Keep related code in modules - Use descriptive module names - Import only what you need

#Python#Intermediate#Modules