Supermarket
Billing System
Computer
Science project
2024-2025
NAME: SOHAM VISHWANATH
DHERE
CLASS: XII
STREAM: SCIENCE
REGISTRATION NO:
BOARD ROLL NO:
NERUL, NAVI MUMBAI
CERTIFICATE
This is to certify that this computer project on “
Supermarket Billing System” has been completed
by “Soham Vishwanath Dhere” of class XII Science, in
partial fulfilment of the curriculum of the Central
Board of Secondary Education leading to the award of
All India Senior School Certificate for the year 2024-
25.
Registration No.:
Board Roll No:
__________________ _________________
External Examiner Internal
Examiner
Date: Date:
__________________ __________________
SCHOOL SEAL PRINCIPAL
DECLARATION
I hereby declare that the project entitled
“Supermarket billing system” has been
submitted to “Tilak Public School” for
subject computer science under the
guidance of Mrs. Reshmi Krishnan is a
record of original done by us and there is
no copy or project related to it has been
submitted to any other school or
educational institute by us.
ACKNOWLEDGEM
ENT
The success and outcome of this project
Required a lot of assistance and teamwork
from both the team members we extremely
fortunate to have got this all along the
completion of our project work. Whatever
we have done is only due to such guidance
and assistance and we would not forget to
thank them. I respect and thank Mrs.
Reshmi Krishnan, for giving us an
opportunity to do this assignment work and
providing us all support and guidance
which made us complete the assignment on
time, we are extremely grateful to her for
providing such a nice support and
guidance.
This project work cannot be completed
without the effort and co-operation from
Vihaan Kadam. Finally, we would like to
express our gratitude to our friends and
respondents for support and willingness to
spend some time with us.
INDEX
SR.N TOPIC PAGE
O NO.
1 Hardware and 8
Software used
2 Introduction to python 9
3 Interface python with 14
MySql
4 Introduction to MySql 15
5 Introduction to the 16
project
6 Flow chart 17
7 List of module used 18
8 List of functions 19
9 Source code 21
10 Output 25
11 Limitations/ 30
Improvements
12 Conclusion 31
13 Bibliography 32
Hardware and
Software used
HARDWARE- SOFTWARE-
Laptop: Avita Windows 11
Processor: Intel i7 10th Python Idle
GEN
SSD: 1tb MySql
Ram: 16gb Microsoft Office
Introduction to
python
Python programming language, developed by Guido
Van Rossum in early 1990s, has become a very popular
programming language among beginners as well as
developers.
What is Python?
Python is an interpreted, object-oriented, high-level
programming language with dynamic semantics. Its
high-level built-in data structures, combined with
dynamic typing and dynamic binding, make it very
attractive for Rapid Application Development, as well
as for use as a scripting or glue language to connect
existing components together. Python's simple, easy to
learn syntax emphasizes readability and therefore
reduces the cost of program maintenance. Python
supports modules and packages, which encourages
program modularity and code reuse. The Python
interpreter and the extensive standard library are
available in source or binary form without charge for
all major platforms, and can be freely distributed.
Uses of Python:
Its ease of use. For those who are new to coding
and programming, Python can be an excellent first
step. It is relatively easy to learn, making it a great
way to start building your programming knowledge.
Its simple syntax. Python is relatively easy to read
and understand, as its syntax is more like English. Its
straightforward layout means that you can work out
what each line of code is doing.
Its thriving community. As it is an open-source
language, anyone can use Python to code. What is
more, there is a community that supports and develops
the ecosystem, adding their own contributions and
libraries.
Its versatility. As we will explore in more detail,
there are many uses for Python. Whether you are
interested in data visualisation, artificial intelligence
or web development, you can find a use for the
language.
Features of Python:
1.Easy to Code
Python is a very high-level programming language, yet
it is effortless to learn. Anyone can learn to code in
Python in just a few hours or a few days. Mastering
Python and all its advanced concepts, packages and
modules might take some more time. However,
learning the basic Python syntax is very easy, as
compared to other popular languages like C, C++, and
Java.
Let us now look at the next feature of python.
2. Easy to Read
Python code looks like simple English words. There is
no use of semicolons or brackets, and the indentations
define the code block. You can tell what the code is
supposed to do simply by looking at it.
We will now investigate the next Python features.
3. Free and Open-Source
Python is developed under an OSI-approved open-
source license. Hence, it is completely free to use,
even for commercial purposes. It doesn't cost anything
to download Python or to include it in your application.
It can also be freely modified and re-distributed.
Let us find out the next feature of python.
4. Robust Standard Library
Python has an extensive standard library available for
anyone to use. This means that programmers do not
have to write their code for every single thing unlike
other programming languages. There are libraries for
image manipulation, databases, unit-testing,
expressions and a lot of other functionalities. In
addition to the standard library, there is also a
growing collection of thousands of components, which
are all available in the Python Package Index.
We'll now learn about the next feature of python.
5. Interpreted
When a programming language is interpreted, it
means that the source code is executed line by line,
and not all at once. Programming languages such as
C++ or Java are not interpreted, and hence need to be
compiled first to run them. There is no need to compile
Python because it is processed at runtime by the
interpreter.
Interface Python
with MySql
Python MySQL Connector is a Python driver that
helps to integrate Python and MySQL. This Python
MySQL library allows the conversion between Python
and MySQL data types. MySQL Connector API is
implemented using pure Python and does not require
any third-party library.
Why choose Python for database programming ?
Following are the reason to choose python for
database programming
• Programming more efficient and faster compared to
other languages.
• Portability of python programs.
• Support platform independent program
development.
• Python supports SQL cursors.
• Python itself take care of open and close of
connections.
• Python supports relational database systems.
• Porting of data from one dbms to other is easily
possible as it support large range of APIs for various
databases.
Introduction to
MySql
SQL, Structured Query Language, was
developed in 1970s in an IBM Laboratory. SQL,
sometimes also referred to as SEQUEL is a 4th
generation non-procedural language.
It is particularly useful in handling structured
data, i.e. data incorporating relations among
entities and variables.
It's based upon relational algebra and tuple
relational calculus, SQL consists of many types
of statements, which may be informally classed
as sublanguages, commonly: a data query
language (DQL).
Introduction to the
Project
The purpose of the project is to build an
application program to reduce the manual work
for managing a supermarket store. It tracks all
the bills and allow us to create bills, view bills.
The User can:
Add products
View bill by just providing bill ID
Create Bill:
This program is designed to streamline
supermarket billing by allowing users to manage
product inventory, create bills, and track
transactions in a MySQL database, reducing
manual effort.
Flowchart
START
Initialize
Database
MEN
U
Add View
Product Create Bill View Bill
Products
EXIT
END
List of Module
Used
Module: Purpose:
mysql.connector Provides MySQL
database connectivity
for connecting,
querying, and
manipulating the
database.
List of Functions
S.No. Function Purpose
1 connect_db() Establishes a
connection to the
MySQL database
using
mysql.connector.
2 initialize_db() Creates the
database if it
doesn’t exist and
connects to it.
3 add_product() Adds a new
product to the
products table in
the database with
specified name,
price, and quantity
4 view_products() Retrieves and
returns all
products from the
products table for
display.
5 create_bill() Creates a new bill
for a customer,
calculates the
total, and saves the
bill and its items in
the database.
6 view_bill() Retrieves and
displays details of
a specific bill,
including customer
name, total, and
itemized list.
7 main_menu() Displays the main
menu and handles
user input for
navigating
different
functionalities of
the system.
Source Code
import mysql.connector
from datetime import datetime
# Database Connection
def connect_db():
return mysql.connector.connect(
host="localhost",
user="root",
password="vihaan",
database="supermarket_billing"
)
# Initialize Database (without table creation)
def initialize_db():
db = connect_db()
cursor = db.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS supermarket_billing")
cursor.execute("USE supermarket_billing")
db.commit()
db.close()
print("Database connection established.")
# Add Product
def add_product(product_name, price, quantity):
db = connect_db()
cursor = db.cursor()
query = "INSERT INTO products (product_name, price, quantity)
VALUES (%s, %s, %s)"
cursor.execute(query, (product_name, price, quantity))
db.commit()
db.close()
print("Product added successfully.")
# View All Products
def view_products():
db = connect_db()
cursor = db.cursor()
cursor.execute("SELECT * FROM products")
products = cursor.fetchall()
db.close()
return products
# Create a Bill
def create_bill(customer_name, items):
db = connect_db()
cursor = db.cursor()
# Calculate total amount
total_amount = sum(item['price'] * item['quantity'] for item in
items)
# Insert into bills table
bill_query = "INSERT INTO bills (customer_name, total_amount)
VALUES (%s, %s)"
cursor.execute(bill_query, (customer_name, total_amount))
bill_id = cursor.lastrowid # Get the last inserted bill_id
# Insert each item into bill_items table
for item in items:
item_query = """
INSERT INTO bill_items (bill_id, product_id, quantity,
price)
VALUES (%s, %s, %s, %s)
"""
cursor.execute(item_query, (bill_id, item['product_id'],
item['quantity'], item['price']))
db.commit()
db.close()
print(f"Bill created successfully for {customer_name} with Bill ID:
{bill_id}")
# View a Bill
def view_bill(bill_id):
db = connect_db()
cursor = db.cursor()
# Get bill information
bill_query = "SELECT * FROM bills WHERE bill_id = %s"
cursor.execute(bill_query, (bill_id,))
bill = cursor.fetchone()
# Get bill items
item_query = """
SELECT products.product_name, bill_items.quantity,
bill_items.price
FROM bill_items
JOIN products ON bill_items.product_id = products.product_id
WHERE bill_items.bill_id = %s
"""
cursor.execute(item_query, (bill_id,))
items = cursor.fetchall()
db.close()
print("Bill ID:", bill[0])
print("Customer Name:", bill[1])
print("Total Amount:", bill[2])
print("Date:", bill[3])
print("\nItems:")
for item in items:
print(f"{item[0]} - Quantity: {item[1]}, Price: {item[2]}")
print("\n")
# Main Menu
def main_menu():
initialize_db()
while True:
print("\nSupermarket Billing System")
print("1. Add Product")
print("2. View Products")
print("3. Create Bill")
print("4. View Bill")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
product_name = input("Enter product name: ")
price = float(input("Enter price: "))
quantity = int(input("Enter quantity: "))
add_product(product_name, price, quantity)
elif choice == '2':
products = view_products()
print("\nProducts:")
for product in products:
print(f"ID: {product[0]}, Name: {product[1]}, Price:
{product[2]}, Quantity: {product[3]}")
elif choice == '3':
customer_name = input("Enter customer name: ")
items = []
while True:
product_id = int(input("Enter product ID (or 0 to
finish): "))
if product_id == 0:
break
quantity = int(input("Enter quantity: "))
# Fetch product price
db = connect_db()
cursor = db.cursor()
cursor.execute("SELECT price FROM products WHERE
product_id = %s", (product_id,))
price = cursor.fetchone()[0]
db.close()
items.append({"product_id": product_id, "quantity":
quantity, "price": price})
create_bill(customer_name, items)
elif choice == '4':
bill_id = int(input("Enter bill ID: "))
view_bill(bill_id)
elif choice == '5':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
# Run the program
main_menu()
Output
Python outputs:
MySql Outputs:
1.Product table
2.Bills table
3.Bill_items table:
Limitations/
Improvements
Error Handling:
There’s no error handling in the code for database
connection issues or invalid inputs (e.g., non-numeric
input for price and quantity). Adding try-except blocks
for database operations and validating inputs would
make the code more reliable and user-friendly.
Code Redundancy and Optimization:
The code repeatedly connects to the database in each
function. This can be optimized by establishing a
single connection for all operations or using
connection pooling. Additionally, retrieving product
prices individually for each item in create_bill could be
optimized by querying all products at once at the
beginning.
Lack of Modular Structure: As the application
grows, a more modular structure is needed. Splitting
the code into separate modules for database
operations, product management, and billing (using
files or classes) would improve maintainability and
scalability. For example, a separate ProductManager
and BillManager class could handle product and bill-
related operations.
User Authentication and Role Management: The
application does not support user authentication or
role-based access control (e.g., admin vs. cashier).
Adding a login feature and defining roles would make
the system more secure and better aligned with the
intended use in a supermarket environment.
Conclusion
This is a user-friendly supermarket
billing program that simplifies the tasks
of adding, viewing, and managing
products and bills. Built with Python
and MySQL as the backend database, it
efficiently handles billing operations,
providing accurate and accessible
information as needed. This program is
designed to streamline billing
processes, making it ideal for small to
medium-sized retail environments.
Bibliography
Computer science with
Python by Sumita Arora.
www.google.com