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

如何解决Python函数与for循环中全局变量totalCost未定义的问题?

问题原因

Python的变量作用域规则规定:如果函数内部需要修改全局作用域中定义的变量,必须先用global关键字声明该变量,否则Python会默认将其识别为函数内部的局部变量。
你在takeOrder()函数中执行了totalCost += float(prices[choice])的修改操作,又没有在函数内提前声明global totalCost,运行时Python只会在函数局部作用域搜索该变量,搜索失败就会抛出变量未定义的报错。

修复方法

在takeOrder()函数的开头添加global totalCost声明即可解决该报错:

def takeOrder():
    global totalCost # 新增这行声明要修改全局变量
    print('What bread?')
    # 剩余原有代码不变
其他需要修复的逻辑问题

你的代码还存在几个会影响运行的小问题,建议同步修改:

  • 酱汁选择的提示文本错误:询问是否加酱汁的inputYesNo里提示内容还是Would you like some cheese?,后续芝士、酱汁的inputMenu提示文本都错误写成了What kind of meat:,会误导用户操作
  • 额外下单数量应该用inputInt而非inputFloat,避免用户输入小数份的三明治
  • more变量仅在用户选择加单时才会定义,如果用户选择不需要加单,后续执行for i in range(more)时会抛出more未定义的报错,需要给more设置默认值0
修复后完整可运行代码
import pyinputplus as pyip
totalCost = 0.0
prices = {
    "wheat": 0.5, "white": 0.25, "sourdough": 0.75,
    "chicken": 0.5, "turkey": 0.45, "ham": 0.3, "tofu": 0.25,
    "cheddar": 0.15, "Swiss": 0.2, "mozzarella": 0.15,
    "mayo": 0.05, "mustard": 0.08, "lettuce": 0.03, "tomato": 0.01
}
order = {}

def takeOrder():
    global totalCost
    order['bread'] = pyip.inputMenu(['wheat','white', 'sourdough'], prompt='请选择面包类型:\n', numbered=True)
    order['meat'] = pyip.inputMenu(['chicken','turkey', 'ham','tofu'], prompt='请选择蛋白质食材:\n', numbered=True)
    cheese_choice = pyip.inputYesNo('是否需要添加芝士?')
    if cheese_choice == 'yes':
        order['cheese'] = pyip.inputMenu(['cheddar','Swiss', 'mozzarella'], prompt='请选择芝士种类:\n', numbered=True)
    sauce_choice = pyip.inputYesNo('是否需要添加酱汁/配菜?')
    if sauce_choice == 'yes':
        order['sauce'] = pyip.inputMenu(['mayo','mustard', 'lettuce','tomato'], prompt='请选择酱汁/配菜:\n', numbered=True)       
    for choice in order:
        if choice in prices:
            totalCost += prices[choice]

takeOrder()
ynmore = pyip.inputYesNo('是否需要追加订单?')
more = 0
if ynmore == 'yes':
    more = pyip.inputInt('请输入需要追加的三明治数量:', min=1)
for i in range(more):
    takeOrder()    
print(f'总费用为:{totalCost} 美元')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:06:03