无法通过循环将两个变量添加到变量

Can't add two variables via a loop to a variable

{'sm': ['q', 0.25, 1000], 'Bug Out Bag': ['q', 0.25, 100000000]}

计算总金额,这是我的代码:

single_or_all_total = input('\nDo you want 1 bag or all the bags? (type: 1 for 1 bag, 2 for all bags)\n')
#calculate for a single bag
if int(single_or_all_total) == 1:
    single_bag_total = input('\nWhich bag? (e.g. type: small for the "small" bag)\n')
    if single_bag_total in coins_in_the_bag:
        total = coins_in_the_bag[single_bag_total][1] * coins_in_the_bag[single_bag_total][2]
        print('The total for bag {} was {}'.format(single_bag_total, total))
        #print(total)
    elif single_bag_total not in coins_in_the_bag:
        print('Sorry, this was not a valid bag. Please re-run file.')
    else:
        print('An error occurred, please re-run script.')

#calculate total for all bags
elif single_or_all_total == 2:
    total=0
    single_bag_total=0
    for coin in coins_in_the_bag:
        total += coins_in_the_bag[single_bag_total][1] * coins_in_the_bag[single_bag_total][2]
    print(total)

问题是,当我 运行 这个时,它 return 什么都没有。

我可以让我的代码达到 if int(single_or_all_total) == 1:,但如果我输入 2 它根本不会崩溃,它只是 return 什么都没有。

我只是想遍历 coins_in_the_bag,同时将每个 value 添加到 total var: ( coins_in_the_bag[single_bag_total][1] * coins_in_the_bag[single_bag_total][2] ) 但它没有输出任何东西。

我做错了什么?

更新错误

    total += coins_in_the_bag[single_bag_total][1] * coins_in_the_bag[single_bag
_total][2]
UnboundLocalError: local variable 'total' referenced before assignment

您从未遇到您怀疑的循环。

根据您将 print 作为函数使用(以及您对 single_or_all_total 的转换),我将推断您正在使用 Python 3.

然后,input returns一个简单的字符串,就像Python中的raw_input 2.

您将 int(single_or_all_total)1 进行比较(很好,并且有效),然后将 single_or_all_total2 进行比较。请注意,第二个版本没有转换为数字 - single_or_all_total 中的字符串永远不会等于 2,只会等于 "2".

相反,尝试 elif int(single_or_all_total) == 2elif single_or_all_total == "2"