Question

The last thing we will learn about in python is functions. Functions are a great way...

The last thing we will learn about in python is functions. Functions are a great way to organize your program - we use them to write code that is executed only under certain circumstances - for instance when you're using Amazon, any of the following are likely functions within their program:

- Add item to cart, determine arrival date,  create a new address, compute taxes, compute shipping charges, charge credit card

Because you can write a task-specific function once, and ensure it works properly, they allow you to break down and write large programs.  

Programming- Python


You will use all the programming techniques we have learned thus like- 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

Homework Answers

Answer #1
Below is a screen shot of the python program to check indentation. Comments are given on every line explaining the code.

Below is the output of the program:

Below is the code to copy:
#CODE STARTS HERE----------------
def add_to_cart(inventory,cart): #Add items to cart from inventory
   print("ITEMS\t\t\t\tPRICE in $")
   for item in inventory: #Print items in store
      print("{0:15}{1:10}".format(item[0],item[1]))
   print("To add items to cart, Enter item name with quantity separated by space. "
        "Enter 'Done' to stop")
   while True: #Loop until user enters done
      inp = input() #Take input
      if inp.lower() == "done":
         break #Exit when user enters Done
      item = " ".join(inp.split()[:-1]) #Get item name
      try:
         quantity = int(inp.split()[-1]) #Get item quantity
      except:
         print("Quantity must be an integer") #Check if quantity is an int
         continue
      price = 0
      for x in inventory: #Find inventory for entered item
         if x[0] == item.lower():
            price = x[1] #Get its price
            break
      if price == 0: #IF item not in inventory, print message
         print("item not in inventory")
         continue
      else: #Add item to cart
         temp_list=[item,quantity,price*quantity]
         cart.append(temp_list)
   total = print_cart(cart) #Print cart
   return cart, total #return values

def print_cart(cart): #Prints cart itemms with total value
   total = 0
   print("ITEMS\t\t\t\tQUANTITY\t\t\tPRICE in $")
   for item in cart:
      print(item[0],"\t\t\t\t",item[1],"\t\t\t\t\t",item[2])
      total+=item[2]
   print("Total : ",total)
   return total

def tax(total):
   rate = 10 #Change rate as required. rate is in %
   return total*rate/100 #return tax

def shipping(cart):
   items= len(cart) #Adds $5 per item for shipping
   return items*5

def main():
   cart = []
   total = 0
   #Inventory of items in store
   inventory = [["mobile",100],["laptop",150],["monitor",40], ["router",24],["processor",15],
             ["graphic card",56],["mouse",10],["keyboard",5]]

   while True: #Loop until user exists
      print("\nEnter coice:\n1. Add items to cart\n2. Show cart\n3. Checkout\n"
           "4. Exit")
      inp = int(input("=> "))
      #CAll respective functions
      if inp == 1:
         cart,total = add_to_cart(inventory,cart)
      elif inp == 2:
         total = print_cart(cart)
      elif inp == 3:
         tax_cost = tax(total)
         shipping_cost = shipping(cart)
         total = print_cart(cart)
         print("Tax: ",tax_cost)
         print("Shipping: ",shipping_cost)
         print("Grand total: ", total+tax_cost+shipping_cost)
      elif inp == 4:
         print("Thank you for shopping with us!")
         break
main()
#CODE ENDS HERE------------------
Know the answer?
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
Similar Questions
Write a program in Java that: 1. will prompt user with a menu that contains options...
Write a program in Java that: 1. will prompt user with a menu that contains options to: a. Add a To-Do Item to a todo list. A To-Do Item contains: i. An arbitrary reference number (4; 44,004; etc.) ii. A text description of the item ("Pick up dry cleaning", etc.) iii. A priority level (1, 2, 3, 4, or 5) b. View an item in the list (based on its reference number) c. Delete an item from the list (based...
For this assignment, you need to submit a Python program that gathers the following employee information...
For this assignment, you need to submit a Python program that gathers the following employee information according to the rules provided: Employee ID (this is required, and must be a number that is 7 or less digits long) Employee Name (this is required, and must be comprised of primarily upper and lower case letters. Spaces, the ' and - character are all allowed as well. Employee Email Address (this is required, and must be comprised of primarily of alphanumeric characters....
Using C++, Python, or Java, write a program that: In this programming exercise you will perform...
Using C++, Python, or Java, write a program that: In this programming exercise you will perform an empirical analysis of the QuickSort algorithm to study the actual average case behavior and compare it to the mathematically predicted behavior. That is, you will write a program that counts the number of comparisons performed by QuickSort on an array of a given size. You will run the program on a large number of arrays of a certain size and determine the average...
IN PYTHON Menu: 1. Hotdog. ($2) 2. Salad ($3)  3. Pizza ($2) 4.Burger ($4) 5.Pasta ($7) Write...
IN PYTHON Menu: 1. Hotdog. ($2) 2. Salad ($3)  3. Pizza ($2) 4.Burger ($4) 5.Pasta ($7) Write a menu-driven program for  Food Court. (You need to use functions!) Display the food menu to a user . 5 options Use numbers for the options and for example "6" to exit. Ask the user what he/she wants and how many of it. (Check the user inputs) AND use strip() function to strip your inputs(if needed) Keep asking the user until he/she chooses the exit...
C PROGRAMMING Doubly Linked List For this program you’ll implement a doubly linked list of strings....
C PROGRAMMING Doubly Linked List For this program you’ll implement a doubly linked list of strings. You must base your code on the doubly linked list implementation given in my Week 8 slides. Change the code so that instead of an ‘int’ each node stores a string (choose a suitable size). Each node should also have a next node pointer, and previous node pointer. Then write functions to implement the following linked list operations: • A printList function that prints...
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression...
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression Evaluator as described in section 7-3b of the book. The program should ask the user for a string that contains a Postfix Expression. It should then use the string's split function to create a list with each token in the expression stored as items in the list. Now, using either the stack classes from 7.2 or using the simulated stack functionality available in a...
Use Python 3.8: Problem Description Many recipes tend to be rather small, producing the fewest number...
Use Python 3.8: Problem Description Many recipes tend to be rather small, producing the fewest number of servings that are really possible with the included ingredients. Sometimes one will want to be able to scale those recipes upwards for serving larger groups. This program's task is to determine how much of each ingredient in a recipe will be required for a target party size. The first inputs to the program will be the recipe itself. Here is an example recipe...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the following subsections can all go in one big file called pointerpractice.cpp. 1.1     Basics Write a function, int square 1(int∗ p), that takes a pointer to an int and returns the square of the int that it points to. Write a function, void square 2(int∗ p), that takes a pointer to an int and replaces that int (the one pointed to by p) with its...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these classes: Product, Customer, and Store. All data members of each class should be marked as **private** (a leading underscore in the name). Since they're private, if you need to access them from outside the class, you should do so via get or set methods. Any get or set methods should be named per the usual convention ("get_" or "set_" followed by the name of...
C++ ONLY -- PRACTICE ASSIGNMENT For our practice assignment we have to turn in 2 files...
C++ ONLY -- PRACTICE ASSIGNMENT For our practice assignment we have to turn in 2 files - Driver.cpp and StringQueue.h Driver.cpp is provided for us, but if there are any changes needed to be made to that file please let me know. Based on the instructions below, what should the code look like for StringQueue.h ? Create a class named StringQueue in a file named StringQueue.h. Create a QueueNode structure as a private member of the class. The node should...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT