0

I'm trying to through the code for Sandwich Maker. The problem statement requires me to write a program that asks user for their sandwich preferences using PyInputPlus. Use inputMenu to get bread, protein info. Use InputYesNo for cheese topping and sauces and inputInt for how many more sanwiches they want to make. Finally, calculate the cost of the sandwich as for all the sanwiches. My problem is that it keeps saying that totalCost is undefined and I have no idea why. I had tried


    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)

But why isn't totalCost defined as a variable here? totalCost is a global variable outside of the function, so why doesn't it work here?

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

1 Answers1

0

It is out of the scope function so you need to declare it inside the function for it to be not unknown. Or you can declare it as global variable (not recommended by me)

Thien Diep
  • 21
  • 2
  • If you declare it inside the function, the total won't accumulate from multiple calls to the function. – Barmar Oct 07 '21 at 01:14