Question

In: Computer Science

Python Assignment You will be writing an inventory system that is backed by JSON data and...

Python Assignment

You will be writing an inventory system that is backed by JSON data and will be working with a starter file that contains a JSON string. The code you write will need to follow the following guidelines.

The what

You’re at work one day and your boss asks you about that fancy programming language you’ve been learning, Python. She asks you if you can use it to read JSON data from a supplier and build an inventory. “Of course!” you say. She tells you that your parts supplier, Midwest Widget Co, has sent the company JSON data that needs to be loaded and then checked against orders. You’ll need to load the JSON data, and then take input from a user to order new parts. If the part is not in stock, or the number of parts is greater than the available inventory, you need to alert the user and show them that its either out of stock or that there are less available than requested. Once the user is done entering in their order, you’ll need to package up their order in JSON format, since that’s what Midwestern Widget Co uses after all!

Specifics

The JSON data is comprised of a few nested dictionaries. In the top level, there is a key called “parts” that maps to a list that contains all the parts available for ordering. Each of those parts is also a key into the dictionary. That key maps to dictionary that has two values, quantity and price. The quantity maps to an integer with the number of parts available for order, the price maps to a float with the price of the part. A sample JSON object is provided below:

{
"parts":[

"widget",

"sprocket",

"thing-a-ma-bob"

],

"widget":{

"price":0.99,

"quantity":74

},

"sprocket":{

"price":3.99,

"quantity":123

},

"thing-a-ma-bob":{

"price":1.78,

"quantity":57

}

}

The strings in the list in parts are the keys for the rest of the data in the dictionary. Those keys map to separate dictionaries with the prices and quantities. The json string is provided in the code, it is called supplier_data.

The ordering system will work like this:

Prompt the user for input, and indicate they can enter in the word “quit” to quit. The user should enter in a part and then the quantity on two separate lines (so you’ll need two input statements). After both pieces of information have been entered in, check if the order is allowed or not, and display an error message with the appropriate information (part doesn’t exist, part exists but not enough quantity). If the order is valid, store it and continue. Once the user enters quit, print out an order summary showing the part, number ordered, the price per part and total per part with a grand total at the end. The order data MUST be stored in a dictionary. You must also allow the user to order a part more than once and validate that both orders are not exceeding the total amount available!

Sample Output

Your program should produce output that is very similar if not identical to this. Major deviations from the formatting will result in points lost. The error handling behavior should be the same.

Welcome to the parts ordering system, please enter in a part name, followed by a quantity

Parts for order are:

sprocket

gizmo

widget

dodad

Please enter in a part name, or quit to exit: blargh Error, part does not exist, try again
Please enter in a part name, or quit to exit: quit

Your order
Total: $0
Thank you for using the parts ordering system!

And another run with an actual order

Welcome to the parts ordering system, please enter in a part name, followed by a quantity

Parts for order are:

sprocket

gizmo

widget

dodad

Please enter in a part name, or quit to exit: gizmo

Please enter in a quantity to order: 1000

Error, only 2 of gizmo are available!

Please enter in a part name, or quit to exit: gizmo

Please enter in a quantity to order: 1

Please enter in a part name, or quit to exit: sprocket

Please enter in a quantity to order: 15

Please enter in a part name, or quit to exit: widget

Please enter in a quantity to order: 1

Please enter in a part name, or quit to exit: quit

Your order
gizmo - 1 @ 7.98 = 7.98
sprocket - 15 @ 3.99 = 59.85
widget - 1 @ 14.32 = 14.32
Total: $82.15
Thank you for using the parts ordering system!

Another run with multiple orders for a single part

Welcome to the parts ordering system, please enter in a part name, followed by a quantity

Parts for order are:

sprocket

gizmo

widget

dodad

Please enter in a part name, or quit to exit: gizmo

Please enter in a quantity to order: 2

Please enter in a part name, or quit to exit: gizmo

Please enter in a quantity to order: 2

Error, only 0 of gizmo are available!

Please enter in a part name, or quit to exit: quit

Your order
gizmo - 2 @ 7.98 = 15.96
Total: $15.96
Thank you for using the parts ordering system!

Tips and Hints

  1. Start on something small and get it working before moving on. Don’t try and tackle it all at once!

  2. You’ll need to validate the input between inputs

  3. You can use print() with no arguments to print out extra blank lines

  4. A while loop is ideal for the main program loop

  5. You’ll need to check if a part has already been ordered before checking if sufficient quantity is available. If it has been ordered, you’ll need to account for that when checking the inventory levels

  6. supplier_data in the provided code is a JSON string. You need to convert it to a dict with json.loads

Good luck!

Solutions

Expert Solution

ANSWER:

I have provided the properly commented and indented code so you can easily copy the code as well as check for correct indentation.
I have provided the output image of the code so you can easily cross-check for the correct output of the code.
Have a nice and healthy day!!

CODE

# importing json module of python
import json

# sample json data
data = """{"parts":["widget","sprocket","thing-a-ma-bob"],
"widget":{
"price":0.99,
"quantity":74
},

"sprocket":{
"price":3.99,
"quantity":123
},

"thing-a-ma-bob":{
"price":1.78,
"quantity":57
}
}"""

# loading json data using loads method of json and storing in json_data
json_data = json.loads(data)

# defining a empty user order dict
orders = {}
# displaying a menu to user
print("Welcome to the parts ordering system, please enter in a part name, followed by a quantity")

#fetching parts from json_data
parts = json_data["parts"]
# displaying parts, using for loop to do the same
print("Parts for order are:")
for part in parts:
    print(part)
    
# infinite while loop for prompting user untill quit is hit
while True:
    # prompting user for part name
    part_name = input("Please enter in a part name, or quit to exit: ")
    
    # if quit exit the loop
    if part_name=="quit":
        break
    # elseif part not in parts list display error
    elif part_name not in parts:
        # display error message
        print("Error, part does not exist, try again")
        # continue loop for correct input
        continue
        
    # otherwise, part name is correct
    # prompting user for order quantity
    # converting input quantity to integer using int function
    quant = int(input("Please enter in a quantity to order: "))
    
    # checking for correct quantity, including quantity from both json_data
    # and users already orders
    
    # order quantity from json_data
    data_quant = json_data[part_name]["quantity"]
    # order quantity from already ordered goods
    # using dict method get to fetch value from passed key, if key not exist
    # returning 0 by default
    ord_quant = orders.get(part_name,0)
    
    # actual quantity present
    actual_quant = data_quant-ord_quant
    
    # checking if quant> actual_quant, displaying error
    if quant> actual_quant:
        print("Error, only {} of {} are available!".format(actual_quant,part_name))
        # continue loop for correct input
        continue
        
    # otherwise order quant is correct, adding quantity in orders dict of user
    # with already present order quantity
    orders[part_name] = ord_quant + quant
    
# after all orders completed, displaying orders detils
print("Your order")
# defining sum counter to fetch total orders value
total = 0
# for loop for every order in orders dict
for order in orders:
    # fetching details from respective datas
    # order price per quantity
    price = json_data[order]["price"]
    # total price of order
    order_price = price * orders[order]
    # displaying message
    print("{} - {} @ {:.2f} = {:.2f}".format(order,orders[order],price,order_price))
    # add order price to total
    total +=order_price
    
# displaying total
print("Total: ${:.2f}".format(total))
# print thank you
print("Thank you for using the parts ordering system!")
    

OUTPUT IMAGE


Related Solutions

Assignment 4 You will be writing an inventory system that is backed by JSON data and...
Assignment 4 You will be writing an inventory system that is backed by JSON data and will be working with a starter file that contains a JSON string. The code you write will need to follow the following guidelines. You’re at work one day and your boss asks you about that fancy programming language you’ve been learning, Python. She asks you if you can use it to read JSON data from a supplier and build an inventory. “Of course!” you...
Python programming problem! Suppose that there is a json file called data from the desktop. I...
Python programming problem! Suppose that there is a json file called data from the desktop. I want to print the value with the key of "year" and "country". Json file below: { "A":{ "year":11, "grade":A, "country":America}, "B":{ "year":18, "grade":C, "country":England}, "C":{ "year":19, "grade":B, "country":China},} I want a code that I can only replace the name of key from year to grade and the code could be work.
Programming language is in python 3 For this project, you will import the json module. Write...
Programming language is in python 3 For this project, you will import the json module. Write a class named NobelData that reads a JSON file containing data on Nobel Prizes and allows the user to search that data. It just needs to read a local JSON file - it doesn't need to access the internet. Specifically, your class should have an init method that reads the file, and it should have a method named search_nobel that takes as parameters a...
Programming language is python 3 For this project, you will import the json module. Write a...
Programming language is python 3 For this project, you will import the json module. Write a class named NeighborhoodPets that has methods for adding a pet, deleting a pet, searching for the owner of a pet, saving data to a JSON file, loading data from a JSON file, and getting a set of all pet species. It will only be loading JSON files that it has previously created, so the internal organization of the data is up to you. The...
The sixth assignment involves writing a Python program to read in the temperatures for ten consecutive...
The sixth assignment involves writing a Python program to read in the temperatures for ten consecutive days in Celsius and store them into an array. The entire array should then be displayed. Next each temperature in the array should be converted to Fahrenheit and the entire array should be again be displayed. The formula for converting Celsius to Fahrenheit is °F = (°C × 1.8) + 32. Finally, the number of cool, warm and hot days should be counted and...
In this assignment you are to make an inventory management system for a car dealership. The...
In this assignment you are to make an inventory management system for a car dealership. The dealerships current method of tracking inventory is using a list which has the color and name of each car they have in inventory. There current inventory list will look like the example below. RED TOYOTAWHITE HONDA...BLACK BMW The types of cars that they order are as follows: TOYOTA, HONDA, BMW, NISSAN, TESLA, DODGE The colors they purchase are as follows: RED, WHITE, BLUE, BLACK,...
Starting out with python Lists and Tuples - US Population Data In this assignment, you will...
Starting out with python Lists and Tuples - US Population Data In this assignment, you will be reading the contents of a file into a list. This file contains the midyear population of the United States, in thousands, during the years 1950 through 1990. The first line in the file contains the population for 1950, the second line contains the populations for 1951, and so forth. You will ask the user to input a specific year to check the population...
For Python: In this assignment you are asked to write a Python program to determine the...
For Python: In this assignment you are asked to write a Python program to determine the Academic Standing of a studentbased on their CGPA. The program should do the following: Prompt the user to enter his name. Prompt the user to enter his major. Prompt the user to enter grades for 3 subjects (A, B, C, D, F). Calculate the CGPA of the student. To calculate CGPA use the formula: CGPA = (quality points * credit hours) / credit hours...
In this assignment, you will create a well-formed JSON object which encapsulates the information specified. Alignment...
In this assignment, you will create a well-formed JSON object which encapsulates the information specified. Alignment This assignment aligns with the following objectives: Identify the differences between these three modes of interacting with data, i.e. web forms, programs, and APIs Recognize well-formed JSON objects Parse JSON objects Details Imagine that using the API provided by a service like Yelp (let's call it YelpYou) you have extracted information about Sichuan Dragon, which has three branches (restaurants) in New York City. The...
in python You will be writing a program that can be used to sum up and...
in python You will be writing a program that can be used to sum up and report lab scores. Your program must allow a user to enter points values for the four parts of the problem solving process (0-5 points for each step), the code (0-20 points), and 3 partner ratings (0-10) points each. It should sum the points for each problem-solving step, the code, and the average of the three partner ratings and print out a string reporting the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT