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
Module 4 Assignment 1: Pseudocode & Python with Variable Scope Overview Module 4 Assignment 1 features...
Module 4 Assignment 1: Pseudocode & Python with Variable Scope Overview Module 4 Assignment 1 features the design of a calculator program using pseudocode and a Python program that uses a list and functions with variable scope to add, subtract, multiply, and divide. Open the M4Lab1ii.py program in IDLE and save it as M4Lab1ii.py with your initials instead of ii. Each lab asks you to write pseudocode that plans the program’s logic before you write the program in Python and...
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....
Submission Question: Recursion with Trees – Depth First Search & Breadth First Search Write a Python...
Submission Question: Recursion with Trees – Depth First Search & Breadth First Search Write a Python program using the Python IDE based on recursion with trees that is both depth first and breadth first searches. The Python program to be developed will demonstrate the use of both depth-first (DFS) and breadth-first (BFS) searches. A tree node structure will be developed that will be used both for DFS and BFS searches. The program will apply recursion both for the DFS and...
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...
Write a Python program named lastNameVolumes that finds the volumes of different 3 D objects such...
Write a Python program named lastNameVolumes that finds the volumes of different 3 D objects such as a cube, sphere, cylinder and cone. In this file there should be four methods defined. Write a method named cubeVolFirstName, which accepts the side of a cube in inches as an argument into the function. The method should calculate the volume of a cube in cubic inches and return the volume. The formula for calculating the volume of a cube is given below....
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...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT