unit 2 :
Functions, Modules and Exception Handling: Functions Definition, Function
Calling, Function Arguments (Required, Keyword, Default), Recursion,
Modules, Built-in Modules, Creating Modules, File Handling (Opening, Closing,
Writing, Reading), Exceptions, Built-in Exceptions (IndexError,
OverflowError, ZeroDivisionError, RuntimeError), Exception Handling.
Functions in python
In Python, functions are blocks of reusable code that perform a specific task. They allow you to
structure your code in a more modular and organized manner. Functions can take inputs, process
them, and return an output.
Syntax of a Function in Python
def function_name(parameters):
"""
Optional multi-line
docstring to describe
the function.
"""
# Function body
statement(s)
return [expression]
- def : A keyword that tells Python we are defining a function.
- function_name : The name of the function. It should be descriptive and follow the same naming
conventions as variable names.
- parameters : A comma-separated list of parameters (arguments) that the function accepts. These
are optional.
1
- : A colon to indicate the start of the function body.
- """Docstring""" : Optional documentation string to describe what the function does.
- statement(s) : The block of code that makes up the function.
- return : An optional statement used to return a value from the function. If not specified, the
function returns None .
Example of a Function in Python
Let's create a simple function that adds two numbers and returns the result.
def add_numbers(a, b):
"""
This function takes two numbers as input
and returns their sum.
"""
result = a + b
return result
# Using the function
sum_result = add_numbers(5, 7)
print(sum_result) # Output: 12
In this example:
- def add_numbers(a, b): defines a function named add_numbers that takes two parameters a
and b .
- """...""" is a docstring that describes what the function does.
- result = a + b is the function body that calculates the sum of a and b .
- return result returns the result of the addition.
- sum_result = add_numbers(5, 7) calls the function with the arguments 5 and 7 , and the result is
stored in the variable sum_result .
2
- print(sum_result) prints the result, which is 12 .
In Python, functions can accept arguments in various ways, allowing for flexible and powerful
function definitions. Here are the different types of function arguments with examples:
1. Positional Arguments
Positional arguments are the most common type of arguments. They are passed to the function in
the correct positional order.
def greet(name, age):
print("Hello,",name," ! You are", age," years old.")
# Using positional arguments
greet("Alice", 30) # Output: Hello, Alice! You are 30 years old.
2. Keyword Arguments
Keyword arguments are passed to the function by explicitly stating the parameter name, allowing
arguments to be passed in any order.
def greet(name, age):
print("Hello,",name,"! You are", age," years old.")
# Using keyword arguments
greet(age=30, name="Alice") # Output: Hello, Alice! You are 30 years old.
3. Default Arguments
Default arguments are parameters that assume a default value if no argument is provided during
the function call.
def greet(name, age=25):
print("Hello,”, name,”! You are”, age,” years old.")
# Using a default argument
greet("Alice") # Output: Hello, Alice! You are 25 years old.
# Overriding the default argument
greet("Bob", 30) # Output: Hello, Bob! You are 30 years old.
3
4. Variable-Length Arguments
Python allows functions to accept an arbitrary number of arguments using *args for non-keyword
arguments
*args (Non-Keyword Variable Arguments)
*args allows a function to accept any number of positional arguments as a tuple.
def add_numbers(*args):
return sum(args)
# Using variable-length positional arguments
print(add_numbers(1, 2, 3)) # Output: 6
print(add_numbers(4, 5, 6, 7)) # Output: 22
Recursion
Recursion is a programming technique where a function calls itself directly or indirectly to solve a
problem. A recursive function typically has two main parts:
1. Base Case: A condition that stops the recursion.
2. Recursive Case: The part of the function where it calls itself with modified arguments.
Example 1: Factorial of a Number
The factorial of a number nnn is the product of all positive integers less than or equal to nnn. It can
be defined recursively as:
factorial(0)=1\text{factorial}(0) = 1factorial(0)=1
factorial(n)=n×factorial(n−1)\text{factorial}(n) = n \times \text{factorial}(n-
1)factorial(n)=n×factorial(n−1)
def factorial(n):
if n == 0:
return 1 # Base case
else:
return n * factorial(n-1) # Recursive case
4
# Example usage
print(factorial(5)) # Output: 120
In this example:
The base case is if n == 0, which returns 1.
The recursive case is n * factorial(n-1), which calls factorial with n-1.
Modules
Modules in Python are files containing Python code that can define functions, classes, and variables.
A module can also include runnable code. The code within the module can be reused across
multiple scripts and programs, providing a way to organize and manage large codebases. Using
modules helps improve code reusability, readability, and maintainability.
Creating a Module
A module is simply a Python file with a .py extension. For example, let's create a module named
[Link].
# [Link]
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
PI = 3.14159
Using a Module
To use a module in another script or module, you can use the import statement.
Importing the Entire Module
# [Link]
import mymodule
5
print([Link]("Alice")) # Output: Hello, Alice!
print([Link](2, 3)) # Output: 5
print([Link]) # Output: 3.14159
Importing Specific Functions or Variables
You can also import specific functions, classes, or variables from a module:
# [Link]
from mymodule import greet, PI
print(greet("Bob")) # Output: Hello, Bob!
print(PI) # Output: 3.14159
Importing with an Alias
Modules or functions can be imported with an alias using the as keyword:
# [Link]
import mymodule as mm
print([Link]("Charlie")) # Output: Hello, Charlie!
print([Link](5, 7)) # Output: 12
Built-in Modules
Python comes with a large standard library of built-in modules that you can use without installing
anything. Here are a few examples:
Using the math Module
The math module provides mathematical functions and constants.
import math
print([Link](16)) # Output: 4.0
print([Link]) # Output: 3.141592653589793
6
Using the datetime Module
The datetime module supplies classes for manipulating dates and times.
import datetime
now = [Link]()
print(now) # Output: current date and time
Package
A package is a way of organizing related modules into a directory hierarchy. A package is a
directory that contains a special __init__.py file, which can be empty or contain initialization code
for the package.
PYTHONPATH
The PYTHONPATH variable in Python is an environment variable that specifies additional
directories where the Python interpreter should look for modules and packages when importing
them. It allows you to add custom directories to the search path, making it easier to organize and
manage your Python code and dependencies.
FILE HANDLING IN PYTHON
In Python, opening a file is typically done using the open() function. This function allows you to
open a file and returns a file object, which you can use to read from or write to the file.
Syntax
file_object = open(filename, mode)
filename: This is the name of the file you want to open. It can be a relative or absolute path.
mode: This is a string that specifies the mode in which the file is opened. The common
modes are:
'r': Read mode, which is the default. It raises an error if the file does not exist.
'w': Write mode. Creates a new file or truncates the existing file. If the file exists, its content is
cleared.
'a': Append mode. Opens the file for writing and appends to the end of the file if it exists.
7
'b': Binary mode. When used with other modes, it opens the file in binary format. For example,
'rb' is for reading a file in binary mode.
't': Text mode. This is the default mode. For example, 'rt' is for reading a file in text mode.
'x': Exclusive creation mode. Creates a new file and opens it for writing. It raises an error if the
file already exists.
Example
# Open a file for reading
file = open('[Link]', 'r')
# Read the contents of the file
content = [Link]()
print(content)
# Close the file
[Link]()
Using with Statement
Using the with statement to open a file is recommended because it ensures the file is properly
closed after its suite finishes, even if an exception is raised.
Example with with Statement
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
In this example, file is automatically closed when the with block is exited.
8
Attributes of file object
File objects in Python come with several attributes and methods that help you interact with the file.
Here are some of the key attributes:
Common Attributes
1. name
o This attribute gives the name of the file.
Example:
with open('[Link]', 'r') as file:
print([Link]) # Output: [Link]
2. mode
o This attribute tells you the mode in which the file was opened.
Example:
with open('[Link]', 'r') as file:
print([Link]) # Output: r
3. closed
o This attribute is a Boolean that indicates whether the file is closed (True) or open
(False).
Example:
file = open('[Link]', 'r')
print([Link]) # Output: False
[Link]()
print([Link]) # Output: True
Closing a File
When a file is closed, it frees up the system resources associated with the file
9
Using close() Method
o You can explicitly close a file by calling the close() method on the file object.
o Example:
file = open('[Link]', 'r')
# Perform file operations
[Link]()
Writing to a File in Python
Writing to a file in Python can be done using the open() function with the appropriate mode and
various methods provided by the file object. Here are the key points:
Opening a File for Writing
Use the open() function with the 'w', 'a', or 'x' mode:
'w': Write mode. Creates a new file or truncates the existing file.
'a': Append mode. Opens the file for writing and appends to the end.
'x': Exclusive creation mode. Creates a new file and raises an error if it already exists.
Example
# Open a file in write mode
with open('[Link]', 'w') as file:
[Link]('Hello, world!\n') # Write a string to the file
# Open a file in append mode
with open('[Link]', 'a') as file:
[Link]('Appending a new line.\n') # Append a string to the file
Writing Methods
1. write(string)
o Writes a string to the file.
Example:
10
with open('[Link]', 'w') as file:
[Link]('Hello, world!')
2. writelines(lines)
o Writes a list of strings to the file.
Example:
lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('[Link]', 'w') as file:
[Link](lines)
Reading from a File in Python
Reading from a file in Python involves opening the file in a mode that allows reading, using
methods provided by the file object to read its contents, and then closing the file to release system
resources. Opening a File for Reading
Use the open() function with the appropriate mode:
'r': Read mode (default). Opens the file for reading.
'rb': Binary read mode. Opens the file for reading in binary format.
Common Methods for Reading
1. read(size)
o Reads and returns up to size characters from the file as a string. If size is omitted or
negative, reads the entire file.
Example:
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
2. readline(size)
o Reads and returns one line from the file. If size is specified, reads up to size
characters of the line.
11
with open('[Link]', 'r') as file:
line = [Link]()
print(line)
3. readlines(hint=-1)
o Reads and returns a list of lines from the file. If hint is specified, reads up to hint
characters.
Example:
with open('[Link]', 'r') as file:
lines = [Link]()
print(lines)
Using with Statement
The with statement is the preferred way to open a file for reading because it ensures that the file is
properly closed after reading, even if an exception occurs:
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
Example Usage
1. Reading the Entire File
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
2. Reading Line by Line
with open('[Link]', 'r') as file:
for line in file:
print(line, end='') # 'end' is used to avoid adding extra newlines
12
fileno()
The fileno() method in Python returns the file descriptor associated with the file object. A file
descriptor is a low-level integer handle used by the operating system to identify an open file.
Syntax
file_descriptor = file_object.fileno()
Return Value
The method returns an integer representing the file descriptor.
Example
with open('[Link]', 'r') as file:
fd = [Link]()
print(fd) # Output: a non-negative integer representing the file descriptor
seek() Method in Python File Handling
The seek() method in Python is used to change the file's current position. It allows you to move to a
specific location in a file for reading or writing. This is particularly useful for random access
operations in a file.
Syntax
file_object.seek(offset, whence)
Parameters
offset: The number of bytes to move the file pointer. It can be a positive or negative integer.
whence: An optional parameter that specifies the reference point for the offset. It can be:
o 0 (default): Absolute file positioning. The offset is from the beginning of the file.
o 1: Relative file positioning. The offset is from the current file position.
o 2: Relative to the file's end. The offset is from the end of the file.
Return Value
The method returns the new absolute position.
13
Example
with open('[Link]', 'r') as file:
[Link](5) # Move to the 6th byte (0-based index)
print([Link]()) # Read from the 6th byte onward
Renaming a File in Python
Renaming a file in Python can be done using the [Link]() method from the os module. This
method allows you to change the name of an existing file or directory.
Syntax
[Link](src, dst)
Parameters
src: The current name or path of the file or directory you want to rename.
dst: The new name or path for the file or directory.
Example
import os
# Current file name
src = 'old_name.txt'
# New file name
dst = 'new_name.txt'
# Renaming the file
[Link](src, dst)
Exception handling in python
Exception handling in Python is a mechanism to handle runtime errors, ensuring the normal flow
of the program even when unexpected events occur. Python provides several tools to manage
exceptions, making your code more robust and easier to debug.
14
Basic Concepts
1. Exception: An event that disrupts the normal flow of the program. It can be caused by
errors like division by zero, file not found, or invalid input.
2. Exception Handling: The process of responding to exceptions when they occur, typically
using try, except, else, and finally blocks.
Syntax
try:
# Code that might raise an exception
except ExceptionType1:
# Code to handle the specific exception
except ExceptionType2:
# Code to handle another specific exception
else:
# Code to execute if no exceptions are raised
finally:
# Code to execute regardless of whether an exception is raised
Example Usage
1. Basic Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
2. Handling Multiple Exceptions
try:
result = 10 / int(input("Enter a number: "))
15
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid number.")
3. Using else and finally Blocks
try:
file = open('[Link]', 'r')
content = [Link]()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
[Link]()
print("File closed.")
Raising Exceptions
You can raise exceptions using the raise statement.
def check_positive(number):
if number < 0:
raise ValueError("The number must be positive.")
return number
try:
check_positive(-10)
except ValueError as e:
print(e)
16
Creating user defined Exceptions
You can define your own exceptions by creating a new class that inherits from the Exception class.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)
17