如何在函数和for循环中修复这个未定义的变量?



我正试图通过三明治制造商的代码。问题陈述要求我编写一个程序,使用PyInputPlus询问用户的三明治偏好。使用inputMenu获取面包、蛋白质信息。使用InputYesNo奶酪超过和酱料和inputInt多少sanwiches他们想要。最后,计算所有三明治的成本。我的问题是,它一直说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])

它超出了作用域函数,因此您需要在函数内部声明它,以使其不是未知的。或者你可以将它声明为全局变量(我不推荐)

最新更新