About Lesson
Importing and Using Modules
- Definition: A module is a file containing Python code (functions, classes, variables) that can be imported and used in other Python programs.
- Built-in Modules: Python comes with a standard library of modules (e.g.,
math
,os
,sys
). pythonimport math print(math.sqrt(16)) # Output: 4.0
- Importing Modules:
- Entire Module:
import module_name
- Specific Function/Class:
from module_name import function_name
- Alias:
import module_name as alias
python
from math import sqrt print(sqrt(16)) # Output: 4.0 import math as m print(m.sqrt(16)) # Output: 4.0
- Entire Module:
Creating Your Own Modules
- Definition: Custom modules can be created by saving Python code in a
.py
file and importing it into other programs. - Example:
-
Create a module (
my_module.py
):
pythondef greet(name): return f"Hello, {name}!"
-
Import and use the module:
pythonimport my_module print(my_module.greet("Alice")) # Output: Hello, Alice!
-