0% found this document useful (0 votes)
8 views38 pages

Python Exception Handling Examples

The document outlines multiple Python programs demonstrating exception handling, file operations, and stack implementations. Each program has a specific aim, such as handling division by zero, counting characters in a file, or managing a binary file with student records. Expected outputs are provided for each program to illustrate their functionality.

Uploaded by

Ayush Tyagi
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)
8 views38 pages

Python Exception Handling Examples

The document outlines multiple Python programs demonstrating exception handling, file operations, and stack implementations. Each program has a specific aim, such as handling division by zero, counting characters in a file, or managing a binary file with student records. Expected outputs are provided for each program to illustrate their functionality.

Uploaded by

Ayush Tyagi
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

Program–1

Aim

To handle division by zero using exception handling.

Program Code
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = a / b
print("Result:", c)

except ZeroDivisionError:
print("Error: Division by zero is not allowed")

except ValueError:
print("Error: Please enter valid integers")

Expected Output
Enter first number: 10
Enter second number: 0
Error: Division by zero is not allowed
Program–2
Aim

To raise an exception when age is less than 18.

Program Code
age = int(input("Enter age: "))

if age < 18:


raise ValueError("Age must be 18 or above")

print("You are eligible")

Expected Output
Enter age: 15
ValueError: Age must be 18 or above
Program–3
Aim

To demonstrate the use of finally clause.

Program Code
try:
f = open("[Link]", "r")
print([Link]())

except FileNotFoundError:
print("File not found")

finally:
print("Program executed successfully")

Expected Output
File not found
Program executed successfully
Program–4
Aim

To read a text file line by line and display each word separated by #.

Algorithm

1. Open the text file in read mode.


2. Read the file line by line.
3. Split each line into words.
4. Display the words separated by #.
5. Close the file.

Program Code

try:
f = open("[Link]", "r")
for line in f:
print("#".join([Link]()))
[Link]()

except FileNotFoundError:
print("File does not exist")

Expected Output:

This#is#a#sample#file
Python#is#easy#to#learn
Program–5
Aim

To count the number of vowels, consonants, uppercase and lowercase characters in a text file.

Algorithm

1. Open the file in read mode.


2. Read the complete content.
3. Check each character.
4. Count vowels, consonants, uppercase and lowercase letters.
5. Display the counts.

Program Code

try:
f = open("[Link]", "r")
text = [Link]()
[Link]()
v = c = u = l = 0
for ch in text:
if [Link]():
if [Link]() in "aeiou":
v += 1
else:
c += 1
if [Link]():
u += 1
if [Link]():
l += 1
print("Vowels:", v)
print("Consonants:", c)
print("Uppercase:", u)
print("Lowercase:", l)

except FileNotFoundError:
print("File not found")

Expected Output:
Vowels: 12
Consonants: 20
Uppercase: 3
Lowercase: 29
Program–6
Aim

To remove all lines containing the character 'a' and write the remaining lines into another
file.

Algorithm

1. Open source file in read mode.


2. Open destination file in write mode.
3. Read each line.
4. Write only lines not containing 'a'.
5. Close both files.

Program Code

try:
f1 = open("[Link]", "r")
f2 = open("[Link]", "w")

for line in f1:


if 'a' not in line:
[Link](line)

[Link]()
[Link]()

print("Lines copied successfully")

except FileNotFoundError:
print("Input file not found")

Expected Output
Lines without character 'a' are copied to output file.
Program–7
Aim

To generate a random number between 1 and 6 (Dice simulation).

Program Code

import random

try:
print("Dice value:", [Link](1, 6))
except Exception:
print("Error occurred")

Expected Output
Dice Value: 4
Program–8
Aim

To implement stack operations using list.

Program Code

stack = []

while True:
try:
print("[Link] [Link] [Link] [Link]")
ch = int(input("Enter choice: "))

if ch == 1:
[Link](input("Enter element: "))
elif ch == 2:
print("Popped:", [Link]())
elif ch == 3:
print(stack)
elif ch == 4:
break

except IndexError:
print("Stack is empty")
except ValueError:
print("Invalid input")

Expected Output
[Link] [Link] [Link] [Link]
Enter choice: 1
Enter element: 10
[10]
Program – 9
Aim
To accept strings/sentences from the user until the user enters “END”, store them in a text
file, and then display only those sentences which begin with an uppercase alphabet.
Algorithm
1. Open a text file in write mode.
2. Accept sentences from the user.
3. Stop input when user enters END.
4. Close the file.
5. Reopen the file in read mode.
6. Display only those sentences starting with an uppercase letter.
7. Handle file-related exceptions.

Program Code
try:
f = open("[Link]", "w")

while True:
s = input("Enter sentence (END to stop): ")
if s == "END":
break
[Link](s + "\n")

[Link]()

f = open("[Link]", "r")
print("\nSentences starting with uppercase letter:")

for line in f:
if line[0].isupper():
print([Link]())
[Link]()

except FileNotFoundError:
print("File error occurred")

Expected Output
Enter sentence (END to stop): Python is easy
Enter sentence (END to stop): this is python
Enter sentence (END to stop): Learning is fun
Enter sentence (END to stop): END

Sentences starting with uppercase letter:


Python is easy
Learning is fun
Program – 10
Aim

To enter item details in a binary file and display them along with the calculated amount
(Price × Quantity).

Algorithm

1. Accept number of records from the user.


2. Store item details in a binary file using pickle.
3. Read records from the file.
4. Calculate amount as Price × Quantity.
5. Display records in the given format.
6. Handle end-of-file and file errors.

Program Code

import pickle

try:
f = open("[Link]", "wb")
n = int(input("Enter number of records: "))

for i in range(n):
ino = int(input("Enter Item No: "))
name = input("Enter Item Name: ")
qty = int(input("Enter Quantity: "))
price = float(input("Enter Price: "))
[Link]([ino, name, qty, price], f)

[Link]()

f = open("[Link]", "rb")
print("\nItem Details\n")

try:
while True:
data = [Link](f)
amount = data[2] * data[3]

print("Item No:", data[0])


print("Item Name:", data[1])
print("Quantity:", data[2])
print("Price per item:", data[3])
print("Amount:", amount)
print("-" * 20)
except EOFError:
pass
[Link]()

except FileNotFoundError:
print("File not found")
except ValueError:
print("Invalid input")

Expected Output
Enter number of records: 1
Enter Item No: 101
Enter Item Name: Pen
Enter Quantity: 10
Enter Price: 5

Item Details

Item No: 101


Item Name: Pen
Quantity: 10
Price per item: 5.0
Amount: 50.0
--------------------
Program – 11
Aim

To reverse a string using stack.

Algorithm

1. Create an empty stack (list).


2. Accept a string from the user.
3. Push each character of the string onto the stack.
4. Pop characters one by one from the stack.
5. Join the popped characters to form the reversed string.
6. Display the reversed string.

Program Code

stack = []

s = input("Enter a string: ")

for ch in s:
[Link](ch)

rev = ""
while stack:
rev = rev + [Link]()

print("Reversed string:", rev)

Expected Output
Enter a string: Python
Reversed string: nohtyP
Program – 12
Aim

To create a stack containing only odd numbers and display the largest odd number present
in the stack.

Algorithm

1. Create an empty stack.

2. Accept numbers from the user.

3. Push only odd numbers into the stack.

4. Display stack contents.

5. Pop elements one by one.

6. Maintain the largest odd number.

7. Display the largest odd number.

Program Code

stack = []
n = int(input("Enter number of elements: "))
for i in range(n):
num = int(input("Enter number: "))
if num % 2 != 0:
[Link](num)
print("Stack contents:", stack)
if stack:
largest = [Link]()

while stack:
temp = [Link]()
if temp > largest:
largest = temp
print("Largest odd number:", largest)
else:
print("No odd numbers entered")

Expected Output
Enter number of elements: 5
Enter number: 10
Enter number: 15
Enter number: 7
Enter number: 20
Enter number: 9

Stack contents: [15, 7, 9]


Largest odd number: 15

Program – 13
Aim

To implement stack operations (Push, Pop, Peek and Display) using list in Python.

Algorithm

1. Create an empty list to represent stack.


2. Display menu options:
o Push
o Pop
o Peek
o Display
o Exit
3. Accept user choice.
4. Perform selected operation:
o Push: Insert element into stack.
o Pop: Remove top element.
o Peek: Display top element.
o Display: Show all elements of stack.
5. Repeat until user chooses Exit.
6. Handle stack underflow using exception handling.

Program Code
stack = []

while True:
print("\n--- STACK MENU ---")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")

try:
ch = int(input("Enter your choice: "))

if ch == 1:
item = input("Enter element to push: ")
[Link](item)
print("Element pushed")
elif ch == 2:
print("Popped element:", [Link]())

elif ch == 3:
print("Top element:", stack[-1])

elif ch == 4:
print("Stack contents:", stack)

elif ch == 5:
print("Exiting program")
break

else:
print("Invalid choice")

except IndexError:
print("Stack is empty")

except ValueError:
print("Please enter a valid number")

Expected Output
--- STACK MENU ---
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter element to push: 10
Element pushed

Enter your choice: 4


Stack contents: ['10']

Enter your choice: 2


Popped element: 10

Enter your choice: 5


Exiting program
Program – 14
Aim

To create a menu-driven program using file handling and perform various string
operations on the contents of a text file.

Operations Performed
1. Write data to a file
2. Display file content
3. Count vowels, consonants, uppercase & lowercase characters
4. Display lines starting with uppercase letter
5. Search a word in the file
6. Exit

Algorithm
1. Display menu options.
2. Accept user choice.
3. Perform selected file/string operation.
4. Repeat until user selects Exit.
5. Handle file-related errors using exception handling.

Program Code
while True:
print("\n--- FILE HANDLING MENU ---")
print("1. Write to file")
print("2. Read file")
print("3. Count vowels, consonants, uppercase, lowercase")
print("4. Display lines starting with uppercase letter")
print("5. Search a word in file")
print("6. Exit")

try:
ch = int(input("Enter your choice: "))

# 1. Write to file
if ch == 1:
f = open("[Link]", "w")
print("Enter text (END to stop):")
while True:
s = input()
if s == "END":
break
[Link](s + "\n")
[Link]()
print("Data written successfully")

# 2. Read file
elif ch == 2:
f = open("[Link]", "r")
print("\nFile Content:")
print([Link]())
[Link]()

# 3. Count characters
elif ch == 3:
f = open("[Link]", "r")
text = [Link]()
[Link]()

v = c = u = l = 0
for chh in text:
if [Link]():
if [Link]() in "aeiou":
v += 1
else:
c += 1
if [Link]():
u += 1
if [Link]():
l += 1

print("Vowels:", v)
print("Consonants:", c)
print("Uppercase:", u)
print("Lowercase:", l)

# 4. Lines starting with uppercase


elif ch == 4:
f = open("[Link]", "r")
print("\nLines starting with uppercase:")
for line in f:
if line[0].isupper():
print([Link]())
[Link]()

# 5. Search a word
elif ch == 5:
word = input("Enter word to search: ")
f = open("[Link]", "r")
found = False
for line in f:
if word in line:
found = True
break
[Link]()

if found:
print("Word found in file")
else:
print("Word not found")

# 6. Exit
elif ch == 6:
print("Exiting program")
break
else:
print("Invalid choice")

except FileNotFoundError:
print("File does not exist")
except ValueError:
print("Please enter a valid number")

Expected Output (Sample)


--- FILE HANDLING MENU ---
1. Write to file
2. Read file
3. Count vowels, consonants, uppercase, lowercase
4. Display lines starting with uppercase letter
5. Search a word in file
6. Exit

Enter your choice: 1


Enter text (END to stop):
Python is Easy
this is file handling
Learning Python
END
Data written successfully

Enter your choice: 4


Lines starting with uppercase:
Python is Easy
Learning Python
Program – 15
Aim

To create a menu-driven program to manage a binary file containing roll number and
name, and perform add, search, update, delete, and display operations.

Operations Performed
1. Create a file
2. Create / Add records
3. Search a record
4. Update a record
5. Delete a record
6. Display all record
7. Exit

Algorithm

1. Display menu options:


o Add record
o Search record
o Update record
o Delete record
o View Record
o Exit
2. Accept user choice.
3. Perform selected operation using binary file ([Link]).
4. Use exception handling to manage file errors.
5. Repeat until user chooses Exit.

Program Code

import pickle
import os

filename = "[Link]"
while True:
print("\n--- BINARY FILE MENU ---")
print("1. Add Record")
print("2. Search Record")
print("3. Update Record")
print("4. Delete Record")
print("5. View All Records")
print("6. Exit")
try:
ch = int(input("Enter your choice: "))

# 1. ADD RECORD
if ch == 1:
f = open(filename, "ab")
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
[Link]([roll, name], f)
[Link]()
print("Record added successfully")

# 2. SEARCH RECORD
elif ch == 2:
f = open(filename, "rb")
r = int(input("Enter roll number to search: "))
found = False

try:
while True:
data = [Link](f)
if data[0] == r:
print("Name:", data[1])
found = True
break
except EOFError:
pass

if not found:
print("Roll number not found")
[Link]()

# 3. UPDATE RECORD
elif ch == 3:
f = open(filename, "rb")
temp = []
r = int(input("Enter roll number to update: "))
found = False

try:
while True:
data = [Link](f)
if data[0] == r:
data[1] = input("Enter new name: ")
found = True
[Link](data)
except EOFError:
pass
[Link]()

f = open(filename, "wb")
for rec in temp:
[Link](rec, f)
[Link]()

if found:
print("Record updated successfully")
else:
print("Roll number not found")

# 4. DELETE RECORD
elif ch == 4:
f = open(filename, "rb")
temp = []
r = int(input("Enter roll number to delete: "))
found = False

try:
while True:
data = [Link](f)
if data[0] != r:
[Link](data)
else:
found = True
except EOFError:
pass
[Link]()

f = open(filename, "wb")
for rec in temp:
[Link](rec, f)
[Link]()

if found:
print("Record deleted successfully")
else:
print("Roll number not found")

# 5. VIEW ALL RECORDS


elif ch == 5:
f = open(filename, "rb")
print("\nRoll No\tName")

try:
while True:
data = [Link](f)
print(data[0], "\t", data[1])
except EOFError:
pass

[Link]()

# 6. EXIT
elif ch == 6:
print("Exiting program")
break

else:
print("Invalid choice")

except FileNotFoundError:
print("Binary file not found")
except ValueError:
print("Invalid input")

Expected Output

--- BINARY FILE MENU ---


1. Add Record
2. Search Record
3. Update Record
4. Delete Record
5. View All Records
6. Exit

Enter your choice: 1


Enter roll number: 2
Enter name: Rohan
Record added successfully

Enter your choice: 2


Enter roll number to search: 2
Name: Rohan

Enter your choice: 5


Roll No Name
2 Rohan
Program – 16
Aim
To create a menu-driven program using CSV file handling to store roll number and name
and perform add, search, update, delete, and display operations.

Algorithm
1. Display menu options.
2. Accept user choice.
3. Perform selected operation on CSV file:
o Add record
o Search record
o Update record
o Delete record
o View all records
4. Use temporary list for update and delete operations.
5. Repeat until user selects Exit.

Program Code
import csv
import os

filename = "[Link]"

# Create file with header if not exists


if not [Link](filename):
f = open(filename, "w", newline="")
writer = [Link](f)
[Link](["Roll", "Name"])
[Link]()

while True:
print("\n--- CSV FILE MENU ---")
print("1. Add Record")
print("2. Search Record")
print("3. Update Record")
print("4. Delete Record")
print("5. View All Records")
print("6. Exit")
try:
ch = int(input("Enter your choice: "))

# 1. ADD RECORD
if ch == 1:
f = open(filename, "a", newline="")
writer = [Link](f)
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
[Link]([roll, name])
[Link]()
print("Record added successfully")
# 2. SEARCH RECORD
elif ch == 2:
r = input("Enter roll number to search: ")
found = False
f = open(filename, "r")
reader = [Link](f)
next(reader)

for row in reader:


if row[0] == r:
print("Name:", row[1])
found = True
break
[Link]()
if not found:
print("Roll number not found")

# 3. UPDATE RECORD
elif ch == 3:
r = input("Enter roll number to update: ")
records = []
found = False
f = open(filename, "r")
reader = [Link](f)
records = list(reader)
[Link]()
for i in range(1, len(records)):
if records[i][0] == r:
records[i][1] = input("Enter new name: ")
found = True
f = open(filename, "w", newline="")
writer = [Link](f)
[Link](records)
[Link]()
if found:
print("Record updated successfully")
else:
print("Roll number not found")

# 4. DELETE RECORD
elif ch == 4:
r = input("Enter roll number to delete: ")
records = []
found = False
s f = open(filename, "r")
reader = [Link](f)
records = list(reader)
[Link]()
new_records = [records[0]]
for i in range(1, len(records)):
if records[i][0] != r:
new_records.append(records[i])
else:
found = True
f = open(filename, "w", newline="")
writer = [Link](f)
[Link](new_records)
[Link]()

if found:
print("Record deleted successfully")
else:
print("Roll number not found")

# 5. VIEW ALL RECORDS


elif ch == 5:
f = open(filename, "r")
reader = [Link](f)
print("\nRoll No\tName")
next(reader)
for row in reader:
print(row[0], "\t", row[1])
[Link]()

# 6. EXIT
elif ch == 6:
print("Exiting program")
break

else:
print("Invalid choice")

except ValueError:
print("Invalid input")
except FileNotFoundError:
print("CSV file not found")

Expected Output (Sample)


--- CSV FILE MENU ---
1. Add Record
2. Search Record
3. Update Record
4. Delete Record
5. View All Records
6. Exit

Enter your choice: 1


Enter roll number: 2
Enter name: Rohan
Record added successfully

Enter your choice: 2


Enter roll number to search: 2
Name: Rohan

Enter your choice: 5


Roll No Name
2 Rohan

Program – 17
Aim
Create a STUDENT table and insert data. Implement the following SQL commands:

 ALTER TABLE (add / modify / drop attribute)


 UPDATE table
 ORDER BY (ascending / descending)
 DELETE tuple(s)
 GROUP BY with MIN, MAX, SUM, COUNT, AVG

Query1: Create Database:

CREATE DATABASE school;


USE school;

Query2: Create Table:

CREATE TABLE student (


rollno INT PRIMARY KEY,
name VARCHAR(30),
class INT,
marks INT
);
Query3: Insert Data into Table

INSERT INTO student VALUES


(1, 'Rohan', 12, 85),
(2, 'Amit', 12, 78),
(3, 'Neha', 11, 92),
(4, 'Pooja', 11, 88),
(5, 'Rahul', 12, 67);

Query4: Alter Table

i) ALTER TABLE student ADD city VARCHAR(20);


ii) ALTER TABLE student MODIFY name VARCHAR(40);

iii) ALTER TABLE student DROP city;


Query5: UPDATE Table Data

UPDATE student SET marks = 80 WHERE rollno = 2;

Query6: Delete Data from Table

DELETE FROM student WHERE rollno = 5;


Query7: ORDER BY with Select Query

i) SELECT * FROM student ORDER BY marks ASC;

ii) SELECT * FROM student ORDER BY marks DESC;


Query8: GROUP BY with Select Query

i) SELECT class, COUNT(*) FROM student GROUP BY class;


ii) SELECT class, MAX(marks) FROM student GROUP BY class;

iii) SELECT class, MIN(marks) FROM student GROUP BY class;


iv) SELECT class, SUM(marks) FROM student GROUP BY class;
v) SELECT class, AVG(marks) FROM student GROUP BY class;
Program – 18
Aim

To create a table in MySQL using Python.


import [Link]
try:
con = [Link](
host="localhost",
user="root",
password="Asob@123",
database="school"
)
cur = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS student (
rollno INT PRIMARY KEY,
name VARCHAR(30),
class INT,
marks INT
)
""")
print("Table created successfully")
except [Link] as e:
print("Error:", e)
finally:
if con.is_connected():
[Link]()
print("MySQL connection closed")

Program – 19
Aim

To insert records into MySQL table using Python.


import [Link]
con = [Link](
host="localhost",
user="root",
password="Asob@123",
database="school"
)
cur = [Link]()
sql = "INSERT INTO student VALUES (%s, %s, %s, %s)"
data = (6, "Sagar", 12, 85)
[Link](sql, data)
[Link]()
print("Record inserted")
[Link]()
Program – 20
Aim

To display records from MySQL table using Python.

Program Code:

import [Link]

con = [Link](
host="localhost",
user="root",
password="Asob@123",
database="school"
)

cur = [Link]()

[Link]("SELECT * FROM student")


records = [Link]()

for row in records:


print(row)

[Link]()
Program – 20
Aim

To display records from MySQL table using Python.

Program Code:

import [Link]

con = [Link](
host="localhost",
user="root",
password="root",
database="school"
)

cur = [Link]()

r = int(input("Enter roll number: "))


sql = "SELECT * FROM student WHERE rollno = %s"
[Link](sql, (r,))

rec = [Link]()

if rec:
print(rec)
else:
print("Record not found")

[Link]()

You might also like