Home > Net >  Python: Unsupported operand type(s) for =: 'int' and 'str'
Python: Unsupported operand type(s) for =: 'int' and 'str'

Time:12-28

I am trying to implement a function in Python that will take a list of integers as input and return the sum of all the even numbers in the list. I have written the following code, but it is giving me an error when I try to run it.

def sum_evens(numbers):
    result = 0
    for num in numbers:
        if num % 2 == 0:
            result  = num
    return result

print(sum_evens([1, 2, 3, 4, 5]))

The error message I am getting is:

TypeError: unsupported operand type(s) for  =: 'int' and 'str'.

Can someone please help me understand why this error is occurring and how I can fix it?

CodePudding user response:

Your code works fine on my computer. However, guessing by your error message, num must be a string. You can fix this by converting it to an integer beforehand:

def sum_evens(numbers):
    result = 0
    for num in numbers:
        # convert to integer
        num = int(num)

        if num % 2 == 0:
            result  = num
    return result

CodePudding user response:

Another alternative using the list comprehension concept (functional paradigm):

def sum_events(numbers):
  return sum(num for num in numbers if int(num) % 2 == 0)
  • Related