Search code examples
pythonlistfunctiondefinition

How can I sum an int with a list? TypeError: unsupported operand type(s) for +: 'int' and 'list'


First of all, I am a fresh student to python, so this might be easy, but I tried my best to research before asking here. Anyway, If I change "for tall in minListe" with " for minListe in [5, 2, -4, 2, -1, 0, 2, -2, 3, 0, 7]" it works, but that's not good enough... Anyone knows how to do this without having to include my list within the function?

total = 0

tall = 0

minListe = [5, 2, -4, 2, -1, 0, 2, -2, 3, 0, 7]

def funksjon2(total):

    total = 0 
    for tall in minListe:
        if minListe == 0:
            break
        total = total + minListe
    return (total)

def main():

    print(funksjon2(total))


if __name__ == "__main__":
    main(

)

Solution

  • If I understood your logic correctly, you are trying to do the following. Try the below code and drop a comment below if it works or not. I have added some comments where I have modified things

    minListe = [5, 2, -4, 2, -1, 0, 2, -2, 3, 0, 7]
    
    def funksjon2(minListe):
        total = 0
        for tall in minListe:
            if tall == 0: # Replaced minListe by tall
                break
            total = total + tall # # Replaced minListe by tall
        return (total)
    
    print(funksjon2(minListe))
    
    > 4 # Answer