Modules in Python
A module in Python is a file containing Python definitions and statements. It allows you to organize your code into reusable components.
Syntax:
# Importing a module
import module_name
Example:
# math module
import math
print(math.sqrt(16)) # Output: 4.0
Importing Modules
Importing modules makes functions, variables, and classes defined in them available for use in your program.
Syntax:
import module_name
Example:
import math
print(math.pi) # Output: 3.141592653589793
What is a Custom Module?
A custom module is simply a Python file (ending in
.py
) that contains functions, variables, or classes that you create. This allows you to organize your code into separate files and reuse them easily.Steps to Create and Use a Custom Module:
1. Create a Python File (Module)
First, create a Python file (e.g., my_module.py
) where you define your functions or variables.
Example (my_module.py):
# This is the custom module (my_module.py)
def greet(name):
return f"Hello, {name}!" # Function to greet someone
def add(a, b):
return a + b # Function to add two numbers
2. Use the Custom Module in Another Python File
Now, you can use the functions or variables defined in my_module.py
by importing it into another Python file.
Example (main.py):
# Importing the custom module
import my_module
# Using the functions from the custom module
print(my_module.greet("Alice")) # Output: Hello, Alice!
print(my_module.add(5, 3)) # Output: 8
3. math Module
The math
module provides mathematical functions, like trigonometric operations, logarithmic functions, etc.
Syntax:
import math
Example:
import math
print(math.factorial(5)) # Output: 120
4. os Module
The os
module provides functions to interact with the operating system, like working with file systems, directories, and processes.
Syntax:
import os
Example:
import os
print(os.getcwd()) # Output: Current working directory
Output:
/path/to/your/directory
5. random Module
The random
module is used to generate random numbers, select random items from a list, and more.
Syntax:
import random
Example:
import random
print(random.randint(1, 10)) # Output: Random number between 1 and 10
Output:
0 Comments