Question

I need this python program to access an excel file, books inventory file. The file called...

I need this python program to access an excel file, books inventory file. The file called (bkstr_inv.xlsx), and I need to add another option [search books], option to allow a customer to search the books inventory, please.

CODE

''' Shows the menu with options and gets the user selection.
'''
def GetOptionFromUser():
print("******************BookStore**************************")
print("1. Add Books")
print("2. View Books")
print("3. Add To Cart")
print("4. View Receipt")
print("5. Buy Books")
print("6. Clear Cart")
print("7. Exit")
print("*****************************************************")
option = int(input("Select your option: "))
return option

'''
Adds a book to the list of books.
reads the name and price and adds it as a dictionary
'''
def AddBook():
b = {}
b["Name"] = input("Enter Book Name: ")
b["Price"] = float(input("Enter Price of the book: "))
Books.append(b)

'''
Prints all the books in the list.
'''
def PrintBooks(books):
if len(books) == 0:
print("No Books to show...")
return
  
print("{name:<15}{price:>10}".format(name = "Name", price = "Price"))
for book in books:
print("{name:<15}{price:>10}".format(name = book["Name"], price = '$' + str(book["Price"])))

'''
Add book to cart.
Reads the book name from user adds the book to cart if the book is in the store.
'''
def AddToCart(Total):
name = input("Enter Book Name: ")
for book in Books:
if(book["Name"] == name):
Cart.append(book)
Total = Total + book["Price"]
print("Books Added to Cart..")
return Total
print("Book Not Found...")
return Total
'''
Prints the books in the cart and their total cost.
'''
def ViewReceipt():
if len(Cart) == 0:
print("No Items in Cart...")
return
PrintBooks(Cart)
print("*****************************************************")
print("Total Cost: $", TotalCartPrice);
print("*****************************************************")
'''
Removes the books in the cart from the store.
shows the recipt.
'''
def BuyBooks():
if len(Cart) == 0:
print("No Items in Cart...")
return
for c in Cart:
for book in Books:
if book["Name"] == c["Name"]:
Books.remove(book)
print("Books Bought..")
ViewReceipt()

'''
Variables.
'''
Books = []
Cart = []
TotalCartPrice = 0.0

'''
Exception handling
'''
try:
'''
Handle each option by calling respective function.
'''
while True:
option = GetOptionFromUser()
if option == 1:
AddBook()
print("Books Added..")
if option == 2:
PrintBooks(Books)
if option == 3:
TotalCartPrice = AddToCart(TotalCartPrice)
if option == 4:
ViewReceipt()
if option == 5:
BuyBooks()
Cart.clear()# clear the cart after buying books.
TotalCartPrice = 0.0
if option == 6:
Cart.clear()
TotalCartPrice = 0.0
print("Cart Cleared..")
if option == 7:
print("Exiting Application...")
break;
except:
print("", end = ' ')
  

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the answer for your question in Python Programming Language.

Kindly upvote if you find the answer helpful.

NOTE : I have used xlrd module to read excel file. To install xlrd module, open python shell and type

"pip install xlrd"

I have used two method ,

  • readExcel() - to load data from excel file to list of books
  • searchBook() - To serach a book from the list of books in the inventory

Kindly find the two methods along with the code.

CODE :

import xlrd

def GetOptionFromUser():
print("******************BookStore**************************")
print("1. Add Books")
print("2. View Books")
print("3. Add To Cart")
print("4. View Receipt")
print("5. Buy Books")
print("6. Clear Cart")
print("7. Search Book")
print("8. Exit")
print("*****************************************************")
option = int(input("Select your option: "))
return option

'''
Reads Books from an excel file bkstr_inv.xlsx
'''
def readExcel():
#Declare Books as global variable
global Books
'''Open the xlsx file using xlrd module'''
workbook = xlrd.open_workbook("bkstr_inv.xlsx")
'''Open the sheet by its index(First sheet's index starts with 0)'''
sheet = workbook.sheet_by_index(0)
'''Get number of rows in the sheet'''
rows = sheet.nrows
'''Loop through each row skipping the header row'''
for i in range(1,rows):
'''Create dictionary for each row'''
b = {}
'''Load name and price of each book'''
b["Name"] = sheet.cell(i,0).value
b["Price"] = sheet.cell(i,1).value
'''Append dictionary to list of books 'Books'''
Books.append(b)
'''
To allow user to search from booksinventory
'''
def searchBook():
'''Prompt the user for book name'''
name = input("Enter book name : ")
'''Set the flag initially to false'''
found = False
'''Loop through every book in Books'''
for eachBook in Books:
'''If name of book matches given name'''
if(eachBook["Name"] == name):
'''Set flag to true and display output'''
found = True
print("Book Name\t\tBook Price")
print("*********************************")
print("{0:<25}{1}".format(eachBook["Name"],eachBook["Price"]))
'''If flag is false, display book not found'''
if(not found):
print("Book with name {0} cannot be found".format(name))
'''
Adds a book to the list of books.
reads the name and price and adds it as a dictionary
'''
def AddBook():
b = {}
b["Name"] = input("Enter Book Name: ")
b["Price"] = float(input("Enter Price of the book: "))
Books.append(b)

'''
Prints all the books in the list.
'''
def PrintBooks(books):
if len(books) == 0:
print("No Books to show...")
return
print("{name:<15}{price:>10}".format(name = "Name", price = "Price"))
for book in books:
print("{name:<15}{price:>10}".format(name = book["Name"], price = '$' + str(book["Price"])))

'''
Add book to cart.
Reads the book name from user adds the book to cart if the book is in the store.
'''
def AddToCart(Total):
name = input("Enter Book Name: ")
for book in Books:
if(book["Name"] == name):
Cart.append(book)
Total = Total + book["Price"]
print("Books Added to Cart..")
return Total
print("Book Not Found...")
return Total
'''
Prints the books in the cart and their total cost.
'''
def ViewReceipt():
if len(Cart) == 0:
print("No Items in Cart...")
return
PrintBooks(Cart)
print("*****************************************************")
print("Total Cost: $", TotalCartPrice);
print("*****************************************************")
'''
Removes the books in the cart from the store.
shows the recipt.
'''
def BuyBooks():
if len(Cart) == 0:
print("No Items in Cart...")
return
for c in Cart:
for book in Books:
if book["Name"] == c["Name"]:
Books.remove(book)
print("Books Bought..")
ViewReceipt()

'''
Variables.
'''
Books = []
Cart = []
TotalCartPrice = 0.0

'''
Exception handling
'''
'''Call readExcel method before program execution'''
readExcel()
try:
while True:
option = GetOptionFromUser()
if option == 1:
AddBook()
print("Books Added..")
if option == 2:
PrintBooks(Books)
if option == 3:
TotalCartPrice = AddToCart(TotalCartPrice)
if option == 4:
ViewReceipt()
if option == 5:
BuyBooks()
Cart.clear()# clear the cart after buying books.
TotalCartPrice = 0.0
if option == 6:
Cart.clear()
TotalCartPrice = 0.0
print("Cart Cleared..")
if option == 7:
searchBook()
if option == 8:
print("Exiting Application...")
break;
except:
print("", end = ' ')

CODE (For readExcel and searchBook method alone)

'''
Reads Books from an excel file bkstr_inv.xlsx
'''
def readExcel():
#Declare Books as global variable
global Books
'''Open the xlsx file using xlrd module'''
workbook = xlrd.open_workbook("bkstr_inv.xlsx")
'''Open the sheet by its index(First sheet's index starts with 0)'''
sheet = workbook.sheet_by_index(0)
'''Get number of rows in the sheet'''
rows = sheet.nrows
'''Loop through each row skipping the header row'''
for i in range(1,rows):
'''Create dictionary for each row'''
b = {}
'''Load name and price of each book'''
b["Name"] = sheet.cell(i,0).value
b["Price"] = sheet.cell(i,1).value
'''Append dictionary to list of books 'Books'''
Books.append(b)
'''
To allow user to search from booksinventory
'''
def searchBook():
'''Prompt the user for book name'''
name = input("Enter book name : ")
'''Set the flag initially to false'''
found = False
'''Loop through every book in Books'''
for eachBook in Books:
'''If name of book matches given name'''
if(eachBook["Name"] == name):
'''Set flag to true and display output'''
found = True
print("Book Name\t\tBook Price")
print("*********************************")
print("{0:<25}{1}".format(eachBook["Name"],eachBook["Price"]))
'''If flag is false, display book not found'''
if(not found):
print("Book with name {0} cannot be found".format(name))

SCREENSHOTS :

Please see the screensots of the code below for the indentations of the code.As python is a language of indentations, kindly check the indentations of the code before execution.

***) 1 import xlrd 2 3 def GetOptionFromUser(): 4. print(* *BookStore* 5 print(1. Add Books) 6 print(2. View Books) 7 p

31 Create dictionary for each row 32 b = {} 33 Load name and price of each book 34 b[Name] = sheet.cell(i,).value 35 b[

61 62. def AddBook(): 63 b = {} 64 b[Name] = input(Enter Book Name: ) 65 b[Price] = float(input(Enter Price of the boo

** ***) ** k) 91 print(Book Not Found...) 92 return Total 93 94 Prints the books in the cart and their total cost. 95 96

121 122 Books = [] 123 Cart = [] 124 TotalCartPrice = 0.0 125 126 127 Exception handling 128 129 Call readExcel method befo== 7: == 151 if option 152 searchBook) 153 if option 8: 154 print(Exiting Application...) 155 break; 156 except: 157 print(

bkstr_inv.xlsx :

B с D E F Book Price 90.78 125.87 345.67 500 A 1 Book Name 2 The Wings of Fire 3 CPP Course 4 Life of Truth 5 Python Course 6

OUTPUT :

itt t t x x *** ****** ******* Bookstore 1. Add Books 2. View Books 3. Add To Cart 4. View Receipt 5. Buy Books 6. Clear Cart***** Book Name Book Price * x x x x x x x x x x x x x x x **************** Django Projects 500.0 ****************** Bookstor

Any doubts regarding this can be explained with pleasure :)

Add a comment
Know the answer?
Add Answer to:
I need this python program to access an excel file, books inventory file. The file called...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this...

    Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this is in Zybooks Existing Code # Type code for classes here class ItemToPurchase: def __init__(self, item_name="none", item_price=0, item_quantity=0): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity # def __mul__(self): # print_item_cost = (self.item_quantity * self.item_price) # return '{} {} @ ${} = ${}' .format(self_item_name, self.item_quantity, self.item_price, print_item_cost) def print_item_cost(self): self.print_cost = (self.item_quantity * self.item_price) print(('{} {} @ ${} = ${}') .format(self.item_name, self.item_quantity, self.item_price,...

  • Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - dis...

    Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - displays the items in the cart ---------------------------------------------------------------------""" import os os.system('clear') print("\n\nCart Contents:") print("Your selected items:", cart) def catMenu(): #function that displays the category menu """catMenu function - displays the categories user picks from ---------------------------------------------------------------------""" import os os.system('clear') print(""" 1 - Books 2 - Electronics 3 - Clothing d - display cart contents x -...

  • Hi, can someone offer input on how to address these 4 remain parts the zybook python...

    Hi, can someone offer input on how to address these 4 remain parts the zybook python questions?   4: Tests that get_num_items_in_cart() returns 6 (ShoppingCart) Your output ADD ITEM TO CART Enter the item name: Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in <module> passed = test_passed(test_passed_output_file) File "/home/runner/local/submission/unit_test_student_code/zyLabsUnitTest.py", line 8, in test_passed cart.add_item(item1) File "/home/runner/local/submission/unit_test_student_code/main.py", line 30, in add_item item_name = str(input('Enter the item name:\n')) EOFError: EOF when reading a line 5: Test that get_cost_of_cart() returns 10 (ShoppingCart)...

  • Use python to code! Q1 - You need to keep track of book titles. Write code...

    Use python to code! Q1 - You need to keep track of book titles. Write code using function(s) that will allow the user to do the following. 1. Add book titles to the list. 2. Delete book titles anywhere in the list by value. 3. Delete a book by position. Note: if you wish to display the booklist as a vertical number booklist , that is ok (that is also a hint) 4. Insert book titles anywhere in the list....

  • I cant get this python program to read all the unique words in a file. It...

    I cant get this python program to read all the unique words in a file. It can only read the number of the unique words in a line. import re import string from collections import Counter # opens user inputted filename ".txt" and (w+) makes new and writes def main(): textname = input("Enter the file to search: ") fh = open(textname, 'r', encoding='utf-8' ) linecount = 0 wordcount = 0 count = {} print("Sumary of the", fh) for line in...

  • Python: I need help with the following quit function ! The quit menu option should not...

    Python: I need help with the following quit function ! The quit menu option should not be case sensitive - 'q' or 'Q' should quit the program menu.add_option('Q', 'Quit', quit_program) NB: Remaining code ! """ Program to create and manage a list of books that the user wishes to read, and books that the user has read. """ from bookstore import Book, BookStore from menu import Menu import ui store = BookStore() def main(): menu = create_menu() while True: choice...

  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

  • Python 3 Question: All I need is for someone to edit the program with comments that...

    Python 3 Question: All I need is for someone to edit the program with comments that explains what the program is doing (for the entire program) def main(): developerInfo() #i left this part out retail = Retail_Item() test = Cash_Register() test.data(retail.get_item_number(), retail.get_description(), retail.get_unit_in_inventory(), retail.get_price()) answer = 'n' while answer == 'n' or answer == 'N': test.Menu() print() print() Number = int(input("Enter the menu number of the item " "you would like to purchase: ")) if Number == 8: test.show_items() else:...

  • In Python and in one file please. (Simple functions with an expressions) Create a function called...

    In Python and in one file please. (Simple functions with an expressions) Create a function called load_inventory(filename). The filename argument in this case specifies the name of a file that contains all the inventory/product information for the store, including product names, descriptions, prices, and stock levels. This function should clear any information already in the product list (i.e., a fresh start) and then re-initialize the product list using the file specified by the filename argument. You can structure your file...

  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT