首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中访问和编辑函数中的变量

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

Stack Overflow用户
提问于 2016-04-03 20:13:18
回答 4查看 154关注 0票数 0

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

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

我研究了很长一段时间,发现很少有东西可以解决这个问题,我试过一些,但它们没有起作用,我不知道如何使用别人。

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

下面是代码,它相当大(我将需要访问和更改的变量放在粗体中):从随机导入随机打印(“幽灵游戏v2.0")打印(”选择困难“)

代码语言:javascript
复制
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)
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-04-03 20:19:31

考虑:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
x=0
z=22
def func(x,y):
    global z
    y=22
    z+=1
    print x,y,z

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

还要注意的是,x的本地版本是打印出来的,而不是全局版本。这就是你所期望的。含糊不清的是,如果没有本地版本的值。Python将全局定义的值视为只读值,除非使用global关键字。

正如注释中所述,一个类来保存这些变量会更好。

票数 0
EN

Stack Overflow用户

发布于 2016-04-03 20:22:07

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

代码语言:javascript
复制
score = 0
alive = True

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

def kill_kill_kill():
    global alive
    alive = False

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

票数 0
EN

Stack Overflow用户

发布于 2016-04-03 20:22:15

全局关键字可能是您正在寻找的。

例如,在以下代码中。

代码语言:javascript
复制
some_variable = 10

def some_function():
    global some_variable
    some_variable = 20

这将导致some_variable (在全局范围内)引用20的值,因为它将保持在10 (在全局范围内),而不使用全局关键字。

更多关于全局和局部变量这里的信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36390596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档