Python:通过函数打印列表中所有项目的总和

时间:2019-07-15 11:22:33

标签: python python-3.x list

我的目标:要通过功能查找并打印列表中所有项目的总和

我的代码:

def list_sum(x):
    if type(x)!='list':
        print("Invalid List item!")
    if type(x)=='list':
        list_length = len(x)
        total = 0
        i = 0
        for i in range (list_length):
            total +=x[i]
            i+=1
        print("The sum of all items in the list is: ",total)

samples = [1,3,5,6,8,45,67,89]

list_sum(samples)

我的输出:

<class 'list'>
Invalid List item!

预期: 224

为什么我会得到输出?

1 个答案:

答案 0 :(得分:1)

if type(x) != list

不是

if type(x) != 'list'