- In Python, a module is a collection of definitions, functions, and statements that are organized together in a single file and can be used within other programs.
- Modules help organize your code into reusable and manageable parts, and can also provide access to a wide range of built-in functionality.
To use a module in your code, you need to first import it using the import
statement.
example of how you could use the math
module to perform some calculations in the context of a car:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import math # Calculating the fuel consumed by a car in liters fuel_consumed = 20 # Calculating the volume of the fuel tank in liters volume = 50 # Calculating the percentage of the fuel tank filled percent_filled = (fuel_consumed / volume) * 100 # Rounding the result to the nearest integer rounded_percent = round(percent_filled) # Calculating the square root of the volume square_root = math.sqrt(volume) # Printing the results print(f"Percent filled: {rounded_percent}%") print(f"Square root of volume: {square_root:.2f}") |
When run, the code outputs:
1 2 3 |
Percent filled: 40% Square root of volume: 7.07 |
You can also import specific definitions or functions from a module using the from ... import ...
statement. For example, if you only need the sqrt
function from the math
module, you can import it like this:
1 2 3 4 5 6 7 8 9 |
from math import sqrt # ... # Calculating the square root of the volume square_root = sqrt(volume) # ... |
As approached above, you don’t have to prefix the function with the module name every time you use it.