函数中定义的变量抛出NameError:在main中使用时未定义的全局名称

时间:2015-12-07 16:20:30

标签: python function

我正在尝试运行我的功能:show_total(),但我收到此错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".\file.py", in <module>
    main()
  File ".\file.py", in main
    total_money = show_total(bags, coins, coin_to_bag)
NameError: global name 'coin_to_bag' is not defined

我的代码如下:

def assign_coin_to_bag(bags, coins):
    coin_to_bag = {}
    print(bags)
    print('\n')
    print (coins)
    print('\n')
    for bag in bags:
        print('For bag: ' + bag )
        coin_type = input('\nWhich coin do you want to put in this bag? ')  #e.g. 0.25 * 2
        coin_amount = input('\nNumber of this type? ')  #e.g. 0.25 * 2
        mattress_status = 'stuffed'
        for coin in coins:
            coin_to_bag[bag] = [coin_type, coin_amount, mattress_status]
    print(coin_to_bag)
    return (coin_to_bag)

def main():
    bags = gather_bag()
    coins = gather_coin()
    coins_in_the_bag = assign_coin_to_bag(bags, coins)
    total_money = show_total(bags, coins, coin_to_bag)

main()

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

coin_to_bagassign_coin_to_bag范围内定义,无法在main中访问。您在assign_coin_to_bag中获得了coins_in_the_bag的返回值,并且需要在调用show_total时使用该变量。

新编程人员犯了一个常见错误,他们认为变量的名称在任何地方都需要相同,即使是跨方法也是如此。实际上,变量的名称对计算机来说绝对没有任何意义。好名字只适用于人类。

作为练习,我们曾经让学生跟踪这样的代码:

def foo(one, three, two):
  print "%s %s %s" % (one, two, three)

def bar():
  return 1, 2, 4

three, two, one = bar()
foo(two, one, three)

弄清楚打印的内容,这是打破变量命名习惯的好习惯。