我正在尝试运行我的功能: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()
感谢您的帮助!
答案 0 :(得分:3)
coin_to_bag
在assign_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)
弄清楚打印的内容,这是打破变量命名习惯的好习惯。