You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python变量未绑定问题求助:如何复用代码减少冗余?

水果库存管理代码:解决NameError与冗余问题

我是一名新程序员,正在调试一套水果库存管理代码。原本打算通过if/elif绑定x、y、z变量后复用后续业务代码,但运行时触发了NameError错误。虽然把代码嵌套进if/elif分支里能正常运行,但原代码近900行,嵌套后冗余代码大量重复,希望能优化到约250行,求解决方案。

原代码

price_apple = 1.00
price_pear = 1.50
apple_stock = 50
pear_stock = 30
totalstock = apple_stock + pear_stock
while totalstock != 0:
  totalstock = apple_stock + pear_stock
  if totalstock == 0:
    print("Sadly we don't have any more fruit in stock.")
    break
  order = input("What would you like to order? ")
  if order == "apples":
    x, y, z = apple_stock, price_apple, "apples"      
  elif order == "pears":
    x, y, z = pear_stock, price_pear, "pears" 
  if order == "apples" or order == "pears" and totalstock > 0:
    number = list(map(int,input("How many would you like to order? ").strip().split()))
    for individual_order in number:
      if x >= individual_order:
        x = x - individual_order
        print(order, )
        print("You have enough", z, "in stock")
        print("Your total price is", str(order * x))
        print("Your", z, "stock is now", x, z)
      else:
        break
  if order != "apples" and order != "pears":
    break

错误信息

Traceback (most recent call last):
    File "/home/runner/School-project/mail.py", line 134, in <module>
        if order == "apples" and x == 0:
NameError: name 'x' is not defined

嵌套可运行但冗余的代码片段

# code
order = input("What would you like to order? ")
if order == "apples":
  x, y, z = apple_stock, price_apple, "apples"
  if order == "apples" and totalstock > 0:
    number = list(map(int,input("How many would you like to order? ").strip().split()))
    for individual_order in number:
      if x >= individual_order:
        x = x - individual_order
        print(order, )
        print("You have enough", z, "in stock")
        print("Your total price is", str(order * x))
        print("Your", z, "stock is now", x, z)
elif order == "pears":
  x, y, z = pear_stock, price_pear, "pears"
  number = list(map(int,input("How many would you like to order? ").strip().split()))
  for individual_order in number:
    if x >= individual_order:
      x = x - individual_order
      print(order, )
      print("You have enough", z, "in stock")
      print("Your total price is", str(order * x))
      print("Your", z, "stock is now", x, z)

问题分析

  1. NameError触发原因:当用户输入的订单不是apples或pears时,x、y、z变量从未被赋值,但后续代码直接尝试读取这些变量,导致报错。
  2. 其他逻辑问题:
    • 条件判断优先级错误:order == "apples" or order == "pears" and totalstock > 0中and优先级高于or,解析逻辑不符合预期。
    • 总价计算错误:order是字符串,不能和整数x相乘,应该用「单价×订单数量」计算。
    • 库存未同步:修改x后未更新原库存变量apple_stock/pear_stock,导致totalstock始终不变,循环无法正常结束。

解决方案

  1. 提前初始化变量:在if/elif分支前给x、y、z赋默认值,避免未定义的情况。
  2. 重构判断逻辑:先校验订单有效性,无效则直接跳过后续处理。
  3. 封装重复逻辑为函数:把订单处理的核心逻辑抽成函数,彻底消除代码冗余。
  4. 修复逻辑错误:修正条件判断、总价计算、库存同步的问题。

优化后完整代码

price_apple = 1.00
price_pear = 1.50
apple_stock = 50
pear_stock = 30

def process_order(stock, price, fruit_name):
    """处理单个水果的订单逻辑"""
    number = list(map(int, input(f"How many {fruit_name} would you like to order? ").strip().split()))
    current_stock = stock
    for individual_order in number:
        if current_stock >= individual_order:
            current_stock -= individual_order
            print(f"You have enough {fruit_name} in stock")
            total_price = individual_order * price
            print(f"Your total price for this order is ${total_price:.2f}")
            print(f"Your {fruit_name} stock is now {current_stock}")
        else:
            print(f"Sorry, not enough {fruit_name} in stock. Only {current_stock} available.")
            break
    return current_stock

while True:
    total_stock = apple_stock + pear_stock
    if total_stock == 0:
        print("Sadly we don't have any more fruit in stock.")
        break
    
    order = input("What would you like to order? ").lower().strip()
    # 初始化变量为默认值,避免NameError
    x, y, z = 0, 0.0, ""
    
    if order == "apples":
        x, y, z = apple_stock, price_apple, "apples"
    elif order == "pears":
        x, y, z = pear_stock, price_pear, "pears"
    else:
        print("Invalid order. Please choose apples or pears.")
        continue
    
    # 处理订单并同步库存
    if order == "apples":
        apple_stock = process_order(x, y, z)
    else:
        pear_stock = process_order(x, y, z)

内容的提问来源于stack exchange,提问作者Jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 13:50:03