0% found this document useful (0 votes)
6 views17 pages

Python Programming Exam Questions

This document is a question paper for the B.E./B.Tech. End Semester Theory Examinations in Electrical and Electronics Engineering, focusing on Problem Solving and Python Programming. It includes various questions related to Python programming concepts, such as characteristics of Python, data structures, recursion, and operators, along with coding tasks and explanations. The paper is structured into two parts, with Part A consisting of short answer questions and Part B containing coding problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

Python Programming Exam Questions

This document is a question paper for the B.E./B.Tech. End Semester Theory Examinations in Electrical and Electronics Engineering, focusing on Problem Solving and Python Programming. It includes various questions related to Python programming concepts, such as characteristics of Python, data structures, recursion, and operators, along with coding tasks and explanations. The paper is structured into two parts, with Part A consisting of short answer questions and Part B containing coding problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Question Paper Code: 2423049

B.E./[Link]. End Semester Theory Examinations, November/December 2025.


Second / Third Semester
Electrical and Electronics Engineering
23CST 201 - PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to Information Technology / Computer Science and Engineering / Artificial Intelligence
and Data Science / Computer and Communication Engineering / Computer Science and Business
Systems / Computer Science and Engineering (Artificial Intelligence and Machine Learning))
(Regulations 2023)
Time: Three Hours Answer ALL Questions Max. Marks 100

PART - A (10 x 2 = 20 Marks)

1. List any four characteristics of Python. (CO 1) [RE]


Python is a high-level programming language that is easy to learn and use. It is an interpreted
language, so programs are executed line by line. Python is platform independent and can run on
different operating systems. It also supports object-oriented programming concepts.

2. Predict the output of following Python code. (CO 1) [UN]


a=-5%3
b=5//3
print(a)
print(b)
The modulus operator returns the remainder after division. In Python, -5 % 3 gives a positive
remainder. The floor division operator returns the quotient without decimals.
The output will be:
1
1

3. Define list. Write a python code to obtain input for a list from user. (CO 2) [RE]
A list is an ordered and mutable collection of elements in Python. Lists can store multiple
values of different data types. They are enclosed within square brackets. Input can be taken using
input() and stored as a list.
Code:
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
[Link](input("Enter element: "))
print(lst)

4. Write a python code using function that takes integer as a parameter, it should return
"True" if given number is prime number else it should return "False". (CO 2) [UN]
A function is defined to accept an integer parameter. The number is checked for divisibility
using a loop. If the number has no divisors other than 1 and itself, it is prime. The function returns
True or False accordingly.
Code:
def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True

5. How do you identify the length of the string in Python? (CO 3) [UN]
The length of a string in Python is identified using the built-in len() function. It returns the
total number of characters in the string. Spaces are also counted as characters. The function helps in
string manipulation operations.

6. Differentiate local and global scope in Python. (CO 3) [UN]


Local variables are declared inside a function and can be accessed only within that function.
Global variables are declared outside a function and can be accessed throughout the program. Local
scope is limited, while global scope is wide. Python determines scope using variable location.

7. List in Python are mutable. Justify with example. (CO 4) [UN]


Lists in Python are mutable, meaning their elements can be changed after creation. Values in
a list can be modified using indexing. This allows updating, inserting, or deleting elements. This
property makes lists flexible data structures.
Example:
A = [10, 20, 30]
A[1] = 50
print(A)
Output:
[10, 50, 30]

8. Give the syntax for declaring and initializing dictionary in Python. (CO 4) [UN]
A dictionary is declared using curly braces. It stores data in key–value pairs. Keys must be
unique and immutable. Syntax example: dict = {1:"A", 2:"B"}.

9. What is Command Line Argument in Python? (CO 5) [RE]


Command line arguments are values passed to a Python program during execution. They are
used to provide input externally. These arguments are accessed using the sys module. Command line
arguments increase program flexibility.

10. How do you create and use own module in Python? (CO 5) [UN]
A module is created by saving Python code in a file with a .py extension. The module can
contain functions and variables. It can be used in another program using the import statement.
Modules promote code reuse and organization.

PART - B (5 x 16 = 80 Marks)

11. a) i) Write a Python code to display Fibonacci using recursion. (CO 1) [AP] (8)
The Fibonacci series is a sequence of numbers in which each number is the sum of the
previous two numbers. Recursion is a technique in which a function calls itself to solve a problem.
Using recursion, the Fibonacci series can be generated in a simple and clear manner.
Definition of Recursion
Recursion is a programming technique where a function calls itself repeatedly until a base
condition is satisfied. It is mainly used to solve problems that can be divided into smaller
subproblems.
Logic of Fibonacci Using Recursion
 If the value of n is 0, the Fibonacci value is 0.
 If the value of n is 1, the Fibonacci value is 1.
 For any other value, Fibonacci(n) is equal to Fibonacci(n-1) + Fibonacci(n-2).
Code:
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-

2) n = int(input("Enter number of terms:

"))

print("Fibonacci Series:") for


i in range(n):
print(fibonacci(i), end=" ")
Explanation of the Program
The function fibonacci is defined using recursion. The base conditions handle the cases when
n is 0 or 1. For other values, the function calls itself to calculate the sum of the previous two
Fibonacci numbers. The for loop is used to display the Fibonacci series up to the given number of
terms.

11. a) ii) Write a Python code using function that accepts list and integer k as a parameter. The
function should return the kth smallest element of a list. (CO 1) [AP] (8)
In Python, lists are used to store multiple values. Finding the kth smallest element in a list is a
common problem in data processing and algorithm design. By using a function, the program becomes
modular, reusable, and easy to understand.
Problem Description
The function should accept a list of elements and an integer k as parameters. The function
should return the kth smallest element present in the list.
Program Logic
 Accept a list of numbers from the user.
 Accept the value of k from the user.
 Sort the list in ascending order.
 Return the element present at position k-1 since list indexing starts from zero.
Code:
def kth_smallest(lst, k):
[Link]()
return lst[k-1]

numbers = []
n = int(input("Enter number of elements: "))

for i in range(n):
[Link](int(input("Enter element: ")))

k = int(input("Enter value of k: "))

result = kth_smallest(numbers, k)
print("The", k, "th smallest element is:", result)
Explanation of the Program
The function kth_smallest takes two parameters: a list and an integer k. The list is first sorted
in ascending order. The element at index k-1 is returned as the kth smallest element. The function is
called from the main program, and the result is displayed.

OR

11. b) Create and illustrate the Tower of Hanoi problem using Python programming.
(CO 1) [AP] (16)
The Tower of Hanoi is a classic problem in computer science used to explain the concept of
recursion. It involves moving a set of disks from one peg to another by following a specific set of
rules. This problem helps students understand recursive thinking, problem decomposition, and
function calls in Python.
Problem Description
The Tower of Hanoi problem consists of three pegs called the source peg, auxiliary peg, and
destination peg. A number of disks are placed on the source peg in such a way that the largest disk is
at the bottom and the smallest disk is at the top. The objective is to move all the disks from the source
peg to the destination peg using the auxiliary peg.
Rules of the Tower of Hanoi
 Only one disk can be moved at a time.
 A larger disk cannot be placed on top of a smaller disk.
 All disks must be moved from the source peg to the destination peg following the above rules.
Illustration of the Problem
Initially, all disks are placed on the source peg. The auxiliary and destination pegs are empty.
By following the rules, the disks are moved step by step until all disks reach the destination peg in the
correct order. The auxiliary peg is used temporarily to assist in moving the disks.
Approach to Solve the Problem
The Tower of Hanoi problem is solved using recursion. The main idea is to move the top n-1
disks from the source peg to the auxiliary peg, then move the nth disk to the destination peg, and
finally move the n-1 disks from the auxiliary peg to the destination peg.
Algorithm Logic (Conceptual)
If there is only one disk, move it directly from the source peg to the destination peg.
If there are more than one disk, first move n-1 disks from source to auxiliary, then move the largest
disk to destination, and finally move the n-1 disks from auxiliary to destination.
Code:
def tower_of_hanoi(n, source, auxiliary, destination):
if n == 1:
print("Move disk 1 from", source, "to", destination)
return

tower_of_hanoi(n-1, source, destination, auxiliary)


print("Move disk", n, "from", source, "to",
destination) tower_of_hanoi(n-1, auxiliary, source,
destination)

n = int(input("Enter number of disks: "))


tower_of_hanoi(n, "Source", "Auxiliary", "Destination")
Explanation of the Program
The function tower_of_hanoi takes four parameters: number of disks, source peg, auxiliary
peg, and destination peg.
If n equals 1, the disk is moved directly from source to destination.
If n is greater than 1, the function calls itself recursively to move n-1 disks to the auxiliary peg, then
moves the largest disk to the destination peg, and finally moves the n-1 disks from auxiliary to
destination.
This process continues until all disks are moved.
Number of Moves in Tower of Hanoi
The total number of moves required to solve the Tower of Hanoi problem is given by the
formula: 2ⁿ − 1
where n is the number of disks.

12. a) Discover the various types of operators in python with the suitable examples.
(CO 2) [AP] (16)
Operators in Python are special symbols or keywords used to perform operations on variables
and values. They are essential for writing expressions, performing calculations, comparing values, and
controlling the flow of a program. Python provides a wide variety of operators to handle different
types of operations efficiently.
Definition of Operator
An operator is a symbol that instructs the Python interpreter to perform a specific operation
on one or more operands. The data or values on which the operator works are called operands.
Classification of Operators in Python
Python operators are classified into several types based on the kind of operation they perform.

Arithmetic Operators
 Arithmetic operators are used to perform basic mathematical calculations.
 The arithmetic operators include addition, subtraction, multiplication, division, modulus,
exponentiation, and floor division.
Example:
a = 10
b=3
Addition: a + b gives 13
Subtraction: a - b gives 7
Multiplication: a * b gives 30
Division: a / b gives 3.333
Modulus: a % b gives 1
Exponentiation: a ** b gives 1000
Floor Division: a // b gives 3
Arithmetic operators are commonly used in calculations such as salary computation, interest
calculation, and mathematical problems.

Relational or Comparison Operators


Relational operators are used to compare two values. The result of a comparison is either true
or false.
The relational operators include greater than, less than, equal to, not equal to, greater than or
equal to, and less than or equal to.
Example:
a = 10
b=5
a > b returns true
a < b returns false
a == b returns
false a != b returns
true a >= b returns
true a <= b returns
false
These operators are mainly used in conditional statements and loops.

Logical Operators
 Logical operators are used to combine multiple conditions or expressions.
 Python provides three logical operators: and, or, and not.
Example:
a = 10
b=5
(a > 5 and b > 2) returns true
(a > 15 or b > 2) returns true
not(a > 5) returns false
Logical operators are widely used in decision making and control flow statements.

Assignment Operators
 Assignment operators are used to assign values to variables. Python also provides compound
assignment operators that perform arithmetic operation and assignment in a single step.
 Examples of assignment operators include =, +=, -=, *=, /=, %=, **=, and //=.
Example:
a = 10
a += 5 results in a = 15
a -= 3 results in a = 12
a *= 2 results in a = 24
Assignment operators make the code shorter and more readable.

Bitwise Operators
 Bitwise operators perform operations on values at the binary level.
 The bitwise operators include AND, OR, XOR, NOT, left shift, and right shift.
Example:
a = 5 (binary 0101)
b = 3 (binary 0011)
a & b gives 1
a | b gives 7
a ^ b gives 6
~a gives -6
a << 1 gives 10
a >> 1 gives 2
Bitwise operators are used in low-level programming and system applications.

Membership Operators
 Membership operators are used to test whether a value is present in a sequence such as a list,
tuple, or string.
 Python provides two membership operators: in and not in.
Example:
list1 = [1, 2, 3, 4]
2 in list1 returns true
5 not in list1 returns true
These operators are useful in searching and validation tasks.

Identity Operators
 Identity operators are used to compare the memory locations of two objects.
 Python provides two identity operators: is and is not.
Example:
a= 10
b = 10
a is b returns true
a is not b returns false
Identity operators check whether two variables refer to the same object in memory.

OR

12. b) Write python programs to (CO 2) [AP] (16)


(i) Exchange the values of two variables
(ii) Circulate the values of n variables
(i) Exchange the values of two variables
The objective of this program is to exchange or swap the values of two variables entered by
the user.
Program Logic
 Read two values from the user.
 Store the values in two variables.
 Use a temporary variable or Python’s multiple assignment feature to swap the values.
 Display the values after swapping.
Code:
a = int(input("Enter value of a: "))
b = int(input("Enter value of b:
")) a, b = b, a
print("After swapping")
print("a =", a)
print("b =", b)
Explanation of the Program
The program uses Python’s multiple assignment feature to exchange the values of two
variables without using a temporary variable. The values on the right-hand side are assigned
simultaneously to the variables on the left-hand side.

(ii) Circulate the values of n variables


Problem Description
The objective of this program is to circulate or rotate the values of n variables in a cyclic
order. The last value moves to the first position, and all other values shift one position to the right.
Program Logic
 Read the number of elements n.
 Store the elements in a list.
 Save the last element temporarily.
 Shift all elements one position to the right.
 Place the last element in the first position.
 Display the circulated list.
Code:
n = int(input("Enter number of elements: "))
values = []
for i in range(n):
[Link](int(input("Enter value: ")))
temp = values[-1]
for i in range(n - 1, 0, -1):
values[i] = values[i - 1]
values[0] = temp
print("Values after circulation:")
print(values)
Explanation of the Program
The program stores all values in a list. The last element is temporarily stored. All other
elements are shifted one position to the right using a loop. Finally, the last element is placed in the
first position, completing one circular rotation.

13. a) i) Write a Python program to compute square root of a given number. (CO 3) [AP] (8)
The square root of a number is a value that, when multiplied by itself, gives the original
number. Computing the square root is a common mathematical operation used in scientific and
engineering applications. Python provides built-in functions to compute the square root easily.
Problem Description
The objective of this program is to calculate the square root of a given number entered by the
user.
Program Logic
 Read a number from the user.
 Use the math module to calculate the square root.
 Display the result.
Code:
import math
num = float(input("Enter a number: "))
result = [Link](num)
print("Square root of the number is:", result)
Explanation of the Program
The program imports the math module which contains the sqrt function. The sqrt function
calculates the square root of the given number. The input number is converted to a floating-point
value to support decimal numbers.
Alternative Method Without math Module
The square root can also be calculated using the exponent operator by raising the number to
the power of 0.5.
Example:
result = num ** 0.5

13. a) ii) Write a Python program to compute sum an array of given numbers. (CO 3) [AP] (8)
An array is a collection of elements stored under a single variable name. Computing the sum
of elements in an array is a basic operation used in many applications such as data analysis, statistics,
and numerical computations. Python provides simple methods to calculate the sum of array elements.
Problem Description
The objective of this program is to compute the sum of all elements present in an array of numbers
entered by the user.
Program Logic
 Read the number of elements in the array.
 Store the elements in a list.
 Initialize a variable to store the sum.
 Traverse the array and add each element to the sum variable.
 Display the final sum.
Code:
n = int(input("Enter number of elements: "))
arr = []
for i in range(n):
[Link](int(input("Enter element: ")))
total = 0
for num in arr:
total += num
print("Sum of array elements:", total)
Explanation of the Program
The program first reads the number of elements and stores them in a list. A variable named
total is initialized to zero. Using a loop, each element of the array is added to total. Finally, the total
sum of all array elements is displayed.
Alternative Method Using Built-in Function
Python also provides a built-in function sum() to calculate the sum of elements in a list.
Example:
total = sum(arr)

OR
13. b) Illustrate the steps involved in Linear Search and Binary search with example of user
choice in Python programming. (CO 3) [AP] (16)
Searching is a fundamental operation in computer programming used to find the position of a
required element in a collection of data. Linear search and binary search are two commonly used
searching techniques. Linear search is simple and works on any list, whereas binary search is efficient
but requires the data to be sorted.
Linear Search
Definition of Linear Search
Linear search is a simple searching technique in which elements are checked one by one from
the beginning of the list until the required element is found or the list ends.
Steps Involzed in Linear Search
Step 1: Read the number of elements and store them in a list.
Step 2: Read the element to be searched from the user.
Step 3: Start from the first element of the list.
Step 4: Compare the current element with the search key.
Step 5: If a match is found, display the position and stop.
Step 6: If the end of the list is reached and no match is found, display not found.
Example of Linear Search (User Choice)
n = int(input("Enter number of elements: "))
arr = []
for i in range(n):
[Link](int(input("Enter element: ")))
key = int(input("Enter element to search: "))
found = False
for i in range(n):
if arr[i] ==
key:
print("Element found at position", i + 1)
found = True
break
if not found:
print("Element not found")
Explanation of Linear Search Program
The program compares each element of the list with the search key. If a match is found, the
position is displayed. If no match is found after checking all elements, the program displays that the
element is not found.

Steps Involved in Binary Search


1. Read the number of elements and store them in a list.
2. Sort the list in ascending order.
3. Read the element to be searched (key).
4. Set the first index as low and the last index as high.
5. Find the middle element of the list.
6. If the middle element matches the search key, display the position.
7. If the search key is smaller than the middle element, search in the left half.
8. If the search key is greater than the middle element, search in the right half.
9. Repeat the process until the element is found or the search range becomes empty.

Example of Binary Search (User Choice)


n = int(input("Enter number of elements: "))
arr = []
for i in range(n):
[Link](int(input("Enter element: ")))
[Link]()
print("Sorted list:", arr)
key = int(input("Enter element to search: "))
low = 0
high = n - 1
found = False
while low <= high:
mid = (low + high) // 2
if arr[mid] == key:
print("Element found at position", mid + 1)
found = True
break
elif key < arr[mid]:
high = mid - 1
else:
low = mid + 1
if not found:
print("Element not found")

Explanation of Binary Search Program


The list is first sorted. The program compares the search key with the middle element. If it
matches, the position is displayed. If not, the search continues in either the left or right half depending
on the comparison. This process continues until the element is found or the list is exhausted.

14. a) Explain the concept of List slicing and List processing methods in Python with examples.
(CO 4) [UN] (16)
A list is a built-in data structure in Python used to store multiple elements in an ordered
manner. Python provides powerful features to access and manipulate list elements efficiently. List
slicing and list processing methods help programmers work with lists in a flexible and effective way.
List Slicing in Python
Definition of List Slicing
List slicing is a technique used to extract a portion of a list by specifying a range of indices. It
allows accessing multiple elements at once without using loops.
Syntax of List Slicing
The general syntax of list slicing is
list_name[start : stop : step]
The start index indicates where slicing begins.
The stop index indicates where slicing ends, but the element at this index is not included.
The step value indicates the interval between elements.

Examples of List Slicing


Example 1
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
Output: [20, 30, 40]
Example 2
print(numbers[:3])
Output: [10, 20, 30]
Example 3
print(numbers[2:])
Output: [30, 40, 50, 60]
Example 4
print(numbers[::2])
Output: [10, 30, 50]
Negative Index Slicing
Python allows negative indices to access elements from the end of the list.
Example
print(numbers[-4:-1])
Output: [30, 40, 50]

Commonly Used List Processing Methods


append() Method
The append method adds an element to the end of the list.
Example
list1 = [1, 2, 3]
[Link](4)
insert() Method
The insert method adds an element at a specific index.
Example
[Link](1, 10)
extend() Method
The extend method adds elements of another list to the existing list.
Example
[Link]([5, 6])
remove() Method
The remove method deletes the first occurrence of a specified element.
Example
[Link](10)
pop() Method
The pop method removes an element at a given index and returns it.
Example
[Link](2)
sort() Method
The sort method arranges the list elements in ascending or descending order.
Example
[Link]()
reverse() Method
The reverse method reverses the order of elements in the list.
Example
[Link]()
count() Method
The count method returns the number of occurrences of an element.
Example
[Link](2)
index() Method
The index method returns the index of the first occurrence of an element.
Example
[Link](3)

OR

14. b) Write a Python program to perform the following. (CO 4) [UN] (16)
(i) Create the below mentioned table:
Emp_id Emp_Name Age Designation
1 John 45 Manager
2 Bas 25 Team Head
3 Sam 57 Developer
4 Jing 50 Tester
(ii) Update the Emp_Name as "Tin" for the Emp_id=4.
(iii) Delete the employee details whose age is greater than 50.
(iv) Display the details of all employees.

(i) Create the below mentioned table:


Code:
employees = {
1: {"Emp_Name": "John", "Age": 45, "Designation": "Manager"},
2: {"Emp_Name": "Bas", "Age": 25, "Designation": "Team Head"},
3: {"Emp_Name": "Sam", "Age": 57, "Designation": "Developer"},
4: {"Emp_Name": "Jing", "Age": 50, "Designation": "Tester"}
}

(ii) Update Emp_Name as "Tin" for Emp_id = 4


employees[4]["Emp_Name"] = "Tin"

(iii) Delete employee details whose age is greater than 50


delete_ids = []
for emp_id, details in [Link]():
if details["Age"] > 50:
delete_ids.append(emp_id)
for emp_id in delete_ids:
del employees[emp_id]

(iv) Display all employee details


print("Employee Details:")
for emp_id, details in [Link]():
print("Emp_id:", emp_id)
print("Emp_Name:", details["Emp_Name"])
print("Age:", details["Age"])
print("Designation:", details["Designation"])
print() # For spacing between employees

Explanation of the Program


Creating the Employee Table
The employee table is created using a dictionary. Each employee ID acts as a key, and the
value is another dictionary containing the employee name, age, and designation.
Updating Employee Name
The employee name for Emp_id 4 is updated by directly accessing the dictionary and
assigning the new name "Tin".
Deleting Employees Based on Age Condition
The program checks each employee’s age. If the age is greater than 50, that employee record
is deleted from the dictionary.
Displaying Employee Details
The final loop displays the details of all remaining employees after update and deletion
operations.
Output Explanation
After execution, the employee with age 57 is removed. The employee with Emp_id 4 has the
updated name "Tin". The remaining employee details are displayed correctly.

15. a) How the contents of the text file can be read using Python? Explain the same with read()
and readline(). (CO 5) [UN] (16)
File handling is an important feature of Python that allows programs to store data
permanently in files and retrieve it when required. Reading data from a text file is a common
operation in applications such as report generation, data processing, and logging. Python provides
several built-in methods to read the contents of a text file easily.

Reading a Text File in Python


Concept of File Reading
Reading a file means accessing the data stored in a file and bringing it into the program for
processing. In Python, files are read using the open() function with a suitable file mode. The file must
be opened in read mode before reading its contents.
Opening a File in Read Mode
To read a text file, the file is opened using the open() function with mode "r".
Syntax:
file_object = open("[Link]", "r")
Once the file is opened, various methods such as read(), readline(), and readlines() can be
used to read the contents of the file.

Using read() Method


Definition of read() Method
The read() method is used to read the entire contents of a file at once. It returns the content of
the file as a single string.
Working of read() Method
When read() is called without any argument, it reads all characters from the current file
pointer position till the end of the file.
Example Program Using read()
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Explanation of read() Program
The file named [Link] is opened in read mode. The read() method reads the entire content of
the file and stores it in the variable content. The content is then printed on the screen. Finally, the file
is closed using the close() method to free system resources.

Using readline() Method


Definition of readline() Method
The readline() method is used to read a single line from a file at a time. Each call to readline()
reads the next line from the file.
Working of readline() Method
When readline() is called, it reads characters from the current file pointer position until a
newline character is encountered. It returns the line as a string.
Example Program Using readline()
file = open("[Link]", "r")
line1 = [Link]()
line2 = [Link]()
print(line1)
print(line2)
[Link]()
Explanation of readline() Program
The file is opened in read mode. The first call to readline() reads the first line of the file. The
second call reads the next line. Each line is printed separately. The file is then closed.

Reading Entire File Line by Line Using readline()


Example:
file = open("[Link]", "r")
while True:
line = [Link]()
if line == "":
break
print(line, end='') # Avoids double newlines
[Link]()

OR

15. b) What is exception handling? Write a Python code to handle any two types of exception.
(CO 5) [UN] (16)
Exception handling is an important concept in Python that helps in managing runtime errors.
Errors may occur during program execution due to invalid input, division by zero, or accessing
unavailable resources. If these errors are not handled properly, the program may terminate abruptly.
Exception handling allows the program to handle errors gracefully and continue execution.
Definition of Exception
An exception is a runtime error that occurs during the execution of a program and disrupts the
normal flow of instructions. Examples of exceptions include division by zero, invalid input, and file
not found errors.
Definition of Exception Handling
Exception handling is a mechanism used to detect, handle, and manage runtime errors in a
program. It prevents abnormal termination of the program and provides meaningful error messages to
the user.
Need for Exception Handling
Exception handling is required to avoid program crashes, handle unexpected inputs, improve
program reliability, and ensure smooth execution of programs. It also helps in debugging and
maintaining programs easily.
Exception Handling Mechanism in Python
Python handles exceptions using the following keywords:
 Try
 Except
 Else
 finally
The cod e that may cause an exception is placed inside the try block. The exception is handled
inside the except block. The else block executes when no exception occurs. The finally block executes
regardless of whether an exception occurs or not.

Types of Exceptions in Python


Python provides many built-in exceptions. Some commonly used exceptions are
ZeroDivisionError, ValueError, TypeError, IndexError, and FileNotFoundError.
Handling ZeroDivisionError
Description of ZeroDivisionError
ZeroDivisionError occurs when a number is divided by zero, which is mathematically
undefined.
Python Program to Handle ZeroDivisionError
Code:
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
Explanation of the Program
The division operation is placed inside the try block. If the user enters zero as the divisor, a
ZeroDivisionError occurs. The except block catches this error and displays an appropriate message
instead of terminating the program.

Handling ValueError
Description of ValueError
ValueError occurs when an invalid value is provided to a function or operation, such as entering a
string instead of an integer.
Python Program to Handle ValueError
Code:
try:
num = int(input("Enter an integer value: "))
print("You entered:", num)
except ValueError:
print("Error: Invalid input. Please enter a valid integer")
Explanation of the Program
The program attempts to convert user input into an integer. If the user enters a non-numeric
value, a ValueError occurs. The except block handles the error and displays a suitable error message.



You might also like