Code icon

The App is Under a Quick Maintenance

We apologize for the inconvenience. Please come back later

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

Chapter 7: Modules and Packages

7.2: Standard Library Modules

In this section, we will delve into the Python Standard Library, which is a set of pre-installed modules that offer a wide range of functionalities. These modules are useful for performing various tasks without the need for third-party libraries. They can be used to work with the file system, interact with the internet, manipulate data, and much more. 

The Python Standard Library is an essential tool for any Python programmer. It includes modules for working with regular expressions, cryptography, network programming, and more. One of the most commonly used modules is the os module, which provides a way to interact with the file system. You can use this module to create, delete, or modify files and directories, as well as to navigate the file system.

Another commonly used module is the urllib module, which provides a way to interact with the internet. You can use this module to download web pages, send HTTP requests, and more. The urllib module is particularly useful for web scraping and data analysis tasks. 

In addition to these commonly used modules, the Python Standard Library includes modules for working with dates and times, parsing XML, and more. These modules can be used to perform a wide range of tasks, from simple file management to complex data analysis.

Here are a few essential standard library modules that you may find useful:

7.2.1: os

The os module provides a way to interact with the operating system. It allows you to perform file and directory operations, such as creating, renaming, or deleting files and directories. Additionally, you can retrieve information about the system, like the environment variables or the current working directory.

Example:

import os 

# Get the current working directory
current_directory = os.getcwd()
print(current_directory)

7.2.2: sys

The sys module provides access to some variables used or maintained by the interpreter and functions that interact with the interpreter. For example, you can use it to access command-line arguments or manipulate the Python path.

Example:

import sys

# Print the Python version
print(sys.version)

7.2.3: re

The re module provides support for regular expressions, which are a powerful tool for text processing. You can use them to search, match, or substitute specific patterns in strings.

Example:

import re

text = "Hello, my name is John Doe"
pattern = r"\b\w{4}\b"

four_letter_words = re.findall(pattern, text)
print(four_letter_words)

7.2.4: json

The json module allows you to work with JSON data by encoding and decoding JSON strings. You can use this module to read and write JSON data to and from files, as well as to convert JSON data to Python objects and vice versa.

Example:

import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert the Python dictionary to a JSON string
json_data = json.dumps(data)
print(json_data)

7.2.5: urllib

The urllib module is a part of Python's standard library and is used for working with URLs. It provides various functions to interact with URLs and fetch data from the internet. The urllib module is further divided into several sub-modules, such as urllib.requesturllib.parse, and urllib.error.

Here's a brief explanation of the most commonly used sub-modules:

  1. urllib.request: This sub-module provides functions to open and read URLs. The most common method is urlopen, which can be used to fetch data from a URL.

Example:

import urllib.request

url = "https://www.example.com"
response = urllib.request.urlopen(url)
content = response.read()

print(content)
  1. urllib.parse: This sub-module contains functions to manipulate and parse URLs, such as splitting a URL into its components or encoding/decoding query parameters.

Example:

from urllib.parse import urlparse, urlencode

url = "https://www.example.com/search?q=python+programming"

# Parse the URL into components
parsed_url = urlparse(url)
print(parsed_url)

# Encode query parameters
query_params = {"q": "python programming", "page": 2}
encoded_params = urlencode(query_params)
print(encoded_params)
  1. urllib.error: This sub-module defines exception classes for handling errors that may occur during URL handling, such as HTTP errors or network-related issues. Some common exceptions are URLError and HTTPError.

Example:

import urllib.request
from urllib.error import URLError, HTTPError

url = "https://www.nonexistentwebsite.com"

try:
    response = urllib.request.urlopen(url)
except HTTPError as e:
    print(f"HTTP error occurred: {e}")
except URLError as e:
    print(f"URL error occurred: {e}")

These sub-modules combined offer a powerful way to interact with the internet and manipulate URLs. However, in many cases, developers prefer to use the third-party library requests for making HTTP requests, as it offers a more user-friendly API and additional features. If you're interested, you can learn more about the requests library here: https://docs.python-requests.org/en/master/

These are just a few examples of the many standard library modules available in Python. To explore more modules and learn about their functionalities, refer to the Python documentation: https://docs.python.org/3/library/

Exercise 7.2.1: Create a Simple Module

In this exercise, you will create a simple module that contains a function to calculate the area of a rectangle.

Instructions:

  1. Create a new Python file called geometry.py.
  2. Define a function named rectangle_area that takes two arguments: length and width.
  3. The function should return the product of length and width.
  4. Import the geometry module in another Python script and use the rectangle_area function.

Solution:

  1. Create geometry.py:
def rectangle_area(length, width):
    return length * width
  1. In another Python script, import the geometry module and use the rectangle_area function:
import geometry

area = geometry.rectangle_area(5, 10)
print(f"Area of the rectangle: {area}")

Output:

Area of the rectangle: 50

Exercise 7.2.2: Create a Custom Text Manipulation Module

Create a custom module called text_manipulation that contains functions for converting a string to uppercase, lowercase, and title case.

Instructions:

  1. Create a Python file called text_manipulation.py.
  2. Define three functions: to_upperto_lower, and to_title.
  3. Each function should take a single argument, a string, and return the modified string.
  4. Import the text_manipulation module in another Python script and use the functions.

Solution:

  1. Create text_manipulation.py:
def to_upper(text):
    return text.upper()

def to_lower(text):
    return text.lower()

def to_title(text):
    return text.title()
  1. In another Python script, import the text_manipulation module and use the functions:
import text_manipulation

text = "this is a sample text"

upper_text = text_manipulation.to_upper(text)
print(f"Uppercase: {upper_text}")

lower_text = text_manipulation.to_lower(text)
print(f"Lowercase: {lower_text}")

title_text = text_manipulation.to_title(text)
print(f"Title case: {title_text}")

Output:

Uppercase: THIS IS A SAMPLE TEXT
Lowercase: this is a sample text
Title case: This Is A Sample Text

Exercise 7.2.3: Create a Module with Constants

In this exercise, you will create a module called constants that contains a few mathematical constants.

Instructions:

  1. Create a Python file called constants.py.
  2. Define variables for the following constants: PIE, and GOLDEN_RATIO.
  3. Import the constants module in another Python script and use the constants.

Solution:

  1. Create constants.py:
PI = 3.141592653589793
E = 2.718281828459045
GOLDEN_RATIO = 1.618033988749895
  1. In another Python script, import the constants module and use the constants:
import constants

print(f"PI: {constants.PI}")
print(f"E: {constants.E}")
print(f"Golden Ratio: {constants.GOLDEN_RATIO}")

Output:

PI: 3.141592653589793
E: 2.718281828459045
Golden Ratio: 1.

7.2: Standard Library Modules

In this section, we will delve into the Python Standard Library, which is a set of pre-installed modules that offer a wide range of functionalities. These modules are useful for performing various tasks without the need for third-party libraries. They can be used to work with the file system, interact with the internet, manipulate data, and much more. 

The Python Standard Library is an essential tool for any Python programmer. It includes modules for working with regular expressions, cryptography, network programming, and more. One of the most commonly used modules is the os module, which provides a way to interact with the file system. You can use this module to create, delete, or modify files and directories, as well as to navigate the file system.

Another commonly used module is the urllib module, which provides a way to interact with the internet. You can use this module to download web pages, send HTTP requests, and more. The urllib module is particularly useful for web scraping and data analysis tasks. 

In addition to these commonly used modules, the Python Standard Library includes modules for working with dates and times, parsing XML, and more. These modules can be used to perform a wide range of tasks, from simple file management to complex data analysis.

Here are a few essential standard library modules that you may find useful:

7.2.1: os

The os module provides a way to interact with the operating system. It allows you to perform file and directory operations, such as creating, renaming, or deleting files and directories. Additionally, you can retrieve information about the system, like the environment variables or the current working directory.

Example:

import os 

# Get the current working directory
current_directory = os.getcwd()
print(current_directory)

7.2.2: sys

The sys module provides access to some variables used or maintained by the interpreter and functions that interact with the interpreter. For example, you can use it to access command-line arguments or manipulate the Python path.

Example:

import sys

# Print the Python version
print(sys.version)

7.2.3: re

The re module provides support for regular expressions, which are a powerful tool for text processing. You can use them to search, match, or substitute specific patterns in strings.

Example:

import re

text = "Hello, my name is John Doe"
pattern = r"\b\w{4}\b"

four_letter_words = re.findall(pattern, text)
print(four_letter_words)

7.2.4: json

The json module allows you to work with JSON data by encoding and decoding JSON strings. You can use this module to read and write JSON data to and from files, as well as to convert JSON data to Python objects and vice versa.

Example:

import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert the Python dictionary to a JSON string
json_data = json.dumps(data)
print(json_data)

7.2.5: urllib

The urllib module is a part of Python's standard library and is used for working with URLs. It provides various functions to interact with URLs and fetch data from the internet. The urllib module is further divided into several sub-modules, such as urllib.requesturllib.parse, and urllib.error.

Here's a brief explanation of the most commonly used sub-modules:

  1. urllib.request: This sub-module provides functions to open and read URLs. The most common method is urlopen, which can be used to fetch data from a URL.

Example:

import urllib.request

url = "https://www.example.com"
response = urllib.request.urlopen(url)
content = response.read()

print(content)
  1. urllib.parse: This sub-module contains functions to manipulate and parse URLs, such as splitting a URL into its components or encoding/decoding query parameters.

Example:

from urllib.parse import urlparse, urlencode

url = "https://www.example.com/search?q=python+programming"

# Parse the URL into components
parsed_url = urlparse(url)
print(parsed_url)

# Encode query parameters
query_params = {"q": "python programming", "page": 2}
encoded_params = urlencode(query_params)
print(encoded_params)
  1. urllib.error: This sub-module defines exception classes for handling errors that may occur during URL handling, such as HTTP errors or network-related issues. Some common exceptions are URLError and HTTPError.

Example:

import urllib.request
from urllib.error import URLError, HTTPError

url = "https://www.nonexistentwebsite.com"

try:
    response = urllib.request.urlopen(url)
except HTTPError as e:
    print(f"HTTP error occurred: {e}")
except URLError as e:
    print(f"URL error occurred: {e}")

These sub-modules combined offer a powerful way to interact with the internet and manipulate URLs. However, in many cases, developers prefer to use the third-party library requests for making HTTP requests, as it offers a more user-friendly API and additional features. If you're interested, you can learn more about the requests library here: https://docs.python-requests.org/en/master/

These are just a few examples of the many standard library modules available in Python. To explore more modules and learn about their functionalities, refer to the Python documentation: https://docs.python.org/3/library/

Exercise 7.2.1: Create a Simple Module

In this exercise, you will create a simple module that contains a function to calculate the area of a rectangle.

Instructions:

  1. Create a new Python file called geometry.py.
  2. Define a function named rectangle_area that takes two arguments: length and width.
  3. The function should return the product of length and width.
  4. Import the geometry module in another Python script and use the rectangle_area function.

Solution:

  1. Create geometry.py:
def rectangle_area(length, width):
    return length * width
  1. In another Python script, import the geometry module and use the rectangle_area function:
import geometry

area = geometry.rectangle_area(5, 10)
print(f"Area of the rectangle: {area}")

Output:

Area of the rectangle: 50

Exercise 7.2.2: Create a Custom Text Manipulation Module

Create a custom module called text_manipulation that contains functions for converting a string to uppercase, lowercase, and title case.

Instructions:

  1. Create a Python file called text_manipulation.py.
  2. Define three functions: to_upperto_lower, and to_title.
  3. Each function should take a single argument, a string, and return the modified string.
  4. Import the text_manipulation module in another Python script and use the functions.

Solution:

  1. Create text_manipulation.py:
def to_upper(text):
    return text.upper()

def to_lower(text):
    return text.lower()

def to_title(text):
    return text.title()
  1. In another Python script, import the text_manipulation module and use the functions:
import text_manipulation

text = "this is a sample text"

upper_text = text_manipulation.to_upper(text)
print(f"Uppercase: {upper_text}")

lower_text = text_manipulation.to_lower(text)
print(f"Lowercase: {lower_text}")

title_text = text_manipulation.to_title(text)
print(f"Title case: {title_text}")

Output:

Uppercase: THIS IS A SAMPLE TEXT
Lowercase: this is a sample text
Title case: This Is A Sample Text

Exercise 7.2.3: Create a Module with Constants

In this exercise, you will create a module called constants that contains a few mathematical constants.

Instructions:

  1. Create a Python file called constants.py.
  2. Define variables for the following constants: PIE, and GOLDEN_RATIO.
  3. Import the constants module in another Python script and use the constants.

Solution:

  1. Create constants.py:
PI = 3.141592653589793
E = 2.718281828459045
GOLDEN_RATIO = 1.618033988749895
  1. In another Python script, import the constants module and use the constants:
import constants

print(f"PI: {constants.PI}")
print(f"E: {constants.E}")
print(f"Golden Ratio: {constants.GOLDEN_RATIO}")

Output:

PI: 3.141592653589793
E: 2.718281828459045
Golden Ratio: 1.

7.2: Standard Library Modules

In this section, we will delve into the Python Standard Library, which is a set of pre-installed modules that offer a wide range of functionalities. These modules are useful for performing various tasks without the need for third-party libraries. They can be used to work with the file system, interact with the internet, manipulate data, and much more. 

The Python Standard Library is an essential tool for any Python programmer. It includes modules for working with regular expressions, cryptography, network programming, and more. One of the most commonly used modules is the os module, which provides a way to interact with the file system. You can use this module to create, delete, or modify files and directories, as well as to navigate the file system.

Another commonly used module is the urllib module, which provides a way to interact with the internet. You can use this module to download web pages, send HTTP requests, and more. The urllib module is particularly useful for web scraping and data analysis tasks. 

In addition to these commonly used modules, the Python Standard Library includes modules for working with dates and times, parsing XML, and more. These modules can be used to perform a wide range of tasks, from simple file management to complex data analysis.

Here are a few essential standard library modules that you may find useful:

7.2.1: os

The os module provides a way to interact with the operating system. It allows you to perform file and directory operations, such as creating, renaming, or deleting files and directories. Additionally, you can retrieve information about the system, like the environment variables or the current working directory.

Example:

import os 

# Get the current working directory
current_directory = os.getcwd()
print(current_directory)

7.2.2: sys

The sys module provides access to some variables used or maintained by the interpreter and functions that interact with the interpreter. For example, you can use it to access command-line arguments or manipulate the Python path.

Example:

import sys

# Print the Python version
print(sys.version)

7.2.3: re

The re module provides support for regular expressions, which are a powerful tool for text processing. You can use them to search, match, or substitute specific patterns in strings.

Example:

import re

text = "Hello, my name is John Doe"
pattern = r"\b\w{4}\b"

four_letter_words = re.findall(pattern, text)
print(four_letter_words)

7.2.4: json

The json module allows you to work with JSON data by encoding and decoding JSON strings. You can use this module to read and write JSON data to and from files, as well as to convert JSON data to Python objects and vice versa.

Example:

import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert the Python dictionary to a JSON string
json_data = json.dumps(data)
print(json_data)

7.2.5: urllib

The urllib module is a part of Python's standard library and is used for working with URLs. It provides various functions to interact with URLs and fetch data from the internet. The urllib module is further divided into several sub-modules, such as urllib.requesturllib.parse, and urllib.error.

Here's a brief explanation of the most commonly used sub-modules:

  1. urllib.request: This sub-module provides functions to open and read URLs. The most common method is urlopen, which can be used to fetch data from a URL.

Example:

import urllib.request

url = "https://www.example.com"
response = urllib.request.urlopen(url)
content = response.read()

print(content)
  1. urllib.parse: This sub-module contains functions to manipulate and parse URLs, such as splitting a URL into its components or encoding/decoding query parameters.

Example:

from urllib.parse import urlparse, urlencode

url = "https://www.example.com/search?q=python+programming"

# Parse the URL into components
parsed_url = urlparse(url)
print(parsed_url)

# Encode query parameters
query_params = {"q": "python programming", "page": 2}
encoded_params = urlencode(query_params)
print(encoded_params)
  1. urllib.error: This sub-module defines exception classes for handling errors that may occur during URL handling, such as HTTP errors or network-related issues. Some common exceptions are URLError and HTTPError.

Example:

import urllib.request
from urllib.error import URLError, HTTPError

url = "https://www.nonexistentwebsite.com"

try:
    response = urllib.request.urlopen(url)
except HTTPError as e:
    print(f"HTTP error occurred: {e}")
except URLError as e:
    print(f"URL error occurred: {e}")

These sub-modules combined offer a powerful way to interact with the internet and manipulate URLs. However, in many cases, developers prefer to use the third-party library requests for making HTTP requests, as it offers a more user-friendly API and additional features. If you're interested, you can learn more about the requests library here: https://docs.python-requests.org/en/master/

These are just a few examples of the many standard library modules available in Python. To explore more modules and learn about their functionalities, refer to the Python documentation: https://docs.python.org/3/library/

Exercise 7.2.1: Create a Simple Module

In this exercise, you will create a simple module that contains a function to calculate the area of a rectangle.

Instructions:

  1. Create a new Python file called geometry.py.
  2. Define a function named rectangle_area that takes two arguments: length and width.
  3. The function should return the product of length and width.
  4. Import the geometry module in another Python script and use the rectangle_area function.

Solution:

  1. Create geometry.py:
def rectangle_area(length, width):
    return length * width
  1. In another Python script, import the geometry module and use the rectangle_area function:
import geometry

area = geometry.rectangle_area(5, 10)
print(f"Area of the rectangle: {area}")

Output:

Area of the rectangle: 50

Exercise 7.2.2: Create a Custom Text Manipulation Module

Create a custom module called text_manipulation that contains functions for converting a string to uppercase, lowercase, and title case.

Instructions:

  1. Create a Python file called text_manipulation.py.
  2. Define three functions: to_upperto_lower, and to_title.
  3. Each function should take a single argument, a string, and return the modified string.
  4. Import the text_manipulation module in another Python script and use the functions.

Solution:

  1. Create text_manipulation.py:
def to_upper(text):
    return text.upper()

def to_lower(text):
    return text.lower()

def to_title(text):
    return text.title()
  1. In another Python script, import the text_manipulation module and use the functions:
import text_manipulation

text = "this is a sample text"

upper_text = text_manipulation.to_upper(text)
print(f"Uppercase: {upper_text}")

lower_text = text_manipulation.to_lower(text)
print(f"Lowercase: {lower_text}")

title_text = text_manipulation.to_title(text)
print(f"Title case: {title_text}")

Output:

Uppercase: THIS IS A SAMPLE TEXT
Lowercase: this is a sample text
Title case: This Is A Sample Text

Exercise 7.2.3: Create a Module with Constants

In this exercise, you will create a module called constants that contains a few mathematical constants.

Instructions:

  1. Create a Python file called constants.py.
  2. Define variables for the following constants: PIE, and GOLDEN_RATIO.
  3. Import the constants module in another Python script and use the constants.

Solution:

  1. Create constants.py:
PI = 3.141592653589793
E = 2.718281828459045
GOLDEN_RATIO = 1.618033988749895
  1. In another Python script, import the constants module and use the constants:
import constants

print(f"PI: {constants.PI}")
print(f"E: {constants.E}")
print(f"Golden Ratio: {constants.GOLDEN_RATIO}")

Output:

PI: 3.141592653589793
E: 2.718281828459045
Golden Ratio: 1.

7.2: Standard Library Modules

In this section, we will delve into the Python Standard Library, which is a set of pre-installed modules that offer a wide range of functionalities. These modules are useful for performing various tasks without the need for third-party libraries. They can be used to work with the file system, interact with the internet, manipulate data, and much more. 

The Python Standard Library is an essential tool for any Python programmer. It includes modules for working with regular expressions, cryptography, network programming, and more. One of the most commonly used modules is the os module, which provides a way to interact with the file system. You can use this module to create, delete, or modify files and directories, as well as to navigate the file system.

Another commonly used module is the urllib module, which provides a way to interact with the internet. You can use this module to download web pages, send HTTP requests, and more. The urllib module is particularly useful for web scraping and data analysis tasks. 

In addition to these commonly used modules, the Python Standard Library includes modules for working with dates and times, parsing XML, and more. These modules can be used to perform a wide range of tasks, from simple file management to complex data analysis.

Here are a few essential standard library modules that you may find useful:

7.2.1: os

The os module provides a way to interact with the operating system. It allows you to perform file and directory operations, such as creating, renaming, or deleting files and directories. Additionally, you can retrieve information about the system, like the environment variables or the current working directory.

Example:

import os 

# Get the current working directory
current_directory = os.getcwd()
print(current_directory)

7.2.2: sys

The sys module provides access to some variables used or maintained by the interpreter and functions that interact with the interpreter. For example, you can use it to access command-line arguments or manipulate the Python path.

Example:

import sys

# Print the Python version
print(sys.version)

7.2.3: re

The re module provides support for regular expressions, which are a powerful tool for text processing. You can use them to search, match, or substitute specific patterns in strings.

Example:

import re

text = "Hello, my name is John Doe"
pattern = r"\b\w{4}\b"

four_letter_words = re.findall(pattern, text)
print(four_letter_words)

7.2.4: json

The json module allows you to work with JSON data by encoding and decoding JSON strings. You can use this module to read and write JSON data to and from files, as well as to convert JSON data to Python objects and vice versa.

Example:

import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert the Python dictionary to a JSON string
json_data = json.dumps(data)
print(json_data)

7.2.5: urllib

The urllib module is a part of Python's standard library and is used for working with URLs. It provides various functions to interact with URLs and fetch data from the internet. The urllib module is further divided into several sub-modules, such as urllib.requesturllib.parse, and urllib.error.

Here's a brief explanation of the most commonly used sub-modules:

  1. urllib.request: This sub-module provides functions to open and read URLs. The most common method is urlopen, which can be used to fetch data from a URL.

Example:

import urllib.request

url = "https://www.example.com"
response = urllib.request.urlopen(url)
content = response.read()

print(content)
  1. urllib.parse: This sub-module contains functions to manipulate and parse URLs, such as splitting a URL into its components or encoding/decoding query parameters.

Example:

from urllib.parse import urlparse, urlencode

url = "https://www.example.com/search?q=python+programming"

# Parse the URL into components
parsed_url = urlparse(url)
print(parsed_url)

# Encode query parameters
query_params = {"q": "python programming", "page": 2}
encoded_params = urlencode(query_params)
print(encoded_params)
  1. urllib.error: This sub-module defines exception classes for handling errors that may occur during URL handling, such as HTTP errors or network-related issues. Some common exceptions are URLError and HTTPError.

Example:

import urllib.request
from urllib.error import URLError, HTTPError

url = "https://www.nonexistentwebsite.com"

try:
    response = urllib.request.urlopen(url)
except HTTPError as e:
    print(f"HTTP error occurred: {e}")
except URLError as e:
    print(f"URL error occurred: {e}")

These sub-modules combined offer a powerful way to interact with the internet and manipulate URLs. However, in many cases, developers prefer to use the third-party library requests for making HTTP requests, as it offers a more user-friendly API and additional features. If you're interested, you can learn more about the requests library here: https://docs.python-requests.org/en/master/

These are just a few examples of the many standard library modules available in Python. To explore more modules and learn about their functionalities, refer to the Python documentation: https://docs.python.org/3/library/

Exercise 7.2.1: Create a Simple Module

In this exercise, you will create a simple module that contains a function to calculate the area of a rectangle.

Instructions:

  1. Create a new Python file called geometry.py.
  2. Define a function named rectangle_area that takes two arguments: length and width.
  3. The function should return the product of length and width.
  4. Import the geometry module in another Python script and use the rectangle_area function.

Solution:

  1. Create geometry.py:
def rectangle_area(length, width):
    return length * width
  1. In another Python script, import the geometry module and use the rectangle_area function:
import geometry

area = geometry.rectangle_area(5, 10)
print(f"Area of the rectangle: {area}")

Output:

Area of the rectangle: 50

Exercise 7.2.2: Create a Custom Text Manipulation Module

Create a custom module called text_manipulation that contains functions for converting a string to uppercase, lowercase, and title case.

Instructions:

  1. Create a Python file called text_manipulation.py.
  2. Define three functions: to_upperto_lower, and to_title.
  3. Each function should take a single argument, a string, and return the modified string.
  4. Import the text_manipulation module in another Python script and use the functions.

Solution:

  1. Create text_manipulation.py:
def to_upper(text):
    return text.upper()

def to_lower(text):
    return text.lower()

def to_title(text):
    return text.title()
  1. In another Python script, import the text_manipulation module and use the functions:
import text_manipulation

text = "this is a sample text"

upper_text = text_manipulation.to_upper(text)
print(f"Uppercase: {upper_text}")

lower_text = text_manipulation.to_lower(text)
print(f"Lowercase: {lower_text}")

title_text = text_manipulation.to_title(text)
print(f"Title case: {title_text}")

Output:

Uppercase: THIS IS A SAMPLE TEXT
Lowercase: this is a sample text
Title case: This Is A Sample Text

Exercise 7.2.3: Create a Module with Constants

In this exercise, you will create a module called constants that contains a few mathematical constants.

Instructions:

  1. Create a Python file called constants.py.
  2. Define variables for the following constants: PIE, and GOLDEN_RATIO.
  3. Import the constants module in another Python script and use the constants.

Solution:

  1. Create constants.py:
PI = 3.141592653589793
E = 2.718281828459045
GOLDEN_RATIO = 1.618033988749895
  1. In another Python script, import the constants module and use the constants:
import constants

print(f"PI: {constants.PI}")
print(f"E: {constants.E}")
print(f"Golden Ratio: {constants.GOLDEN_RATIO}")

Output:

PI: 3.141592653589793
E: 2.718281828459045
Golden Ratio: 1.