0% found this document useful (0 votes)
38 views66 pages

Lets Go

The document is a practical file for a Computer Science course for the session 2024-2025, detailing various programming tasks and SQL queries to be completed by the student, Shivansh Gupta. It includes tasks related to string manipulation, file handling, database operations, and data analysis. Each task is accompanied by a date and remarks section, indicating the completion status.

Uploaded by

Arnav Bisht
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)
38 views66 pages

Lets Go

The document is a practical file for a Computer Science course for the session 2024-2025, detailing various programming tasks and SQL queries to be completed by the student, Shivansh Gupta. It includes tasks related to string manipulation, file handling, database operations, and data analysis. Each task is accompanied by a date and remarks section, indicating the completion status.

Uploaded by

Arnav Bisht
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/ 66

COMPUTER

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

19 Write a program to update and delete 04


student records based on roll number December
2024
20 -- Consider tables 'ORDERS' (OrderID, 04
CustomerID, OrderDate, TotalAmount) and December
'ORDER_ITEMS' (OrderID, ProductID, 2024
Quantity, Price)
5. Write SQL queries too:
- Find customers who placed orders above
₹10000
- Display of daily sales report for last month
- List of top five products by sales quantity
- Calculate monthly revenue
- Find orders containing specific product

21 -- Consider a table 'STUDENT' with columns 11


(RollNo, Name, Class, Section, Marks) December
Write SQL queries to: 2024
- Display all students who scored above 75
marks
- Display student names in alphabetical
order
- Count number of students in each section
- Find average marks for each class
- Update marks of a specific student
22 -- Consider tables 'EMPLOYEE' (EmpID, 18
Name, Department, Salary) and December
'DEPARTMENT' (DeptID, DeptName, 2024
Location)
Write SQL queries to:
- List all employees with their department
names
- Find department wise total salary
- Display employees earning more than
average salary
- List of departments with more than five
employees
- Find the highest paid employee in each
department
23 -- Consider tables 'LIBRARY' (BookID, Title, 15 January
Author, Publisher, Copies) and 'ISSUE' 2024
(IssueID, BookID, StudentID, IssueDate,
ReturnDate)
Write SQL queries to:
- Display all books with more than two
copies
- Find books that are currently issued
- Count number of books by each author
- List of students who have overdue books
- Display most popular book (most times
issued)

24 -- Consider table 'PRODUCTS' (ProductID, 15 January


Name, Category, Price, Stock) 2024
Write SQL queries too:
- Find products with price greater than
average price
- Display number of products in each
category
- List of products with stock less than 10
- Find the most expensive product in each
category
- Update prices of all products in a specific
category
PRACTICAL-1
Question –
Write a program to find the greatest number in each list of numbers using a function.

Input :
def largest_number(numbers):

largest = numbers[0]

for num in numbers:


if num > largest:
largest = num

return largest.

number = eval(input("Enter the list: "))


l=largest_number(number)
print("The largest number in the given list is", l)

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

number = int(input("Enter the number: "))


s=sum_of_digits(number)
print("Sum of digits:", s)

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

text = input("Enter the string: ")


c=count_vowels(text)
print("Number of vowels:", c)

Output :

PRACTICAL-4
Question –
Write a function to check if a given string is a palindrome.

Input :
def palindrome(s):
return s == s[::-1]

string = input("Enter the word: ")


p= palindrome(string)
print("Is the string a palindrome?", p)

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

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


if is_prime(num):
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")

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

n = int(input("Enter number of students: "))


for i in range(n):
roll = input(f"Enter roll number {i+1}: ")
name = input(f"Enter name {i+1}: ")
marks = float(input(f"Enter marks {i+1}: "))
writer.writerow([roll, name, marks])

def find_students_above_threshold():
threshold = float(input("\nEnter marks threshold: "))
print(f"\nStudents with marks above {threshold}:")

with open('students.csv', 'r') as file:


reader = csv.DictReader(file)
for row in reader:
if float(row['Marks']) > threshold:
print(f"Name: {row['Name']}, Marks: {row['Marks']}")

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

n = int(input("Enter number of employees: "))


for i in range(n):
emp_id = input(f"Enter employee ID {i+1}: ")
name = input(f"Enter name {i+1}: ")
dept = input(f"Enter department {i+1}: ")
salary = float(input(f"Enter salary {i+1}: "))
writer.writerow([emp_id, name, dept, salary])

def find_employees_with_a():
print("\nEmployees with name starting with 'a':")

with open('employees.csv', 'r') as file:


reader = csv.DictReader(file)
for row in reader:
if row['Name'].lower().startswith('a'):
print(f"Name: {row['Name']}, Department: {row['Department']}")

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

# Give hint after 3 attempts


if attempts == 3:
hint = "even" if secret_number % 2 == 0 else "odd"
print(f"Hint: The number is {hint}")
print(f"Attempts left: {max_attempts - attempts}")
print(f"\nGame Over! The number was {secret_number}")
number_guessing_game()

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 = []

for char in expr:


if char == '(':
stack.append(char)
elif char == ')':
if not stack:
print("Unbalanced parentheses")
return
stack.pop()

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

- Display student names in alphabetical order

- Count number of students in each section

- Find average marks for each class


- Update marks of a specific student
PRACTICAL-18

-- Consider tables 'EMPLOYEE' (EmpID, Name,


Department, Salary) and 'DEPARTMENT' (DeptID,
DeptName, Location)
- List all employees with their department names

- Find department wise total salary


- Display employees earning more than average
salary

- List of departments with more than 1 employees

- Find the highest paid employee in each


department
PRACTICAL-19

-- Consider tables 'LIBRARY' (BookID, Title, Author, Publisher,


Copies) and 'ISSUE' (IssueID, BookID, StudentID, IssueDate,
ReturnDate)
- Display all books with more than 2 copies

- Find books that are currently issued

- Count number of books by each author


- Display most popular book (most times issued)
PRACTICAL-20

-- Consider table 'PRODUCTS' (ProductID, Name,


Category, Price, Stock)
- Find products with price greater than average
price

- Display number of products in each category

- List of products with stock less than 10


- Find the most expensive product in each category

- Update prices of all products in a specific category


PRACTICAL-21

-- Consider tables 'ORDERS' (OrderID, CustomerID,


OrderDate, TotalAmount) and 'ORDER_ITEMS' (OrderID,
ProductID, Quantity, Price)
- Find customers who placed orders above ₹10000

- List of top 5 products by sales quantity


- Find orders containing specific product
PRACTICAL-22

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

n = int(input("Enter number of students: "))


for i in range(n):
print(f"\nEnter details for student {i+1}:")
roll_no = int(input("Roll No: "))
name = input("Name: ")
class_name = input("Class: ")
marks = float(input("Marks: "))

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

choice = input("Enter your choice (1-3): ")

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

elif choice == '2':


name = input("Enter name to search: ")
cursor.execute("SELECT * FROM students WHERE name LIKE %s", (f"%{name}%",))
records = cursor.fetchall()
if records:
print("\nMatching Records:")
for record in records:
print(f"Roll No: {record[0]}, Name: {record[1]}, Class: {record[2]}, Marks: {record[3]}")
else:
print("No matching records found")
elif choice == '3':
break

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

choice = input("Enter your choice (1-3): ")

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

elif choice == '2':


roll_no = int(input("Enter roll number to delete: "))
cursor.execute("DELETE FROM students WHERE roll_no = %s", (roll_no,))
if cursor.rowcount > 0:
print("Record deleted successfully")
else:
print("Student not found")

elif choice == '3':


break
conn.commit()

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.

I certify this practical file is up to my expectation & as per guidelines issued


by Central Board of Secondary Education, New Delhi.

INTERNAL EXAMINER

SCHOOL STAMP
ACKNOWLEDGMENT

I would like to express my sincere gratitude to my teacher Ms. Preeti tandon


who gave me this golden opportunity to work on this practical file which also
helped me in doing a lot of research work. Their constructive advice and
constant motivation have been responsible for the successful completion of
this file. I am grateful to them for their continuous guidance and
encouragement.

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

S. No. Topic Page no.


1 Introduction 1
2 Working Idea 2
3 Requirements 3
4 Features 4
5 Python SQL Interface 6
6 Working Code 7
7 Output 13
8 Conclusion 19
9 Bibliography 21
INTRODUCTION
The world of technology is constantly evolving, with data
management and integration between different platforms becoming
increasingly important. One of the major advancements in this field
is the integration of MySQL with Python, which provides a seamless
way to manage and interact with databases programmatically. This
project explores the development of a Management System that
integrates MySQL with Python to store, retrieve, and manipulate
records efficiently.

The primary motivation behind this project is to offer a practical


solution for hotels to manage their rooms and customers through an
intuitive, code-driven simple interface. By using Python for logic and
MySQL for the data storage, the system ensures reliable database
management while leveraging the simplicity and flexibility of
Python.

In this project, various operations such as adding new rooms,


updating room or guests status, and querying the database for
specific information are implemented through Python scripts
interfacing with MySQL databases.
WORKING IDEA
The Hotel Management System works by connecting a Python-based
frontend to a MySQL backend database. The system allows users to
perform basic CRUD (Create, Read, Update, Delete) operations.
When the user wants to add a new room to the hotel, they enter the
room details (such as room number, type, and price) into the
system. This data is then stored in a MySQL database.
Python is used to handle the business logic of the program, including
checking if a room already exists, updating room details like status
(available, occupied, maintenance), and handling potential errors
such as trying to add a room without providing all necessary details.
The system also allows users to view the current inventory of rooms,
update room statuses, and search for rooms based on room number
or type. The database is updated in real-time to reflect any changes
made, ensuring that room information is always accurate.
Additionally, the system manages bookings by allowing users to
create new bookings, view existing bookings, check in guests, check
out guests, and cancel bookings. The booking details, including guest
information and room assignments, are stored in the database and
updated in real-time to ensure accurate tracking of room availability
and guest stays.
Requirements

 Python
 IDE
 Python library: - mysql.connector
 My SQL Server
FEATURES

1. Add New Rooms: The system provides functionality to input


details of new rooms and store them in the database. Users can
input the room number, type (Single/Double/Suite), price per
night, and other relevant information, which will be stored in
the respective tables in MySQL.
2. Update Room Status: Users can update room details, such as
status (available, occupied, maintenance), when necessary. This
helps keep track of room availability dynamically as guests
check in and out or as rooms undergo maintenance.
3. Delete Rooms: Rooms that are no longer part of the hotel can
be removed from the system, ensuring that the room inventory
only lists rooms that are available for booking. This function
prevents clutter in the database and allows for more effective
room management.
4. View Rooms: The system allows users to view the entire
inventory of rooms, displaying room details in a user-friendly
format. This helps hotel managers to understand the current
room availability and status at a glance.
5. Create New Bookings: The system allows users to create new
bookings by entering guest details and selecting an available
room. This ensures that guest information and room
assignments are accurately recorded in the database.
6. View Bookings: Users can view all existing bookings, displaying
details such as guest name, room number, total amount, and
booking status. This helps in managing and tracking guest stays
effectively.
7. Check-in Guests: The system provides functionality to check in
guests by updating the booking status to 'checked_in'. This
ensures that the room status is updated accordingly and the
guest's stay is accurately recorded.
8. Check-out Guests: Users can check out guests by updating the
booking status to 'checked_out' and making the room available
again. This helps in managing room availability and ensuring
accurate billing.
9. Cancel Bookings: The system allows users to cancel bookings by
updating the booking status to 'cancelled' and making the room
available again. This helps in managing room availability and
ensuring that the database reflects the current booking status.
HOW PYTHON WAS INTERFACED WITH SQL

Python interacts with the MySQL database using the


mysql.connector library. The system establishes a connection with
the MySQL server by passing credentials (hostname, username,
password) to the mysql.connector.connect() function. Once the
connection is established, SQL queries can be executed through
Python functions using cursor objects. For example, to add a new
room to the database, the SQL INSERT statement is executed by
passing the relevant parameters from the Python function.
The Python code also manages the closing of the connection after
each transaction to ensure that no connection leaks occur. Error
handling is implemented to catch any database-related exceptions
and provide meaningful feedback to the user.
PYTHON CODE-
import mysql.connector as sql

def connect_db():
con = sql.connector.connect(
host="localhost",
user="root",
password="2358",
database="hotel_booking"
)
return con, con.cursor()

def room_menu(conn, cursor):


while True:
print("\n=== Room Management ===")
print("1. Add Room")
print("2. View All Rooms")
print("3. Update Room Status")
print("4. Back to Main Menu")

choice = input("\nEnter your choice (0-4): ")

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

def add_room(conn, cursor):


print("\n=== Add New Room ===")
print("(Enter '0' at any prompt to cancel and return to menu)")

room_number = input("Enter room number: ")


if room_number == '0':
return

room_type = input("Enter room type (Single/Double/Suite): ")


if room_type == '0':
return
while True:
price = input("Enter price per night: ")
if price == '0':
return
if price.isfloat():
break
else:
print("Enter a valid price")

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

for room in rooms:


print(f"\nRoom ID: {room[0]}")
print(f"Room Number: {room[1]}")
print(f"Type: {room[2]}")
print(f"Price per night: ${room[3]}")
print(f"Status: {room[4]}")

def update_room_status(conn, cursor):


print("\n=== Update Room Status ===")
room_number = input("Enter room number: ")
print("\nAvailable statuses:")
print("1. Available")
print("2. Occupied")
print("3. Maintenance")

status_choice = input("Enter new status (1-3): ")


status = {'1': 'available', '2': 'occupied', '3': 'maintenance'}

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

def booking_menu(conn, cursor):


while True:
print("\n=== Booking Management ===")
print("1. New Booking")
print("2. View Bookings")
print("3. Check-in Guest")
print("4. Check-out Guest")
print("5. Cancel Booking")
print("6. Back to Main Menu")

choice = input("\nEnter your choice (0-6): ")

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

def create_booking(conn, cursor):


print("\n=== New Booking ===")

first_name = input("Enter guest first name: ")


last_name = input("Enter guest last name: ")
phone = input("Enter guest phone number: ")
email = input("Enter guest email: ")

cursor.execute("INSERT INTO guests (first_name, last_name, phone, email) VALUES


(%s, %s, %s, %s)", (first_name, last_name, phone, email))
con.commit()
guest_id = cursor.lastrowid
cursor.execute("SELECT room_id, room_number, room_type, price_per_night FROM rooms
WHERE status = 'available'")
available_rooms = cursor.fetchall()

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

room_number = input("\nEnter room number to book: ")


cursor.execute("SELECT room_id, price_per_night FROM rooms WHERE room_number = %s
AND status = 'available'", (room_number,))
room = cursor.fetchone()

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

for booking in bookings:


print(f"\nBooking ID: {booking[0]}")
print(f"Guest: {booking[1]} {booking[2]}")
print(f"Room: {booking[3]}")
print(f"Total Amount: ${booking[4]}")
print(f"Status: {booking[5]}")
def check_in_guest(conn, cursor):
booking_id = input("\nEnter booking ID to check in: ")

cursor.execute("UPDATE bookings SET status = 'checked_in' WHERE booking_id = %s AND


status = 'confirmed'", (booking_id,))

if cursor.rowcount > 0:
con.commit()
print("Guest checked in successfully!")
else:
print("Invalid booking ID or booking cannot be checked in!")

def check_out_guest(conn, cursor):


booking_id = input("\nEnter booking ID to check out: ")

cursor.execute("SELECT room_id FROM bookings WHERE booking_id = %s", (booking_id,))


result = cursor.fetchone()

if result:
room_id = result[0]

cursor.execute("UPDATE bookings SET status = 'checked_out' WHERE booking_id =


%s AND status = 'checked_in'", (booking_id,))

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

def cancel_booking(conn, cursor):


booking_id = input("\nEnter booking ID to cancel: ")

cursor.execute("SELECT room_id FROM bookings WHERE booking_id = %s", (booking_id,))


result = cursor.fetchone()

if result:
room_id = result[0]

cursor.execute("UPDATE bookings SET status = 'cancelled'WHERE booking_id = %s


AND status = 'confirmed'", (booking_id,))

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

def main_menu(conn, cursor):


while True:
print("\n=== Hotel Booking System ===")
print("1. Room Management")
print("2. Booking Management")
print("3. Exit")

choice = input("\nEnter your choice (1-3): ")

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

# Initialize the connection and start the program


con, cursor = connect_db()
main_menu(con, cursor)
MYSQL TABLES

Data in bookings table

Data in guests table


Data in rooms table
PYTHON INTERFACE-
Adding new room

Showing all available room


Updating the status of a room

Registering a new booking


Check-in a guest

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/

You might also like