Python水果商店:如何实现葡萄订购量超库存时循环请求输入
水果商店程序库存校验循环实现方案
你的核心问题是缺少循环逻辑引导用户重新输入符合库存的葡萄订购量,同时代码还有一些细节问题需要优化,比如输入格式兼容、异常处理等。以下是修改后的完整代码:
import random amount_of_apples = random.randint(1, 100) price_of_apples = random.randint(1, 10) amount_of_grapes = random.randint(1, 50) price_of_grapes = random.randint(5, 15) stock = ["apples","grapes"] basket = [] greeting = "Hello and welcome to Pennants." availability = f"We have the following fruits available to purchase: {stock[0]} and {stock[1]}" print(greeting) print(availability) print(f"We have {amount_of_apples} Apples available to purchase. Each Apple cost £{price_of_apples}.") print(f"We have {amount_of_grapes} bunches of grapes available to purchase. Each bunch of grapes cost £{price_of_grapes}.") # 统一处理输入格式,兼容大小写和空格 order = input("What would you like to purchase?").strip().lower() if order == "grapes": basket.append("Grapes") def order_check(): while True: try: G2 = input("How many bunches of grapes would you like to buy?") grape_quantity = int(G2) # 检查数量是否为正且不超过库存 if grape_quantity <= 0: print("Please enter a positive number.") continue if grape_quantity > amount_of_grapes: print(f"Unfortunately we don't have enough grapes to fulfill your request. We have {amount_of_grapes} grapes available to buy. Please enter a valid quantity.") else: # 计算总价并展示篮子信息 total_price = grape_quantity * price_of_grapes print(f"Your basket: {grape_quantity} {basket[0]}") print(f"Total cost: £{total_price}") break # 符合条件,退出循环 except ValueError: # 处理非数字输入的情况 print("Please enter a valid number.") if basket: # 只有用户选择了葡萄才调用校验函数 order_check()
关键改动说明:
- 输入格式兼容:对用户输入的订单类型做了
strip().lower()处理,不管用户输入"Grapes"、" grapes"还是"GRAPES"都能正确识别 - 循环校验逻辑:用
while True构建循环,直到用户输入符合要求的数量才退出 - 异常处理:加入
try-except捕获非数字输入的情况,避免程序崩溃 - 库存与合法性双重校验:既检查是否超过库存,也确保输入是正整数
- 字符串格式化优化:改用f-string让代码更简洁易读
- 条件调用校验函数:只有当用户选择了葡萄时才执行
order_check,避免空篮子报错
内容的提问来源于stack exchange,提问作者TheThinker
相关产品推荐
相关产品推荐

