Skip to content Skip to sidebar Skip to footer

Python, Functions Changing Values

So I am having trouble getting this system to work, and I can't be sure that I'm asking the right question, but here is what is happening and what I want to happen. money = 1 def

Solution 1:

money + 2 is a no-op. You actually have to assign money to a new value

money = money + 2
# or
money += 2

But then you'll find you get an error - you can't assign to variables outside a function scope. You can use the global keyword:

global money
money += 2

This will allow you to change the value of money within the function.

However, the recommended way is passing money as a parameter:

def gainM(money):
    money +=2Stats()
    return money

if money == 1:
    money = gainM(money)

If you're using the second option (which you should be), you also need to change your Stats function, to have a money parameter as well.

defStats(money):
     printprint"money " + str(money)

Otherwise the function will print 1 instead of 3.

Another recommendation - use string formatting.

'money %d' % money  # the old way'money {}'.format(money)  # the new and recommended way

Now you pass money into the Stats function.

def gainM(money):
    money +=2Stats(money)
    return money

Solution 2:

You need to assign the new value to money. Like so:

money = money + 2

Or the shorthand form:

money += 2

Also, if the variable is outside your function, you need to declare it global(so it doesn't instead create a local variable)

So you end up with:

def gainM():
    global money
    money += 2
    Stats()

Edit: just to clarify, I'm not saying you should use global variables. In general they are a bad idea(though they may be useful in some situations). However, that's what this particular example needs to work. Chances are, however, that what you want is probably a class with instance variables that the methods of that class modify. However, given that you don't seem to have grasped the basics of the language yet, take things one step at a time and don't worry about any words in my previous sentences you didn't understand for now :)

Post a Comment for "Python, Functions Changing Values"