简体   繁体   中英

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

I am trying to write a function that takes in a list of integers and returns the sum of all the even numbers in the list

Here is my code:

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

However, when I try to run this code I get the following error:

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

Your code seems fine. I guess you are having problems because the values in your list are probably not numbers and are strings. Check the type of values in your list and convert them to int or float.

The error you are seeing occurs when you try to use the modulo operator (%) on a string and an integer . This error indicates that you are trying to perform the modulo operation on a string value, which is not supported.

To fix this error, you need to make sure that the values in the numbers list are all integers. You can do this by using the int() function to convert the values to integers before trying to perform the modulo operation.

def sum_evens(numbers):
    total = 0
    for num in numbers:
        # Convert the value to an integer before performing the modulo operation
        if int(num) % 2 == 0:
            total += int(num)
    return total

def abc(num): s=0 for i in list: if i%2==0: s+=i print(s) abc(num)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM