In: Computer Science
Python
It's time to put everything together! This week you will write a program 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. I leave the bulk of design up to you (hint - think A LOT about it before you start programming!!) but 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 (bonus - different based on
shipping state?) and shipping costs (based on number of items?),
and returns their values to the main program
- Bonus: Set up a list of lists with all the items/prices in your
store and only let users pick from that list
Program Code Screenshot:
Sample output:
The screenshots are attached below for reference.
Please follow them for proper indentation and output.
Program to copy:
import random
def getTax(s):
state=input("Enter state")#read state name to compute tax
amount
if state=="state1":
tax=0.1*s
elif state=="state2":
tax=(0.2*s)
else:
tax=0.3*s
return tax#return tax amount
def getShippingCharges(n):
return 10*n#returns shipping charges(10 for each item)
prices=[100,200,300,400]
items=["item1","item2","item3","item4"]#names of items are stored
in list
l=[]
for i in range(len(items)):
r=random.randint(0,len(prices)-1)
l.append([items[i],prices[r]])#prices are stored with item names in
l list
prices.pop(r)
total=0
num_items=0
cart=[]
while True:
print("Item Price")
print("----------------")
for i in l:
print(i[0],i[1],sep="\t")#print the items available
print("Enter name of item to add to cart:")
n=input()
if n=="done":
break
q=int(input("Enter Quantity"))#read name and item quantity
num_items+=q
for k in l:
if k[0]==n:
total=total+(q*k[1])#compute total
cart.append([n,q])#add item to cart
username=input("Enter Name:")
address=input("Enter shipping address")#read inputs from user
tax=getTax(total)#get tax and charges for shipment
ship_charges=getShippingCharges(num_items)
print()
print("Purchase summary")
print("-----------------")#print the details
print("Items Quantity")
for i in cart:
print(i[0],str(i[1]),sep="\t")
print("The cart amount is:",total)#print the cart amount
total=total+tax+ship_charges#calculate total amount that includes
the tax and ship charges
print("The shipment charges are:",ship_charges)
print("The tax is:",tax)#print the details
print("The total cost is:",total)