Question

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 - checkout
    """)  
    category = input('\nSelect one of the categories or checkout:')
    return category

def log_File(logfile,logrecord): #function that controls the log file
    """Function that appends the log activity.
       ------------------------------------------------------------------"""
    log= open(logfile,"a")
    log.writelines(logrecord)
    log.close()
    
def itemDescription (category): #function that reads the category's file 
    """Reads the category's text file that has the inventory items for the chosen
       category and returns a list with the item descriptions and prices.
       -----------------------------------------------------------------------------"""
    import os
    os.system('clear') 
    fi = open(category + '.txt',"r", encoding = "ISO-8859-1") 
    itemfile = fi.readlines()    # list of item descriptions and price
    itemlist = []
    for i in itemfile:           # creates item list 
        if len(i) > 1:           
            d = i.split(',') #splits the list at the comma
            d[0] = d[0].strip()     #Item name
            d[1] = float(d[1].strip()) # Item price
            d[2] = int(d[2].strip()) #Item quantity
            itemlist.append(d) #adds to list
    fi.close()
    return itemlist
def itemMenu (category, itemList): #function that displays the items to choose from in menu form
    """itemMenu function - displays the menu of items
       ---------------------------------------------------------------------"""
    import os
    os.system('clear')   
    print ('\n\n\t\t\t\t\t ' + category,'menu')
    print('\n\t\t\t {0:3s} \t {1:26s}  {2:8s}'.format('No.', 'Item Description', 'Price '))
    print('\t\t\t {0:3s} \t {1:26s} {2:8s}'
          .format('===', '===========================', '========')) 
    
    for n in range(0, len(itemList)):
        print('\t\t\t {0:2d}  \t{1:26s} \t ${2:8.2f}'.format(n+1,itemList[n][0], itemList[n][1])) #formats list
    print('\t\t\t  {0:2s} \tdisplay cart contents'.format("d"))
    print('\t\t\t  {0:2s} \tcheckout'.format("x"))
    choice = input('\nSelect the ' + category + ' number or checkout:')
    return choice
def confirmAdd(itemList, category, cart): #Confirms item function
    """confirmAdd function - confirms the users selected item and adds the item to cart
       ---------------------------------------------------------------------"""
    import os
    os.system('clear')
    confirm = input(" Would you like to add one " + itemList[category-1][0] + " (y/n?):")
    if confirm == 'y':
        found = False #if the item isn't added more than once
        for d in cart:
            if itemList[category-1][0] == d[0]: 
                found = True #if the item is added more than once add one to quantity
                d[2] += 1 #increments quantity by 1 if multiple of same item is added to cart
                break
        if not found:
            cart.append(itemList[category-1])
                              
# Global code
book_list = itemDescription('books')
elect_list = itemDescription('electronics')
cloth_list = itemDescription('clothing')

date=str(datetime.datetime.now())
lf= "IT109A9Log.txt" #log file where all information is stored

more_carts = 'y'     
carts = 0            
total_items = 0       
total_cost = 0.0     

while more_carts == 'y':
    cart = []        
    more_items = 'y'
    while more_items == 'y':
        category=catMenu() #Category function
        if category == 'x':
            more_items = 'n'
            break
        elif category == 'd':
             displayCart() #Display cart function         
        elif category not in '123':
            print('Invalid category selected')
            continue
        if category == '1':
            choice = 0
            while choice != 'x':
                choice = itemMenu('Book', book_list) 
                if choice == 'x':
                     continue
                elif choice == 'd':
                     displayCart() #display cart function 
                elif int(choice) <= len(book_list):
                    confirm = confirmAdd(book_list,int(choice),cart)  #Confirm for books
                else:
                     print('Invalid item selected') 
        elif category == '2':
             choice = 0
             while choice != 'x':
                 choice = itemMenu('Electronics', elect_list) 
                 if choice == 'x':
                     continue
                 elif choice == 'd':
                     displayCart() #display cart function 
                 elif int(choice) <= len(elect_list):
                     confirm = confirmAdd(elect_list,int(choice),cart)  #Confirm for elecs
                 else:
                     print('Invalid item selected') 
        elif category == '3':      
              choice = 0
              while choice != 'x':
                  choice = itemMenu('Clothing', cloth_list) 
                  if choice == 'x':
                     continue
                  elif choice == 'd':
                       displayCart() #display cart function 
                  elif int(choice) <= len(cloth_list):
                       confirm = confirmAdd(cloth_list,int(choice),cart)  #Confirm for clothing
                  else:
                     print('Invalid item selected') 
    if category == 'x':
        print('\t\tCheckout selected')
        displayCart() 
    cart_items, cart_cost = 0, 0.0
    os.system('clear')
    for item in cart:
        cart_items += item[2] #quantity calculation
        cart_cost += item[1] * item[2] #QTY * price
    print('\nTotal number of items:', cart_items)
    print('\nTotal cost of your items:${0:8.2f}'.format(cart_cost))
    total_items += cart_items
    total_cost += cart_cost
    if cart_items > 0:
        carts += 1
    cartlog_list= ['\n\nDate: ' + date,  
           '\nType of log: Cart', 
           '\nCart Number: ' + str(carts),
           '\nTotal number of items for the cart: ' + str(cart_items),
           '\nTotal cost of items:${0:8.2f}'.format(cart_cost)]
    log_File(lf,cartlog_list) #log of carts

    more_carts = input('\nWould you like more carts(y/n)? ')


sessionLog_List= ['\n\nDate: ' + date,
           '\nType of log: Session',
           '\nNumber of carts: ' + str(carts),
           '\nTotal number of items: '+ str(total_items),
           '\nTotal cost of items:${0:8.2f}'.format(total_cost)]
log_File(lf,sessionLog_List) #log of session

#final output
os.system('clear')    
print('\n\n\tTotal number of carts: ', carts)
print('\tTotal number of items: ', total_items)
print('\tTotal cost of items:  ${0:8.2f}'.format(total_cost))



input('\n\nHit Enter to end program')
    
0 0
Add a comment Improve this question Transcribed image text
Answer #1

## updated the code lines with descriptions wherever required

def displayCart(): #displays the cart function
"""displayCart function - displays the items in the cart
---------------------------------------------------------------------"""
import os # Imports Operating System library to perform OS based operation
os.system('clear') # Clears the console screen
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 - checkout
""") # Prints a menu with option numbers for user to select
category = input('\nSelect one of the categories or checkout:') # saves the user input in the category variable
return category # returns the category

def log_File(logfile,logrecord): #function that controls the log file
"""Function that appends the log activity.
------------------------------------------------------------------"""
log= open(logfile,"a") # opens the logfile in append mode
log.writelines(logrecord) # appends the logrecord at the end of the file
log.close() # closes the logfile
  
def itemDescription (category): #function that reads the category's file
"""Reads the category's text file that has the inventory items for the chosen
category and returns a list with the item descriptions and prices.
-----------------------------------------------------------------------------"""
import os
os.system('clear')
fi = open(category + '.txt',"r", encoding = "ISO-8859-1") # opens corresponding category file in read mode in given endcoding
itemfile = fi.readlines() # list of item descriptions and price
itemlist = []
for i in itemfile: # creates item list
if len(i) > 1:   
d = i.split(',') #splits the list at the comma
d[0] = d[0].strip() #Item name
d[1] = float(d[1].strip()) # Item price
d[2] = int(d[2].strip()) #Item quantity
itemlist.append(d) #adds to list
fi.close()
return itemlist # returns the read list of items

def itemMenu (category, itemList): #function that displays the items to choose from in menu form
"""itemMenu function - displays the menu of items
---------------------------------------------------------------------"""
import os
os.system('clear')   
print ('\n\n\t\t\t\t\t ' + category,'menu')
print('\n\t\t\t {0:3s} \t {1:26s} {2:8s}'.format('No.', 'Item Description', 'Price ')) # Prints the heading in given format
print('\t\t\t {0:3s} \t {1:26s} {2:8s}'
.format('===', '===========================', '========'))
  
for n in range(0, len(itemList)):
print('\t\t\t {0:2d} \t{1:26s} \t ${2:8.2f}'.format(n+1,itemList[n][0], itemList[n][1])) # formats and prints the list items
print('\t\t\t {0:2s} \tdisplay cart contents'.format("d"))
print('\t\t\t {0:2s} \tcheckout'.format("x"))
choice = input('\nSelect the ' + category + ' number or checkout:')
return choice # returns the choice given by user

def confirmAdd(itemList, category, cart): #Confirms item function
"""confirmAdd function - confirms the users selected item and adds the item to cart
---------------------------------------------------------------------"""
import os
os.system('clear')
confirm = input(" Would you like to add one " + itemList[category-1][0] + " (y/n?):")
if confirm == 'y':
found = False #if the item isn't added more than once
for d in cart:
if itemList[category-1][0] == d[0]:
found = True #if the item is added more than once add one to quantity
d[2] += 1 #increments quantity by 1 if multiple of same item is added to cart
break
if not found:
cart.append(itemList[category-1])
  
# Global code
book_list = itemDescription('books')
elect_list = itemDescription('electronics')
cloth_list = itemDescription('clothing')

date=str(datetime.datetime.now()) # stores the current time in date variable
lf= "IT109A9Log.txt" #log file where all information is stored

more_carts = 'y'   
carts = 0
total_items = 0   
total_cost = 0.0   

while more_carts == 'y':
cart = []
more_items = 'y'
while more_items == 'y':
category=catMenu() #Category function
if category == 'x':
more_items = 'n'
break
elif category == 'd':
displayCart() #Display cart function   
elif category not in '123':
print('Invalid category selected')
continue
if category == '1':
choice = 0
while choice != 'x':
choice = itemMenu('Book', book_list)
if choice == 'x':
continue
elif choice == 'd':
displayCart() #display cart function
elif int(choice) <= len(book_list):
confirm = confirmAdd(book_list,int(choice),cart) #Confirm for books
else:
print('Invalid item selected')
elif category == '2':
choice = 0
while choice != 'x':
choice = itemMenu('Electronics', elect_list)
if choice == 'x':
continue
elif choice == 'd':
displayCart() #display cart function
elif int(choice) <= len(elect_list):
confirm = confirmAdd(elect_list,int(choice),cart) #Confirm for elecs
else:
print('Invalid item selected')
elif category == '3':
choice = 0
while choice != 'x':
choice = itemMenu('Clothing', cloth_list)
if choice == 'x':
continue
elif choice == 'd':
displayCart() #display cart function
elif int(choice) <= len(cloth_list):
confirm = confirmAdd(cloth_list,int(choice),cart) #Confirm for clothing
else:
print('Invalid item selected')
if category == 'x':
print('\t\tCheckout selected')
displayCart()
cart_items, cart_cost = 0, 0.0
os.system('clear')
for item in cart:
cart_items += item[2] #quantity calculation
cart_cost += item[1] * item[2] #QTY * price
print('\nTotal number of items:', cart_items)
print('\nTotal cost of your items:${0:8.2f}'.format(cart_cost))
total_items += cart_items
total_cost += cart_cost
if cart_items > 0:
carts += 1
cartlog_list= ['\n\nDate: ' + date,
'\nType of log: Cart',
'\nCart Number: ' + str(carts),
'\nTotal number of items for the cart: ' + str(cart_items),
'\nTotal cost of items:${0:8.2f}'.format(cart_cost)]
log_File(lf,cartlog_list) #log of carts

more_carts = input('\nWould you like more carts(y/n)? ')


sessionLog_List= ['\n\nDate: ' + date,
'\nType of log: Session',
'\nNumber of carts: ' + str(carts),
'\nTotal number of items: '+ str(total_items),
'\nTotal cost of items:${0:8.2f}'.format(total_cost)]
log_File(lf,sessionLog_List) #log of session

#final output
os.system('clear')
print('\n\n\tTotal number of carts: ', carts)
print('\tTotal number of items: ', total_items)
print('\tTotal cost of items: ${0:8.2f}'.format(total_cost))

input('\n\nHit Enter to end program')

Add a comment
Know the answer?
Add Answer to:
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...
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,...

  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • Python3 programming help needed LAB*: Program: Online shopping cart (continued) Need the below code edited to...

    Python3 programming help needed LAB*: Program: Online shopping cart (continued) Need the below code edited to run properly for the lab.. class ItemPurchase:     def __init__(self, nameitem='none', item_prc=0, item_quntity=0, item_descrp = 'none'):         self.nameitem = nameitem         self.item_prc = item_prc         self.item_quntity = item_quntity         self.item_descrp = item_descrp     def print_itemvaluecost(self):              string = '{} {} @ ${} = ${}'.format(self.nameitem, self.item_quntity, self.item_prc(self.item_quntity * self.item_prc))         valuecost = self.item_quntity * self.item_prc         return string, valuecost     def print_itemdescription(self):         string...

  • Python3 programming help needed LAB*: Program: Online shopping cart (continued) Need the below code edited to run prope...

    Python3 programming help needed LAB*: Program: Online shopping cart (continued) Need the below code edited to run properly for the lab.. class ItemPurchase:     def __init__(self, nameitem='none', item_prc=0, item_quntity=0, item_descrp = 'none'):         self.nameitem = nameitem         self.item_prc = item_prc         self.item_quntity = item_quntity         self.item_descrp = item_descrp     def print_itemvaluecost(self):              string = '{} {} @ ${} = ${}'.format(self.nameitem, self.item_quntity, self.item_prc(self.item_quntity * self.item_prc))         valuecost = self.item_quntity * self.item_prc         return string, valuecost     def print_itemdescription(self):         string = '{}: {}'.format(self.nameitem, self.item_descrp)         print(string , end='\n')         return string class Shopping_Cart:     #Parameter...

  • Something is preventing this python code from running properly. Can you please go through it and...

    Something is preventing this python code from running properly. Can you please go through it and improve it so it can work. The specifications are below the code. Thanks list1=[] list2=[] def add_player(): d={} name=input("Enter name of the player:") d["name"]=name position=input ("Enter a position:") if position in Pos: d["position"]=position at_bats=int(input("Enter AB:")) d["at_bats"] = at_bats hits= int(input("Enter H:")) d["hits"] = hits d["AVG"]= hits/at_bats list1.append(d) def display(): if len(list1)==0: print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG")) print("ORIGINAL TEAM") for x...

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