【问题标题】:How can I fix this undefined variable within a function and a for loop [duplicate]如何在函数和 for 循环中修复这个未定义的变量 [重复]
【发布时间】:2021-10-07 01:07:20
【问题描述】:

我正在尝试通过 Sandwich Maker 的代码。问题陈述要求我编写一个程序,使用 PyInputPlus 询问用户的三明治偏好。使用 inputMenu 获取面包、蛋白质信息。使用 InputYesNo 表示奶酪浇头和酱汁,使用 inputInt 表示他们还想制作多少三明治。最后,计算所有三明治的三明治成本。我的问题是它一直说 totalCost 是未定义的,我不知道为什么。我试过了


    import pyinputplus as pyip
    totalCost = float(0)
    x = 0
#dictionary for the price of each ingredient
    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 = {}
#take order
    def takeOrder():
        print('What bread?')
        order['bread'] = pyip.inputMenu( ['wheat','white', 'sourdough'], prompt = 'What kind of bread?: \n ',numbered= True)
        order['meat'] = pyip.inputMenu( ['chicken','turkey', 'ham','tofu'], prompt = 'What kind of meat?: \n ',numbered= True)
        cheese_choice = pyip.inputYesNo('Would you like some cheese?')
        if cheese_choice == 'yes':
            order['cheese'] = pyip.inputMenu( ['cheddar','Swiss', 'mozzarella'],prompt = 'What kind of meat: \n',numbered= True)
        sauce_choice = pyip.inputYesNo('Would you like some cheese?')
        if sauce_choice == 'yes':
            order['sauce'] = pyip.inputMenu( ['mayo','mustard', 'lettuce','tomato'],prompt = 'What kind of meat: \n',numbered= True)       
    #take order 
        for choice in order:
            if choice in prices.keys():
                totalCost += float(prices[choice])
    takeOrder()
#ask for how many more orders customer would want. Calls the takeOrder function this amount of time.
    ynmore = pyip.inputYesNo('would you like more?')
    if ynmore == 'yes':
        more = pyip.inputFloat('how many more orders of this would you like?', min = 1)
    for i in range(more):
        takeOrder()    
    print(totalCost)

但是为什么这里没有将 totalCost 定义为变量呢? totalCost 是函数外的全局变量,为什么在这里不起作用?

for choice in order:
    if choice in prices.keys():
        totalCost += float(prices[choice])

【问题讨论】:

  • 你需要global totalCost。您分配给的任何变量都是局部变量,除非它被声明为全局变量。
  • @Barmar 不是第 2 行在做什么吗?
  • @chickitychinachinesechicken 第 2 行不在函数中。
  • 有兴趣,谢谢确认..

标签: python


【解决方案1】:

它超出了范围函数,因此您需要在函数内声明它以使其不为人所知。或者你可以将它声明为全局变量(我不推荐)

【讨论】:

  • 如果你在函数中声明它,总数不会从多次调用函数中累积。
猜你喜欢
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 2016-11-02
相关资源
最近更新 更多