Python Functions, Modules, and Packages
Introduction of Unit
In Python, functions, modules, and packages are essential for writing
efficient, organized, and reusable code. These features promote
modular programming, allowing developers to break down complex
programs into smaller, manageable units. This unit covers how to
create and use functions, organize projects using modules, and how
Python packages enhance the ability to reuse and maintain code.
Organizing Python Code Using Functions
1. What are Functions?
o A function is a block of reusable code that performs a
specific task. Functions help in organizing code, making it
more readable and easier to maintain. Python provides a
rich syntax for defining and using functions.
2. Defining a Function:
o A function is defined using the def keyword followed by
the function name, parameters (if any), and a block of
code.
def function_name(parameters):
# code block
return result
3. Advantages of Using Functions:
o Code Reusability: Functions allow code to be reused
multiple times without redundancy.
o Code Organization: They provide structure to code,
making it easier to understand and maintain.
o Debugging: Functions make it easier to isolate and fix
specific parts of the code.
o Modularity: Breaking code into functions promotes
modular programming.
4. Types of Functions:
o Built-in Functions: These are pre-defined functions in
Python, like print(), len(), max(), etc.
o User-Defined Functions: Functions that are created by the
programmer to serve specific needs.
o Anonymous Functions (Lambda): These are functions
defined without a name, usually for short-term usage.
5. Function Parameters and Arguments:
o Functions can take inputs, known as parameters, which
allow dynamic behavior.
o Python supports default arguments, keyword arguments,
variable-length arguments (*args, **kwargs).
6. Return Statement:
o Functions can return values using the return statement,
allowing them to pass the result back to the caller.
7. Example of a Function:
# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)
# function call with two values
add_numbers(5, 4)
1. Simple function without parameters
# A function to print a greeting message
def greet():
print("Hello, welcome to Python programming!")
# Calling the function
greet()
2. Function with parameters
# A function that takes two numbers and returns their sum
def add_numbers(a, b):
return a + b
# Calling the function with arguments
result = add_numbers(5, 10)
print("Sum:", result)
3. Function with default arguments
# A function that calculates the area of a rectangle with default
height and width
def area_of_rectangle(height=5, width=10):
return height * width
# Calling the function without providing arguments (uses default
values)
print("Area:", area_of_rectangle())
# Calling the function with arguments
print("Area:", area_of_rectangle(6, 7))
4. Function with return values
# A function that checks if a number is even or odd
def is_even(number):
if number % 2 == 0:
return True
else:
return False
# Using the function
num = 4
if is_even(num):
print(f"{num} is even.")
else:
print(f"{num} is odd.")
5. Function with variable-length arguments (using *args)
# A function that accepts multiple arguments and returns their sum
def sum_all(*args):
total = 0
for num in args:
total += num
return total
# Calling the function with a variable number of arguments
print("Total sum:", sum_all(1, 2, 3, 4, 5))
6. Function with keyword arguments (using **kwargs)
# A function that accepts keyword arguments and prints them
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function with keyword arguments
print_info(name="Aparajita", role="Professor", department="FCE")
7. Recursive function
# A function to calculate factorial of a number using recursion
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
# Calling the function to find factorial
print("Factorial of 5:", factorial(5))
Organizing Python Projects into Modules
1. What are Modules?
o A module is a file containing Python code (functions,
classes, or variables) that can be imported and used in
other Python scripts. The use of modules helps in dividing
a large program into smaller, manageable parts.
2. Creating a Module:
o Any Python file (with a .py extension) is considered a
module. For example, a file named mymodule.py is a
module.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
3. Using Modules:
o Modules can be imported into another Python script using
the import keyword.
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
4. Advantages of Using Modules:
o Code Reusability: Modules allow code to be reused in
different programs.
o Namespace Management: They provide a way to avoid
naming conflicts by isolating the scope of functions and
variables.
o Simplifying Maintenance: If a module needs to be
updated, the changes will reflect wherever the module is
imported.
Importing Own Modules and External Modules
1. Importing Own Modules:
o Own modules are those created by the user. To use
functions, variables, or classes from another Python file,
you simply import that file as a module.
import mymodule
2. Importing Specific Elements from Modules:
o You can import specific functions, variables, or classes
from a module using the from keyword.
from mymodule import greet
3. Importing External Modules:
o Python provides a vast ecosystem of external modules
that can be installed using pip (Python’s package
manager). Examples include requests, numpy, and
pandas.
pip install requests
import requests
response = requests.get('https://example.com')
print(response.status_code)
4. Aliasing Modules:
o You can provide an alias to a module using the as
keyword, making it easier to reference.
import numpy as np
Module Working
Creating a Python Module
A Python module is simply a .py file. For example, let's say we create
a file named MCA_math_operations.py with the following content:
# MCA_math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
Importing a Module
To use the functions defined in a module, you can import it into your
main script using the import statement.
# main.py
import MCA_math_operations
# Using the add function from the MCA_math_operations module
result = MCA_math_operations.add(10, 5)
print("Addition:", result)
result = MCA_math_operations.subtract(10, 5)
print("Subtraction:", result)
result = MCA_math_operations.multiply(10, 5)
print("Multiplication:", result)
result = MCA_math_operations.divide(10, 5)
print("Division:", result)
Example Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Importing Specific Functions
You can also import specific functions or variables from a module.
from MCA_math_operations import add, divide
print(add(8, 2)) # Output: 10
print(divide(8, 2)) # Output: 4.0
Aliasing Modules
You can give an alias to a module using the as keyword to shorten the
name.
import MCA_math_operations as mo
print(mo.add(3, 7)) # Output: 10
Types of Modules
1. Built-in Modules: Modules that come pre-installed with
Python, such as math, random, datetime.
2. User-defined Modules: Modules created by users (like
MCA_math_operations.py).
3. External Libraries: Modules that are installed using a package
manager like pip.
Example with Built-in Module (math):
import math
1. print(math.sqrt(16)) # Output: 4.0
2. print(math.pi) # Output: 3.141592653589793
Example with Built-in Module (date time):
import datetime
# Current date and time
now = datetime.datetime.now()
print("Now:", now)
# Formatting date
formatted_now = now.strftime("%d-%m-%Y %H:%M:%S")
print("Formatted:", formatted_now)
# Create specific date
custom = datetime.datetime(2021, 12, 25, 10, 30)
print("Custom Date:", custom)
# Today's date
today = datetime.date.today()
print("Today:", today)
# Add 10 days to today
future = today + datetime.timedelta(days=10)
print("Future Date:", future)
# Difference between two dates
difference = future - today
print("Difference:", difference.days, "days")
Understanding Packages
1. What are Packages?
o A package is a collection of Python modules organized
into directories. A package usually contains an __init__.py
file, which distinguishes it as a package. Packages allow for
better organization of modules in larger projects.
o A Python package is like a folder that contains multiple
related files (modules). These files can be Python scripts
that provide specific functions or classes, which you can
use in your programs.
Think of a package as a collection of tools designed for a
specific purpose. For example:
A math package might have tools for advanced
calculations.
o A web package might help you create websites.
o To use these tools in your code, you can "import" the
package and access its features. This way, you don't have
to write everything from scratch!
Example:
import math # math is a built-in Python package
result = math.sqrt(16) # Using the sqrt() function from the math
package
print(result) # Output: 4.0
2. Creating a Package:
o A directory with an __init__.py file is considered a
package.
markdown
mypackage/
__init__.py
module1.py
module2.py
3. Importing from a Package:
o Once the package is set up, modules within the package
can be imported.
from mypackage import module1
4. Nested Packages:
o Packages can contain sub-packages, further improving
code organization in large projects.
5. Examples of Common Python Packages:
o NumPy: For numerical computations.
o Pandas: For data manipulation and analysis.
o Django: For web development.
o Flask: A lightweight web framework.
Prepare well for NumPy & Panda – Important from
placement point of view. Atleast 15 methods of each
package.
6. NumPy Package :
To install and use the NumPy package in Python:
1. Installing NumPy
If you don’t have NumPy installed yet, you can install it using the
Python package manager pip. Open your terminal or command
prompt and run the following command:
pip install numpy
Once installed, NumPy is ready to use in your Python code.
2. Using NumPy
To use NumPy in your program, you need to import it at the
beginning of your Python script. Here’s an example of how you can
use it:
import numpy as np # 'np' is a common alias for numpy, so you
can use shorter names in your code.
# Example 1: Creating an array
arr = np.array([1, 2, 3, 4, 5])
print("Array:", arr) o/p?
# Example 2: Creating a 2D array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print("Matrix:\n", matrix) o/p?
# Example 3: Performing operations (e.g., sum of array elements)
sum_array = np.sum(arr)
print("Sum of array:", sum_array) o/p?
# Example 4: Generating arrays of zeros or ones
zeros = np.zeros((3, 3))
print("3x3 matrix of zeros:\n", zeros) o/p?
# Example 5: Basic mathematical operations
arr2 = np.array([10, 20, 30, 40, 50])
addition = arr1 + arr2 # Adding two arrays element-wise
print("Array after addition:", addition) o/p?
Addition :
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result_add = arr1 + arr2
print("Addition:", result_add)
_________________________________________
Subtraction: arr1 - arr2
Multiplication/Division: arr1 * arr2, arr1 / arr2
Sum of elements: np.sum(arr1)
Key Features of NumPy
Efficient arrays: NumPy is great for creating and working with
arrays, which are like lists but faster and more powerful.
Mathematical operations: You can perform complex
mathematical operations like addition, multiplication, and
trigonometric functions on these arrays with ease.
Multidimensional arrays: NumPy allows the creation of
multidimensional arrays (e.g., matrices) for more advanced
computations like linear algebra.