Python, Functions changing values

后端 未结 2 1137
南旧
南旧 2021-01-15 18:01

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.

相关标签:
2条回答
  • 2021-01-15 18:37

    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 :)

    0 讨论(0)
  • 2021-01-15 18:51

    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 += 2
        Stats()
        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.

    def Stats(money):
         print
         print "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 += 2
        Stats(money)
        return money
    
    0 讨论(0)
提交回复
热议问题