0% found this document useful (0 votes)
27 views23 pages

Python Practical Programs

Uploaded by

naikaryan2801
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)
27 views23 pages

Python Practical Programs

Uploaded by

naikaryan2801
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
You are on page 1/ 23

List of Practical

1. Write the program for the following:

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.

# Ask user for name and age


name = input("Enter your name: ")
age = int(input("Enter your age: "))

# Calculate the year when user will turn 100


current_year = 2025
year_when_100 = current_year + (100 - age)

# Print the message


print(f"Hello {name}, you will turn 100 years old in the year
{year_when_100}.")

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.

# Ask the user to enter a number


num = int(input("Enter a number: "))

# Check if the number is even or odd


if num % 2 == 0:
print(f"The number {num} is even.")
else:
print(f"The number {num} is odd.")

c. Write a program to generate the Fibonacci series.


# Ask the user how many terms they want in the series
number_of_terms = int(input("Enter how many terms of Fibonacci series you
want: "))

# Starting two numbers of the Fibonacci series


first = 0
second = 1

print("Fibonacci Series:")

for count in range(number_of_terms):


print(first, end=" ")
next_number = first + second
first = second
second = next_number
d. Write a function that reverses the user defined value.

# This function takes a text and returns it reversed


def reverse_input(user_text):
reversed_text = user_text[::-1] # Reverses the string
return reversed_text

# Ask the user to enter a value


input_value = input("Enter something to reverse: ")

# Call the function and save the result


result = reverse_input(input_value)

# Show the reversed value


print("Reversed value is:", result)

e. Write a function to check the input value is Armstrong and also write the
function for Palindrome.

# Function to check Armstrong number


def is_armstrong(number):
digit_count = len(str(number)) # Count digits
total = 0
for digit in str(number):
total += int(digit) ** digit_count
return total == number

# Function to check Palindrome number


def is_palindrome(number):
return str(number) == str(number)[::-1]

# Ask user for input


user_input = input("Enter a number: ")
number = int(user_input)

# 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

# Ask the user to enter a number


user_input = int(input("Enter a number to find its factorial: "))

# Call the function and print the result


result = find_factorial(user_input)
print("Factorial of", user_input, "is:", result)

2 : Write the program for the following:


a. Write a function that takes a character (i.e. a string of length 1) and returns True
if it is a vowel, False otherwise

# Function to check if a character is a vowel


def is_vowel(char):
# Convert to lowercase so it works for both uppercase and lowercase
letters
char = char.lower()

# Check if the character is in the set of vowels


if char in ['a', 'e', 'i', 'o', 'u']:
return True
else:
return False

# --- Example Usage ---


letter = input("Enter a single character: ")

# Validate input length


if len(letter) == 1:
if is_vowel(letter):
print(f"'{letter}' is a vowel.")
else:
print(f"'{letter}' is not a vowel.")
else:
print("Please enter only one character.")
b. Define a function that computes the length of a given list or string.

# Function to compute the length of a list or string


def compute_length(data):
count = 0
for item in data:
count += 1
return count

# --- Example Usage ---


# For a string
text = "Hello"
print(f"The length of '{text}' is {compute_length(text)}")

# For a list
my_list = [1, 2, 3, 4, 5]
print(f"The length of the list {my_list} is {compute_length(my_list)}")

c. Define a procedure histogram() that takes a list of integers and prints a


histogram to the screen. For example, histogram([4, 9, 7]) should print the
following:
****
*********
*******

# Function to print a histogram from a list of integers


def histogram(numbers):
for num in numbers:
print('*' * num)

# --- Example Usage ---


data = [4, 9, 7]
histogram(data)

3. Write the program for the following:


a. A pangram is a sentence that contains all the letters of the English alphabet at
least
once, for example: The quick brown fox jumps over the lazy dog. Your task here
is to write a function to check a sentence to see if it is a pangram or not.

import string # For lowercase alphabet

# Function to check if a sentence is a pangram


def is_pangram(sentence):
# Convert sentence to lowercase
sentence = sentence.lower()
# Get all letters of the alphabet
alphabet = set(string.ascii_lowercase)

# Check if all letters are present in the sentence


return alphabet.issubset(set(sentence))

# --- Example Usage ---


text = "The quick brown fox jumps over the lazy dog"
if is_pangram(text):
print("The sentence is a pangram.")
else:
print("The sentence is NOT a pangram.")

OR

# Function to check if a sentence is a pangram


def is_pangram(sentence):
# Convert the sentence to lowercase
sentence = sentence.lower()

# Define all letters in the English alphabet


alphabet = "abcdefghijklmnopqrstuvwxyz"

# Check if each letter in alphabet is in the sentence


for letter in alphabet:
if letter not in sentence:
return False
return True

# --- Example Usage ---


text = "The quick brown fox jumps over the lazy dog"
if is_pangram(text):
print("The sentence is a pangram.")
else:
print("The sentence is NOT a pangram.")

b. Take a list, say for example this one:


a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.

# Given list
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

# Loop through the list and print numbers less than 5


for number in a:
if number < 5:
print(number)
4. Write the program for the following:
a. Write a program that takes two lists and returns True if they have at least one
common member.

# Function to check common members


def find_common_members(list1, list2):
common = [] # empty list to store common members

for item in list1:


if item in list2 and item not in common: # avoid duplicates
common.append(item)

if common: # if list is not empty


return True, common
else:
return False, []

# Example usage:
list1 = [1, 2, 3, 4, 5]
list2 = [5, 3, 7, 8, 9]

print("List 1:", list1)


print("List 2:", list2)

result, common_items = find_common_members(list1, list2)

✅ The two lists have common member(s):", common_items)


if result:
print("

❌ No common members found.")


else:
print("

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']

# Remove elements at index 0, 2, 4, 5


# We'll use list comprehension to keep only the others
result = [my_list[i] for i in range(len(my_list)) if i not in (0, 2, 4, 5)]

print("Original List:", my_list)


print("After Removing 0th, 2nd, 4th, 5th elements:", result)
c. Write a Python program to clone or copy a list

# Original list
my_list = [1, 2, 3, 4, 5]

# Method 1: Using slicing [:]


cloned_list1 = my_list[:]

# Method 2: Using list() constructor


cloned_list2 = list(my_list)

# Method 3: Using copy() method


cloned_list3 = my_list.copy()

print("Original List:", my_list)


print("Cloned List 1 ([:]):", cloned_list1)
print("Cloned List 2 (list()):", cloned_list2)
print("Cloned List 3 (copy()):", cloned_list3)

5. Write the program for the following:


a. Write a Python script to sort (ascending and descending) a dictionary by value
# Original dictionary
my_dict = {"apple": 10, "banana": 5, "cherry": 20, "date": 15}

# Sort by value (ascending)and item[1] means value


asc_sorted = dict(sorted(my_dict.items(), key=lambda item: item[1]))

# Sort by value (descending)and item[1] means value


#lambda creates a small, one-line function without using def.

desc_sorted = dict(sorted(my_dict.items(), key=lambda item: item[1],


reverse=True))

print("Original Dictionary:", my_dict)


print("Sorted by Value (Ascending):", asc_sorted)
print("Sorted by Value (Descending):", desc_sorted)

.
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}

# Method 1: Using update()


result = {}
for d in (dic1, dic2, dic3): # iterate through dictionaries
result.update(d)

print("Concatenated Dictionary:", result)

# Method 2: (Python 3.5+) Using {**dict}, Dictionary unpacking method


result2 = {**dic1, **dic2, **dic3}
print("Concatenated Dictionary (method 2):", result2)

c. Write a Python program to sum all the items in a dictionary.


# Sample dictionary
my_dict = {'a': 100, 'b': 200, 'c': 300}

# Sum all values


total = sum(my_dict.values())

print("The sum of all items in the dictionary is:", total)

6. Write the program for the following:


a. Write a Python program to read an entire text file.

# Open the file in read mode ('r')


file = open("./templates/Sample.txt", "r")

# Read the entire content


content = file.read()

# Print the content


print("File Content:\n")
print(content)

# Close the file


file.close()# Open the file in read mode ('r')

b. Write a Python program to append text to a file and display the text.

# Append text to a file and then display the content

# Open the file in append mode ('a')


with open("templates/sample.txt", "a") as file:
file.write("\nThis is a new line of text appended to the file.")

# 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)

c. Write a Python program to read last n lines of a file.


# Program to read last n lines of a file

def read_last_n_lines(filename, n):


try:
with open(filename, "r") as file:
# Read all lines
lines = file.readlines()
# Get last n lines, -n give the index position and :slice it till
the end of the line
last_lines = lines[-n:]
return last_lines
except FileNotFoundError:
print("File not found!")
return []

# 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)

print(f"Last {n} lines of {filename}:")


for line in last_lines:
print(line, end="") # end="" to avoid extra blank lines

7. Write the program for the following:


a. Design a class that store the information of student and display the same
# Student class to store and display student information

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

# Method to display student information


def display_info(self):
print("Student Information")
print("Name:", self.name)
print("Roll No:", self.roll_no)
print("Course:", self.course)

# Create student objects


s1 = Student("Aditya", 101, "BSc IT")
s2 = Student("Rahul", 102, "Computer Science")
# Display their details
s1.display_info()
print() # for spacing
s2.display_info()

b. Implement the concept of inheritance using python


class Person:
def __init__(self, name):
self.name = name

def display(self):
print("Name:", self.name)

class Student(Person): # inherits from Person


def __init__(self, name, roll_no):
super().__init__(name) # call Person’s constructor
self.roll_no = roll_no

def display(self):
super().display() # call parent’s display
print("Roll No:", self.roll_no)

class Teacher(Person): # another child


def __init__(self, name, subject):
super().__init__(name)
self.subject = subject

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:

a. Write a program to implement exception handling.


def divide_numbers(a, b):
try:
result = a / b # This may raise ZeroDivisionError if b = 0
print(f"Result: {result}")
except ZeroDivisionError: # Handles division by zero
print("Error: Cannot divide by zero!")
except TypeError: # Handles if a or b is not a number
print("Error: Both inputs must be numbers!")


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

9. Write the program for the following:


a. Try to configure the widget with various options like: bg=”red”, family=”times”,
size=18

import tkinter as tk
from tkinter import font

# Create the main window


root = tk.Tk()
root.title("Widget Configuration Example")
root.geometry("400x200")

# Create a custom font


custom_font = font.Font(family="Times", size=18)

# Create a Label widget with options


label = tk.Label(root,
text="Hello, Tkinter!",
bg="red", # background color
fg="white", # text color
font=custom_font) # font family & size

label.pack(pady=50)

# Run the GUI loop


root.mainloop()
b. Try to change the widget type and configuration options to experiment with
other widget types like Message, Button, Entry, Checkbutton, Radiobutton, Scale
Etc.

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()

10. Design the database applications for the following:


a. Design a simple database application that stores the records and retrieve the
Same.
import sqlite3

# -----------------------------
# Create or connect to database
# -----------------------------
conn = sqlite3.connect("students.db")
cursor = conn.cursor()

# Create table if not exists


cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
""")
conn.commit()

# -----------------------------
# 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.")

def update_student(student_id, name, age, grade):


cursor.execute("UPDATE students SET name=?, age=?, grade=? WHERE id=?",
(name, age, grade, student_id))


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")

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

if choice == "1":
name = input("Enter name: ")
age = int(input("Enter age: "))
grade = input("Enter grade: ")
add_student(name, age, grade)

elif choice == "2":


view_students()

elif choice == "3":


name = input("Enter name to search: ")
search_student(name)

elif choice == "4":


student_id = int(input("Enter student ID to update: "))
name = input("Enter new name: ")
age = int(input("Enter new age: "))
grade = input("Enter new grade: ")
update_student(student_id, name, age, grade)

elif choice == "5":


student_id = int(input("Enter student ID to delete: "))
delete_student(student_id)
🚪
elif choice == "6":
print(" Exiting program...")
break

⚠️ Invalid choice, try again.")


else:
print("

# 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()

# Check if table exists


cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND
name='students'")
if cur.fetchone() is None:
cols_sql = ", ".join(f"{k} {v}" for k, v in EXPECTED_SCHEMA.items())
cur.execute(f"CREATE TABLE students ({cols_sql})")
conn.commit()
conn.close()
print("Created 'students' table.")
return

# Ensure all expected columns exist


cur.execute("PRAGMA table_info(students)")
existing_cols = {row["name"] for row in cur.fetchall()}

for col, coltype in EXPECTED_SCHEMA.items():


if col not in existing_cols:
cur.execute(f"ALTER TABLE students ADD COLUMN {col} {coltype}")
print(f"Added missing column: {col}")
conn.commit()
conn.close()

def add_student():
name = input("Enter name: ").strip()
if not name:
print("Name cannot be empty.")
return

age_s = input("Enter age (optional): ").strip()


age = int(age_s) if age_s.isdigit() else None
course = input("Enter course/grade (optional): ").strip() or None
created_at = datetime.now(timezone.utc).isoformat()

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

print(f"\n{'ID':<4} {'Name':<20} {'Age':<5} {'Course':<15} {'Created


At'}")
print("-" * 70)
for r in rows:
print(f"{r['id']:<4} {r['name']:<20} {str(r['age'] or ''):<5}
{str(r['course'] or ''):<15} {r['created_at']}")
print()
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']

cur.execute("UPDATE students SET name=?, age=?, course=? WHERE id=?",


(new_name, new_age, new_course, sid))
conn.commit()
print("Student updated.")
conn.close()

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

confirm = input(f"Delete student '{row['name']}'? (y/N): ").lower()


if confirm == "y":
cur.execute("DELETE FROM students WHERE id=?", (sid,))
conn.commit()
print("Deleted.")
else:
print("Cancelled.")
conn.close()

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()

# Check if table exists


cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND
name='students'")
if cur.fetchone() is None:
cols_sql = ", ".join(f"{k} {v}" for k, v in EXPECTED_SCHEMA.items())
cur.execute(f"CREATE TABLE students ({cols_sql})")
conn.commit()
conn.close()
print("Created 'students' table.")
return

# Ensure all expected columns exist


cur.execute("PRAGMA table_info(students)")
existing_cols = {row["name"] for row in cur.fetchall()}

for col, coltype in EXPECTED_SCHEMA.items():


if col not in existing_cols:
cur.execute(f"ALTER TABLE students ADD COLUMN {col} {coltype}")
print(f"Added missing column: {col}")
conn.commit()
conn.close()

def add_student():
name = input("Enter name: ").strip()
if not name:
print("Name cannot be empty.")
return

age_s = input("Enter age (optional): ").strip()


age = int(age_s) if age_s.isdigit() else None
course = input("Enter course/grade (optional): ").strip() or None
created_at = datetime.now(timezone.utc).isoformat()

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

print(f"\n{'ID':<4} {'Name':<20} {'Age':<5} {'Course':<15} {'Created


At'}")
print("-" * 70)
for r in rows:
print(f"{r['id']:<4} {r['name']:<20} {str(r['age'] or ''):<5}
{str(r['course'] or ''):<15} {r['created_at']}")
print()

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']

cur.execute("UPDATE students SET name=?, age=?, course=? WHERE id=?",


(new_name, new_age, new_course, sid))
conn.commit()
print("Student updated.")
conn.close()

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

confirm = input(f"Delete student '{row['name']}'? (y/N): ").lower()


if confirm == "y":
cur.execute("DELETE FROM students WHERE id=?", (sid,))
conn.commit()
print("Deleted.")
else:
print("Cancelled.")
conn.close()

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()

You might also like