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:
STARTING_ITEMS_IN_INVENTORY = 20
num_items = STARTING_ITEMS_IN_INVENTORY
while num_items > 0:
print("We have " + str(num_items) + " items in inventory.")
buy_num = int(input("How many would you like to buy? "))
if buy_num <= num_items:
num_items -= buy_num
print("Now we have " + str(num_items) + " left.")
else:
print("There is not enough in inventory for that purchase.")
print("All out!")
Initialization:
- The program initializes the inventory count (
STARTING_ITEMS_IN_INVENTORY
) with a starting value.
While Loop:
- Continues running as long as the inventory (
num_items
) is greater than zero.
Buying Items:
- The user inputs the number of items they wish to buy.
- If the requested number (
buy_num
) is less than or equal to the available inventory, the program subtracts the purchased amount and updates the inventory. - If the user requests more items than available, an error message is displayed.
End Condition:
- When the inventory reaches zero, the loop ends, and the program prints “All out!”.
Leave a comment