在函数中定义的变量抛出NameError:在main中使用时未定义全局名称 [英] variable defined in a function throws NameError: global name not defined when used in main

查看:249
本文介绍了在函数中定义的变量抛出NameError:在main中使用时未定义全局名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行我的函数: show_total(),但我得到这个错误:

I'm trying to run my function: show_total() , but I get this error:

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

我的代码如下所示:

my code looks like:

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()

感谢您的帮助!

推荐答案

coin_to_bag assign_coin_to_bag 的范围,并且无法在 main 中进行访问。您在 coins_in_the_bag 中捕获了 assign_coin_to_bag 的返回值,并且需要在调用 show_total

coin_to_bag is a defined in the scope of assign_coin_to_bag, and is not accessible in main. You caught the return value of assign_coin_to_bag in coins_in_the_bag, and need to use that variable in your call to show_total.

新程序员做出一个常见错误,认为无论使用哪个变量,变量的名称都应该相同甚至跨越方法。事实上,变量的名称对计算机来说绝对没有任何意义。

There's a common error new programmers make, which is thinking the name of a variable needs to be the same wherever it's used, even across methods. In fact, the name of the variable means absolutely nothing to the computer. Good names are only there for humans.

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

As an exercise, we used to have students trace code like this:

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)

找出打印的内容,这将是一个很好的练习来打破变量命名习惯。

Figure out what gets printed, and that will be good practice to break the variable naming habit.

这篇关于在函数中定义的变量抛出NameError:在main中使用时未定义全局名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆