Python Modules
Modules in Python are files that contain Python code, including variables, functions, and classes, that can be imported and used in other Python scripts. They allow you to organize your code into reusable components and avoid repetition. In this lesson, we will cover the basics of modules in Python and how to use them.
Importing Modules
To use a module in your Python script, you need to import it using the import
keyword. For example, to import the math
module:
import math
print(math.sqrt(16)) # Output: 4.0
Using Aliases
You can use aliases to refer to modules with a different name. This can be useful when working with modules with long names or to avoid naming conflicts. For example:
import math as m
print(m.sqrt(16)) # Output: 4.0
Importing Specific Items
You can also import specific items from a module using the from ... import
syntax. For example, to import only the sqrt
function from the math
module:
from math import sqrt
print(sqrt(16)) # Output: 4.0
Creating Your Own Modules
You can create your own modules by writing Python code in a file with a .py
extension. For example, you can create a module called my_module.py
with the following content:
# my_module.py
def greet(name):
print(f'Hello, {name}!')
You can then import and use this module in another Python script:
import my_module
my_module.greet('Alice') # Output: 'Hello, Alice!'
Conclusion
Modules in Python are a powerful way to organize and reuse code. By understanding how to import modules, use aliases, import specific items, and create your own modules, you can write more modular and maintainable Python code.