Python Practical Programs
Python Practical Programs
a. Create a program that asks the user to enter their name and their age. Print out a
message addressed to them that tells them the year that they will turn 100 years
old.
b. Enter the number from the user and depending on whether the number is even or
odd, print out an appropriate message to the user.
print("Fibonacci Series:")
e. Write a function to check the input value is Armstrong and also write the
function for Palindrome.
# Check Armstrong
if is_armstrong(number):
print(number, "is an Armstrong number.")
else:
print(number, "is NOT an Armstrong number.")
# Check Palindrome
if is_palindrome(number):
print(number, "is a Palindrome.")
else:
print(number, "is NOT a Palindrome.")
f. Write a recursive function to print the factorial for a given number.
# Function to find factorial using recursion
def find_factorial(number):
if number == 1 or number == 0:
return 1
else:
return number * find_factorial(number - 1)
#find_factorial(4)
# 4 * find_factorial(3)
# 4 * (3 * find_factorial(2))
# 4 * (3 * (2 * find_factorial(1)))
# 4 * (3 * (2 * 1))
# 4 * 3 * 2 * 1 = 24
# For a list
my_list = [1, 2, 3, 4, 5]
print(f"The length of the list {my_list} is {compute_length(my_list)}")
OR
# Given list
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# Example usage:
list1 = [1, 2, 3, 4, 5]
list2 = [5, 3, 7, 8, 9]
b. Write a Python program to print a specified list after removing the 0th, 2nd, 4th
and 5th elements.
# Original list
my_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
# Original list
my_list = [1, 2, 3, 4, 5]
.
b. Write a Python script to concatenate the following dictionaries to create a new
one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
# Sample dictionaries
dic1 = {1: 10, 2: 20}
dic2 = {3: 30, 4: 40}
dic3 = {5: 50, 6: 60}
b. Write a Python program to append text to a file and display the text.
# Now open the file again in read mode to display the content
with open("templates/sample.txt", "r") as file:
content = file.read()
print("File Content after appending:\n")
print(content)
# Example usage
filename = "templates/sample.txt" # change path if your file is in
./templates/Sample.txt
n = 3 # number of lines to read from the end
last_lines = read_last_n_lines(filename, n)
class Student:
# Constructor to initialize student details
def __init__(self, name, roll_no, course):
self.name = name # instance variable
self.roll_no = roll_no # instance variable
self.course = course # instance variable
def display(self):
print("Name:", self.name)
def display(self):
super().display() # call parent’s display
print("Roll No:", self.roll_no)
def display(self):
super().display()
print("Subject:", self.subject)
# Execution
s = Student("Aditya", 101)
t = Teacher("Rahul", "Python")
s.display()
t.display()
8. Write the program for the following:
✅
else:
print("Division successful ")
finally:
print("Execution finished (finally block runs always).")
# 🎯 Test Cases
divide_numbers(10, 2) # Normal case
divide_numbers(5, 0) # Division by zero
divide_numbers("10", 2) # Invalid type
import tkinter as tk
from tkinter import font
label.pack(pady=50)
import tkinter as tk
from tkinter import font
root = tk.Tk()
root.title("Tkinter Widget Configurations")
root.geometry("500x500")
# Custom font
custom_font = font.Font(family="Times", size=16)
# 1. Message Widget
msg = tk.Message(root, text="This is a Message widget",
width=400,
bg="lightblue",
font=custom_font)
msg.pack(pady=10)
# 2. Button Widget
btn = tk.Button(root, text="Click Me",
bg="green", fg="white",
font=("Arial", 14, "bold"))
btn.pack(pady=10)
# 3. Entry Widget
entry = tk.Entry(root, font=("Courier", 14), bg="yellow")
entry.insert(0, "Type here...")
entry.pack(pady=10)
# 4. Checkbutton Widget
chk_var = tk.BooleanVar()
chk = tk.Checkbutton(root, text="I agree",
variable=chk_var,
bg="pink",
font=("Helvetica", 14))
chk.pack(pady=10)
# 5. Radiobutton Widgets
radio_var = tk.StringVar(value="Option 1")
rb1 = tk.Radiobutton(root, text="Option 1", variable=radio_var, value="Option
1", font=("Verdana", 14))
rb2 = tk.Radiobutton(root, text="Option 2", variable=radio_var, value="Option
2", font=("Verdana", 14))
rb1.pack(pady=5)
rb2.pack(pady=5)
# 6. Scale Widget
scale = tk.Scale(root, from_=0, to=100, orient="horizontal",
bg="lightgreen", font=("Times", 12))
scale.pack(pady=20)
root.mainloop()
# -----------------------------
# Create or connect to database
# -----------------------------
conn = sqlite3.connect("students.db")
cursor = conn.cursor()
# -----------------------------
# Functions for DB operations
# -----------------------------
def add_student(name, age, grade):
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
(name, age, grade))
✅
conn.commit()
print(f" Student '{name}' added successfully!")
def view_students():
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
📋
if rows:
print("\n Student Records:")
for row in rows:
print(row)
⚠️
else:
print(" No records found.")
def search_student(name):
cursor.execute("SELECT * FROM students WHERE name LIKE ?", ('%' + name +
'%',))
rows = cursor.fetchall()
🔎
if rows:
print("\n Search Results:")
for row in rows:
print(row)
⚠️
else:
print(" No student found with that name.")
✅
conn.commit()
print(f" Student with ID {student_id} updated successfully!")
def delete_student(student_id):
cursor.execute("DELETE FROM students WHERE id=?", (student_id,))
🗑️
conn.commit()
print(f" Student with ID {student_id} deleted successfully!")
# -----------------------------
# Menu-driven program
# -----------------------------
while True:
print("\n====== Student Database Menu ======")
print("1. Add Student")
print("2. View All Students")
print("3. Search Student")
print("4. Update Student")
print("5. Delete Student")
print("6. Exit")
if choice == "1":
name = input("Enter name: ")
age = int(input("Enter age: "))
grade = input("Enter grade: ")
add_student(name, age, grade)
# Close DB connection
conn.close()
b. Design a database application to search the specified record from the database.
# student_db.py
import sqlite3
from datetime import datetime, timezone
DB_FILE = "students.db"
# Expected schema
EXPECTED_SCHEMA = {
"id": "INTEGER PRIMARY KEY AUTOINCREMENT",
"name": "TEXT NOT NULL",
"age": "INTEGER",
"course": "TEXT",
"created_at": "TEXT"
}
def get_conn():
"""Return a sqlite3 connection with row factory."""
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row
return conn
def init_db():
"""Ensure DB and table exist with all expected columns."""
conn = get_conn()
cur = conn.cursor()
def add_student():
name = input("Enter name: ").strip()
if not name:
print("Name cannot be empty.")
return
conn = get_conn()
cur = conn.cursor()
cur.execute(
"INSERT INTO students (name, age, course, created_at) VALUES (?, ?, ?,
?)",
(name, age, course, created_at)
)
conn.commit()
print(f"Student added with id={cur.lastrowid}")
conn.close()
def list_students():
conn = get_conn()
cur = conn.cursor()
cur.execute("SELECT * FROM students ORDER BY id")
rows = cur.fetchall()
conn.close()
if not rows:
print("No students found.")
return
if q.isdigit():
cur.execute("SELECT * FROM students WHERE id = ?", (int(q),))
row = cur.fetchone()
if row:
print_student(row)
else:
print("No student found with that ID.")
else:
cur.execute("SELECT * FROM students WHERE name LIKE ?", (f"%{q}%",))
rows = cur.fetchall()
if not rows:
print("No student found with that name.")
else:
for r in rows:
print_student(r)
print("-" * 40)
conn.close()
def print_student(r):
print(f"ID: {r['id']}")
print(f"Name: {r['name']}")
print(f"Age: {r['age']}")
print(f"Course: {r['course']}")
print(f"Created At: {r['created_at']}")
def update_student():
sid = input("Enter student ID to update: ").strip()
if not sid.isdigit():
print("Invalid ID.")
return
sid = int(sid)
conn = get_conn()
cur = conn.cursor()
cur.execute("SELECT * FROM students WHERE id = ?", (sid,))
row = cur.fetchone()
if not row:
print("Student not found.")
conn.close()
return
def delete_student():
sid = input("Enter student ID to delete: ").strip()
if not sid.isdigit():
print("Invalid ID.")
return
sid = int(sid)
conn = get_conn()
cur = conn.cursor()
cur.execute("SELECT name FROM students WHERE id=?", (sid,))
row = cur.fetchone()
if not row:
print("Student not found.")
conn.close()
return
def main_menu():
init_db()
while True:
print("\n--- Student DB Menu ---")
print("1) Add student")
print("2) List students")
print("3) Search student")
print("4) Update student")
print("5) Delete student")
print("6) Exit")
choice = input("Choose (1-6): ").strip()
if choice == "1":
add_student()
elif choice == "2":
list_students()
elif choice == "3":
search_students()
elif choice == "4":
update_student()
elif choice == "5":
delete_student()
elif choice == "6":
print("Goodbye!")
break
else:
print("Invalid choice, try again.")
if __name__ == "__main__":
main_menu()
c. Design a database application to that allows the user to add, delete and modify
the records.
# student_db.py
import sqlite3
from datetime import datetime, timezone
DB_FILE = "students.db"
# Expected schema
EXPECTED_SCHEMA = {
"id": "INTEGER PRIMARY KEY AUTOINCREMENT",
"name": "TEXT NOT NULL",
"age": "INTEGER",
"course": "TEXT",
"created_at": "TEXT"
}
def get_conn():
"""Return a sqlite3 connection with row factory."""
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row
return conn
def init_db():
"""Ensure DB and table exist with all expected columns."""
conn = get_conn()
cur = conn.cursor()
def add_student():
name = input("Enter name: ").strip()
if not name:
print("Name cannot be empty.")
return
conn = get_conn()
cur = conn.cursor()
cur.execute(
"INSERT INTO students (name, age, course, created_at) VALUES (?, ?, ?,
?)",
(name, age, course, created_at)
)
conn.commit()
print(f"Student added with id={cur.lastrowid}")
conn.close()
def list_students():
conn = get_conn()
cur = conn.cursor()
cur.execute("SELECT * FROM students ORDER BY id")
rows = cur.fetchall()
conn.close()
if not rows:
print("No students found.")
return
def search_students():
q = input("Enter ID or name to search: ").strip()
conn = get_conn()
cur = conn.cursor()
if q.isdigit():
cur.execute("SELECT * FROM students WHERE id = ?", (int(q),))
row = cur.fetchone()
if row:
print_student(row)
else:
print("No student found with that ID.")
else:
cur.execute("SELECT * FROM students WHERE name LIKE ?", (f"%{q}%",))
rows = cur.fetchall()
if not rows:
print("No student found with that name.")
else:
for r in rows:
print_student(r)
print("-" * 40)
conn.close()
def print_student(r):
print(f"ID: {r['id']}")
print(f"Name: {r['name']}")
print(f"Age: {r['age']}")
print(f"Course: {r['course']}")
print(f"Created At: {r['created_at']}")
def update_student():
sid = input("Enter student ID to update: ").strip()
if not sid.isdigit():
print("Invalid ID.")
return
sid = int(sid)
conn = get_conn()
cur = conn.cursor()
cur.execute("SELECT * FROM students WHERE id = ?", (sid,))
row = cur.fetchone()
if not row:
print("Student not found.")
conn.close()
return
print("Leave blank to keep current value.")
new_name = input(f"Name [{row['name']}]: ").strip() or row['name']
new_age_s = input(f"Age [{row['age']}]: ").strip()
new_age = int(new_age_s) if new_age_s.isdigit() else row['age']
new_course = input(f"Course [{row['course']}]: ").strip() or row['course']
def delete_student():
sid = input("Enter student ID to delete: ").strip()
if not sid.isdigit():
print("Invalid ID.")
return
sid = int(sid)
conn = get_conn()
cur = conn.cursor()
cur.execute("SELECT name FROM students WHERE id=?", (sid,))
row = cur.fetchone()
if not row:
print("Student not found.")
conn.close()
return
def main_menu():
init_db()
while True:
print("\n--- Student DB Menu ---")
print("1) Add student")
print("2) List students")
print("3) Search student")
print("4) Update student")
print("5) Delete student")
print("6) Exit")
choice = input("Choose (1-6): ").strip()
if choice == "1":
add_student()
elif choice == "2":
list_students()
elif choice == "3":
search_students()
elif choice == "4":
update_student()
elif choice == "5":
delete_student()
elif choice == "6":
print("Goodbye!")
break
else:
print("Invalid choice, try again.")
if __name__ == "__main__":
main_menu()