函数计算错误,返回0而不是500k,我做错了什么?

时间:2013-12-29 15:09:45

标签: python python-3.x

我该如何解决这个问题?

pricec = {
    "Case" : 56950,
    "PSU" : 48950,
    "Mobo" : 59500,
    "GPU" : 124990,
    "Memory" : 57800,
    "CPU" : 53900,
    "SSD" : 99900,
    "Cooling" : 0
}

total = 0

def pricet(total, pricec):
    for x in pricec:
        total += pricec[x]
        return total
pricet(total, pricec)

print ("Build Cost: " + str(total)+"kr")

1 个答案:

答案 0 :(得分:5)

您没有从pricet()函数的返回值设置总变量。

pricec = {
    "Case" : 56950,
    "PSU" : 48950,
    "Mobo" : 59500,
    "GPU" : 124990,
    "Memory" : 57800,
    "CPU" : 53900,
    "SSD" : 99900,
    "Cooling" : 0
}

def pricet(pricec):
    total = 0
    for x in pricec:
        total += pricec[x]
    return total

total = pricet(pricec)

print("Build Cost: " + str(total) + "k")

此外,有一种更简单的方法来对词典的值进行求和而不是循环:

def pricet(pricec):
    return sum(pricec.values())