变量未在功能中更新

时间:2014-05-11 15:27:16

标签: python function python-3.4

我是Python新手,但请耐心等待。

在我的代码中,我尝试通过room函数将变量2变为west()

代码:

编辑:我已经隔离了大部分非基本代码。

room = 1

cmds = 'west'.lower()

def isValidCMD(cmd):
    if cmd in cmds:
        return True
    else:
        print("Unknown command. For help type /help, for available options type /options")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)
        return False

def runCMD(cmd):
    if cmd == '/help':
        help()
    elif cmd == '/exit':
        exit()
    elif cmd == '/about':
        about()
    elif cmd == '/stats':
        stats()
    elif cmd == '/options':
        options()
    elif cmd == 'north':
        north()
    elif cmd == 'south':
        south()
    elif cmd == 'east':
        east()
    elif cmd == 'west':
        west()
    elif cmd == '/lookaround':
        look_around()

def west():
    if room == 1:
        print("You head on over to the lab, to get some advice from Professor Andrew.")
        return 2 #LINE 40 < -------
    elif room == 7:
        print("You head back to Auderban Square feeling primed for battle.")
    else:
        print("You cannot go west.")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)

def main():
    while True:
        # Town 
        if room == 1:
            print("\nYou are at the centre of town, Auderban Square.".upper())
            print("\nYou look at the signpost and see 4 signs.")
            print("\t- North - Twinleaf Forest")
            print("\t- South - Store of Celestia")
            print("\t- East - Deskemon Training Ground")
            print("\t- West - Auderban's Deskemon centre")
        # Lab
        elif room == 2:
            print("You are at Auderban's Deskemon Centre")
            AndrewConv()
            print("\nYou see the exit at the door.")
            print("\t- East - Auderban Square")

        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)
main()

输出:

room保留其值1

请给出一些未来的建议,这样我两次不会犯同样的错误。

2 个答案:

答案 0 :(得分:1)

west()函数替换为:

def west():
    global room
    ...

答案 1 :(得分:0)

全局变量被广泛认为是错误的编程实践,因为很难确定在大型程序中何时何地修改它们。它们也使得线程安全和可重入代码几乎不可能编写。

一个简单的方法是让每个函数接受room作为参数并返回“新房间”。然后,每次调用时,您都可以更新主函数中的room命令。

尽管如此,你最终可能会记录更多的房间。考虑使用像字典或类这样的可变数据结构来存储游戏状态,然后将其传递给命令函数。这样,跟上许多状态变量一样简单,你仍然不需要全局变量。

def main():
    state = {'room': 1}
    while True:
        [...]
        if isValidCMD(cmd, state):
            runCMD(cmd, state)

def west(state):
    thisroom = state['room']
    if thisroom == 1:
        print("You head on over to the lab, to get some advice from Professor Andrew.")
        state.update(room=2)
    elif thisroom == 7:
        print("You head back to Auderban Square feeling primed for battle.")
    else:
        print("You cannot go west.")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)

此代码还存在一些其他问题。例如,您在每个命令提示符中复制命令提示符代码,这很容易且容易出错,而且不必要,因为无论如何您将返回main()

已编辑:以下是一个最小的,可运行的示例:

def main():
    state = {'room': 1}
    for i in range(20):
        oldroom = state['room']
        nextroom(state)
        print("Went from room {} to room {}.".format(oldroom, state['room']))

def nextroom(state):
    state['room'] += 2
相关问题