1

我正在尝试以艰难的方式学习 python 中的一项练习,但我被困在了一些事情上。我创建了一个函数,如果其中一个语句得到满足,我想把它放在另一个函数中。这是我试图做到这一点的大纲:

def room_1():
    print "Room 1"
    button_push = False

    while True:
       next = raw_input("> ")

        if next == "1":
            print "You hear a click but nothing seems to happen."
            button_push = True

        elif next == "2":
            print "You enter room 2"
            room_2()

def room_2():
    print "Room 2"

    while True:
        next =raw_input("> ")

        if next == "1" and button_push:
            print "You can enter Room 3"
            room_3()

如果 button_push 完成了,那么我想在 room_2 中看到它。有人可以帮我吗?

4

1 回答 1

1

您可以button_push作为参数传递给下一个房间:

def room_1():
    print "Room 1"
    button_push = False

    while True:
       next = raw_input("> ")

        if next == "1":
            print "You hear a click but nothing seems to happen."
            button_push = True

        elif next == "2":
            print "You enter room 2"
            room_2(button_push)  # pass button_push as argument

def room_2(button_push):  # Accept button_push as argument
    print "Room 2"

    while True:
        next =raw_input("> ")

        if next == "1" and button_push:  # button_push is now visible from this scope
            print "You can enter Room 3"
            room_3()
于 2013-08-24T23:45:02.860 回答