-1

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • (1) you probably meant `gold = gold + 1`, not `gold + 1 = gold` (2) see https://stackoverflow.com/questions/929777/why-does-assigning-to-my-global-variables-not-work-in-python – mkrieger1 Dec 14 '20 at 09:10
  • In general you can't do this in Python. `int` objects are immutable. But the correct way to approach this depends on exactly what you are doign – juanpa.arrivillaga Dec 14 '20 at 09:10
  • 1
    Mandatory link to [Ned Batchelder](https://nedbatchelder.com/text/names.html) – quamrana Dec 14 '20 at 09:15
  • 1
    The `gold` in the function is an argument, which is like a local variable — it's not the global variable with the same name that you are passing in the call to it. – martineau Dec 14 '20 at 09:23

3 Answers3

0

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.

0

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)
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

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.

Baktash
  • 19
  • 2