In: Computer Science
Python
This week you will write a program in Python that mimics an online shopping cart . You will use all the programming techniques we have learned thus far this semester, including if statements, loops, lists and functions. It should include all of the following:
The basics - Add items to a cart until the user says "done" and then print out a list of items in the cart and a total price.
- Ensure the user types in numbers for quantities
- "Hardcode" the price of items into a list and pick from it
randomly for each item
- Get the user's name and shipping address
- Separate functions that compute tax and shipping costs and
returns their values to the main program
Here is the code :
import random
def store():
items={"apple":20,"banana":10,"mango":30,"strawberry":40,"lichi":15,"grapes":25,"guava":26}
return items
def printCart(cart,name,address,tax,shippingCost): #all details of cart is printed
total=0.0
print('----------Your Cart---------')
for item in cart:
total=total+item[2]
print('Item name : {}\nQuantity : {}\nPrice : {}'.format(item[0],item[1],item[2]))
print('--------')
print('Name : {}\nAddress : {}\nTax:{}\nShipping Cost : {}'.format(name,address,tax,shippingCost))
print('\nTotal Price : {}'.format(total+tax+shippingCost))
def computeTax(cart):
tax=0.0;
for item in cart:
tax=tax+item[2]*5/100 #5% per item price
return tax
def genShippingCost(address):
l=len(address)
r=random.randint(0,l) #we randomly generate a number by the length of the string address and return a reasonable value as shipping cost
return r/l*100
def main():
print("Our Store :")
print(store()) #The store function defined above contains the item and its price which is called directly inside print function
print("Enter the item and quantity\nEx:- 'apple 2'\nEnter 'done' to finish\n")
cart=[]
while True:
inp=input()
if inp=="done": #when user enters done we take the name , address as input and compute tax, shipping cost and finnaly display the cart by calling the print cart function
print('---------Shipping Details----------\nEnter Name :')
name=input()
print('Enter address : ')
address=input()
tax=computeTax(cart)
shippingCost=genShippingCost(address)
printCart(cart,name,address,tax,shippingCost)
break #when user enters done and the calculations and printing is over we get out of the loop thus ending the program
inp=inp.split(' ')
itemname=inp[0]
qty=int(inp[1])
try: #we try fetching the price of the item from the store, if the item is not present in store then an error occurs
price=store()['{}'.format(itemname)]*qty
cart.append([itemname,qty,price])
except: #if any error occur in the above try block then the below line is executed
print("The item is not in our store")
main()