DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

Simple Python Library with Usage

Here's an example of a simple library that calculates the area and perimeter of a rectangle:

  1. Create a new Python module named rectangle.py.

  2. Write the following code inside rectangle.py:

def calculate_area(length, width):
    """Calculate the area of a rectangle."""
    return length * width

def calculate_perimeter(length, width):
    """Calculate the perimeter of a rectangle."""
    return 2 * (length + width)
Enter fullscreen mode Exit fullscreen mode
  1. Create another Python file named main.py to demonstrate how to use the library.

  2. Write the following code inside main.py:

# Importing the library module
import rectangle

# Using the library functions
length = 5
width = 3

area = rectangle.calculate_area(length, width)
perimeter = rectangle.calculate_perimeter(length, width)

print("Rectangle Area:", area)
print("Rectangle Perimeter:", perimeter)
Enter fullscreen mode Exit fullscreen mode
  1. Save both rectangle.py and main.py in the same directory.

  2. Run main.py using the Python interpreter:

$ python main.py
Enter fullscreen mode Exit fullscreen mode

Output:

Rectangle Area: 15
Rectangle Perimeter: 16
Enter fullscreen mode Exit fullscreen mode

In this example, we created a library module (rectangle.py) that defines two functions: calculate_area() and calculate_perimeter(). These functions perform calculations based on the given length and width of a rectangle.

In the main.py file, we imported the rectangle module and used its functions to calculate the area and perimeter of a rectangle with a length of 5 and width of 3. The results were then printed to the console.

By following this approach, you can create your own libraries/modules and import them into your code to reuse the defined functionality.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay