Introduction
Python modules are like magic spell books for programmers. Instead of writing the same spells (code) over and over again, you can import them and use them whenever needed. Let’s dive into how to use modules effectively in Python!
Importing a Module
To use a module in Python, you need to import it first. Python has built-in modules, and you can also create your own.
import math
print(math.sqrt(25)) # Output: 5.0
Here, we imported the math
module and used its sqrt()
function to calculate the square root of 25.
Importing Specific Functions
If you only need a specific function from a module, you can import just that function.
from math import sqrt
print(sqrt(49)) # Output: 7.0
Now, you don’t have to write math.sqrt()
, just sqrt()
directly!
Giving a Module an Alias
Sometimes module names are long. You can rename them for convenience using as
.
import datetime as dt
print(dt.datetime.now()) # Prints the current date and time
Short and sweet!
Importing Everything from a Module
If you want to import all functions and variables from a module, use *
. Be careful, though—it can make debugging harder!
from math import *
print(pi) # Output: 3.141592653589793
This imports everything from math
, so you can use pi
directly.
Creating and Importing Your Own Module
You can create your own module by making a .py
file. Let’s create mymodule.py
:
# mymodule.py
def greet(name):
return f"Hello, {name}! Welcome to Python."
Now, import it into another script:
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice! Welcome to Python.
Finding Out What’s Inside a Module
Use dir()
to see all the functions and variables inside a module.
import math
print(dir(math)) # Shows everything inside the math module
Summary
Concept | Description |
---|---|
import module_name |
Imports an entire module |
from module import X |
Imports a specific function/variable |
import module as alias |
Renames a module while importing |
from module import * |
Imports everything from a module |
dir(module_name) |
Lists all available functions/variables |
Using modules makes Python programming simpler, cleaner, and more powerful!
0 Comments