Study Guide

4.10.4 Inventory CodeHS Answers

4.10.4 Inventory CodeHS Answers

4.10.4: Inventory CodeHS general answer I see across the web:

STARTING_ITEMS_IN_INVENTORY = 20
num_items = STARTING_ITEMS_IN_INVENTORY

# Enter your code here

INVENTORY_ITEMS = 20
num = INVENTORY_ITEMS
while num > 0:
print("We have " + str(num) + " items in inventory.")
To_Buy = int(input("How many would you like to buy? "))
if To_Buy > num:
print("There is not enough in inventory for that purchase.")


This code snippet for managing an inventory system in Python has a few issues that must be addressed for it to work correctly.

Let’s provide a corrected version of the code:

# Initialize inventory
inventory = 20

# Run the loop while there are items in inventory
while inventory > 0:
    print(f"We have {inventory} items in inventory.")
    # Ask the user how many items they want to buy
    try:
        buy = int(input("How many would you like to buy? "))
        if buy <= inventory:
            inventory -= buy
            if inventory > 0:
                print(f"Now we have {inventory} left.")
            else:
                print("All out!")
        else:
            print("Sorry, we don't have that many items. Try again.")
    except ValueError:
        print("Please enter a valid number.")