为什么说全局名称不定义?蟒蛇

时间:2011-04-04 21:58:53

标签: python if-statement syntax-error

我正在编写一个非常简单的猜测玩家进行猜测的动物游戏。我花了很长时间来填充所有信息,我知道这是非常冗长的,可能会以更短的方式完成,但我是初学者。问题是,其中一部分不起作用。我将把代码放入并突出显示不起作用的区域并解释会发生什么......

def animalmenu():
    print()
    print()
    print('Welcome to the menu. I am thinking of an animal. Select the option\'s below to try and guess my animal.')
    print()
    print('a) No. of Legs')
    print('b) Type of animal')
    print('c) Preffered Climate')
    print('d) Size')
    print('e) Colour')
    print('f) Diet')
    print('g) Habitat')
    print('h) Can be kept as pet')
    print('i) Guess the animal')
    print()
    AniChoice = input('Choose your option: ')
    if AniChoice == 'a':
        choicea()
    if AniChoice == 'b':
        choiceb()
    if AniChoice == 'c':
        choicec()
    if AniChoice == 'd':
        choiced()
    if AniChoice == 'e':
        choicee()
    elif AniChoice == 'f':
        choicef()
    elif AniChoice == 'g':
        choiceg()
    elif AniChoice == 'h':
        choiceh()
    elif AniChoice == 'i':
        guessing()

这就是菜单的基本布局。然后,对于每个选项,都有一个子菜单,例如:

def choicea():
    print()
    print('')
    print()
    guessleg = input('Guess the number of legs (insects may be listed as \'lots\': ')
    if leg == guessleg:
        print('True')
        print('r = Return to menu, g = guess again.')

    elif leg != guessleg:
        print('False')
        print('r = Return to menu, g = guess again.')

这些子菜单工作正常,直到你到子菜单的f到我...我不知道有什么问题。您可以从代码的另一个区域获得您想要猜测的数据......

def animalchoice():
    asdf = ('dog', 'monkey', 'parrot', 'fox', 'mouse', 'lady-bird', 'badger', 'shark', 'whale', 'pigeon')
    from random import choice
    animal = choice(asdf)
    if animal == 'dog':
        leg = '4'
        breed = 'mammal'
        climate = 'any'
        size = 'dog+'
        colour = 'depends'
        diet = 'a'
        habitat = 'ground'
        pet = 'yes'

    if animal == 'monkey':
        leg = '4'
        breed = 'mammal'
        climate = 'hot'
        size = 'dog+'
        colour = 'brown'
        diet = 'c'
        habitat = 'tree'
        pet = 'no'
对于更多的动物来说,这仍在继续。当我运行脚本时,它工作正常。我在不同的地方添加了循环等,没关系。但是当我尝试从菜单中运行说选项g(def choiceg)时,会出现各种错误,基本上说全局名称'habitat'(我们试图在该特定区域猜测的东西)不是定义。我用与其他区域相同的方式对这些区域进行编码,但它不起作用......我做错了什么?除了冗长的脚本编写方式.... 救命!?!?!如何防止错误???

4 个答案:

答案 0 :(得分:4)

定义这些变量时,您可以在这些函数中设置 。它们实际上根本不是全局变量。你的主要选择是

  1. 将它们配置为全局变量,
  2. 创建要传递的“状态”对象(例如设置data['habitat'] = 'tree'并从animalchoice函数返回),
  3. 将函数放在类中,并将值存储为类变量,如:
  4. class GuessingGame(object): [...] def animalchoice(self): asdf = ('dog', 'monkey', 'parrot', 'fox', 'mouse', 'lady-bird', 'badger', 'shark', 'whale', 'pigeon') from random import choice animal = choice(asdf) if animal == 'dog': self.leg = '4' self.breed = 'mammal' self.climate = 'any' self.size = 'dog+'

    我不能告诉你哪一个是“最好的”,因为这取决于你想要如何构建你的程序的其余部分。

答案 1 :(得分:2)

除了其他答案,您可以将代码重构为:

from random import choice

data = {
    "dog": dict(
        leg = '4',
        breed = 'mammal',
        climate = 'any',
        size = 'dog+',
        colour = 'depends',
        diet = 'a',
        habitat = 'ground',
        pet = 'yes',
    ),

    "monkey": dict(
        leg = '4',
        breed = 'mammal',
        climate = 'hot',
        size = 'dog+',
        colour = 'brown',
        diet = 'c',
        habitat = 'tree',
        pet = 'no',
    ),
    # <<Add animals here>> ....
}

data["animal"] = data[choice(data.keys())]    # Current random animal

def animalmenu():
    choices = {
        "a": ("No. of Legs", "leg"),
        "b": ("Type of animal", "breed"),
        "c": ("Preffered Climate", "climate"),
        "d": ("Size", "size"),
        "e": ("Colour", "colour"),
        # <<add attributes here>>...
    }

    while True:
        for k, v in choices.items():
            print "%s) %s" % (k, v[0])

        option = raw_input('Choose your option: ')
        if not option:
            break

        if option in choices:
            guess_attr(choices[option][0], choices[option][1])

        print


def guess_attr(caption, attr):
    global data

    while True:
        guess = str(raw_input('Guess the %s :' % caption))
        ok = guess==str(data["animal"][attr])
        print ok
        if ok:
            break

        option = raw_input('r = Return to menu, g = guess again: ')
        if option=="r":
            break

    print


animalmenu()

这样,您可以轻松添加动物和属性,而无需修改所有代码。

答案 2 :(得分:1)

全局变量是适用于整个程序的变量。在您的示例中,您说栖息地不起作用,返回错误全局变量未初始化。这意味着你可能已经在其他函数中声明了栖息地,也许是choicea,但是你自己在choicea中定义它,只有choicea可以访问它。换句话说,它不是全球性的。如果你想让它成为全局的,你应该在任何函数之外声明它,并且,为了安全起见,也要在循环之外。有时奇怪的事情发生在变量上。每个人在编程生涯中都会犯这个错误。

此外,我建议您使用单独的文件,而不是列出程序中的所有内容吗?还是一个数据库来保存值?这样,您不必在每次想要更改值的开头时修改代码......只是一个友好的建议。

答案 3 :(得分:0)

去过那里,犯了那个错误:-) 在使用它的每个函数的开头定义你的全局变量(例如,栖息地)和'全局'。

快速谷歌提出了以下文章:

http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-function.htm

还可以在python文档中查找“global”以获取完整的解释/说明。

(顺便说一句,我认为将代码复制到Stackoverflow时,制表有点破碎)