Priyans Bhatt, Python
Priyans Bhatt, Python
I confirm that I understand my coursework needs to be submitted online via Google Classroom under the
relevant module page before the deadline in order for my assignment to be accepted and marked. I am
fully aware that late submissions will be treated as non-submission and a marks of zero will be awarded.
Table of Contents
Table of Contents
Introduction ................................................................................................................... 1
Algorithms. .................................................................................................................... 3
Flowchart ....................................................................................................................... 5
Pseudocode ................................................................................................................... 7
Data Structure ............................................................................................................... 9
Program ....................................................................................................................... 12
The termination of the program: ................................................................................ 23
Testing ......................................................................................................................... 23
Testing 1: ................................................................................................................... 23
Testing 2: ................................................................................................................... 25
Testing 3: ................................................................................................................... 27
Testing 4: ................................................................................................................... 29
Testing 5: ................................................................................................................... 30
Conclusion ................................................................................................................... 31
Appendix:..................................................................................................................... 32
Main.py ...................................................................................................................... 32
Utils.py ....................................................................................................................... 40
List of Figures
Figure 1: Picture of Python .............................................................................................. 1
Figure 2: Algorithm .......................................................................................................... 3
Figure 3: Flowchart to add two numbers ......................................................................... 6
Figure 4: Example of Pseudo Code................................................................................. 7
Figure 5: Data Structure Explained ............................................................................... 10
Figure 6: Costume Rental Terminal............................................................................... 15
Figure 7: Output in the text file ...................................................................................... 16
Figure 8: Costume returned .......................................................................................... 21
Figure 9: Costume returned in the text file. ................................................................... 22
Figure 10: Terminal of program. .................................................................................... 23
Figure 11:Try and except .............................................................................................. 25
Figure 12: Negative value in terminal ............................................................................ 26
Figure 13: Input value exceeding the instruction ........................................................... 27
Figure 14: Costume rented............................................................................................ 28
Figure 15: Multiple costume rented in text file ............................................................... 28
Figure 16: Return in Terminal........................................................................................ 30
Figure 17: Return in Text File ........................................................................................ 30
Figure 18: Stock changed by Renting ........................................................................... 31
Figure 19: Stock changed by returning.......................................................................... 31
List to Tables
Table 1: To demonstrate how try and expect is being used .......................................... 24
Table 2: Costume selection, rental, and return with incorrect numbers. ........................ 25
Table 3: File generation of renting costume (Renting multiple customers) .................... 27
Table 4: File generation of returning process of costume.............................................. 29
Table 5: Show the update in stock of costume .............................................................. 30
CS4051NI FUNDAMENTALS OF COMPUTING
Introduction
A well-liked programming language is Python. In 1991, Guido van Rossum produced it,
and it became available.
It's used for website creation, software creation, mathematics, scripting for systems.
1
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
2
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Algorithms.
Figure 2: Algorithm
Step 1: Start.
Step 4: Go to Step 5 if the item has already been hired; otherwise, go to Step 9.
Step 5: Access the desired local variables from the desired global variables.
3
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Step 7: If today is more recent than the item return date for each record in rents.db, then
ask the user if the consumer has responded; if so, go Step-31
Step 8: Immediately go to Step 19 if any of the items have been returned; otherwise, go
to Step 9.
Step 9: Access the desired local variables from the desired global variables.
Step 11: Allow entry to be obtained from the DB using the requested ID.
Step 13: Reduce rent quantity from DB according to the prompt from above.
Step 14: Rental unit days should be prompt (1 unit day = 5 days).
Step 15: Let rent quantity from, rental unit days from prompt, and total price be a
multiplication of the price from entry.
Step 16: Display the invoice together with the entry and the calculations above.
Step 17: Final rental confirmation; if yes, move on to step 18; otherwise, move on to
step 36.
Step 21: Allow entity from accessible DB to be parsed using prompted ID.
Step 22: Calculate the total cost from the entries by multiplying the entry's price by the
rent quantity and the rental unit's days from the database.
Step 23: If the return date is the same as today, go on to Step 24, if it is early, move on
to Step 26, and if it is late, move on to Step 31.
4
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Step 27: If you need to lower the price in the event of an early return, move to Step-28;
otherwise, go to Step-29. To locals, DB
Step 28: Subtract the anticipated cost of the days not used from the total cost.
Step 32: prompt if late return fee is necessary and if no go-to Step-34
Step 33: By figuring out the cost each day per unit of the item, add the fine price to the
overall cost.
Step 36: Ask the user if they wish to stop; if not, move on to Step 1.
Flowchart
The visual representation of a program's flow is a flowchart. A flow chart typically uses
four basic shapes. An illustration of a process' individual steps in chronological
sequence is called a flowchart. It is a versatile tool that may be customized for a wide
range of uses and used to describe a number of processes, including manufacturing
processes, administrative or service processes, project plans, and others. It is a typical
tool for process analysis and one of the seven fundamental quality tools. Flowcharts,
often known as flow charts, use forms like rectangles, ovals, diamonds, and perhaps
many more to identify the type of step and connecting arrows to denote flow and
sequence. Flowcharts are among the most frequently used diagrams in the world, being
utilized in a variety of industries by both technical and non-technical people.
5
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
6
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Pseudocode
func prompt_yn(txt):
_input = input(_args_0 + " [y/n]: ").lower()
if _input not in ('y', 'n'):
_input = prompt_yn(txt)
if choi_input == 'y':
return True
return False
func handle_known_rentals:
if not DB.rents: return
7
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
func handle_new_rentals():
table_print(DB.stocks)
id = input("Enter ID of item you want to rent: ")
db_entry = DB.stocks[id]
rent_qty = input("Enter quantity you wish to rent: ")
entry.qty -= rent_qty
rent_unit_days = input("Enter unit days you want to rent (1 unit day = 5 days): ")
total_price = entry.price * rent_qty * rent_unit_days
_print_invoice_
if cofirm("Do you want to rent now?"):
name = input("Enter you name: ")
contact = input("Enter you phone number: ")
DB.commit(entry, [today(), rent_qty, rent_unit_days, name, contact])
func handle_returns():
print_table(DB.rents)
id = input("Enter the ID of item that had been returned")
entry = DB.rents[id]
stock_entry = DB.stocks[entry.IID]
total_price = stock_entry.price * entry.rent_qty * entry.rent_unit_days
_print_invoice_
if entry.return_date == datetime.date.today():
stock_entry.qty += entry.qty
commit(rm(entry), stock_entry)
elif (entry.return_date - today).days > 0:
handle_early_return(id)
else:
handle_new_return(id)
func handle_late_rental(id):
entry = DB.rents[id]
stock_entry = DB.stocks[entry.IID]
total_price = stock_entry.price * entry.rent_qty * entry.rent_unit_days
days_late = (datetime.date.today() - entry.return_date).days
if prompt_yn("Do you want to fine the costumer?"):
fine_price = ( stock_entry.price / 5 ) * entry.qty * days_late
8
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
total_price += fine_price
_print_invoice_
function handle_early_return(id):
entry = DB.rents[id]
stock_entry = DB.stocks[entry.IID]
total_price = stock_entry.price * entry.rent_qty * entry.rent_unit_days
days_early = ( entry.return_date - datetime.date.today() ).days
if prompt_yn("Do you want to deduct price from the costumer (un-used days)?"):
discount_price = ( stock_entry.price / 5 ) * entry.qty * days_early
total_price -= discount_price
_print_invoice_
func main():
print("Welcome - banner")
print_table(DB.stocks)
if DB.rent:
handle_known_rentals()
else:
handle_new_return()
if prompt_yn("Do you wish to exit?"):
exit(0)
else:
main()
main()
Data Structure
A data structure is not just employed for data organization. Data processing, retrieval,
and archiving are further uses for it. Almost every software system or program that has
been created uses many fundamental and sophisticated forms of data structures.
Therefore, we need to be knowledgeable about data structures. A data structure may be
chosen or created in computer science and computer programming to store data in
order to be used with different methods. In some circumstances, the design of the data
structure and the algorithm's fundamental operations are closely related. Each data
9
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
structure includes details about the values of the data, the connections between the
data, and, occasionally, functions that can be used to manipulate the data.
10
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
By enclosing it in curly brackets, you can define a list of key-value pairs as a dictionary
(). There is a colon between each key and its matching value (:).
Python, plural A tuple is a group of items with commas separating them. A tuple is
somewhat akin to a list in terms of indexing, nested items, and repetition, however a
tuple is immutable as opposed to mutable lists.
Unordered items are placed together to form a set. Each set element must be
immutable, without any duplication (cannot be changed). However, a set can be altered
on its own. We can add or remove stuff from it. Union, intersection, symmetric
difference, and other mathematical set operations
11
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Program
The whole process and the code for making an order for a costume with the costume
rental system are provided below. The code also includes an illustration of the section
for processing both new and returning rentals.
def handle_new_rentals():
global db
_t = "stocks"
tdb = db[_t]
_db = db.rents
char = prompt_num(
"Please select an ID of available item you want to rent: ", len(tdb), 1
)
item_id = char - 1
entry = tdb[item_id]
char = prompt_num(
"Enter quantity of the item you would like to rent: ",
entry["Qty"],
1,
True, # Saving an entity, since we need at least one quantity of an item.
)
rental_qty = char
entry["Qty"] -= rental_qty
char = prompt_num(
"Enter unit day(s) you want to rent the item for (1 unit day = 5 days): ",
367,
1,
)
rental_unit_days = char
total_price = entry["Price"] * rental_qty * rental_unit_days
invoice_table = [
{
"Name": entry["Name"],
"Brand": entry["Brand"],
"Price": f'$ {entry["Price"]}',
"Rented Qty": rental_qty,
"Rental days": rental_unit_days * 5,
"Total Price": f"$ {total_price}",
}
]
print("-" * 43)
print("\n" * 3)
print("YOUR INVOICE", end="\n\n")
12
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
print_table(invoice_table)
char = prompt_yn("Would you now like to rent the item?")
if char == "y":
tdb[item_id] = entry
db[_t] = tdb
_id = 1
if len(_db):
_id = _db[-1]["ID"] + 1
username = input("Please enter your name sir: ")
contact = input("And just your phone number: ")
rental_entry = {
"ID": _id,
"IID": entry["ID"],
"Date of rental": today(),
"Rental unit days": rental_unit_days,
"Rental qty": rental_qty,
"Username": username,
"Contact": contact,
}
if len(_db):
_db.append(rental_entry)
commit(_db, "rents")
db.rents = _db
else:
commit([rental_entry], "rents")
db.rents = [Map(rental_entry)]
commit(tdb, _t)
print_table(db.stocks)
print("\n" * 3)
print_table(db.rents)
print(end="\n" * 2)
else:
entry = {}
tdb = []
def handle_known_rentals():
global db
_t = "rents"
_db = db.stocks
tdb = db[_t]
if not tdb:
return
print("-----Rentals-----")
print_table(tdb)
for entry in tdb:
13
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
_entry = _db[entry["IID"] - 1]
return_date = parse_date_str(entry["Date of rental"]) + unit_days(
entry["Rental unit days"]
)
if today() > return_date:
print(end="\n" * 2)
more_days = (today() - return_date).days
print(
f'{entry["Username"]} was supposed to return {_entry["Name"]} on
{return_date}, it has been {more_days} days since no return. You may want to call him
on {entry["Contact"]}'
)
char = prompt_yn("Did he respond/you called?")
if char == "y":
handle_late_return(entry["ID"])
return
char = prompt_yn("Has any of above costume been returned?")
if char == "y":
handle_returns()
else:
handle_new_rentals()
14
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
15
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
The whole method for returning a costume to the costume rental system is listed here.
The code demonstrates the steps for a typical return, a late return, and even an early
return in three different segments.
def handle_returns():
global db
_t = "rents"
tdb = db[_t]
edb = db.earnings
_db = db.stocks
char = prompt_num("Please select an ID of the returened rental: ", len(tdb), 1)
item_id = char - 1
entry = tdb[item_id]
_entry = _db[entry["IID"] - 1]
print(end="\n" * 2)
total_price = _entry["Price"] * entry["Rental unit days"] * entry["Rental qty"]
return_date = parse_date_str(entry["Date of rental"]) + unit_days(
entry["Rental unit days"]
)
invoice_table = [
{
"Customer's Name": entry["Username"],
"Item's Name": _entry["Name"],
"Brand": _entry["Brand"],
"Price": f'$ {_entry["Price"]}',
"Rented Qty": entry["Rental qty"],
"Contact": entry["Contact"],
"Rental date": entry["Date of rental"],
"Return date": return_date,
"Total Price": f"$ {total_price}",
}
]
print_table(invoice_table)
if return_date == today():
_id = 1
16
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
if len(edb):
_id = edb[-1]["ID"]
earning_entry = {
"ID": _id,
"username": entry["Username"],
"contact": entry["Contact"],
"price_per_unit": _entry["Price"],
"total_price": total_price,
"date_of_rental": entry["Date of rental"],
"date_of_return": return_date,
"rental_qty": entry["Rental qty"],
"rental_unit_days": entry["Rental unit days"],
}
if len(edb):
edb.append(earning_entry)
db.earnings = edb
commit(edb, "earnings")
else:
commit([earning_entry], "earnings")
db.earnings = [Map(earning_entry)]
for _index, _entry in enumerate(_db):
if entry["IID"] == _entry["ID"]:
_entry["Qty"] += entry["Rental qty"]
_db[_index] = _entry
commit(_db, "stocks")
db.stocks = _db
for index, _entry in enumerate(tdb):
if _entry["ID"] == entry["ID"]:
del tdb[index]
commit(tdb, "rents")
db.rents = tdb
elif (return_date - today()).days > 0:
handle_early_return(entry["ID"])
else:
handle_late_return(entry["ID"])
def handle_late_return(_id):
global db
_t = "rents"
tdb = db[_t]
edb = db.earnings
_db = db.stocks
entry = tdb[_id - 1]
_entry = _db[entry["IID"] - 1]
item_qty = entry["Rental qty"]
17
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
18
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
commit(edb, "earnings")
else:
commit([earning_entry], "earnings")
db.earnings = [Map(earning_entry)]
for _index, _entry in enumerate(_db):
if entry["IID"] == _entry["ID"]:
_entry["Qty"] += entry["Rental qty"]
_db[_index] = _entry
commit(_db, "stocks")
db.stocks = _db
for index, _entry in enumerate(tdb):
if _entry["ID"] == entry["ID"]:
del tdb[index]
commit(tdb, "rents")
db.rents = tdb
def handle_early_return(_id):
global db
_t = "rents"
tdb = db[_t]
edb = db.earnings
_db = db.stocks
entry = tdb[_id - 1]
_entry = _db[entry["IID"] - 1]
item_qty = entry["Rental qty"]
total_price = _entry["Price"] * entry["Rental unit days"] * item_qty
return_date = parse_date_str(entry["Date of rental"]) + unit_days(
entry["Rental unit days"]
)
days_early = (return_date - today()).days
return_date -= timedelta(days=days_early)
choice = prompt_yn(
f"Return date seemed to be {days_early} days ahead, would you like to charge for
the rent till today instead of previously mentioned date?"
)
print(end="\n" * 2)
if choice == "n":
price_per_day_per_item = _entry["Price"] / 5
deduction_price = price_per_day_per_item * item_qty * days_early
total_price -= deduction_price
invoice_table = [
{
"Customer's Name": entry["Username"],
"Item's Name": _entry["Name"],
"Brand": _entry["Brand"],
19
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
20
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
21
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
22
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Testing
Testing 1:
23
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
24
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Testing 2:
Table 2: Costume selection, rental, and return with incorrect numbers.
25
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
26
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Testing 3:
Table 3: File generation of renting costume (Renting multiple customers)
27
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
28
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Testing 4:
Expected Results The text files are created, and the output
is shown in a shell.
29
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Testing 5:
30
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Conclusion
This project gave us practical experience with the costume rental system while also
assisting in our efforts to improve the Python programming language. With the aid of
this project, I was able to comprehend many data structures used in Python
programming, including list, tuple, dictionary, and others. Overall, because of the
project's intricacy, I was able to learn the fundamentals of programming while also
sharpening my problem-solving abilities. The renting system for costumes is entirely
discussed in the coursework and may be used in daily life. Since the rental and return of
the user information is generated in a text file together with the revenue and the quantity
of the stock also increases and decreases in accordance with those earnings, the
business operated project helped to understand how the business operates.
31
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
Appendix:
Main.py
#!/usr/bin/env python3
def handle_returns():
global db
_t = "rents"
tdb = db[_t]
edb = db.earnings
_db = db.stocks
32
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
33
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
if entry["IID"] == _entry["ID"]:
_entry["Qty"] += entry["Rental qty"]
_db[_index] = _entry
commit(_db, "stocks")
db.stocks = _db
for index, _entry in enumerate(tdb):
if _entry["ID"] == entry["ID"]:
del tdb[index]
commit(tdb, "rents")
db.rents = tdb
elif (return_date - today()).days > 0:
handle_early_return(entry["ID"])
else:
handle_late_return(entry["ID"])
def handle_late_return(_id):
global db
_t = "rents"
tdb = db[_t]
edb = db.earnings
_db = db.stocks
entry = tdb[_id - 1]
_entry = _db[entry["IID"] - 1]
item_qty = entry["Rental qty"]
total_price = _entry["Price"] * entry["Rental unit days"] * item_qty
return_date = parse_date_str(entry["Date of rental"]) + unit_days(
entry["Rental unit days"]
)
days_late = (today() - return_date).days
return_date += timedelta(days=days_late)
choice = prompt_yn(
f"Looks like you've submitted the item {days_late} days late, would you like to
charge costumer fine for it?"
)
print(end="\n" * 2)
if choice == "y":
price_per_day_per_item = _entry["Price"] / 5
fine_price = price_per_day_per_item * item_qty * days_late
total_price += fine_price
invoice_table = [
{
"Customer's Name": entry["Username"],
"Item's Name": _entry["Name"],
"Brand": _entry["Brand"],
"Price": f'$ {_entry["Price"]}',
34
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
def handle_early_return(_id):
global db
_t = "rents"
tdb = db[_t]
35
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
edb = db.earnings
_db = db.stocks
entry = tdb[_id - 1]
_entry = _db[entry["IID"] - 1]
item_qty = entry["Rental qty"]
total_price = _entry["Price"] * entry["Rental unit days"] * item_qty
return_date = parse_date_str(entry["Date of rental"]) + unit_days(
entry["Rental unit days"]
)
days_early = (return_date - today()).days
return_date -= timedelta(days=days_early)
choice = prompt_yn(
f"Return date seemed to be {days_early} days ahead, would you like to charge for
the rent till today instead of previously mentioned date?"
)
print(end="\n" * 2)
if choice == "n":
price_per_day_per_item = _entry["Price"] / 5
deduction_price = price_per_day_per_item * item_qty * days_early
total_price -= deduction_price
invoice_table = [
{
"Customer's Name": entry["Username"],
"Item's Name": _entry["Name"],
"Brand": _entry["Brand"],
"Price": f'$ {_entry["Price"]}',
"Rented Qty": entry["Rental qty"],
"Contact": entry["Contact"],
"Rental date": entry["Date of rental"],
"Return date": return_date,
"Total Price": f"$ {total_price}",
}
]
print_table(invoice_table)
_id = 1
if len(edb):
_id = edb[-1]["ID"]
earning_entry = {
"ID": _id,
"username": entry["Username"],
"contact": entry["Contact"],
"price_per_unit": _entry["Price"],
"total_price": total_price,
"date_of_rental": entry["Date of rental"],
"date_of_return": return_date,
"rental_qty": entry["Rental qty"],
36
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
def handle_new_rentals():
global db
_t = "stocks"
tdb = db[_t]
_db = db.rents
char = prompt_num(
"Please select an ID of available item you want to rent: ", len(tdb), 1
)
item_id = char - 1
entry = tdb[item_id]
char = prompt_num(
"Enter quantity of the item you would like to rent: ",
entry["Qty"],
1,
True, # Saving an entity, since we need at least one quantity of an item.
)
rental_qty = char
entry["Qty"] -= rental_qty
char = prompt_num(
"Enter unit day(s) you want to rent the item for (1 unit day = 5 days): ",
367,
1,
)
rental_unit_days = char
37
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
38
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
entry = {}
tdb = []
def handle_known_rentals():
global db
_t = "rents"
_db = db.stocks
tdb = db[_t]
if not tdb:
return
print("-----Rentals-----")
print_table(tdb)
for entry in tdb:
_entry = _db[entry["IID"] - 1]
return_date = parse_date_str(entry["Date of rental"]) + unit_days(
entry["Rental unit days"]
)
if today() > return_date:
print(end="\n" * 2)
more_days = (today() - return_date).days
print(
f'{entry["Username"]} was supposed to return {_entry["Name"]} on
{return_date}, it has been {more_days} days since no return. You may want to call him
on {entry["Contact"]}'
)
char = prompt_yn("Did he respond/you called?")
if char == "y":
handle_late_return(entry["ID"])
return
char = prompt_yn("Has any of above costume been returned?")
if char == "y":
handle_returns()
else:
handle_new_rentals()
def main():
global db
db = Map({"stocks": read(), "rents": read("rents"), "earnings": read("earnings")})
print("Welcome to the Costume Rental Terminal", end="\n" * 2)
print("-----Items-----")
print_table(db.stocks)
try:
print(end="\n" * 2)
if read("rent"):
39
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
handle_known_rentals()
else:
handle_new_rentals()
exit_prompt("Do you wish to exit now?")
main()
except Exception as e:
print()
print(f"Exception -> {e}")
print(end="\n" * 2)
print("Press enter to continue..", end="", flush=True)
input()
exit_prompt("Do you wish to exit now?")
main()
if __name__ == "__main__":
main()
Utils.py
class State:
StockStructure = {
"ID": int,
"name": str,
"brand": str,
"price": float,
"qty": int,
}
RentalStructure = {
"ID": int,
"IID": int,
"date_of_rental": str,
"rental_unit_days": int,
"rental_qty": int,
"username": str,
40
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
"contact": str,
}
EarningStructure = {
"ID": int,
"username": str,
"contact": str,
"price_per_unit": float,
"total_price": float,
"date_of_rental": str,
"date_of_return": str,
"rental_qty": int,
"rental_unit_days": int,
}
DateFormat = "%Y-%m-%d"
IN_NON_DELIMITED_CELL = 1
IN_DELIMITED_CELL = 2
# This helps use use dot-notation. (Instead of using dict['key'], we'll also be able to use
dict.key)
class Map(dict):
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
self[k] = v
if kwargs:
for k, v in kwargs.items():
self[k] = v
41
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
super(Map, self).__delitem__(key)
del self.__dict__[key]
if current_state == State.IN_DELIMITED_CELL:
if character == quotechar:
stack.pop()
else:
cell_values[-1] += character
return cell_values
42
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
def read(type="stocks"):
if type.startswith("rent"):
path = "./rentals.csv"
elif type.startswith("stock"):
path = "./stocks.csv"
elif type.startswith("earn"):
path = "./earnings.csv"
else:
raise ValueError("Unknown database collection specified in type argument.")
db: list[dict] = []
try:
with open(path, "r") as f:
for line in f:
line = line.strip()
cell_values = get_cell_values(line, '"', ",")
db.append(parse_cell_values(cell_values, type))
except Exception as e:
print(f"Exception -> {e}")
return db
def print_table(db):
43
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
def today():
return date.today()
def parse_date_str(date_str):
if type(date_str) != str:
date_str = str(date_str)
return datetime.strptime(date_str, State.DateFormat).date()
def unit_days(_unit_days):
return timedelta(days=_unit_days * 5)
44
Priyans Bhatt
CS4051NI FUNDAMENTALS OF COMPUTING
def prompt_yn(prompt):
print(end="\n" * 2)
try:
char = input(f"{prompt} [y/n]: ").lower()
while char not in ("y", "n"):
char = prompt_yn(prompt)
except KeyboardInterrupt:
exit_prompt()
return prompt_yn(prompt)
except Exception as e:
print(e)
return prompt_yn(prompt)
return char
45
Priyans Bhatt