如何在python中访问和编辑函数内部的变量

时间:2016-04-03 20:13:18

标签: python function variables

我是新的(-ish)到python,今天我做了一个游戏,在我完成后我意识到我犯了一个大错:

在函数内部我必须访问和编辑变量,这些变量也可以在其他函数中访问和更改,也可能在将来的函数之外。我不知道该怎么做。

我已经研究了很长时间,发现很少有可能解决这个问题的事情,我已经尝试了一些,但他们还没有工作,我不明白如何使用他人。

你可以试着帮我解决这个问题,如果你发现别人,请告诉我,因为我不太擅长调试:(

以下是下面的代码,它非常大(我已经将我需要访问的变量放入并以粗体更改):     来自随机导入randint     打印(" Ghost Game v2.0")     打印("选择难度")

score       = 0
alive       = True
difficulty  = 0
doors       = 0
ghost_door  = 0
action      = 0
ghost_power = 0
                #define the function 'ask_difficulty'
def ask_difficulty() :
    difficulty = input ("Hard, Normal, Easy")
    set_difficulty()



                # define the function 'set_difficulty' which sets the            difficulty.
def set_difficulty() :
if difficulty == 'Hard' or 'Normal' or 'Easy' :
    if difficulty == 'Hard' :
        doors = 2

     elif difficulty == 'Normal' :
         doors = 3

     elif difficulty == 'Easy' :
         doors = 5

else:
    print ("Invalid input, please type Hard, Normal, or Easy")
    ask_difficulty()



            # define the function 'ghost_door_choose' which sets the ghost door and the chosen door


def ghost_door_choose(x):
    ghost_door = randint (1, x)

    print (doors + " doors ahead...")
    print ("A ghost behind one.")
    print ("Which do you open?")

    if doors == 2 :
        door = int("Door number 1, or door number 2...")
        if 1 or 2 in door :
            ghost_or_no()

        else :
            print ("Invalid input")
            ghost_door_choose(difficulty)


    elif doors == 3 :
        door = int("Door number 1, door number 2, or door number 3")
        if 1 or 2 or 3 in door :
            ghost_or_no()

        else:
            print ("Invalid input")
            ghost_door_choose(difficulty)


   elif doors == 5 :
        print("Door number 1, door number 2, door number 3, door number 4,     or door number 5.")
        if 1 or 2 or 3 or 4 or 5 in door :
            ghost_or_no()

        else:
            print ("Invalid input")
            ghost_door_choose(difficulty)


                 # define the function 'ghost_or_no'
def ghost_or_no() :
    if door == ghost_door:
        print ("GHOST!!")
        print ("Initiating battle...")
        battle()

    else:
        print ("No ghost, you\'ve been lucky, but will luck remain with you...")
       score = score + 1
        ghost_door_choose(difficulty)

                # define the function 'battle' which is the battle program
def battle() :
    ghost_power = randint (1, 4)               # 1 = Speed,  2 = Strength,  3 = The ghost is not friendly, 4 = The ghost is friendly

    print ("You have 3 options")
    print ("You can flee, but beware, the ghost may be fast  (flee),")
    print ("You can battle it, but beware, the ghost might be strong (fight),")
    print ("Or you can aproach the ghost and be friendly, but beware, the ghost may not be friendly (aproach)...")
    action = input ("What do you choose?")

    if flee in action :
        action = 1

    elif fight in action :
        action = 2

    elif aproach in action :
        action = 3

    else :
        print ("Invalid input")
        battle()

    if ghost_power == action :
        if action == 1:
            print ("Oh no, the ghost\'s power was speed!")
            print ("DEFEAT")
            print ("You\'r score is " + score)
            alive = False

        elif action == 2:
            print ("Oh no, the ghost\'s power was strength!")
            print ("DEFEAT")
            print ("You\'r score is " + score)
            alive = False

        elif action == 3:
            print ("Oh no, the ghost wasn\'t friendly ")
            alive = False

    elif ghost_power == 4 and action == 3 :
        print ("Congratulations, The ghost was friendly!")
        score = score + 1
        ghost_door_choose(difficulty)

    elif ghost_power != action and ghost_power != 4 :
        if action == 1:
            print ("Congratulations, the ghost wasn\'t fast!")
            score = score + 1
             ghost_door_choose(difficulty)

        elif action == 2:
            print ("Congratulations, you defeated the ghost!")
            score = score +1
            ghost_door_choose(difficulty)

    elif ghost_power != action and ghost_power == 4 :
        if action == 1:
            print ("You ran away from a friendly ghost!")
            print ("Because you ran away for no reason, your score is now 0")
            score = 0
            ghost_door_choose(difficulty)
        elif action == 1:
            print ("You killed a friendly ghost!")
            print ("Your score is now 0 because you killed the friendly ghost")
            score = 0
            ghost_door_choose(difficulty)



                    #actual game loop

ask_difficulty()

while alive :
    ghost_door_choose(doors)

4 个答案:

答案 0 :(得分:0)

考虑:

x=0
z=22
def func(x,y):
    y=22
    z+=1
    print x,y,z

func('x','y')    

当您致电func时,您将获得UnboundLocalError: local variable 'z' referenced before assignment

要修复我们函数中的错误,请执行以下操作:

x=0
z=22
def func(x,y):
    global z
    y=22
    z+=1
    print x,y,z

global关键字允许更改对全局定义变量的本地引用。

另请注意,打印的是x的本地版本,而不是全局版本。这是你所期望的。不明确的是,如果没有值的本地版本。除非您使用global关键字,否则Python会将全局定义的值视为只读。

如评论中所述,持有这些变量的类会更好。

答案 1 :(得分:0)

脚本顶部的那些变量是全局的,要在函数中设置它们,您必须在函数中将它们声明为全局变量。作为一个较小的例子,

score = 0
alive = True

def add_score(value):
    """Add value to score"""
    global score
    score += value

def kill_kill_kill():
    global alive
    alive = False

下一步是创建可能变得复杂的类。例如,如果您想要按用户跟踪分数,但用户可以拥有多个角色,每个角色都有自己的活力,那么您将开始构建类来表示这些东西。

答案 2 :(得分:0)

全局关键字可能就是您要找的。

例如,在以下代码中。

some_variable = 10

def some_function():
    global some_variable
    some_variable = 20

这将导致some_variable(在全局范围内)引用值20.在不使用global关键字的情况下,它将保持在10(在全局范围内)。

有关全局和局部变量的更多信息here

答案 3 :(得分:0)

一个函数有自己的变量范围 - 对于许多语言都是如此。这意味着一旦函数完成执行,变量就不复存在了(Python的垃圾收集将清理它们。)

老式学校(通常不赞成,不一定公平)这样做的方法是使用全局变量。这些是您在函数范围之外声明的变量,通常在源代码的开头,并且可以在整个程序的各种函数和类中使用。

有很多理由让人们不必使用全局变量,从性能问题到让它们与本地范围的变量混淆,但它们是一种快速简便的方法来保存信息并在整个程序中访问它。 / p>

要使用全局,您需要在函数中声明您正在使用该变量,如下所示:

MyGlobal="This is a global variable"
def MyFunction():
    global MyGlobal
    MyGlobal += " and my function has changed it"
if __name__=="__main__":
    print MyGlobal
    MyFunction()
    print MyGlobal

说到这里,向函数传递信息和从函数传递信息的常用方法是使用参数和返回值 - 这是一种更好的设计方法,而且通常是教授的。这是一种设计方法,而不是对代码的更改;你编写程序时将全局变量保持在绝对最小值。

要采用上面的示例,这会将我们的代码更改为以下内容:

def MyFunction(MyArg):
    MyArg+=" and my function has given me a new version of it"
    return MyArg
if __name__=="__main__":
    MyVariable="This is a variable"
    print MyVariable
    MyVariable = MyFunction(MyVariable)
    print MyVariable

请注意,这更灵活 - 我可以像上面一样使用它来更改MyVariable的值,但我也可以使用相同的函数将新值返回到另一个变量,保持原始原样不变。

我希望这会有所帮助,对不起,如果我有点啰嗦。