Lets Go
Lets Go
SCIENCE
PRACTICAL FILE
(SESSION 2024-2025)
SHIVANSH GUTPA
XII-A
12115
S Topic Date Remarks
No.
1 Write a program to input a string and 24 April 2024
determine whether it is a palindrome or not.
2 Write a function to calculate the sum of all 15 May 2024
digits in each number
3 Write a function to count the number of 22 May 2024
vowels (a,e,i,o,u) in each string
4 Write a program to input a list/tuple of 29 May 2024
elements, search for a given element in the
list/tuple.
5 Write a function to check if a given number07 August
is prime 2024
6 Write a Program to count and display the 14 August
words ending with n (stud.txt). 2024
7 Write a program to display the words only if
21 August
the length is greater than 4. 2024
8 Write a program to replace the letter “a” 28 August
with “@” . 2024
9 Write a program to search and display the 04
record of employee whose name is input by September
user in binary file emp.dat. 2024
10 Write a program to modify the record of a 11
student whose roll number is input by user September
from the binary file stud.dat 2024
11 Write a program to input roll number 18
and name from the user for 5 students September
and then write onto a binary file “a.dat”. 2024
12 Write a program to search any employee 25
number and display employee details. September
2024
13 Write a program to store employee records 16 October
in a CSV file and display employees whose 2024
names start with 'a'
14 Create a program to simulate a rolling dice. 23 October
2024
15 Write a program to check if parentheses in 30 October
an expression are balanced using stack 2024
16 Write a program to connect to MySQL 13
database and create a student table November
2024
17 Write a program to insert multiple student 20
records with user input November
2024
18 Write a program to display all records and 27
implement name-based search November
2024
Input :
def largest_number(numbers):
largest = numbers[0]
return largest.
Output :
PRACTICAL-2
Question –
Write a function to calculate the sum of all digits in each number.
Input :
def sum_of_digits(n):
total = 0
while n > 0:
digit = n % 10
total += digit
n = n // 10
return total
Output :
PRACTICAL-3
Question –
Write a function to count the number of vowels (a,e,i,o,u) in each string
Input :
def count_vowels(s):
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
return count
Output :
PRACTICAL-4
Question –
Write a function to check if a given string is a palindrome.
Input :
def palindrome(s):
return s == s[::-1]
Output :
PRACTICAL-5
Question –
Write a function to check if a given number is prime.
Input :
def is_prime(number):
"""
"""
if number < 2:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
Output :
PRACTICAL-6
Question –
Write a program to read employee data from a text file and print employees with salary > 5000.
Input :
print("Filtered Employe Records (Salary > 5000):")
f = open("employees.txt", 'r')
for line in f:
name, position, salary = line.strip().split(", ")
if int(salary) > 5000:
print(f"Name: {name}, Position: {position}, Salary: {salary}")
f.close()
Output :
PRACTICAL-7
Question –
Write a program to read numbers from user, store them in a file, and create another file containing only odd
numbers.
Input :
infile = open('existing_file.txt', 'r')
outfile = open('odd_numbers.txt', 'w')
for line in infile:
number = int(line.strip())
if number % 2 != 0:
outfile.write(f"{number}\n")
infile.close()
outfile.close()
Output :
PRACTICAL-8
Question –
Write a program to read words from a text file and create two separate files - one with words starting with 'a'
and another with remaining words.
Input :
infile = open('existing_file.txt', 'r')
a = []
na = []
for line in infile:
word = line.strip()
if word[0].lower() == 'a':
a.append(word)
else:
na.append(word)
infile.close()
Output :
PRACTICAL-9
Question –
Write a program to store student details (roll no, name, class, marks) in a binary file and display them.
Input :
import pickle
f1 = open("Student.dat", "rb")
rno = int(input("Enter the roll no to search: "))
flag = 0
try:
while True:
r = pickle.load(f1)
if rno == r[0]:
rollno, name, marks = r # Unpack the tuple
print(f"Roll No: {rollno}, Name: {name}, Marks: {marks}")
flag = 1
except EOFError:
if flag == 0:
print("Record not found…")
finally:
f1.close()
Output :
PRACTICAL-10
Question –
Write a program to store names and surnames in a binary file and display records where name/surname starts
with 'a.’
Input :
import pickle
file = open('usernames.dat', 'rb')
loaded_usernames = pickle.load(file)
filtered_usernames = []
for username in loaded_usernames:
if username.startswith('a'):
filtered_usernames.append(username)
if filtered_usernames:
print("Usernames starting with 'a':", filtered_usernames)
else:
print("No usernames start with 'a'.")
file.close()
Output :
PRACTICAL-11
Question –
Write a program to modify marks of a specific student in a binary file containing student records.
Input :
import pickle
f=open("student.dat","ab")
rollno = int (input("Enter Roll Number: "))
name=input("Enter Name :")
marks = int(input("Enter Marks: "))
rec = [rollno, name, marks]
pickle.dump(rec, f)
f.close()
Output :
PRACTICAL-12
Question –
Write a program to store student records in a CSV file and display students having marks above a given
threshold
Input :
import csv
def create_student_records():
with open('students.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Roll', 'Name', 'Marks'])
def find_students_above_threshold():
threshold = float(input("\nEnter marks threshold: "))
print(f"\nStudents with marks above {threshold}:")
create_student_records()
find_students_above_threshold()
Output :
PRACTICAL-13
Question –
Write a program to store employee records in a CSV file and display employees whose names start with 'a'
Input :
import csv
def create_employee_records():
with open('employees.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['ID', 'Name', 'Department', 'Salary'])
def find_employees_with_a():
print("\nEmployees with name starting with 'a':")
create_employee_records()
find_employees_with_a()
Output :
PRACTICAL-14
Question –
Create a number guessing game where computer generates a random number, and user gets hints to guess it
Input :
import random
def number_guessing_game():
secret_number = random.randint(1, 25)
attempts = 0
max_attempts = 5
print("Welcome to Number Guessing Game!")
print(f"I am thinking of a number between 1 and 25. You have {max_attempts} attempts.")
while attempts < max_attempts:
guess = int(input("\nEnter your guess: "))
attempts += 1
if guess == secret_number:
print(f"Congratulations! You guessed it in {attempts} attempts!")
return
elif guess < secret_number:
print("Too low!")
else:
print("Too high!")
Output :
PRACTICAL-15
Question –
Write a program to implement stack operations (push, pop, peek) using list
Input :
def stack_operations():
stack = []
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
item = input("Enter item to push: ")
stack.append(item)
print(f"{item} pushed to stack")
elif choice == '2':
if stack:
print(f"{stack.pop()} popped from stack")
else:
print("Stack is empty")
elif choice == '3':
if stack:
print(f"Top element is: {stack[-1]}")
else:
print("Stack is empty")
elif choice == '4':
if stack:
print("Stack elements:", stack)
else:
print("Stack is empty")
elif choice == '5':
break
else:
print("Invalid choice")
stack_operations()
Output :
PRACTICAL-16
Question –
Write a program to check if parentheses in an expression are balanced using stack
Input :
def check_balanced_parentheses():
expr = input("Enter an expression with parentheses: ")
stack = []
if stack:
print("Unbalanced parentheses")
else:
print("Balanced parentheses")
check_balanced_parentheses()
Output :
PRACTICAL-17
-- Consider a table 'STUDENT' with columns (RollNo,
Name, Class, Section, Marks)
- Display all students who scored above 75 marks
Question –
Write a program to connect to MySQL database and create a student table
Input :
import mysql.connector
def create_student_table():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="2358",
database="school"
)
cursor = conn.cursor()
create_table_query = """
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
marks FLOAT
)
"""
cursor.execute(create_table_query)
print("Table created successfully")
conn.close()
create_student_table()
Output :
PRACTICAL-23
Question –
Write a program to insert multiple student records with user input
Input :
import mysql.connector
def insert_student_records():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="2358",
database="school"
)
cursor = conn.cursor()
insert_query = """
INSERT INTO students (roll_no, name, class, marks)
VALUES (%s, %s, %s, %s)
"""
values = (roll_no, name, class_name, marks)
cursor.execute(insert_query, values)
conn.commit()
print("\nRecords inserted successfully")
conn.close()
insert_student_records()
Output :
PRACTICAL-24
Question –
Write a program to display all records and implement name-based search
Input :
import mysql.connector
def display_and_search():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="2358",
database="school"
)
cursor = conn.cursor()
while True:
print("\n1. Display all records")
print("2. Search by name")
print("3. Exit")
if choice == '1':
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
print("\nStudent Records:")
for record in records:
print(f"Roll No: {record[0]}, Name: {record[1]}, Class: {record[2]}, Marks: {record[3]}")
conn.close()
display_and_search()
Output :
PRACTICAL-25
Question –
Write a program to update and delete student records based on roll number
Input :
import mysql.connector
def update_delete_records():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="2358",
database="school"
)
cursor = conn.cursor()
while True:
print("\n1. Update student marks")
print("2. Delete student record")
print("3. Exit")
if choice == '1':
roll_no = int(input("Enter roll number to update: "))
new_marks = float(input("Enter new marks: "))
cursor.execute("UPDATE students SET marks = %s WHERE roll_no = %s", (new_marks, roll_no))
if cursor.rowcount > 0:
print("Marks updated successfully")
else:
print("Student not found")
conn.close()
update_delete_records()
Output :
COMPUTER
SCIENCE
PROJECT
(SESSION 2024-2025)
ARNAV BISHT
XII-A
21687073
CERTIFICATE
This is to certify that Arnav Bisht of class XII-A of Bal Bharati public school, has
successfully completed Computer Science practical file under my supervision,
during the academic session 2024-25. He has taken a keen interest and has
shown utmost sincerity in the completion of this practical file.
INTERNAL EXAMINER
SCHOOL STAMP
ACKNOWLEDGMENT
I would also like to thank my parents and friends who helped me a lot in
completing this file within the given period.
Arnav Bisht
XII -A
Table Of Content
Python
IDE
Python library: - mysql.connector
My SQL Server
FEATURES
def connect_db():
con = sql.connector.connect(
host="localhost",
user="root",
password="2358",
database="hotel_booking"
)
return con, con.cursor()
if choice == '4':
break
elif choice == '1':
add_room(conn, cursor)
elif choice == '2':
view_rooms(cursor)
elif choice == '3':
update_room_status(conn, cursor)
else:
print("Invalid choice. Please try again.")
price = float(price)
cursor.execute("INSERT INTO rooms VALUES (%s, %s, %s, 'available')", (room_number,
room_type, price))
con.commit()
print("Room added successfully!")
def view_rooms(cursor):
print("\n=== All Rooms ===")
cursor.execute("SELECT * FROM rooms ORDER BY room_number")
rooms = cursor.fetchall()
if not rooms:
print("No rooms found!")
return
if status_choice in status:
try:
cursor.execute("UPDATE rooms SET status = %s WHERE room_number = %s",
(status[status_choice], room_number))
if cursor.rowcount > 0:
con.commit()
print("Room status updated successfully!")
else:
print("Room not found!")
except sql.connector.Error as err:
print(f"Error: {err}")
else:
print("Invalid status choice!")
if choice == '6':
break
elif choice == '1':
create_booking(conn, cursor)
elif choice == '2':
view_bookings(cursor)
elif choice == '3':
check_in_guest(conn, cursor)
elif choice == '4':
check_out_guest(conn, cursor)
elif choice == '5':
cancel_booking(conn, cursor)
else:
print("Invalid choice. Please try again.")
if not available_rooms:
print("No rooms available!")
return
print("\nAvailable Rooms:")
for room in available_rooms:
print(f"Room {room[1]} ({room[2]}) - ${room[3]} per night")
if not room:
print("Invalid room number or room not available!")
return
total_amount = room[1]
cursor.execute("INSERT INTO bookings (guest_id, room_id, total_amount, status)
VALUES (%s, %s, %s, 'confirmed')", (guest_id, room[0], total_amount))
cursor.execute("UPDATE rooms SET status = 'occupied' WHERE room_id = %s",
(room[0],))
con.commit()
print(f"\nBooking confirmed! Total amount: ${total_amount}")
def view_bookings(cursor):
print("\n=== View Bookings ===")
cursor.execute("SELECT b.booking_id, g.first_name, g.last_name, r.room_number,
b.total_amount, b.status FROM bookings b JOIN guests g ON b.guest_id = g.guest_id JOIN
rooms r ON b.room_id = r.room_id ORDER BY b.booking_id")
bookings = cursor.fetchall()
if not bookings:
print("No bookings found!")
return
if cursor.rowcount > 0:
con.commit()
print("Guest checked in successfully!")
else:
print("Invalid booking ID or booking cannot be checked in!")
if result:
room_id = result[0]
if cursor.rowcount > 0:
cursor.execute("UPDATE rooms SET status = 'available' WHERE room_id = %s",
(room_id,))
con.commit()
print("Guest checked out successfully!")
else:
print("Invalid booking ID or booking cannot be checked out!")
else:
print("Booking not found!")
if result:
room_id = result[0]
if cursor.rowcount > 0:
cursor.execute("UPDATE rooms SET status = 'available' WHERE room_id = %s",
(room_id,))
con.commit()
print("Booking cancelled successfully!")
else:
print("Invalid booking ID or booking cannot be cancelled!")
else:
print("Booking not found!")
if choice == '1':
room_menu(conn, cursor)
elif choice == '2':
booking_menu(conn, cursor)
elif choice == '3':
print("Thank you for using the Hotel Booking System!")
con.close()
exit(0)
else:
print("Invalid choice. Please try again.")
Check-out a guest
Canceling a booking
CONCLUSION
This project successfully demonstrates the integration
of MySQL with Python for an effective and efficient
Inventory Management System. By utilizing Python for
program logic and MySQL for database management,
we achieved a seamless interaction between code and
data storage. This system provides a practical solution
for managing inventory in real-time, automating tasks
like record insertion, updating, and deletion.
The project's core objectives, including a user-friendly
interface, error-handling mechanisms, and database
operations, were accomplished effectively. This system
showcases how Python, when paired with robust SQL
databases like MySQL, can be used to create scalable,
flexible, and functional applications.
Looking forward, there is ample scope for further
enhancements. Additional features like graphical
reporting, integration with web platforms, and
enhanced security protocols could be incorporated into
the system to extend its applicability and robustness.
The project underscores the growing importance of
software development that blends programming logic
with reliable data management for optimized, real-
world applications.
In conclusion, this project is not only a comprehensive
application of Python-MySQL integration but also
provides a platform for future innovations and
customizations to cater to larger, more complex
inventory systems. The simplicity of Python combined
with the scalability of MySQL offers a powerful solution
for efficient data handling in various domains.
BIBLIOGRAPHY
The sources referenced in this project highlight various
tools and concepts essential for developing the
Inventory Management System. Python and MySQL, as
integral technologies, are extensively documented in
official references such as Python’s official
documentation and MySQL’s reference manual. These
resources provide detailed insights into the
functionality, commands, and syntax required for
interfacing between Python and MySQL.
https://docs.python.org/3/
https://dev.mysql.com/doc/
https://dev.mysql.com/doc/connector-python/en/
https://www.jetbrains.com/pycharm/documentation/
https://stackoverflow.com/