I want to take a variable with an integer assigned to it then call a function that can just simply add to that variable's number.
This is what I've tried:
gold = 0
print(gold)
def addgold(gold):
gold + 1 = gold
addgold(gold)
print(gold)
I want to take a variable with an integer assigned to it then call a function that can just simply add to that variable's number.
This is what I've tried:
gold = 0
print(gold)
def addgold(gold):
gold + 1 = gold
addgold(gold)
print(gold)
As the comments say, in general this is a bad thing to do. However, you can do it this way:
gold = 0
print(gold)
def addgold():
global gold
gold += 1 #Same as gold=gold+1
addgold(gold)
print(gold)
However it is better in this case to just use gold += 1
in any place you'd use addgold()
, as they do the same thing.
I think you meant to return gold:
gold = 0
print(gold)
def addgold(gold):
gold = gold + 1
return gold
gold = addgold(gold)
print(gold)
Also to be clear about functions, their parameters and local variables, this code below is exactly the same as the above:
gold = 0
print(gold)
def addgold(foo): # parameter is now named foo
foo = foo + 1
return foo
gold = addgold(gold)
print(gold)
One of the problems is that you should return the value of your variable in addgold function, then when you call it, gives you a number and you can save it in new variable like this code :
gold= 0
def addgold(gold):
gold =gold +1
return gold
new_gold = addgold(gold)
print(new_gold)
good luck.