类型错误: %: 'str' 和 'int' 的操作数类型不受支持的操作数



我正在尝试编写一个函数,该函数接受整数列表并返回列表中所有偶数的总和

下面是我的代码:
def sum_evens(numbers):
total = 0
for num in numbers:
if num % 2 == 0:
total += num
return total

然而,当我尝试运行这段代码时,我得到以下错误:

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

您的代码看起来不错。我猜你有问题,因为你的列表中的值可能不是数字,而是字符串。检查列表中值的类型,并将其转换为int或float。

当您尝试在字符串上使用模运算符(%)时,您看到的错误发生aninteger. 此错误表明您正在尝试对字符串值执行模操作,该操作不受支持。

要修复此错误,需要确保数字列表中的值都是整数。在尝试执行取模操作之前,您可以通过使用int()函数将值转换为整数来实现这一点。

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

defabc (num):s = 0对于list中的I:如果我% 2 = = 0:+ =我打印(s)abc (num)

相关内容

最新更新