无法从函数中更改全局变量

时间:2015-04-06 15:13:42

标签: python variables global local

我试图将我迄今为止学到的一些东西都用到一个简单的文本游戏中,但是我在一个函数中尝试更改全局变量时遇到了麻烦换了另一个。

keynumb = 0

这是全局变量。我试图在函数内部将其更改为1,然后在另一个函数中调用它(if 1 open the door, if 0 don't)等。

一直试着大约一个小时,直到我的大脑刚刚死在我身上,希望有人能指出我做错了什么。

我在代码中添加了行号。

干杯。

from sys import exit

keynumb = 0


def start():
    print "You are in a room with two doors in front of you. One on the left, and one on the right."
    while True:
        door_choice = raw_input("Do you take the left or right door? Your choice: ")
        if "left" in door_choice or "Left" in door_choice:
            dark_room()
        elif "right" in door_choice:
            monster_room()
        else:
            print "I don't understand."

def dark_room():
    print "You find yourself in a dark room, unable to see anything."
    while True:
        dr_choice = raw_input("What do you do?")
        if "light" and "switch" in dr_choice or "turn" and "light" in dr_choice:
            print "You've turn on the light and the room is illuminated."
            print "On the floor is a small silver key."
            dr_choice_light = raw_input("What do you do?")
            if "pick" in dr_choice_light:
                print "You pick up the key and exit back the way you came."
                keynumber()   *************
                start()
            elif "nothing" in dr_choice_light:
                print "You do nothing. Nothing happens."
            elif "back" in dr_choice_light or "exit" in dr_choice_light:
                start()     
        else:
            print "That didn't do anything."        


def monster_room():
    print "It seems this door is locked and requires a key."
    while True:
        mons = raw_input("What do you do?")
        if "key" in mons and keynumb == 0:   **************
            print "You don't have a key, dummy. Might as well turn back.."
        elif "key" in mons and keynumb == 1:
            print "You open it using the small silver key."
            print "You enter the room and a huge monster looks up from his iPhone. \"You want to get past me?\" he says. Well, if you know what 4 + 4 is then I'll let you pass." 
            answer = raw_input("What is 4+4?")
            if answer == "8":
                print "\"Well done!\" says the monster. He smiles as you pass to the door behind him."
            else: 
                print "Stupid. You die."
                exit
        elif "back" in mons:
            print "You turn back."
            start()     
        else:
            print "I don't understand."

def keynumber():   **********
    global keynumb += 1
    return keynumb


start()

1 个答案:

答案 0 :(得分:3)

keynumber

中的语法错误

你想要像

这样的东西
def keynumber():
    global keynumb
    keynumb += 1

我遗漏了return语句,因为你似乎还没有在那里使用它