Python Can';t通过循环向变量添加两个变量

Python Can';t通过循环向变量添加两个变量,python,addition,Python,Addition,计算总金额,以下是我的代码: {'sm': ['q', 0.25, 1000], 'Bug Out Bag': ['q', 0.25, 100000000]} 问题是,当我运行它时,它什么也不返回 如果int(single_或all_total)==1,我可以让我的代码命中,但是如果我输入2,它根本不会崩溃,它不会返回任何东西 我只是想在包中循环查看硬币,同时将每个值添加到总计变量中: (coins\u in__u袋子[单个袋子][1]*coins\u in_袋子[单个袋子][2])但它没有输

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

{'sm': ['q', 0.25, 1000], 'Bug Out Bag': ['q', 0.25, 100000000]}
问题是,当我运行它时,它什么也不返回

如果int(single_或all_total)==1,我可以让我的代码命中
,但是如果我输入
2
,它根本不会崩溃,它不会返回任何东西

我只是想在包中循环查看
硬币,同时将每个
值添加到
总计
变量中:
(coins\u in__u袋子[单个袋子][1]*coins\u in_袋子[单个袋子][2])
但它没有输出任何东西

我做错了什么

更新错误

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)

你从来没有击中你怀疑的环

从您使用的
print
函数(以及对
single\u或\u all\u total
的转换),我将推断您使用的是Python 3

然后,
input
返回一个简单字符串,就像Python 2中的
raw\u input
一样

您将
int(single\u或\u all\u total)
1
(这很好,而且有效),然后将
single\u或\u all\u total
2
进行比较。请注意,第二个版本忽略了对数字的转换,
single\u或\u all\u total
中的字符串永远不会等于
2
,只有
“2”


相反,尝试一下
elif int(single\u或\u all\u total)==2
elif single\u或\u all\u total==“2”

好的捕获,尽管这并不能完全解决所有问题。您能看看上面更新的错误吗,它仍然与这个“总计”变量有关。
total
尚未定义。尝试将
total=0
放在循环之前请查看更新,现在给我。total+=coins\u in\u the\u bag[single\u bag\u total][1]*coins\u in\u bag[single\u bag\u total][2]键错误:0我不知道您的确切数据,所以这主要是猜测,但从
if
语句的顶部分支来看,我建议您尝试使用
coin
而不是
single\u bag\u total
(因为
coin
迭代的值与上面的
single\u bag\u total
迭代的值相同)
    total += coins_in_the_bag[single_bag_total][1] * coins_in_the_bag[single_bag
_total][2]
UnboundLocalError: local variable 'total' referenced before assignment