0% found this document useful (0 votes)
9 views21 pages

Python Lab Programs for Students

The document contains a collection of Python programming exercises and their solutions, covering topics such as temperature conversion, student grading, sequence data types, Fibonacci series, matrix operations, vowel checking, exception handling, GUI development with Tkinter, file reading, and database applications using SQLite. Each exercise includes a brief description, code implementation, and sample output. The exercises are designed for educational purposes at SS Degree College, Bobbili.

Uploaded by

nagarajumeesalan
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)
9 views21 pages

Python Lab Programs for Students

The document contains a collection of Python programming exercises and their solutions, covering topics such as temperature conversion, student grading, sequence data types, Fibonacci series, matrix operations, vowel checking, exception handling, GUI development with Tkinter, file reading, and database applications using SQLite. Each exercise includes a brief description, code implementation, and sample output. The exercises are designed for educational purposes at SS Degree College, Bobbili.

Uploaded by

nagarajumeesalan
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

Index of Python Lab

[Link] PROGRAM TITLE [Link] REMARKS


Write a menu driven program to convert the given
temperature from Fahrenheit to Celsius and vice
versa depending upon user’s choice.
1

Write a python program to calculate total marks,


percentage and grade of a student. Marks obtained
in each of the three subjects are to be input by the
user.
Assign grades according to the following criteria :
2 Grade A: Percentage >=80
Grade B: Percentage>=70 and 80
Grade C: Percentage>=60 and <70
Grade D: Percentage>=40 and <60
Grade E: Percentage <40

Demonstrate various methods of Sequence Data


3 Types
Write a python program to display the first n terms
4 of Fibonacci series.

Write a python program to calculate the sum and


5 product of two compatible matrices

Write a function that takes a character and returns


6 True if it is a vowel and False otherwise.

Write a program to implement exception handling.


7
Develop a Python GUI calculator using Tkinter
8

Write a Python program to read last 5 lines of a file


9

Design a simple database application that stores


10 the records and retrieve the same

Design a database application to search the


11 specified record from the database.
Design a database application to that allows the
12 user to add, delete and modify the records

SS DEGREE COLLEGE, BOBBILI 1


1. Write a menu driven program to convert the given temperature from Fahrenheit to Celsius and vice
versa depending upon user’s choice.

Program:

def fahrenheit_to_celsius(f):
return (f - 32) * 5 / 9

def celsius_to_fahrenheit(c):
return (c * 9 / 5) + 32
def menu():
while True:
print("\n--- Temperature Converter ---")
print("1. Convert Fahrenheit to Celsius")
print("2. Convert Celsius to Fahrenheit")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':
f = float(input("Enter temperature in Fahrenheit: "))
c = fahrenheit_to_celsius(f)
print(f"{f}°F is equal to {c:.2f}°C")

elif choice == '2':


c = float(input("Enter temperature in Celsius: "))
f = celsius_to_fahrenheit(c)
print(f"{c}°C is equal to {f:.2f}°F")

elif choice == '3':


print("Exiting program. Goodbye!")
break

else:
print("Invalid choice! Please enter 1, 2, or 3.")

# Run the menu


menu()

Output:
--- Temperature Converter ---
1. Convert Fahrenheit to Celsius
2. Convert Celsius to Fahrenheit
3. Exit
Enter your choice (1/2/3): 1
Enter temperature in Fahrenheit: 100
100.0°F is equal to 37.78°C
SS DEGREE COLLEGE, BOBBILI 2
2. Write a python program to calculate total marks, percentage and grade of a student. Marks
obtained in each of the three subjects are to be input by the user.
Assign grades according to the following criteria :
Grade A: Percentage >=80
Grade B: Percentage>=70 and 80
Grade C: Percentage>=60 and <70
Grade D: Percentage>=40 and <60
Grade E: Percentage <40

Program:
# Function to calculate grade based on percentage
def calculate_grade(percentage):
if percentage >= 80:
return 'A'
elif percentage >= 70:
return 'B'
elif percentage >= 60:
return 'C'
elif percentage >= 40:
return 'D'
else:
return 'E'
# Input marks for 3 subjects
print("Enter marks for 3 subjects (out of 100 each):")
mark1 = float(input("Subject 1: "))
mark2 = float(input("Subject 2: "))
mark3 = float(input("Subject 3: "))
# Calculate total and percentage
total = mark1 + mark2 + mark3
percentage = total / 3
# Get grade
grade = calculate_grade(percentage)
# Display results
print("\n--- Student Report ---")
print(f"Total Marks: {total}/300")
print(f"Percentage: {percentage:.2f}%")
print(f"Grade: {grade}")
Output:
Enter marks for 3 subjects (out of 100 each):
Subject 1: 75
Subject 2: 80
Subject 3: 65
--- Student Report ---
Total Marks: 220.0/300
Percentage: 73.33%
Grade: B

SS DEGREE COLLEGE, BOBBILI 3


3. Demonstrate various methods of Sequence Data Types

Program:
print("=== STRING Methods ===")
s = "Hello, Python!"
print("Original String:", s)
print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Find 'Python':", [Link]("Python"))
print("Replace 'Python' with 'World':", [Link]("Python", "World"))
print("Split:", [Link]())
print("Slice [0:5]:", s[0:5])
print("Length:", len(s))

print("\n=== LIST Methods ===")


my_list = [10, 20, 30, 40]
print("Original List:", my_list)
my_list.append(50)
print("After append(50):", my_list)
my_list.insert(2, 25)
print("After insert at index 2:", my_list)
my_list.remove(30)
print("After remove(30):", my_list)
print("Pop element:", my_list.pop())
print("List after pop:", my_list)
print("Index of 25:", my_list.index(25))
print("Reverse list:", list(reversed(my_list)))
print("Length:", len(my_list))

print("\n=== TUPLE Methods ===")


my_tuple = (1, 2, 2, 3, 4)
print("Original Tuple:", my_tuple)
print("Count of 2:", my_tuple.count(2))
print("Index of 3:", my_tuple.index(3))
print("Length:", len(my_tuple))
print("Slice [1:4]:", my_tuple[1:4])

print("\n=== RANGE ===")


r = range(1, 10, 2)
print("Range object:", r)
print("Converted to list:", list(r))
print("Length of range:", len(r))
print("Check if 5 in range:", 5 in r)

SS DEGREE COLLEGE, BOBBILI 4


Output:
=== STRING Methods ===
Original String: Hello, Python!
Uppercase: HELLO, PYTHON!
Lowercase: hello, python!
Find 'Python': 7
Replace 'Python' with 'World': Hello, World!
Split: ['Hello,', 'Python!']
Slice [0:5]: Hello
Length: 14

=== LIST Methods ===


Original List: [10, 20, 30, 40]
After append(50): [10, 20, 30, 40, 50]
After insert at index 2: [10, 20, 25, 30, 40, 50]
...

SS DEGREE COLLEGE, BOBBILI 5


4. Write a python program to display the first n terms of Fibonacci series.

Program:
# Function to generate Fibonacci series
def fibonacci_series(n):
a, b = 0, 1
count = 0

print(f"\nFirst {n} terms of Fibonacci series:")


while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1

# Main program
n = int(input("Enter the number of terms: "))

if n <= 0:
print("Please enter a positive integer.")
else:
fibonacci_series(n)

Output:
Enter the number of terms: 7

First 7 terms of Fibonacci series:


0112358

SS DEGREE COLLEGE, BOBBILI 6


5. Write a python program to calculate the sum and product of two compatible matrices

Program :

# Function to add two matrices


def add_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
[Link](A[i][j] + B[i][j])
[Link](row)
return result

# Function to multiply two matrices


def multiply_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
sum = 0
for k in range(len(B)):
sum += A[i][k] * B[k][j]
[Link](sum)
[Link](row)
return result

# Input matrices
print("Enter dimensions of Matrix A (rows and columns):")
rows_A = int(input("Rows: "))
cols_A = int(input("Columns: "))

print("Enter elements of Matrix A:")


A = []
for i in range(rows_A):
row = list(map(int, input(f"Row {i+1}: ").split()))
[Link](row)

print("\nEnter dimensions of Matrix B:")


rows_B = int(input("Rows: "))
cols_B = int(input("Columns: "))

print("Enter elements of Matrix B:")


B = []
for i in range(rows_B):

SS DEGREE COLLEGE, BOBBILI 7


row = list(map(int, input(f"Row {i+1}: ").split()))
[Link](row)

# Check compatibility and compute


if rows_A == rows_B and cols_A == cols_B:
print("\nSum of matrices:")
sum_matrix = add_matrices(A, B)
for row in sum_matrix:
print(row)
else:
print("\nMatrices are not compatible for addition.")

if cols_A == rows_B:
print("\nProduct of matrices:")
product_matrix = multiply_matrices(A, B)
for row in product_matrix:
print(row)
else:
print("\nMatrices are not compatible for multiplication.")

Output :
Matrix A:
23
123
456

Matrix B:
23
789
10 11 12

Sum of matrices:
[8, 10, 12]
[14, 16, 18]

Matrices are not compatible for multiplication.

SS DEGREE COLLEGE, BOBBILI 8


6. Write a function that takes a character and returns True if it is a vowel and False otherwise.

Program:
def is_vowel(char):
vowels = 'aeiouAEIOU'
return char in vowels

# Example usage
ch = input("Enter a character: ")

if len(ch) != 1:
print("Please enter a single character.")
else:
if is_vowel(ch):
print(f"'{ch}' is a vowel.")
else:
print(f"'{ch}' is not a vowel.")

Output:
Enter a character: e
'e' is a vowel.

Enter a character: B
'B' is not a vowel.

SS DEGREE COLLEGE, BOBBILI 9


7. Write a program to implement exception handling.

Program:
# Program to demonstrate exception handling

try:
# Taking input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Performing division
result = num1 / num2
print(f"Result: {num1} / {num2} = {result}")

except ZeroDivisionError:
print("Error: Cannot divide by zero.")

except ValueError:
print("Error: Please enter only numeric values.")

except Exception as e:
print(f"An unexpected error occurred: {e}")

else:
print("Division performed successfully.")

finally:
print("This block always executes (end of program).")

Output:
Enter first number: 20
Enter second number: 4
Result: 20 / 4 = 5.0
Division performed successfully.
This block always executes (end of program).

Enter first number: ten


Error: Please enter only numeric values.
This block always executes (end of program).

SS DEGREE COLLEGE, BOBBILI 10


8. Develop a Python GUI calculator using Tkinter

Program:
import tkinter as tk
from tkinter import messagebox

class Calculator:
def __init__(self, root):
[Link] = root
[Link]("Simple Calculator")
[Link]("300x400")
[Link](False, False)

[Link] = ""
self.input_text = [Link]()

self.create_widgets()

def create_widgets(self):
input_frame = [Link]([Link], height=50, bd=0, highlightbackground="black", highlightcolor="black",
highlightthickness=1)
input_frame.pack(side=[Link], fill="both")

input_field = [Link](input_frame, font=('arial', 18), textvariable=self.input_text, justify='right')


input_field.pack(fill="both", ipadx=8, ipady=15)

# Buttons Frame
btns_frame = [Link]([Link])
btns_frame.pack(fill="both", expand=True)

# Button layout
buttons = [
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['C', '0', '=', '+']
]

for row in buttons:


row_frame = [Link](btns_frame)
row_frame.pack(expand=True, fill="both")
for btn_text in row:
button = [Link](row_frame, text=btn_text, font=('arial', 18), fg="black", border=0,
command=lambda x=btn_text: self.on_button_click(x))

SS DEGREE COLLEGE, BOBBILI 11


[Link](side="left", expand=True, fill="both")

def on_button_click(self, char):


if char == "C":
[Link] = ""
self.input_text.set("")
elif char == "=":
try:
result = str(eval([Link]))
self.input_text.set(result)
[Link] = result # for continued calculations
except Exception as e:
[Link]("Error", "Invalid Input")
self.input_text.set("")
[Link] = ""
else:
[Link] += str(char)
self.input_text.set([Link])

# Run the Calculator


if __name__ == "__main__":
root = [Link]()
calc = Calculator(root)
[Link]()

Output:

SS DEGREE COLLEGE, BOBBILI 12


9. Write a Python program to read last 5 lines of a file

Program:

def read_last_lines(filename, num_lines=5):


try:
with open(filename, 'r') as file:
lines = [Link]()
last_lines = lines[-num_lines:]
return last_lines
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")

# Example usage:
filename = "[Link]" # Replace with your file path
last_five = read_last_lines(filename)

if last_five:
print("Last 5 lines of the file:")
for line in last_five:
print(line, end='') # 'end' avoids double newlines
.
Output:

SS DEGREE COLLEGE, BOBBILI 13


10. Design a simple database application that stores the records and retrieve the same

Program:

import sqlite3

# Connect to SQLite database (creates file if it doesn't exist)


conn = [Link]("[Link]")
cursor = [Link]()

# Create table if it doesn't exist


[Link]('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT
)
''')

# Function to insert a user


def insert_user(name, age, email):
[Link]("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", (name, age, email))
[Link]()
print(" Record added successfully.")

# Function to display all users


def fetch_users():
[Link]("SELECT * FROM users")
records = [Link]()
print("\n User Records:")
for row in records:
print(f"ID: {row[0]} | Name: {row[1]} | Age: {row[2]} | Email: {row[3]}")
print()

# Simple CLI loop


def main():
while True:
print("\n===== User Database Menu =====")
print("1. Add New Record")
print("2. Show All Records")
print("3. Exit")

choice = input("Enter choice (1/2/3): ")

SS DEGREE COLLEGE, BOBBILI 14


if choice == '1':
name = input("Enter name: ")
age = int(input("Enter age: "))
email = input("Enter email: ")
insert_user(name, age, email)

elif choice == '2':


fetch_users()

elif choice == '3':


print("Exiting program.")
break

else:
print(" Invalid choice. Please try again.")

# Close connection when done


[Link]()

if __name__ == "__main__":
main()

Output:

SS DEGREE COLLEGE, BOBBILI 15


11. Design a database application to search the specified record from the database.

Program:
import sqlite3

# Connect to SQLite database (creates file if it doesn't exist)


conn = [Link]("[Link]")
cursor = [Link]()

# Create table if it doesn't exist


[Link]('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT
)
''')

# Function to insert a user


def insert_user(name, age, email):
[Link]("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", (name, age, email))
[Link]()
print(" Record added successfully.")

# Function to display all users


def fetch_users():
[Link]("SELECT * FROM users")
records = [Link]()
print("\n All User Records:")
for row in records:
print(f"ID: {row[0]} | Name: {row[1]} | Age: {row[2]} | Email: {row[3]}")
print()

# Function to search users by name


def search_user_by_name(name):
[Link]("SELECT * FROM users WHERE name LIKE ?", ('%' + name + '%',))
records = [Link]()
if records:
print(f"\n Search Results for '{name}':")
for row in records:
print(f"ID: {row[0]} | Name: {row[1]} | Age: {row[2]} | Email: {row[3]}")
else:
print(f" No records found matching: '{name}'")

SS DEGREE COLLEGE, BOBBILI 16


# CLI menu
def main():
while True:
print("\n===== User Database Menu =====")
print("1. Add New Record")
print("2. Show All Records")
print("3. Search Record by Name")
print("4. Exit")

choice = input("Enter choice (1-4): ")

if choice == '1':
name = input("Enter name: ")
age = int(input("Enter age: "))
email = input("Enter email: ")
insert_user(name, age, email)

elif choice == '2':


fetch_users()

elif choice == '3':


search_name = input("Enter name to search: ")
search_user_by_name(search_name)

elif choice == '4':


print("Exiting program.")
break

else:
print(" Invalid choice. Please try again.")

# Close connection
[Link]()

if __name__ == "__main__":
main()

Output:

SS DEGREE COLLEGE, BOBBILI 17


SS DEGREE COLLEGE, BOBBILI 18
12. Design a database application to that allows the user to add, delete and modify the records
Program:
import sqlite3

# Connect to SQLite database (or create it)


conn = [Link]("[Link]")
cursor = [Link]()

# Create the users table if it doesn't exist


[Link]('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT
)
''')

# ---------------------- CRUD Functions ----------------------

def insert_user(name, age, email):


[Link]("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", (name, age, email))
[Link]()
print(" Record added successfully.")

def view_users():
[Link]("SELECT * FROM users")
records = [Link]()
if records:
print("\n All User Records:")
for row in records:
print(f"ID: {row[0]} | Name: {row[1]} | Age: {row[2]} | Email: {row[3]}")
else:
print(" No records found.")

def delete_user(user_id):
[Link]("DELETE FROM users WHERE id = ?", (user_id,))
[Link]()
if [Link]:
print(f" Record with ID {user_id} deleted.")
else:
print(f" No record found with ID {user_id}.")

def update_user(user_id, name, age, email):


[Link]("UPDATE users SET name = ?, age = ?, email = ? WHERE id = ?", (name, age, email,
user_id))
SS DEGREE COLLEGE, BOBBILI 19
[Link]()
if [Link]:
print(f" Record with ID {user_id} updated.")
else:
print(f" No record found with ID {user_id}.")

# ---------------------- CLI Menu ----------------------

def main():
while True:
print("\n===== User Database Menu =====")
print("1. Add New Record")
print("2. View All Records")
print("3. Update Record by ID")
print("4. Delete Record by ID")
print("5. Exit")

choice = input("Enter choice (1-5): ")

if choice == '1':
name = input("Enter name: ")
age = int(input("Enter age: "))
email = input("Enter email: ")
insert_user(name, age, email)

elif choice == '2':


view_users()

elif choice == '3':


try:
user_id = int(input("Enter ID of record to update: "))
name = input("Enter new name: ")
age = int(input("Enter new age: "))
email = input("Enter new email: ")
update_user(user_id, name, age, email)
except ValueError:
print(" Invalid input. ID and age must be integers.")

elif choice == '4':


try:
user_id = int(input("Enter ID of record to delete: "))
delete_user(user_id)
except ValueError:
print(" Invalid input. ID must be an integer.")

elif choice == '5':


SS DEGREE COLLEGE, BOBBILI 20
print(" Exiting program.")
break

else:
print(" Invalid choice. Please enter a number between 1 and 5.")

# Close the database connection


[Link]()

if __name__ == "__main__":
main()

Output:

SS DEGREE COLLEGE, BOBBILI 21

You might also like