0

我对编程很陌生(如果我没有正确提出这个问题,很抱歉)。这是来自 LPTHW 练习 36:

我的错误:

Traceback (most recent call last):
  File "ex36.py", line 329, in <module>
    start()
  File "ex36.py", line 149, in start
    arena()
  File "ex36.py", line 161, in arena
    if stealth == True:
NameError: global name 'stealth' is not defined

我的假设:我认为“隐身”是在前面的函数 start() 中定义的,但该定义没有延续到 arena()。我该如何解决它,为什么从一个功能“隐身”不延续到另一个功能?

我的代码(正在进行的基于文本的游戏):

    from sys import argv

    script, enemy = argv
    ...
    def start():
        print """ Choose a skill to train in
        """
        stealth = False
        gun = False
        knife = False
        heal = False
        skill = raw_input("> ")

        if 'gun' in skill:
            print """
            """
            gun = True
            skill = gun
        ...
        else:
            dead()

        arena()

    def arena():
        print """ You enter the arena.  Will you:
        hide, hunt for food, or search for water?
            """

        path = raw_input("> ")

        if "hide" in path:
            print """ Hide
            """

            if stealth == True:
                print """ Witness
                """
                witness()
            else:
                battle()
        ...
        else:
            print """ Dead
            """
            dead()
start()

非常感谢所有建议。谢谢您的帮助。

4

1 回答 1

0

在一个函数中本地定义的变量具有本地范围,并且不能在另一个分离函数中自动访问。您可能要考虑在调用时传递stealthto ,例如,然后将其定义为 的参数,即arenastartarena(stealth)stealtharena

def arena(stealth):
于 2013-07-20T20:17:16.807 回答