Python Documentation

Modules

Modules in Python

Modules in Python are files containing Python definitions and statements. They allow you to organize and reuse code across different programs.

Importing Modules

You can import modules using the import statement.

import module_name

from module_name import function_name

from module_name import *

Creating Modules

You can create your own modules by saving Python code in a .py file.

def greet(name):
ㅤㅤreturn f"Hello, {name}!"

def farewell(name):
ㅤㅤreturn f"Goodbye, {name}!"

Using Modules

After importing a module, you can use its functions and variables.

import my_module

print(my_module.greet("Alice"))
print(my_module.farewell("Bob"))

Built-in Modules

Python comes with many built-in modules that provide additional functionality.

import math

print(math.pi)
print(math.sqrt(16))

The dir() Function

The dir() function can be used to find out which names a module defines.

import math

print(dir(math))

Modules are a powerful way to organize and reuse code in Python. They help in maintaining large codebases and promote code reusability.