Menu iconMenu iconPython Programming Unlocked for Beginners
Python Programming Unlocked for Beginners

Chapter 7: Modules and Packages

7.3: Creating Your Own Modules

In this section, we will discuss creating your own Python packages. A package is a collection of Python modules that are organized in a directory hierarchy. By creating your own packages, you can structure your code in a more organized and modular way, making it easier to maintain and share.

When creating your own package, it is important to consider the overall structure and organization of your modules. You may want to group related modules together into subpackages, or create a separate package for each major component of your code. This can help to keep your code organized and easy to navigate. 

Another important consideration when creating a package is how to properly document your code. This can include writing docstrings for your modules and functions, as well as creating a README file that explains how to use your package and any dependencies that it may have.

Once you have created your package, you can share it with others by uploading it to the Python Package Index (PyPI) or by making it available on GitHub. This can be a great way to contribute to the Python community and to showcase your coding skills. 

Overall, creating your own Python packages can be a valuable skill for any Python developer. By organizing your code in a more modular and maintainable way, you can improve the quality and reliability of your code, making it easier to build and maintain complex applications.

7.3.1: To create a Python package, follow these steps:

  1. Create a directory: Start by creating a new directory for your package. The directory's name should be descriptive of the package's functionality. For example, if you're creating a package for handling dates and times, you might name the directory datetime_utils.
  2. Add an __init__.py file: Inside the newly created directory, create a file named __init__.py. This file is required for Python to treat the directory as a package. The __init__.py file can be empty or contain package-level initialization code.
  3. Add modules: Inside the package directory, create Python files (with a .py extension) for each module you want to include in your package. These files will contain the functions, classes, and variables that you want to make available to users of your package. 
  4. Importing and using your package: To use your package in a Python script or another package, simply import it using the import statement. You can use the package name and the module name separated by a dot to import specific modules or objects from your package.

For example, let's create a package called datetime_utils that contains two modules: date_operations and time_operations.

  1. Create a directory named datetime_utils.
  2. Inside the datetime_utils directory, create an empty file named __init__.py.
  3. Create two Python files inside the datetime_utils directory: date_operations.py and time_operations.py.

date_operations.py:

def days_between_dates(date1, date2):
    delta = date2 - date1
    return delta.days

time_operations.py:

def seconds_between_times(time1, time2):
    delta = time2 - time1
    return delta.total_seconds()
  1. In another Python script, import and use the datetime_utils package:
from datetime import datetime
from datetime_utils import date_operations, time_operations

date1 = datetime(2022, 1, 1)
date2 = datetime(2022, 1, 10)

days = date_operations.days_between_dates(date1, date2)
print(f"Days between dates: {days}")

time1 = datetime(2022, 1, 1, 12, 0, 0)
time2 = datetime(2022, 1, 1, 14, 30, 0)

seconds = time_operations.seconds_between_times(time1, time2)
print(f"Seconds between times: {seconds}")

Output:

Days between dates: 9
Seconds between times: 9000.0

This is a basic example of creating a Python package. While this example is simple, it is important to note that creating more complex packages with nested directories and multiple modules is also possible. For instance, a package could contain sub-packages that correspond to different sections of an application, or modules that are designed to work together in a particular way. Additionally, there are many different ways that packages can be used, such as for creating reusable code libraries, distributing code to others, or simply for organizing code within a larger project. Therefore, it is important to consider the specific needs of your project when deciding how to structure your package.

Exercise 7.3.1: Creating a Simple Math Package

Create a package called simple_math that contains two modules: basic_operations and advanced_operations.

Instructions:

  1. Create a directory named simple_math and add an empty __init__.py file.
  2. Create a basic_operations.py module that contains the following functions: addsubtractmultiply, and divide.
  3. Create an advanced_operations.py module that contains the following functions: power and sqrt (square root).
  4. In a separate Python script, import and use the simple_math package to perform some calculations.

Solution:

simple_math/basic_operations.py:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        raise ValueError("Division by zero is not allowed")
    return x / y

simple_math/advanced_operations.py:

def power(x, y):
    return x ** y

def sqrt(x):
    if x < 0:
        raise ValueError("Square root of a negative number is not allowed")
    return x ** 0.5

main.py:

from simple_math import basic_operations, advanced_operations

print("Addition:", basic_operations.add(5, 3))
print("Subtraction:", basic_operations.subtract(5, 3))
print("Multiplication:", basic_operations.multiply(5, 3))
print("Division:", basic_operations.divide(5, 3))
print("Power:", advanced_operations.power(5, 3))
print("Square root:", advanced_operations.sqrt(9))

Output:

Addition: 8
Subtraction: 2
Multiplication: 15
Division: 1.6666666666666667
Power: 125
Square root: 3.0

Exercise 7.3.2: Creating a Text Processing Package

Description: Create a package called text_processing that contains a module called text_utils with the following functions: count_wordscount_characters, and average_word_length.

Instructions:

  1. Create a directory named text_processing and add an empty __init__.py file.
  2. Create a text_utils.py module with the specified functions.
  3. In a separate Python script, import and use the text_processing package to process a sample text.

Solution:

text_processing/text_utils.py:

def count_words(text):
    return len(text.split())

def count_characters(text):
    return len(text)

def average_word_length(text):
    words = text.split()
    total_characters = sum(len(word) for word in words)
    return total_characters / len(words)

main.py:

from text_processing import text_utils

sample_text = "This is a sample text for the text_processing package."

print("Word count:", text_utils.count_words(sample_text))
print("Character count:", text_utils.count_characters(sample_text))
print("Average word length:", text_utils.average_word_length(sample_text))

Output:

Word count: 9
Character count: 50
Average word length: 4.555555555555555

Exercise 7.3.3: Creating a Geometry Package

Create a package called geometry that contains a module called area_calculations with the following functions: rectangle_areatriangle_area, and circle_area.

Instructions:

  1. Create a directory named geometry and add an empty __init__.py file.
  2. Create an area_calculations.py module with the specified functions.
  3. In a separate Python script, import and use the geometry package to calculate the areas of different shapes.

Solution:

geometry/area_calculations.py:

import math

def rectangle_area(width, height):
    return width * height

def triangle_area(base, height):
    return 0.5 * base * height

def circle_area(radius):
    return math.pi * radius * radius

main.py:

from geometry import area_calculations

print("Rectangle area:", area_calculations.rectangle_area(5, 3))
print("Triangle area:", area_calculations.triangle_area(5, 3))
print("Circle area:", area_calculations.circle_area(5))

Output:

Rectangle area: 15
Triangle area: 7.5
Circle area: 78.53981633974483

7.3: Creating Your Own Modules

In this section, we will discuss creating your own Python packages. A package is a collection of Python modules that are organized in a directory hierarchy. By creating your own packages, you can structure your code in a more organized and modular way, making it easier to maintain and share.

When creating your own package, it is important to consider the overall structure and organization of your modules. You may want to group related modules together into subpackages, or create a separate package for each major component of your code. This can help to keep your code organized and easy to navigate. 

Another important consideration when creating a package is how to properly document your code. This can include writing docstrings for your modules and functions, as well as creating a README file that explains how to use your package and any dependencies that it may have.

Once you have created your package, you can share it with others by uploading it to the Python Package Index (PyPI) or by making it available on GitHub. This can be a great way to contribute to the Python community and to showcase your coding skills. 

Overall, creating your own Python packages can be a valuable skill for any Python developer. By organizing your code in a more modular and maintainable way, you can improve the quality and reliability of your code, making it easier to build and maintain complex applications.

7.3.1: To create a Python package, follow these steps:

  1. Create a directory: Start by creating a new directory for your package. The directory's name should be descriptive of the package's functionality. For example, if you're creating a package for handling dates and times, you might name the directory datetime_utils.
  2. Add an __init__.py file: Inside the newly created directory, create a file named __init__.py. This file is required for Python to treat the directory as a package. The __init__.py file can be empty or contain package-level initialization code.
  3. Add modules: Inside the package directory, create Python files (with a .py extension) for each module you want to include in your package. These files will contain the functions, classes, and variables that you want to make available to users of your package. 
  4. Importing and using your package: To use your package in a Python script or another package, simply import it using the import statement. You can use the package name and the module name separated by a dot to import specific modules or objects from your package.

For example, let's create a package called datetime_utils that contains two modules: date_operations and time_operations.

  1. Create a directory named datetime_utils.
  2. Inside the datetime_utils directory, create an empty file named __init__.py.
  3. Create two Python files inside the datetime_utils directory: date_operations.py and time_operations.py.

date_operations.py:

def days_between_dates(date1, date2):
    delta = date2 - date1
    return delta.days

time_operations.py:

def seconds_between_times(time1, time2):
    delta = time2 - time1
    return delta.total_seconds()
  1. In another Python script, import and use the datetime_utils package:
from datetime import datetime
from datetime_utils import date_operations, time_operations

date1 = datetime(2022, 1, 1)
date2 = datetime(2022, 1, 10)

days = date_operations.days_between_dates(date1, date2)
print(f"Days between dates: {days}")

time1 = datetime(2022, 1, 1, 12, 0, 0)
time2 = datetime(2022, 1, 1, 14, 30, 0)

seconds = time_operations.seconds_between_times(time1, time2)
print(f"Seconds between times: {seconds}")

Output:

Days between dates: 9
Seconds between times: 9000.0

This is a basic example of creating a Python package. While this example is simple, it is important to note that creating more complex packages with nested directories and multiple modules is also possible. For instance, a package could contain sub-packages that correspond to different sections of an application, or modules that are designed to work together in a particular way. Additionally, there are many different ways that packages can be used, such as for creating reusable code libraries, distributing code to others, or simply for organizing code within a larger project. Therefore, it is important to consider the specific needs of your project when deciding how to structure your package.

Exercise 7.3.1: Creating a Simple Math Package

Create a package called simple_math that contains two modules: basic_operations and advanced_operations.

Instructions:

  1. Create a directory named simple_math and add an empty __init__.py file.
  2. Create a basic_operations.py module that contains the following functions: addsubtractmultiply, and divide.
  3. Create an advanced_operations.py module that contains the following functions: power and sqrt (square root).
  4. In a separate Python script, import and use the simple_math package to perform some calculations.

Solution:

simple_math/basic_operations.py:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        raise ValueError("Division by zero is not allowed")
    return x / y

simple_math/advanced_operations.py:

def power(x, y):
    return x ** y

def sqrt(x):
    if x < 0:
        raise ValueError("Square root of a negative number is not allowed")
    return x ** 0.5

main.py:

from simple_math import basic_operations, advanced_operations

print("Addition:", basic_operations.add(5, 3))
print("Subtraction:", basic_operations.subtract(5, 3))
print("Multiplication:", basic_operations.multiply(5, 3))
print("Division:", basic_operations.divide(5, 3))
print("Power:", advanced_operations.power(5, 3))
print("Square root:", advanced_operations.sqrt(9))

Output:

Addition: 8
Subtraction: 2
Multiplication: 15
Division: 1.6666666666666667
Power: 125
Square root: 3.0

Exercise 7.3.2: Creating a Text Processing Package

Description: Create a package called text_processing that contains a module called text_utils with the following functions: count_wordscount_characters, and average_word_length.

Instructions:

  1. Create a directory named text_processing and add an empty __init__.py file.
  2. Create a text_utils.py module with the specified functions.
  3. In a separate Python script, import and use the text_processing package to process a sample text.

Solution:

text_processing/text_utils.py:

def count_words(text):
    return len(text.split())

def count_characters(text):
    return len(text)

def average_word_length(text):
    words = text.split()
    total_characters = sum(len(word) for word in words)
    return total_characters / len(words)

main.py:

from text_processing import text_utils

sample_text = "This is a sample text for the text_processing package."

print("Word count:", text_utils.count_words(sample_text))
print("Character count:", text_utils.count_characters(sample_text))
print("Average word length:", text_utils.average_word_length(sample_text))

Output:

Word count: 9
Character count: 50
Average word length: 4.555555555555555

Exercise 7.3.3: Creating a Geometry Package

Create a package called geometry that contains a module called area_calculations with the following functions: rectangle_areatriangle_area, and circle_area.

Instructions:

  1. Create a directory named geometry and add an empty __init__.py file.
  2. Create an area_calculations.py module with the specified functions.
  3. In a separate Python script, import and use the geometry package to calculate the areas of different shapes.

Solution:

geometry/area_calculations.py:

import math

def rectangle_area(width, height):
    return width * height

def triangle_area(base, height):
    return 0.5 * base * height

def circle_area(radius):
    return math.pi * radius * radius

main.py:

from geometry import area_calculations

print("Rectangle area:", area_calculations.rectangle_area(5, 3))
print("Triangle area:", area_calculations.triangle_area(5, 3))
print("Circle area:", area_calculations.circle_area(5))

Output:

Rectangle area: 15
Triangle area: 7.5
Circle area: 78.53981633974483

7.3: Creating Your Own Modules

In this section, we will discuss creating your own Python packages. A package is a collection of Python modules that are organized in a directory hierarchy. By creating your own packages, you can structure your code in a more organized and modular way, making it easier to maintain and share.

When creating your own package, it is important to consider the overall structure and organization of your modules. You may want to group related modules together into subpackages, or create a separate package for each major component of your code. This can help to keep your code organized and easy to navigate. 

Another important consideration when creating a package is how to properly document your code. This can include writing docstrings for your modules and functions, as well as creating a README file that explains how to use your package and any dependencies that it may have.

Once you have created your package, you can share it with others by uploading it to the Python Package Index (PyPI) or by making it available on GitHub. This can be a great way to contribute to the Python community and to showcase your coding skills. 

Overall, creating your own Python packages can be a valuable skill for any Python developer. By organizing your code in a more modular and maintainable way, you can improve the quality and reliability of your code, making it easier to build and maintain complex applications.

7.3.1: To create a Python package, follow these steps:

  1. Create a directory: Start by creating a new directory for your package. The directory's name should be descriptive of the package's functionality. For example, if you're creating a package for handling dates and times, you might name the directory datetime_utils.
  2. Add an __init__.py file: Inside the newly created directory, create a file named __init__.py. This file is required for Python to treat the directory as a package. The __init__.py file can be empty or contain package-level initialization code.
  3. Add modules: Inside the package directory, create Python files (with a .py extension) for each module you want to include in your package. These files will contain the functions, classes, and variables that you want to make available to users of your package. 
  4. Importing and using your package: To use your package in a Python script or another package, simply import it using the import statement. You can use the package name and the module name separated by a dot to import specific modules or objects from your package.

For example, let's create a package called datetime_utils that contains two modules: date_operations and time_operations.

  1. Create a directory named datetime_utils.
  2. Inside the datetime_utils directory, create an empty file named __init__.py.
  3. Create two Python files inside the datetime_utils directory: date_operations.py and time_operations.py.

date_operations.py:

def days_between_dates(date1, date2):
    delta = date2 - date1
    return delta.days

time_operations.py:

def seconds_between_times(time1, time2):
    delta = time2 - time1
    return delta.total_seconds()
  1. In another Python script, import and use the datetime_utils package:
from datetime import datetime
from datetime_utils import date_operations, time_operations

date1 = datetime(2022, 1, 1)
date2 = datetime(2022, 1, 10)

days = date_operations.days_between_dates(date1, date2)
print(f"Days between dates: {days}")

time1 = datetime(2022, 1, 1, 12, 0, 0)
time2 = datetime(2022, 1, 1, 14, 30, 0)

seconds = time_operations.seconds_between_times(time1, time2)
print(f"Seconds between times: {seconds}")

Output:

Days between dates: 9
Seconds between times: 9000.0

This is a basic example of creating a Python package. While this example is simple, it is important to note that creating more complex packages with nested directories and multiple modules is also possible. For instance, a package could contain sub-packages that correspond to different sections of an application, or modules that are designed to work together in a particular way. Additionally, there are many different ways that packages can be used, such as for creating reusable code libraries, distributing code to others, or simply for organizing code within a larger project. Therefore, it is important to consider the specific needs of your project when deciding how to structure your package.

Exercise 7.3.1: Creating a Simple Math Package

Create a package called simple_math that contains two modules: basic_operations and advanced_operations.

Instructions:

  1. Create a directory named simple_math and add an empty __init__.py file.
  2. Create a basic_operations.py module that contains the following functions: addsubtractmultiply, and divide.
  3. Create an advanced_operations.py module that contains the following functions: power and sqrt (square root).
  4. In a separate Python script, import and use the simple_math package to perform some calculations.

Solution:

simple_math/basic_operations.py:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        raise ValueError("Division by zero is not allowed")
    return x / y

simple_math/advanced_operations.py:

def power(x, y):
    return x ** y

def sqrt(x):
    if x < 0:
        raise ValueError("Square root of a negative number is not allowed")
    return x ** 0.5

main.py:

from simple_math import basic_operations, advanced_operations

print("Addition:", basic_operations.add(5, 3))
print("Subtraction:", basic_operations.subtract(5, 3))
print("Multiplication:", basic_operations.multiply(5, 3))
print("Division:", basic_operations.divide(5, 3))
print("Power:", advanced_operations.power(5, 3))
print("Square root:", advanced_operations.sqrt(9))

Output:

Addition: 8
Subtraction: 2
Multiplication: 15
Division: 1.6666666666666667
Power: 125
Square root: 3.0

Exercise 7.3.2: Creating a Text Processing Package

Description: Create a package called text_processing that contains a module called text_utils with the following functions: count_wordscount_characters, and average_word_length.

Instructions:

  1. Create a directory named text_processing and add an empty __init__.py file.
  2. Create a text_utils.py module with the specified functions.
  3. In a separate Python script, import and use the text_processing package to process a sample text.

Solution:

text_processing/text_utils.py:

def count_words(text):
    return len(text.split())

def count_characters(text):
    return len(text)

def average_word_length(text):
    words = text.split()
    total_characters = sum(len(word) for word in words)
    return total_characters / len(words)

main.py:

from text_processing import text_utils

sample_text = "This is a sample text for the text_processing package."

print("Word count:", text_utils.count_words(sample_text))
print("Character count:", text_utils.count_characters(sample_text))
print("Average word length:", text_utils.average_word_length(sample_text))

Output:

Word count: 9
Character count: 50
Average word length: 4.555555555555555

Exercise 7.3.3: Creating a Geometry Package

Create a package called geometry that contains a module called area_calculations with the following functions: rectangle_areatriangle_area, and circle_area.

Instructions:

  1. Create a directory named geometry and add an empty __init__.py file.
  2. Create an area_calculations.py module with the specified functions.
  3. In a separate Python script, import and use the geometry package to calculate the areas of different shapes.

Solution:

geometry/area_calculations.py:

import math

def rectangle_area(width, height):
    return width * height

def triangle_area(base, height):
    return 0.5 * base * height

def circle_area(radius):
    return math.pi * radius * radius

main.py:

from geometry import area_calculations

print("Rectangle area:", area_calculations.rectangle_area(5, 3))
print("Triangle area:", area_calculations.triangle_area(5, 3))
print("Circle area:", area_calculations.circle_area(5))

Output:

Rectangle area: 15
Triangle area: 7.5
Circle area: 78.53981633974483

7.3: Creating Your Own Modules

In this section, we will discuss creating your own Python packages. A package is a collection of Python modules that are organized in a directory hierarchy. By creating your own packages, you can structure your code in a more organized and modular way, making it easier to maintain and share.

When creating your own package, it is important to consider the overall structure and organization of your modules. You may want to group related modules together into subpackages, or create a separate package for each major component of your code. This can help to keep your code organized and easy to navigate. 

Another important consideration when creating a package is how to properly document your code. This can include writing docstrings for your modules and functions, as well as creating a README file that explains how to use your package and any dependencies that it may have.

Once you have created your package, you can share it with others by uploading it to the Python Package Index (PyPI) or by making it available on GitHub. This can be a great way to contribute to the Python community and to showcase your coding skills. 

Overall, creating your own Python packages can be a valuable skill for any Python developer. By organizing your code in a more modular and maintainable way, you can improve the quality and reliability of your code, making it easier to build and maintain complex applications.

7.3.1: To create a Python package, follow these steps:

  1. Create a directory: Start by creating a new directory for your package. The directory's name should be descriptive of the package's functionality. For example, if you're creating a package for handling dates and times, you might name the directory datetime_utils.
  2. Add an __init__.py file: Inside the newly created directory, create a file named __init__.py. This file is required for Python to treat the directory as a package. The __init__.py file can be empty or contain package-level initialization code.
  3. Add modules: Inside the package directory, create Python files (with a .py extension) for each module you want to include in your package. These files will contain the functions, classes, and variables that you want to make available to users of your package. 
  4. Importing and using your package: To use your package in a Python script or another package, simply import it using the import statement. You can use the package name and the module name separated by a dot to import specific modules or objects from your package.

For example, let's create a package called datetime_utils that contains two modules: date_operations and time_operations.

  1. Create a directory named datetime_utils.
  2. Inside the datetime_utils directory, create an empty file named __init__.py.
  3. Create two Python files inside the datetime_utils directory: date_operations.py and time_operations.py.

date_operations.py:

def days_between_dates(date1, date2):
    delta = date2 - date1
    return delta.days

time_operations.py:

def seconds_between_times(time1, time2):
    delta = time2 - time1
    return delta.total_seconds()
  1. In another Python script, import and use the datetime_utils package:
from datetime import datetime
from datetime_utils import date_operations, time_operations

date1 = datetime(2022, 1, 1)
date2 = datetime(2022, 1, 10)

days = date_operations.days_between_dates(date1, date2)
print(f"Days between dates: {days}")

time1 = datetime(2022, 1, 1, 12, 0, 0)
time2 = datetime(2022, 1, 1, 14, 30, 0)

seconds = time_operations.seconds_between_times(time1, time2)
print(f"Seconds between times: {seconds}")

Output:

Days between dates: 9
Seconds between times: 9000.0

This is a basic example of creating a Python package. While this example is simple, it is important to note that creating more complex packages with nested directories and multiple modules is also possible. For instance, a package could contain sub-packages that correspond to different sections of an application, or modules that are designed to work together in a particular way. Additionally, there are many different ways that packages can be used, such as for creating reusable code libraries, distributing code to others, or simply for organizing code within a larger project. Therefore, it is important to consider the specific needs of your project when deciding how to structure your package.

Exercise 7.3.1: Creating a Simple Math Package

Create a package called simple_math that contains two modules: basic_operations and advanced_operations.

Instructions:

  1. Create a directory named simple_math and add an empty __init__.py file.
  2. Create a basic_operations.py module that contains the following functions: addsubtractmultiply, and divide.
  3. Create an advanced_operations.py module that contains the following functions: power and sqrt (square root).
  4. In a separate Python script, import and use the simple_math package to perform some calculations.

Solution:

simple_math/basic_operations.py:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        raise ValueError("Division by zero is not allowed")
    return x / y

simple_math/advanced_operations.py:

def power(x, y):
    return x ** y

def sqrt(x):
    if x < 0:
        raise ValueError("Square root of a negative number is not allowed")
    return x ** 0.5

main.py:

from simple_math import basic_operations, advanced_operations

print("Addition:", basic_operations.add(5, 3))
print("Subtraction:", basic_operations.subtract(5, 3))
print("Multiplication:", basic_operations.multiply(5, 3))
print("Division:", basic_operations.divide(5, 3))
print("Power:", advanced_operations.power(5, 3))
print("Square root:", advanced_operations.sqrt(9))

Output:

Addition: 8
Subtraction: 2
Multiplication: 15
Division: 1.6666666666666667
Power: 125
Square root: 3.0

Exercise 7.3.2: Creating a Text Processing Package

Description: Create a package called text_processing that contains a module called text_utils with the following functions: count_wordscount_characters, and average_word_length.

Instructions:

  1. Create a directory named text_processing and add an empty __init__.py file.
  2. Create a text_utils.py module with the specified functions.
  3. In a separate Python script, import and use the text_processing package to process a sample text.

Solution:

text_processing/text_utils.py:

def count_words(text):
    return len(text.split())

def count_characters(text):
    return len(text)

def average_word_length(text):
    words = text.split()
    total_characters = sum(len(word) for word in words)
    return total_characters / len(words)

main.py:

from text_processing import text_utils

sample_text = "This is a sample text for the text_processing package."

print("Word count:", text_utils.count_words(sample_text))
print("Character count:", text_utils.count_characters(sample_text))
print("Average word length:", text_utils.average_word_length(sample_text))

Output:

Word count: 9
Character count: 50
Average word length: 4.555555555555555

Exercise 7.3.3: Creating a Geometry Package

Create a package called geometry that contains a module called area_calculations with the following functions: rectangle_areatriangle_area, and circle_area.

Instructions:

  1. Create a directory named geometry and add an empty __init__.py file.
  2. Create an area_calculations.py module with the specified functions.
  3. In a separate Python script, import and use the geometry package to calculate the areas of different shapes.

Solution:

geometry/area_calculations.py:

import math

def rectangle_area(width, height):
    return width * height

def triangle_area(base, height):
    return 0.5 * base * height

def circle_area(radius):
    return math.pi * radius * radius

main.py:

from geometry import area_calculations

print("Rectangle area:", area_calculations.rectangle_area(5, 3))
print("Triangle area:", area_calculations.triangle_area(5, 3))
print("Circle area:", area_calculations.circle_area(5))

Output:

Rectangle area: 15
Triangle area: 7.5
Circle area: 78.53981633974483