0

Why does money print as 0 rather than as the entered values? How can I extract the variable from this function to be used elsewhere in the program?

   money = 0


def enterMoney(money):
  moneyInsert = float(input("How much money do you want to desposit into the machine? \n (Minimum $10):  "))
  money = float(money) + float(moneyInsert)
  if money < 10:
    print("Not enough money entered, please enter more.")
    enterMoney(money)




# mainline #

print ("======================================")
print ("  WELCOME TO CASINO DWARFS MACHINE!   ")
print ("        ENTER MONEY AND BEGIN!        ")
print ("                                      ")

enterMoney(money)
print (money)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    Because you didn't declare `money` as `global` in your function. You just created a new local variable with the name `money` and set its value, leaving the original one unchanged. See: https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – Random Davis Mar 09 '22 at 19:12

1 Answers1

0

To get a value out of a function, return it:

def enterMoney(money=0):
    print("How much money do you want to desposit into the machine?")
    moneyInsert = float(input("(Minimum $10):  "))
    money += float(moneyInsert)
    if money >= 10:
        return money
    print("Not enough money entered, please enter more.")
    return enterMoney(money)

and then assign it to a value when you call the function:

money = enterMoney()
print(money)
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 1
    Yes, but I wanted to answer their immediate question without rewriting their function completely. One lesson at a time. :) – Samwise Mar 09 '22 at 19:20