0% found this document useful (0 votes)
23 views24 pages

Python Functions and Parameter Passing

Uploaded by

akmiffashish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views24 pages

Python Functions and Parameter Passing

Uploaded by

akmiffashish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 3

Functions: Program Routines- Defining Functions- More on Functions: Calling Value-


Returning Functions- Calling Non-Value-Returning Functions- Parameter Passing - Keyword
Arguments in Python - Default Arguments in Python-Variable Scope. Recursion: Recursive
Functions.

Program Routines
• A program routine is a set of instructions designed to perform a specific task in a program.
• In Python, functions are the primary means to create program routines.
Advantages of Program Routines / Functions:
1. Reusability – Write once and reuse multiple times.
2. Modularity – Programs can be divided into smaller, logical parts.
3. Readability – Code becomes easier to understand.
4. Maintainability – Easier to debug, test, and update.
5. Abstraction – Hides the internal details; user interacts with input/output only.

Python Functions
Function Declaration
The syntax to declare a function is:

Defining a Function
We can define a function in Python, using the def keyword. We can add any type of functionalities and
properties to it as we require.
The def keyword stands for define. It is used to create a user-defined function. It marks the beginning of a
function block and allows you to group a set of statements so they can be reused when the function is called.
Explanation:
• def: Starts the function definition.
• function_name: Name of the function.
• parameters: Inputs passed to the function (inside ()), optional.
• Indented code: The function body that runs when called.

1. Built-in Functions – Predefined functions provided by Python.


2. User-Defined Functions – Functions created by the programmer to perform specific tasks.

Built-in Functions
• Python provides a large number of pre-defined functions that can be used directly.
• Examples include: print(), len(), sum(), max(), min(), type(), range(), sorted(), etc.
Characteristics:
1. Already available in Python, no need to define.
2. Can be used by simply calling the function with required arguments.
3. Reduce coding effort and errors.

Examples of Built-in Functions


1. print() – Outputs to console
print("Hello, World!")
Output:
Hello, World!
2. len() – Returns the length of a string, list, tuple, or dictionary
name = "Deepika"
print(len(name))
Output:
7

User-Defined Functions
• These are functions created by the programmer to perform a specific task.
• They allow reusability, modularity, and abstraction.
• Created using the def keyword.
Eg:
def add(a, b):
return a + b
result = add(10, 20)
print("Sum:", result)
output:
Sum: 30

Calling a function:
 In Python, we use the name of the function to make a function call.
 If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)

Example:

def sample_function():
print('This is a user-defined function') sample_function()
Value-Returning Functions :
A value-returning function is a function that performs some task and then sends a value back
to the caller using the return statement. The returned value can be stored in a variable or used
in an expression.
Example
def add(a, b):
return a + b
result = add(5, 7)
print("Sum:", result)
Output
Sum: 12
Non-Value-Returning Functions:
Definition
A non-value-returning function is a function that performs a task (like printing or updating data) but
does not return any value using the return statement. If checked, its return value is None.
Example
def greet(name):
print("Hello,", name)
greet("Anita")
greet("Ravi")
Output
Hello, Anita
Hello, Ravi

Parameter Passing in Python


• Information can be passed into functions as arguments.
• Arguments are written after the function name, inside parentheses.
• Multiple arguments can be added, separated by commas.
• In Python, all parameters are passed by reference (i.e., a reference to the object is passed, not a
copy).
Immutable objects (like strings, numbers, tuples) → changes inside the function do not affect the original
value.
Mutable objects (like lists, dictionaries, sets) → changes inside the function affect the original object,
unless reassigned to a new one.

Example 1: Immutable Object (String)


def fn1(name):
print(f'Hello! {name}')
name = 'Raja'
name = 'Rama'
fn1(name)
print(f'name outside the function is {name}')
Output:
Hello! Rama
name outside the function is Rama
Explanation:
• The changes made in the called function do not affect the value outside the function.
• This is because the variable name is redefined inside the function, so it becomes a local variable.
• When we assign 'Raja' inside the function, it creates a new reference, but it does not change the
original value outside.
Example 2: Mutable Object (List – Modified Inside Function)
def myFun(x):
x[0] = 20
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[20, 11, 12, 13, 14, 15]
Explanation:
• Lists are mutable, so changes made inside the function affect the original list.
• Both x and lst refer to the same object in memory.

Example 3: Mutable Object (Reassigned Inside Function)


def myFun(x):
x = [20, 30, 40]
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[10, 11, 12, 13, 14, 15]
Explanation:
• Inside the function, x is reassigned to a new list [20, 30, 40].
• This reassignment creates a new local reference and does not affect the original list lst.
Actual Arguments vs. Formal Parameters
ActualArguments(Arguments):
The values or data passed to a function when it is called.
• FormalParameters(Parameters):
The variables (placeholders) defined in the function header that receive the actual arguments.

Example
def addition(x, y):
result = x + y
print(f"Sum: {result}")

addition(2, 3)
Output:
Sum: 5
• Actual arguments provide the input values.
• Formal parameters act as placeholders for those values inside the function.
Mutable vs. Immutable Arguments
• When a function is called, the values of actual arguments are assigned to the corresponding formal
parameters.
• The behavior depends on whether the argument is mutable or immutable.

Immutable Arguments
• Immutable objects: int, float, string, tuple.
• Changes made inside the function do not affect the original object outside.
Example:
def change_value(x):
x = 50
a = 10
change_value(a)
print("Outside function:", a)
Output:
Outside function: 10

Mutable Arguments
• Mutable objects: list, dictionary, set.
• Changes made inside the function do affect the original object outside.
Example:
def modify_list(lst):
lst[0] = 100
numbers = [10, 20, 30]
modify_list(numbers)
print("Outside function:", numbers)
Output:
Outside function: [100, 20, 30]
Python function arguments
In Python, there are different ways to pass arguments to a function. They are as follows.

1. Positional Arguments (or) Required Arguments


2. Default Arguments
3. Keyword Arguments
4. Variable-length Arguments

1. Positional Arguments (or) Required Arguments


➢ The positional arguments are the arguments passed to a function in the same positional
order as they defined in the function definition.
➢ Here, the number of arguments and order of arguments in the function call should
exactly match with the respective function definition.
➢ If any mismatch leads to error.
➢ The positional arguments are also known as required arguments.
Example:
def student_details(name, age, grade):
print("Name:", name)
print("Age:", age)
print("Grade:", grade)
student_details("Ravi", 15, "10th")
output
Name: Ravi
Age: 15
Grade: 10th

2. Default Arguments
➢ The default argument is an argument which is set with a default value in the function
definition.
➢ If the function is called with value then, the function executed with provided value,
otherwise, it executed with the default value given in the function definition.
Example:

def addition(num1, num2, num3=300):


return num1 + num2 + num3
result = addition(10, 20, 30)
print(f'Sum = {result}')
result = addition(10, 20)
print(f'Sum = {result}')
Output:
Sum = 60
Sum=330

3. Keyword Arguments
➢ The keyword argument is an argument passed as a value along with the parameter name
(parameter_name = value).
➢ When keyword arguments are used, we may ignore the order of arguments.
➢ We may pass the arguments in any order because the Python interpreter uses the
keyword provided to match with the respective parameter.
12
Example:
def student_info(rollNo, name, dept, year):
print(f'Roll Number : {rollNo}')
print(f'Student Name : {name}')
print(f'Department : {dept}')
print(f'Year of Study : {year}')
student_info(name='Rama', dept='CSE', rollNo=111, year=4)
Output:
Roll Number : 111
Student Name : Rama
Department : CSE
YearofStudy:4

Variable-length Arguments
➢ The Python provides variable-length of arguments which enable us to pass an arbitrary
number of arguments.
➢ Here, all the arguments are stored as a tuple of parameters in the function definition.
And they are accessed using the index values (similar to a tuple).
Example:
def largest(*numbers):
return max(numbers)
print(largest(20, 35))
print(largest(2, 5, 3))
print(largest(10, 40, 80, 50))
print(largest(16, 3, 9, 12, 44, 40))
Output:
35
5
80
44

Variable Scope:
variable scope refers to the region of a program where a variable is defined and can be accessed or modified.
Scoping rules determine the visibility and lifetime of a variable within different parts of a program.
Understanding variable scope is fundamental for writing modular, efficient, and error-free code.
Python uses the LEGB Rule for resolving variable names, which stands for Local, Enclosing, Global, and
Built-in scopes.
Local Scope (L)

Enclosing Scope (E)

Global Scope (G)

Built-in Scope (B)

Local Scope: Variables declared within a function or block have local scope, meaning they are only
accessible within that function or block.
Eg:

def local_example():
x=5
print("Inside function, x =", x)
local_example()

output:
Inside function, x = 5

Enclosing Scope
• This is the scope of any enclosing functions, used in nested functions.
• The inner function can access variables of the outer (enclosing) function but cannot modify them
directly unless using nonlocal.
Eg:
def outer():
message = "Hello"
def inner():
print("Inner says:", message)
inner()
outer()
output:
Inner says: Hello

Global Scope: Variables declared outside of any function or block have global scope, meaning they can be
accessed from anywhere in the program.
Eg:
x = 10
def show():
print("Inside function, x =", x)
show()
print("Outside function, x =", x)
output:
Inside function, x = 10
Outside function, x = 10
Built-in Scope
It is the outermost scope in Python.
It contains all the names that are pre-defined in Python (like functions, exceptions, constants, types).
Examples: print(), len(), max(), min(), int, str, etc.

Eg:
print(len("Hello"))
print(max([2, 8, 4]))
print(min([2, 8, 4]))
output:
5
8
2

Recursion:
Recursion is a programming technique where a function calls itself in order to solve a problem. Recursive
functions typically have two main parts:

Base Case: This is a condition that determines when the recursion should stop. Without a base case, the
function would continue to call itself indefinitely, leading to a stack overflow error.
Purpose:
• It prevents infinite recursion.
• Provides a direct solution to the simplest/smallest input.
Eg:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
output:
120

Recursive Case: This is the part of the function where it calls itself with a modified version of the input.
This repetition continues until the base case is reached.

Purpose:
• Breaks down a big problem into smaller subproblems.
• Moves the problem closer to the base case.
Eg:
def sum_numbers(n):
return n + sum_numbers(n - 1)
print(sum_numbers(5))

output:
Recursive case: n + sum_numbers(n-1)
Again, without base case → infinite recursion.
Result: RecursionError
UNIT 4

UNIT IV:

Objects and their use: Software Objects - Turtle Graphics – Turtle attributes Modular
Design: Modules - Top-Down Design - Python Modules - Text Files: Opening, reading
and writing text files – Exception Handling.

Software Objects in Python

1. Introduction
In programming, especially in Object-Oriented Programming (OOP), the concept
of objects is fundamental.
A software object is a model or representation of a real-world entity. It contains:
• State (data, properties, or attributes).
• Behavior (functions or methods that define what the object can do).
Objects allow programmers to create modular, reusable, and realistic programs by
mapping real-world things into code.

2. Objects in Python
• In Python, everything is an object, including integers, strings, lists, functions,
and user-defined data structures.
• An object is always created from a class, which acts as a blueprint.
• A class defines the attributes (variables) and methods (functions), while the
object represents a specific instance of that class.
For example:
• A class Car defines properties like brand, color, and methods like drive(),
stop().
• An object like mycar = Car("Toyota", "Red") represents a specific car with
those features.

3. Key Characteristics of Software Objects


1. Identity
o Every object has a unique identity in memory.
o Even two objects with the same data are stored at different memory
locations.
2. State (Attributes)
o Represents the data or properties of the object.
o For example, a Student object may have attributes like name, age,
roll_number.
3. Behavior (Methods)
o Represents the actions or functions that the object can perform.
o For example, a Student object can perform methods like study(),
attend_class().

Example in Python
class Car:
def __init__(self, brand, color):
[Link] = brand
[Link] = color

def drive(self):
return f"{[Link]} {[Link]} is driving on the road"

def stop(self):
return f"{[Link]} {[Link]} has stopped"

# Creating objects
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")

print([Link]())
print([Link]())
Output:
Red Toyota is driving on the road
Blue Honda has stopped

Advantages of Software Objects


1. Encapsulation
o Combines data and functions into a single unit.
o Protects data by controlling access.
2. Reusability
o Classes can be reused to create multiple objects.
o Example: The Car class can be used to create hundreds of car objects.
3. Abstraction
o Hides complex implementation details from the user.
o Example: When we call drive(), we don’t need to know how the engine
works internally.
4. Modularity
o Objects make code more organized and structured.
o Each object can be developed and tested independently.
5. Closer to Real-World Modeling
o Easy to design programs by mapping them with real-world entities like
Student, BankAccount, Car, Teacher, etc.
.

Turtle Graphics in Python


1. Introduction

Turtle Graphics is a popular way to introduce programming concepts through simple


graphics. It provides a drawing board and a turtle (pen) that can be controlled with
commands. Using functions, we can move the turtle around the screen to draw shapes,
patterns, and designs.

It is included in Python’s standard library (turtle module), so no extra installation is


required.

2. Basic Concepts

Turtle – a cursor shaped like an arrow that moves and draws on the screen.

Screen – the window where the turtle draws.

Movement Commands – forward(), backward(), left(), right().

Pen Control – penup(), pendown(), color(), pensize().

Shapes – Circles, polygons, and complex figures can be drawn.

Turtle
• The turtle is a small cursor, usually shaped like an arrow, that moves around
the screen.
• Wherever the turtle moves, it can draw a line (if the pen is down).
• It can be controlled by giving commands such as moving forward, turning left
or right, or lifting the pen.
• In Python, the turtle is created by calling [Link]().
Example:
import turtle
t = [Link]()
[Link](100)
[Link]()
Output: The turtle moves forward and draws a straight line.

2. Screen
• The screen is the drawing area where the turtle moves.
• It acts like a canvas or paper.
• The turtle starts at the center of the screen (0,0).
• The screen can be customized with a background color or title.
Example:
import turtle
s = [Link]()
[Link]("lightblue")
[Link]("My Turtle Screen")
t = [Link]()
[Link](50)
[Link]()
Output: A circle is drawn on a light blue background with the title "My Turtle
Screen".

3. Movement Commands
These commands control the movement of the turtle:
• forward(x) – moves the turtle forward by x units in the current direction.
• backward(x) – moves the turtle backward by x units.
• left(angle) – turns the turtle left by the given angle in degrees.
• right(angle) – turns the turtle right by the given angle in degrees.
Example:
import turtle
t = [Link]()
[Link](100)
[Link](90)
[Link](100)
[Link]()
Output: An L-shaped line.

4. Pen Control
Pen control commands decide how the turtle draws on the screen.
• penup() – lifts the pen; the turtle moves without drawing.
• pendown() – puts the pen down; the turtle draws while moving.
• color(c) – sets the pen color, e.g., color("red").
• pensize(n) – sets the thickness of the pen line.
Example:
import turtle
t = [Link]()
[Link](5)
[Link]("red")
[Link](100)
[Link]()
[Link](50)
[Link]()
[Link]("blue")
[Link](100)
[Link]()
Output: A thick red line, a gap, and then a blue line.

5. Shapes
Turtle can draw not only straight lines but also shapes such as circles, triangles,
rectangles, polygons, and even complex designs.
• circle(radius) – draws a circle of given radius.
• Polygons are drawn using loops with forward() and right()/left().
Example 1: Circle
import turtle
t = [Link]()
[Link](80)
[Link]()
Output: A circle with radius 80.

More examples:
Example A square.
import turtle
t = [Link]()
for i in range(4):
[Link](100)
[Link](90)
[Link]()
Output: A square.

Example : A Rectangle
import turtle
t = [Link]()
for i in range(2):
[Link](150)
[Link](90)
[Link](80)
[Link](90)
[Link]()
Output: A rectangle.

Turtle Attributes:

In the context of turtle graphics, a turtle object represents a cursor that moves around a
canvas, drawing lines and shapes. These turtle objects have various attributes that
control their appearance and behavior. Some common turtle attributes include:
Position: The turtle's position on the canvas, usually represented by its x and y
coordinates.

Direction: The direction the turtle is facing, often measured in degrees clockwise
from the positive x-axis.

Pen State: Whether the turtle's pen is up (not drawing) or down (drawing).

Pen Color: The color of the turtle's pen.

Pen Size: The width of the lines drawn by the turtle's pen.

Turtle Speed: The speed at which the turtle moves on the canvas.

These attributes can be manipulated to create various drawings and designs using
turtle graphics.

Modular Design and Modules:

Modular design is an approach to software design where a system is divided into


separate modules, each responsible for a specific aspect of functionality. These
modules are self-contained units that can be developed, tested, and maintained
independently. In Python, modules are files containing Python code, typically grouped
by functionality.

Advantages of Modular Design:

Encapsulation: Modules encapsulate related functionality, hiding implementation


details and promoting abstraction.

Reuse: Modular design encourages code reuse, as modules can be imported and used
in multiple parts of a program or in different projects.

Maintainability: Modules make it easier to manage and maintain code, as changes to


one module are less likely to impact other parts of the system.

Scalability: Modular design facilitates the scalability of software systems, allowing


them to grow in size and complexity without becoming unwieldy.

Collaboration: Modular design promotes collaboration among developers, as


different team members can work on separate modules simultaneously.
Top-down design:
Top-down design, also known as stepwise refinement or top-down programming, is a
problem-solving approach used in software development to break down complex
problems into smaller, more manageable sub-problems. It involves starting with a
high-level overview of the problem and progressively breaking it down into smaller
and more detailed steps until each step is simple enough to be implemented easily.

The key principles of top-down design are:

Divide and Conquer: The problem is divided into smaller sub-problems that are
easier to solve individually. Each sub-problem is then further divided into even
smaller sub-problems, and so on, until the problems are small enough to be solved
directly.

Abstraction: Top-down design emphasizes abstraction, which involves focusing on


the essential features of a problem while ignoring unnecessary details. This helps in
simplifying the problem and breaking it down into more manageable components.

Stepwise Refinement: The problem-solving process proceeds step by step, with each
step refining the solution and adding more detail. This iterative approach allows for a
gradual and systematic development of the solution.

Modularity: The solution is organized into modules or functions, each responsible for
a specific task or sub-problem. Modularity promotes code reuse, readability, and
maintainability.

Hierarchical Structure: The problem-solving process follows a hierarchical


structure, with higher-level modules calling lower-level modules to delegate tasks and
coordinate the solution.

Testing and Validation: At each level of refinement, the solution is tested and
validated to ensure that it meets the requirements and behaves as expected. This helps
in identifying and correcting errors early in the development process.

Top-down design is often used in conjunction with other software development


methodologies, such as structured programming and object-oriented programming. It
provides a systematic and organized approach to problem-solving, making it easier to
manage complex projects and develop maintainable and scalable software solutions.

Python modules:

1. Introduction
A module in Python is a file containing code such as functions, variables, and
classes. Modules are used to organize programs, avoid repetition, and allow
reusability of code.
Python supports two main types of modules:
1. Built-in Modules – pre-installed with Python, ready for use.
2. User-Defined Modules – created by programmers to meet specific needs.
Both play a crucial role in software development by making programs modular,
manageable, and efficient.

2. Built-in Modules
Explanation
Built-in modules are part of Python’s Standard Library. They are already available
when Python is installed, so programmers can simply use them by importing. These
modules save time because programmers do not need to write basic logic themselves.

Types of Built-in Modules with Examples


(i) Mathematical (math)
Provides advanced math functions.
import math
print([Link](49))
print([Link](6))
print([Link](24, 36))
Output:
7.0
720
12

(ii) Random Numbers (random)


Generates random values.
import random
print([Link](1, 100))
print([Link](2, 5))
print([Link](["apple", "banana", "cherry"]))
Possible Output:
87
3.42
banana

(iii) Date and Time (datetime)


Used for handling dates and times.
import datetime
today = [Link]()
now = [Link]()
print(today)
print([Link]("%H:%M:%S"))
Output:
2025-09-07
[Link]
(iv) File and OS Handling (os)
Manages files and directories.
import os
print([Link]())
print([Link]("."))
Output:
C:\Users\Deepika
['[Link]', '[Link]']

(v) System Functions (sys)


Provides information about the Python interpreter.
import sys
print([Link])
print([Link])
Output:
3.11.7
win32

(vi) Regular Expressions (re)


Pattern matching in strings.
import re
text = "Python is powerful"
x = [Link]("power", text)
print([Link]())
Output:
power

Explanation:
Built-in modules provide ready-made functions for mathematics, randomness, dates,
files, system-level operations, and text searching. They make Python powerful and
versatile without writing everything from scratch.

User-Defined Modules
Explanation
User-defined modules are created by programmers for specific purposes. They are
Python files (.py) that contain functions, variables, or classes.
Such modules are very useful in large projects where code can be organized into
multiple files and reused across programs.

Steps to Use User-Defined Modules


1. Create a module (e.g., my_module.py).
2. Write code inside the file.
3. Import the module in another Python program.
4. Use the functions or variables inside it.
Types of User-Defined Modules with Examples
(i) Functions Module
math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
[Link]
import math_utils
print(math_utils.add(10, 5))
print(math_utils.multiply(3, 4))
Output:
15
12

(ii) Variables Module


[Link]
app_name = "Library System"
version = "2.0"
[Link]
import config
print(config.app_name)
print([Link])
Output:
Library System
2.0

(iii) Class-based Module


[Link]
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return 3.14159 * self.r * self.r
[Link]
from shapes import Circle
c = Circle(5)
print([Link]())
Output:
78.53975
.

Text Files: Opening, Reading and Writing in Python


Text files are widely used to store and manipulate data in many applications. In
Python, file handling is performed using built-in functions. File operations generally
involve the following steps: opening a file, reading or writing data, and then closing
the file. It is also important to handle exceptions to ensure the program runs smoothly
even when errors occur.

1. Opening a Text File


The open() function is used to open a file. It requires two arguments: the file name and
the mode in which the file is to be opened.
• "r" – Read mode (default; file must exist)
• "w" – Write mode (creates new file or overwrites existing one)
• "a" – Append mode (adds new data without removing old content)
• "r+" – Read and Write mode
Example:
file = open("[Link]", "r")

2. Reading from a Text File


Python provides several methods for reading data from files:
• read() – reads the entire file as one string
• readline() – reads a single line from the file
• readlines() – reads all lines and stores them in a list
• Iteration (for line in file:) – reads file line by line
Example:
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

file = open("[Link]", "r")


line = [Link]()
print(line)
[Link]()

file = open("[Link]", "r")


lines = [Link]()
print(lines)
[Link]()

file = open("[Link]", "r")


for line in file:
print(line)
[Link]()

3. Writing to a Text File


To write data into a file, it must be opened in "w" or "a" mode.
• "w" overwrites the file if it already exists.
• "a" appends data to the end of the file.
Example:
file = open("[Link]", "w")
[Link]("Hello, World!\n")
[Link]("This is a new line.\n")
[Link]()

file = open("[Link]", "a")


[Link]("This line is appended.\n")
[Link]()

4. Closing a File
Closing a file is necessary to release system resources and ensure data is written
properly. The close() method is used for this purpose.
Example:
file = open("[Link]", "r")
data = [Link]()
print(data)
[Link]()

Alternatively, the with statement can be used, which closes the file automatically after
execution.
Example:
with open("[Link]", "r") as file:
data = [Link]()
print(data)

Exception Handling in Python and Its Types


Exception handling in Python is a way to deal with errors that occur during program
execution. An exception is an unwanted event or error that interrupts the normal flow
of the program. If not handled, the program stops suddenly. With exception handling,
we can catch such errors, display meaningful messages, and allow the program to
continue running instead of crashing.
Python provides the try, except, else, finally blocks and the raise keyword to manage
exceptions.

1. Single Exception Handling


In this type, the program is prepared to handle only one specific type of error. If that
error occurs, the except block is executed. This is the simplest form of exception
handling.
It is used when the programmer is sure about the kind of error that may arise. For
example, converting a string to an integer may fail if the string is not numeric. In such
a case, only ValueError needs to be handled.
Example:
try:
x = int("abc")
except ValueError:
print("Invalid conversion to integer")
Output:
Invalid conversion to integer

2. Multiple Exception Handling


Sometimes, more than one type of error may occur inside a block of code. In such
cases, multiple except blocks can be used. Each block handles a different error.
Python checks each exception type one by one and executes the matching block.
This method is useful when we want to handle different errors in different ways. For
example, dividing by zero and missing files are completely unrelated errors, and each
requires its own handling.
Example:
try:
f = open("[Link]", "r")
print(10/0)
except FileNotFoundError:
print("File not found")
except ZeroDivisionError:
print("Division by zero not allowed")
Output (if file does not exist):
File not found
Output (if file exists):
Division by zero not allowed

3. Multiple Exceptions in One Block


In some cases, two or more exceptions need the same handling. Writing separate
except blocks would be repetitive. Python allows grouping exceptions in a tuple, so a
single block can handle all of them.
This is useful when the program does not need to differentiate between the errors and
can respond in the same way.
Example:
try:
num = int("xyz")
f = open("[Link]", "r")
except (ValueError, FileNotFoundError):
print("Value error or file not found error occurred")
Output:
Value error or file not found error occurred

4. Else Block
The else block is special. It runs only when no exception occurs in the try block. This
helps in separating the normal execution logic from the error-handling logic.
It is useful when you want to perform some task only if the risky code worked
correctly.
Example:
try:
num = int("123")
except ValueError:
print("Invalid input")
else:
print("Conversion successful:", num)
Output:
Conversion successful: 123

5. Finally Block
The finally block is always executed, whether there is an error or not. It is used for
cleanup operations such as closing files, disconnecting databases, or releasing
resources.
Even if an exception occurs and is not caught, the finally block will still run before the
program stops.
Example:
try:
f = open("[Link]", "w")
[Link]("Hello")
except Exception as e:
print("Error:", e)
finally:
[Link]()
print("File closed")
Output:
File closed

You might also like