'How do I pull a variable out of a function to be used elsewhere? [duplicate]
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)
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
