函数中定义的变量引发名称错误:在main中使用时未定义全局名称

2024-04-19 05:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图运行我的函数: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

我的代码看起来是:

^{pr2}$

谢谢你的帮助!在


Tags: to函数inpymostmainshow错误
1条回答
网友
1楼 · 发布于 2024-04-19 05:33:45

coin_to_bag是在assign_coin_to_bag范围内定义的,在main中不可访问。您在coins_in_the_bag中捕获了assign_coin_to_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)

找出打印出来的是什么,这将是一个很好的实践来打破变量命名的习惯。在

相关问题 更多 >