Python Lab · Experiment 26
Create a module of geometrical shapes and use it
PythonWeek 5JNTUH R22 · CS206ES
Aim
To write a Python module shapes.py whose functions find the area and perimeter of a circle, rectangle, square and triangle, and a main program that imports this module and uses its functions.
Algorithm
- Create a file
shapes.py. This file is the module. - In it, write one function for each operation: area and perimeter of a circle, rectangle, square and triangle, and a check for whether three sides can form a triangle.
- Add a test block under
if __name__ == "__main__":that runs only whenshapes.pyitself is run, not when it is imported. - In the main program (a separate file in the same folder), write
import shapes. - Call the module's functions with the module name in front, such as
shapes.circle_area(7), and print the results. - Import one function directly with
from shapes import square_areaand call it without the module name.
Program
# Main program. Save it in the same folder as shapes.py.
import shapes
from shapes import square_area
print("Module name:", shapes.__name__)
print("Module description:", shapes.__doc__)
radius = 7
print(f"\nCircle with radius {radius}")
print(f"Area = {shapes.circle_area(radius):.2f}")
print(f"Perimeter = {shapes.circle_perimeter(radius):.2f}")
length, width = 8, 5
print(f"\nRectangle {length} x {width}")
print("Area =", shapes.rectangle_area(length, width))
print("Perimeter =", shapes.rectangle_perimeter(length, width))
side = 4
print(f"\nSquare with side {side}")
print("Area =", square_area(side))
print("Perimeter =", shapes.square_perimeter(side))
for a, b, c in [(3, 4, 5), (1, 2, 5)]:
print(f"\nTriangle with sides {a}, {b}, {c}")
if shapes.is_triangle(a, b, c):
print(f"Area = {shapes.triangle_area(a, b, c):.2f}")
print("Perimeter =", shapes.triangle_perimeter(a, b, c))
else:
print("These sides cannot form a triangle")Output
"""Area and perimeter of common geometrical shapes."""
import math
def circle_area(radius):
return math.pi * radius ** 2
def circle_perimeter(radius):
return 2 * math.pi * radius
def rectangle_area(length, width):
return length * width
def rectangle_perimeter(length, width):
return 2 * (length + width)
def square_area(side):
return side * side
def square_perimeter(side):
return 4 * side
def is_triangle(a, b, c):
# Each side must be shorter than the sum of the other two
return a + b > c and b + c > a and a + c > b
def triangle_perimeter(a, b, c):
return a + b + c
def triangle_area(a, b, c):
# Heron's formula
s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))
if __name__ == "__main__":
# Runs only when this file is run directly, not on import
print("Testing shapes module")
print("Square of side 2 has area", square_area(2))Module name: shapes
Module description: Area and perimeter of common geometrical shapes.
Circle with radius 7
Area = 153.94
Perimeter = 43.98
Rectangle 8 x 5
Area = 40
Perimeter = 26
Square with side 4
Area = 16
Perimeter = 16
Triangle with sides 3, 4, 5
Area = 6.00
Perimeter = 12
Triangle with sides 1, 2, 5
These sides cannot form a triangleRecorded by running this exact program.
How it works
A module is simply a .py file. Any Python file can be imported by another file in the same folder, using its name without .py. To try this program, save the module as shapes.py (its code is shown under the run above) and the main program as, say, main.py in the same folder, then run python main.py.
When Python runs import shapes, it runs shapes.py once from top to bottom, which defines its functions. Inside the module, __name__ is "shapes", so the test block under if __name__ == "__main__": is skipped. That is why "Testing shapes module" does not appear in the output. If you run python shapes.py directly, __name__ is "__main__" and the test block runs.
The first string in the module is its docstring, which the main program prints as shapes.__doc__.
The triangle area uses Heron's formula: with s = (a + b + c) / 2, area = √(s(s − a)(s − b)(s − c)). For sides 3, 4 and 5, s = 6 and the area is √(6 × 3 × 2 × 1) = 6.
Common mistakes
Naming the module after a built-in or standard module, such as
math.pyorrandom.py. Python then imports your file instead of the real module, and other code breaks. Pick a unique name likeshapes.py.Keeping the module and the main program in different folders. Python looks for modules in the folder of the program being run (and its installed library folders), so
import shapesfails withModuleNotFoundError.Writing
import shapes.py. The import statement takes the module name without the.pyextension.Calling
circle_area(7)after onlyimport shapes. With a plain import, the function must be called asshapes.circle_area(7); to use the short name, writefrom shapes import circle_area.
Viva questions
Try to answer each one aloud before you open it.
What is a module in Python?
A module is a file containing Python code, such as functions, classes and variables, that other programs can import and reuse. The module name is the file name without
.py.What is the difference between import shapes and from shapes import square_area?
import shapesbrings in the module, and its functions are used asshapes.square_area().from shapes import square_areabrings that one name into the program, so it is called assquare_area().What is the use of if __name__ == "__main__"?
Code under it runs only when the file is run directly. When the file is imported as a module,
__name__is the module's name, so that code is skipped. It is used for tests and demos inside a module.Where does Python look for a module when you import it?
In the folders listed in
sys.path. The first is the folder of the program being run, followed by the standard library and installed package folders.What is the difference between a module and a package?
A module is a single
.pyfile. A package is a folder of modules, usually with an__init__.pyfile, imported with dotted names such aspackage.module.How can you see the names a module defines?
With
dir(shapes), which lists its functions, variables and the modules it imported.help(shapes)shows its docstrings.