-1

I have only began coding a week or two ago so i still dont know quite a few basics but essentially what happens is my "money" variable resets back to ten whenever the function restarts and if I put the variable outside i get an error saying that "money was referenced before assignment" I've tried other options like a global statement which still has the same issue.

def main():

    money = 10.00
    print('Welcome to the vending machine.')




    print('The snacks available are:')
    print('1. Chips - $2.50')
    print('2. Chocolate Bar - $3.00')
    print('3. Water - $1.90')
    print('4. Cookie - $0.85')
    print('5. Skittles - $2.00')
    print('6. Pringles - $4.00')
    print('7. Exit')
    print('You have',money,'remaining!')

    a = input('What would you like to purchase?')
    if a == '1':
        money = money - 2.5 
        print('You have bought chips for $2.50 you have $',money,'remaining!')

    if a == '2':
        money = money - 3
        print('You have bought a chocolate bar for $3.00 and have $',money,'remaining!')

    if a == '3':
        money = money - 1.90
        print('You have bought water for $1.90 and have $',money,'remaining!')

    if a == '4':
        money = money - 0.85
        print('You have bought a cookie for $0.85 and have $',money,'remaining!')

    if a == '5':
        money = money - 2.00
        print('You habe bought skittles for $2.00 and have $',money,'remaining!')

    if a == '6':
        money = money - 4.00
        print('You have bought pringles for $4.00 and have $',money, 'remaining!')

    c = input('Would you like to make another purchase? Y/N').upper()
    if c == 'Y':
        main()
    if c == 'N':
        exit
    else:
        exit


main()
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Bushaba
  • 11
  • `function restarts` what's that mean. You mean when you type `Y` and it call main method again? – Toan Quoc Ho Sep 04 '19 at 06:28
  • Agree with @PatrickArtner use of while loop is the way to go. Wanted to address "money was referenced before assignment" error. Find the explanation here https://stackoverflow.com/questions/370357/python-variable-scope-error – TKerr Sep 04 '19 at 06:54

3 Answers3

4

You set money = 10 at the start of def main() - if you call it again it will be reset to it because it is a local variable in the scope of your main method.

You can define it outside and provide it as parameter:

def main(money):
    # no money def here, it is provided as parameter

    # your code

    if c == 'Y':
        main(money) # pass the remainder money on
    else:
        exit()

main(10) # call the main() with your initial money

A better way would be to read up on loops and handle the looping in a while loop instead of recursing into main(...) again and again.


Version using while, a lookup dict for wares/prices, some loops and checking:

def menu(items, money):
    print('The snacks available are:')

    for key,value in sorted(items):
        if value[1]:
          print(f"{key}. {value[0]} - ${value[1]}")
        else:
            print(f"{key}. {value[0]}")

    print(f'You have ${money} remaining!')

# your wares
ex = "Exit"    
what = {'1': ('Chips', 2.5),        '2': ('Chocolate Bar', 3),
        '3': ('Water', 1.9),        '4': ('Cookie', 0.85),
        '5': ('Skittles', 2),     '6': ('Pringles', 4),
        '7': (ex, None)}

def main(money = 10.0):
    menu(what.items(), money)
    while True:
        a = input('What would you like to purchase? ') 

        # handle bad input
        if a not in what:
            print("Not possible. Try again:")
            # reprint menu
            menu(what.items(), money)
            continue

        if what[a][0] == ex:
            print("Bye.")
            break
        else:
            thing, cost = what[a] 
            if cost < money:
                money -= cost
                print(f'You have bought {thing} for ${cost}. You have $ {money} remaining!')
            else:
                print(f"Too expensive. You have $ {money} remaining!'")

        c = input('Would you like to make another purchase? Y/N ').upper()

        if c == 'N':
            print("Bye.")
            break

main()

Output:

The snacks available are:
1. Chips - $2.5
2. Chocolate Bar - $3
3. Water - $1.9
4. Cookie - $0.85
5. Skittles - $2
6. Pringles - $4
7. Exit
You have $10.0 remaining!
What would you like to purchase? 1
You have bought Chips for $2.5. You have $ 7.5 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 2
You have bought Chocolate Bar for $3. You have $ 4.5 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 3
You have bought Water for $1.9. You have $ 2.6 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 4
You have bought Cookie for $0.85. You have $ 1.75 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 5
Too expensive. You have $ 1.75 remaining!'
Would you like to make another purchase? Y/N Y
What would you like to purchase? 6
Too expensive. You have $ 1.75 remaining!'
Would you like to make another purchase? Y/N Y
What would you like to purchase? 7
Bye.
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    @Bushaba you definitly want to read and re-read the last advice in this answer : don't use recursion when you can solve the problem with plain iteration. – bruno desthuilliers Sep 04 '19 at 06:43
0

Declare to use global variables within a function

money = 10.0

def main():
    global money
    money = 5.0
    # ...
MeiK
  • 391
  • 3
  • 5
  • It's the right way to use the global statement indeed, but https://stackoverflow.com/questions/19158339/why-are-global-variables-evil - better not to advise using globals when they're not needed. – bruno desthuilliers Sep 04 '19 at 06:40
-1

Define your variable 'money' outside the function as a global variable. Like this;

money = 10.0

def main():
   global money
   #some stuff 
Erdal Dogan
  • 557
  • 1
  • 4
  • 10
  • 2
    wrong usage of the `global` keyword: [read here](https://docs.python.org/3.7/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python) – Patrick Artner Sep 04 '19 at 06:32
  • I had tried this earlier but had the same issue, the issue has been resolved but thank you – Bushaba Sep 04 '19 at 06:33
  • 1
    @PatrickArtner Yep you're right, my bad. Editing the post accordingly, even though someone posted correct way. – Erdal Dogan Sep 04 '19 at 06:36