Your problem is in the scope of you money
variable. Recall that a functions variable are isolated from the rest of a program, and the only values it has access to are ones it declared:
def function():
variable = "value"
# This variable is declared inside the function
Or the values passed to it as arguments:
def function(num):
# code here
variable = "value"
function(variable) # calling function and passing a variable to it
However even if you pass a value to a function, the function can’t permanently modify it as it really only copies the variable to work with it.
A couple options for you to modify your money variable are to declare it as global
within the function:
variable = "value"
def change_variable():
global variable # include variable as a global
variable = "new value"
Though I would not recommend this option as global variables can often get messy and hard to work with. Another would be to pass money
as an argument and then return
it:
variable = 5
def change_variable(var_to_change):
var_to_change += 5 # Modify variable
return var_to_change # return it
variable = change_variable(variable)
# and assign it to variable outside of function
Yet another option could be, if instead of modifying money
in the function, what if you return the positive or negative value of bet
and add that to money? Now your function does not need to have money
passed to it, and you can still avoid the use of a global:
variable = 5
def subtract(num):
return -num #return negative value of num
variable += subtract(5)
# and add it to variable