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

2024-09-27 21:34:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能解决这个问题?你知道吗

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")

Tags: inforreturngpudefcpupsutotal
1条回答
网友
1楼 · 发布于 2024-09-27 21:34:33

您没有从pricet()函数的返回值设置total变量。你知道吗

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())

相关问题 更多 >

    热门问题