【问题标题】:main() function will not output value for coin_to_bagmain() 函数不会输出 coin_to_bag 的值
【发布时间】:2015-12-04 17:46:07
【问题描述】:

我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".\file.py", line 113, in <module>
    main()
  File ".\file.py", line 111, in main
    cs_in_the_b = assign_c2b(bs, cs, c2b)
NameError: global name 'c2b' is not defined

当我运行我的代码时:

cs = ['quarter','dime','nickel']
bs = ['sm','med','lg']

def assign_c2b(bs, cs):
    '''
    assign_c2b() assigns cs to bs
    specifically c2b{} stores this association between the c and b
    '''
    c2b = {}#'test'}
    print('Here are your bs:\n')
    print(bs)
    print('\n')
    print('Here are your c types:\n')
    print (cs)

    for b in bs:
        c_type = input('Number of this type?    e.g. type 1 for Quarter "["Quarter", "Nickel"]" ')  #e.g. 0.25 * 2
        c_amount = input('Number of this type?  e.g. 15')  #e.g. 0.25 * 2
        for c in cs:
            c2b[b] = [c_type, c_amount]

    print(c2b)

    return (c2b)


def main():
    bs = gather_b()
    cs = gather_c()
    cs_in_the_b = assign_c2b(bs, cs, c2b)

main()

我只是想让我的 var c2bmain() 中调用时显示一些东西。也许我完全忽略了原因,但还没有弄清楚。有人可以帮忙吗?谢谢!!

【问题讨论】:

  • 您的 assign_coin_to_bag 函数,按照定义,只接受 2 个参数,但您在 main() 中传递了 3 个参数。我怀疑您实际上并不想要第三个参数,因为该函数似乎在构造您的字典。
  • 只有bscsmain 中定义,c2b 应该来自assign_c2b 调用中的哪里?

标签: python dictionary main


【解决方案1】:
def main():
    bags = gather_bag()
    coins = gather_coin()
    coins_in_the_bag = assign_coin_to_bag(bags, coins, coin_to_bag)

coin_to_bag 在调用 assign_coin_to_bag 时从未定义。

即使已定义,assign_coin_to_bag 也需要 2 个参数(def assign_coin_to_bag(bags, coins) 但您尝试使用 3 来调用它。

【讨论】:

  • 哇,这真的很有帮助。我想我已经看这个太久了。再次感谢@DeepSpace
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
相关资源
最近更新 更多