添加整数时变量不会改变

时间:2016-06-01 13:39:45

标签: python python-3.x variables

我制作了这个代码,当你选择一个蓝莓时,你的蓝莓留在一个,我不知道为什么。我希望用户获得多个蓝莓,但它似乎只能保持一个。

def blueberryfound(blueberries):
    print("        .-~~~~-.")
    print("       /  ( ( ' \ ")
    print("      | ( )   )  | ")
    print("      \ ) ' }  / /")
    print("       \,,,,,,,,/")
    leaveorpick = input("Enter P to pick or L to leave the blueberry!").lower()
    if leaveorpick == "p":
        print("")
        print("You chose to keep the berry.")
        blueberries = blueberries + 1
        print("You now have",blueberries,"blueberries.")

1 个答案:

答案 0 :(得分:1)

integer变量是不可变的,这意味着

def blueberryfound(val):
    val = val + 1

blueberries = 1
blueberryfound(blueberries)

不起作用。函数内只有val递增,外部变量blueberries不会改变。相反,你可以做到

def blueberryfound(val):
    return val + 1

blueberries = 1
blueberries = blueberryfound(blueberries)

或者,您可以使用面向对象的方法,其中玩家对象具有许多属性,blueberries是其中之一。然后,您的函数可以操纵给定播放器实例的所有属性。

class Player(object):
    blueberries = 0

def blueberryfound(player):
    player.blueberries += 1

player = Player()
blueberryfound(player)