Python, Functions changing values

后端 未结 2 1158
南旧
南旧 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: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
    

提交回复
热议问题