Modules in Python are simply files with a .py extension that contain Python definitions and statements. Modules can define functions, classes, and variables. They allow us to organize and reuse code in a neat and efficient manner.
Imagine we have a file named math_operations.py with a few simple mathematical functions. It might look like this:
# math_operations.py
def add(x, y):
return x + y # Returns the sum of x and y
def subtract(x, y):
return x - y # Returns the difference of x and y
def multiply(x, y):
return x * y # Returns the product of x and y
def divide(x, y):
if y != 0: # Checks if y is not zero
return x / y # Returns the quotient of x and y
else:
return 'Division by zero is not allowed'
In another file (say main.py), we can use these functions by importing the math_operations module:
import math_operations # Imports the custom module
print(math_operations.add(2, 3)) # Calls the 'add' function from the module and prints 5
print(math_operations.subtract(7, 1)) # Calls the 'subtract' function from the module and prints 6
print(math_operations.multiply(4, 5)) # Calls the 'multiply' function from the module and prints 20
print(math_operations.divide(8, 2)) # Calls the 'divide' function from the module and prints 4
Or we can use the from ... import ... syntax instead. This can make your code cleaner because it eliminates the need to use the module name or alias as a prefix:
from math_operations import add, subtract
print(add(2, 3)) # Calls the 'add' function directly and prints 5
print(subtract(7, 1)) # Calls the 'subtract' function directly and prints 6
Creating and using custom modules help in making your code more readable and manageable, especially for large projects.
Challenge: Temperature Conversion
You are an intern at a weather agency and are tasked to develop a program to help meteorologists around the world convert temperatures with ease. Your assignment is to create a Python module named temperature that contains two functions: celsius2fahrenheit() and fahrenheit2celsius().
💡
Navigate to the PROJECT tab at the top of the page (next to the DESCRIPTION and SUBMISSIONS tabs) to create and edit files.
celsius2fahrenheit() should take a temperature in Celsius as input and convert it to Fahrenheit. fahrenheit2celsius() should take a temperature in Fahrenheit as input and convert it to Celsius. Each function should return the converted temperature.
The input and output are handled automatically by the main.py module.
Input
Output
C 0
32.00
F 32
0.00
C 100
212.00
F 212
100.00
Note: The formula for converting Celsius to Fahrenheit is (°C × 9/5) + 32, and the formula for converting Fahrenheit to Celsius is (°F - 32) × 5/9.