0% found this document useful (0 votes)
48 views24 pages

Updated Mtbs

This document describes a metro ticket booking system project implemented using Python and MySQL. The system allows users to book and cancel tickets, view booked tickets, and provide suggestions or complaints. Key functions include booking tickets, canceling tickets, updating the database, and making payments.

Uploaded by

Sangeetha MD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views24 pages

Updated Mtbs

This document describes a metro ticket booking system project implemented using Python and MySQL. The system allows users to book and cancel tickets, view booked tickets, and provide suggestions or complaints. Key functions include booking tickets, canceling tickets, updating the database, and making payments.

Uploaded by

Sangeetha MD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

PROJECT

IN

COMPUTER SCIENCE (083)


Academic Year 2023-24

METRO TICKET
BOOKING SYSTEM

NAME : Sai Supriya CLASS : XII

ROLL.NO : 33

REG. NO : 202230293 ACADEMIC YEAR: 2023 – 24


CERTIFICATE

This is to certify that this project report entitled Metro Ticket Booking System is a

bonafide record of the project work done by Sai Supriya of class XII Reg.No

202230293 in the academic year 2023 – 2024. The project has been submitted in partial

fulfilment of AISSCE for practical held at Christ Academy CBSE School.

Date: 27/06/2023 Teacher in Charge

Internal Examiner External Examiner


PRINCIPAL
ACKNOWLEDGEMENT

I solemnly take the opportunity to thank all the helping hands who made me to complete this
project. First of all I thank the Almighty for keeping me hale and healthy in order to successfully
complete my work.

I wish to express my sincere gratitude to Dr. Fr.Lebin, Principal of Christ Academy, for permitting
me to carry out the project and for the facilities provided for the fulfilment of this project work.

I am greatly indebted to Mrs. Subhashini Thota, Teacher in Computer Science who gave me
immense support and guidance throughout the completion of this project. I express my gratitude towards
my team members for bringing out collective productivity.

Last but not the least, I express my heartiest thanks to my lovable parents and friends for their
prayers, suggestions and encouragement for the successful completion of the project.
CONTENTS

❖ ABSTRACT

❖ SYSTEM REQUIREMENTS

❖ PROJECT DESIGN

❖ DATABASE TABLES

❖ SOURCE CODE

❖ SAMPLE OUTPUT

❖ CONCLUSION

❖ BIBLIOGRAPHY
ABSTRACT

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van

Rossum and first released in 1991, Python’s design philosophy emphasizes code readability with its

notable use of significant whitespace and indent levels. Its language constructs and object-oriented

approach aim to help programmers write clear, logical code for small and large-scale purposes.

This Project, Metro Ticket Booking System is implemented using the Python programming language,

with MySQL as the database.

This project is a command-line ticket booking system for a metro service. It allows users to book and

cancel tickets, view tickets booked, and put forth any suggestions or complaints. The system uses Python

programming language and SQL database management system to store and retrieve data related to tickets,

stations, schedules, payments, and suggestions. The project is designed to provide a simple and user-

friendly interface for customers to book and manage their tickets, while also providing a secure and

reliable payment system. Overall, this project demonstrates the use of programming and database

management skills to create a functional and efficient system for a real-world application.

There are several important functions used in this project, including:

1. `book_ticket()`: This function allows the users to book a metro ticket by selecting their starting and

destination stations, and provides the fare and booking details.

2. `cancel_ticket()`: This function allows the users to cancel a previously booked ticket and calculates the

refund amount based on the time remaining before departure.


3. `update_database()`: This function updates the database with any changes made to booked or cancelled

tickets.

4. `payment()`: This function allows the users to make payments using either a credit card or a debit card.

These functions work together to provide a seamless experience for users to book, manage, and cancel

their metro tickets.


SYSTEM REQUIREMENTS
HARDWARE COMPONENTS:

RAM : 2 GB (Minimum)

4 GB (Recommended)

Operating System : 32 bit x86

64 bit x64 (Recommended)

Hard Disk Memory


: Minimum 250 MB Free

Processor : Dual Core 2.80 GHz or Greater

Screen Resolution : 1366 x 768 (Optimal)

Graphics Card : Minimum 64 MB

SOFTWARE COMPONENTS:

Platform : Windows 7/8/10/11 with SP1

Python Version : Python 3.0 or Greater


PROJECT DESIGN
DATABASE TABLES
SOURCE CODE
CREATE TABLE users ( user_id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id),
UNIQUE KEY (email));

CREATE TABLE schedules (id INT(11) NOT NULL AUTO_INCREMENT,


start_station VARCHAR(255) NOT NULL,
dest_station VARCHAR(255) NOT NULL,
departure_time TIME NOT NULL,
arrival_time TIME NOT NULL,
PRIMARY KEY (id));

CREATE TABLE feedback ( id INT(11) NOT NULL AUTO_INCREMENT,


user_id INT(11) NOT NULL,
message TEXT NOT NULL,
types varchar(50) NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(user_id));

CREATE TABLE stations ( id INT(11) NOT NULL AUTO_INCREMENT,


name VARCHAR(255) NOT NULL,
PRIMARY KEY (id));

CREATE TABLE tickets (id INT(11) NOT NULL AUTO_INCREMENT,


user_id INT(11) NOT NULL,
start_station VARCHAR(255) NOT NULL,
dest_station VARCHAR(255) NOT NULL,
fare INT(11) NOT NULL,
booking_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
status ENUM('booked', 'cancelled') NOT NULL DEFAULT 'booked',
PRIMARY KEY (id), FOREIGN KEY(user_id) REFERENCES users(user_id));

CREATE TABLE cancellations ( id INT(11) NOT NULL AUTO_INCREMENT,


ticket_id INT(11) NOT NULL,
cancellation_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
refund INT(11) NOT NULL,
PRIMARY KEY (id));

import mysql.connector as mys


import datetime
import re
from datetime import timedelta

# Connect to MySQL database


mydb = mys.connect(host="localhost", user="root", password="Sa!@g7O2", database="mtbs")
mycursor = mydb.cursor(buffered=True)
stations = ["Geeta Nagar", "Gurudev Chauraha", "Iit Kanpur", "Kalyanpur", "Llr Hospital", "Moti Jheel",
"Rawatpur", "Spm Hospital", "Vishwavidyalaya"]
fares = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55]
station_schedules = [
("Geeta Nagar", "Gurudev Chauraha", "09:00:00", "09:10:00"),
("Gurudev Chauraha", "Geeta Nagar", "09:20:00", "09:30:00"),
("Geeta Nagar", "IIT Kanpur", "09:40:00", "09:50:00"),
("IIT Kanpur", "Geeta Nagar", "10:00:00", "10:10:00"),
("Gurudev Chauraha", "IIT Kanpur", "10:20:00", "10:30:00"),
("IIT Kanpur", "Gurudev Chauraha", "10:40:00", "10:50:00"),
# Add more station schedules as needed
]

# Insert station schedules into the schedules table


sql = "INSERT INTO schedules (start_station, dest_station, departure_time, arrival_time) VALUES (%s, %s,
%s, %s)"
mycursor.executemany(sql, station_schedules)
mydb.commit()

print("Station schedules added successfully!")

print("Welcome to Kanpur Metro!")

def is_valid_email(email):
email_regex = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(email_regex, email) is not None

def is_valid_aadhaar(aadhaar):
aadhaar_regex = r'^\d{12}$'
return re.match(aadhaar_regex, aadhaar) is not None
while True:
print("Choose to:")
print("1. Sign up")
print("2. Sign in")
choce = int(input())
if choce == 1:
name = input("Enter your name:")
email = input("Enter your email: ")
password = input("Enter your password: ")
sql = "INSERT INTO users (name, email, password) VALUES ( %s, %s, %s)"
val = (name, email, password)
mycursor.execute(sql, val)
mydb.commit()
print("You have signed up successfully")

# Validate email format


if not is_valid_email(email):
print("Invalid email format. Please try again.")
continue
# Check if email exists in the database

sql = "SELECT * FROM users WHERE email = %s"


val = (email,)
mycursor.execute(sql, val)
user = mycursor.fetchone()

if not user:
print("Email not found. Please try again.")
continue

# Check if the password matches


if user[3] != password:
print("Incorrect password. Please try again.")
continue

# User authentication successful, continue with ticket booking or cancellation


print("Authentication successful! Welcome, " + user[1] + ".")
break
elif choce == 2:
email = input("Enter your email: ")
password = input("Enter your password: ")

# Validate email format


if not is_valid_email(email):
print("Invalid email format. Please try again.")
continue
# Check if email exists in the database

sql = "SELECT * FROM users WHERE email = %s"


val = (email,)
mycursor.execute(sql, val)
user = mycursor.fetchone()

if not user:
print("Email not found. Please try again.")
continue

# Check if the password matches


if user[3] != password:
print("Incorrect password. Please try again.")
continue

# User authentication successful, continue with ticket booking or cancellation


print("Authentication successful! Welcome, " + user[1] + ".")
break
while True:
print("\nPlease select an option:")
print("1. Book Ticket")
print("2. Cancel Ticket")
print("3. View Tickets")
print("4. Credit score")
print("5. Suggestions and Complaints")
print("6. Exit")
choice = int(input())

if choice == 1:
print('''The available stations are:
1.Geeta Nagar
2.Gurudev Chauraha
3.IIT Kanpur
4.Kalyanpur
5.LLR Hospital
6.Moti Jheel
7.Rawatpur
8.SPM Hospital
9.Vishwavidyalaya''')
start_station = input("Enter your starting station: ").title()
dest_station = input("Enter your destination station: ").title()

# Validate Aadhar number format


def is_valid_aadhar(aadhar):
aadhar_regex = r'^\d{12}$'
return re.match(aadhar_regex, aadhar) is not None

# Get passenger details


passenger_details = []
while True:
if len(passenger_details) >= 10:
print("Maximum number of passengers reached.")
break

print("\nEnter Passenger Details:")


name = input("Name: ")
age = int(input("Age: "))
aadhar = input("Aadhar Number: ")

if not is_valid_aadhar(aadhar):
print("Invalid Aadhar number. Please try again.")
continue

passenger_details.append({"name": name, "age": age, "aadhar": aadhar})

add_more_passengers = input("Add more passengers? (yes/no): ")


if add_more_passengers.lower() != "yes":
break

# Query the schedules table to fetch the departure time

sql = "SELECT departure_time FROM schedules WHERE start_station = %s AND dest_station = %s"
val = (start_station, dest_station)
mycursor.execute(sql, val)
departure_time = mycursor.fetchone()
if departure_time:
print("Departure time: ", departure_time[0])
else:
print("No schedule found for the selected stations.")

# Continue with the ticket booking process


print("Confirm booking (yes/no):")
confirm = input().lower()

if confirm == "yes":
# Calculate fare for each passenger
fare = 0
for passenger in passenger_details:
age = passenger["age"]
if age >= 60 or age < 12:
fare += 0.5 * 10 # Apply 50% discount for senior citizens and children
else:
fare += 10

print("Your fare is: Rs. ", fare)

def payment():
global fare
print("\nPayment Details:")
print("Total Amount to be Paid:", fare)
print("1. Use Credit score")
print("2. Pay with Credit Card")
print("3. Pay with Debt Card")
print("4. Pay with atm")

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

if choice == 1:
sql = "Select count(user_id) from tickets where user_id ={}".format(user[0])
mycursor.execute(sql)
ticket = mycursor.fetchall()
print("You have", ticket, "credentials")
s = [(5,)]
if ticket < s:
print("You do not have sufficient credentials")
payment()
else:
a = input("Do you want to use them?(yes/no): ")
if a == 'yes':

if ticket > s:
fare -= 0.1 * 10
print("Your fare is:", fare)
else:
print("Not applicaple")
else:
payment()

elif choice == 2 or choice == 3:


print("\nPayment Successful! Thank you for booking with us.")

elif choice == 4:
atm_number = input("Enter ATM account number: ")
print("enter the bank name in lower case")
bank_name = input("Enter bank name ['icici', 'hdfc', 'axis', 'sbi']")
# Check if ATM account number is valid
if len(atm_number) != 10 or not atm_number.isdigit():
print("Invalid ATM account number. Please try again.")
# Check if bank name is valid
elif bank_name.lower() not in ["icici", "hdfc", "axis", "sbi"]:
print("Invalid bank name. Please try again.")
else:
print("\nInvalid choice. Please try again.")
return

payment()

# Insert ticket into the database


user_id = user[0]
sql = "INSERT INTO tickets (user_id, start_station, dest_station, fare, status) VALUES (%s, %s, %s,
%s, %s)"
val = (user_id, start_station, dest_station, fare, 'booked')
mycursor.execute(sql, val)
mydb.commit()
ticket_id = mycursor.lastrowid
booking_time = datetime.datetime.now()
# Ticket confirmation
ticket_id = mycursor.lastrowid
booking_time = datetime.datetime.now()
print("Ticket booked successfully!")
print("Your ticket number is:", ticket_id)
print("Your booking time is:", booking_time.strftime("%Y-%m-%d %H:%M:%S"))

elif choice == 2:
ticket_id = int(input("Enter the ticket ID: "))

# Check if the ticket exists and belongs to the current user


t = user[0]
print('The user is:', t)

sql = "Select * from tickets where id='{}' and user_id ={}".format(ticket_id,user[0])

mycursor.execute(sql)
ticket = mycursor.fetchone()
s = int(ticket[4])

if not ticket:
print("Invalid ticket number.")
elif ticket[6] == "cancelled":
print("Ticket has already been cancelled.")
else:
print("Time:", ticket[5])
booking_time = ticket[5]
departure_time = booking_time + timedelta(minutes=30)
time_before_departure = departure_time - datetime.datetime.now()

if time_before_departure < timedelta(minutes=0):


refund = 0
status = "expired"
elif time_before_departure < timedelta(minutes=30):
refund = ticket[4] // 2
status = "cancelled"
elif time_before_departure < timedelta(hours=1):
refund = ticket[4] // 4
status = "cancelled"
elif time_before_departure >= timedelta(hours=1):
refund = ticket[4] // 2
status = "cancelled"

mycursor = mydb.cursor()
sql = "UPDATE tickets SET status = %s WHERE id = %s"
val = (status, ticket_id)
mycursor.execute(sql, val)
mydb.commit()

cancellation_time = datetime.datetime.now()
mycursor = mydb.cursor()
sql = "INSERT INTO cancellations (ticket_id, cancellation_time, refund) VALUES (%s, %s, %s)"
val = (ticket_id, cancellation_time, refund)
mycursor.execute(sql, val)
mydb.commit()

print("Ticket cancelled successfully!")


if refund > 0:
print("Refund amount: Rs. ", refund)
else:
print("No refund applicable.")

elif choice == 3:
sql = "Select * from tickets where user_id ={}".format(user[0])
mycursor.execute(sql)
ticket = mycursor.fetchall()
if ticket is not None:
for i in ticket:
s = ticket.index(i)
print('_'*40)
print('\n','Ticket ID =', ticket[s][0],'\n', "User ID =", ticket[s][1],'\n', "Start Station =", ticket[s][2],'\n',
"Destination Station =", ticket[s][3],'\n', "Fare =", ticket[s][4],'\n', "Booking time =", ticket[s][5],'\n', "Status =",
ticket[s][6],'\n')
print('_'*40)
else:
print('You need to book tickets to view history')
elif choice == 4:
sql = "Select count(user_id) from tickets where user_id ={}".format(user[0])
mycursor.execute(sql)
ticket = mycursor.fetchall()
t = [(5,)]
if ticket > t:
print("You have", ticket, "credit score")
else:
print("You need to have booked at least", t, "times to obtain credit score")

elif choice == 5:
feedback_types = input("Enter 'S' for suggestion or 'C' for complaint: ")
if feedback_types.upper() == "S":
feedback_types = "Suggestion"
elif feedback_types.upper() == "C":
feedback_types = "Complaint"
else:
print("Invalid feedback type. Please try again.")
continue

feedback_text = input("Enter your " + feedback_types.lower() + ": ")

# Insert feedback into the feedback table


message = input()
types = 'suggestion, complaint'
sql = "INSERT INTO feedback (user_id, message, types) VALUES (%s, %s, %s)"
val = (user[0], feedback_text, types)
mycursor.execute(sql, val)
mydb.commit()

print("\nThank you for your " + feedback_types.lower() + "! We appreciate your feedback.")

elif choice == 6:
print("Thank you for using Kanpur Metro!")
break

else:
print("Invalid choice. Please try again.")
SAMPLE OUTPUTS
CONCLUSION
In conclusion, the metro ticket booking system is a useful application that allows users to

book and cancel metro tickets, view their booking history, and make payments using credit or

debit cards. The system is designed to be user-friendly and efficient, with a simple interface

that enables users to complete their bookings quickly and easily.

The system uses a database to store information about metro, stations, and bookings, and also

includes features such as cancellation policies and refund calculations. Overall, the metro

ticket booking system is a practical and effective solution for people who want to book metro

tickets in a hassle-free manner.

While this project provides a good foundation for a metro ticket booking system, there are still

many areas where it can be improved. For example, the system could be enhanced by adding

more advanced features such as seat selection, metro schedule information, and real-time

status updates. Additionally, the user interface could be made more visually appealing and

user-friendly to enhance the overall user experience.

Benefits/Advantages:

- Provides a simple and efficient way to book and cancel metro tickets.

- Provides an automated payment system for ticket booking.

Drawbacks:

- The project is limited to a fixed number of stations and routes.

- There is no authentication system for user accounts, which can make the system vulnerable

to hacking.

- The payment system is not integrated with any payment gateway, which could be a

limitation for large-scale implementation.


Suggestions:

- The addition of an authentication system could make the system more secure and reliable.

- The project could also be extended to cover more routes and stations.

Future Enhancements:

- Addition of a notification system for metro delays, cancellations, and rescheduling.

- Integration with GPS tracking to provide real-time metro tracking and arrival/departure

times.

- Addition of a mobile application to make ticket booking and cancellation more accessible

and convenient for users.

BIBLIOGRAPHY
—› Computer Science with Python (Textbook for Class XII) by Sumita Arora

—› https://github.com

—+ https://codemy.com

—› https://www.geeksforgeeks.org

—+ https://stackoverflow.com

You might also like