定义一个名为 myfunc() 的函数,该函数接受任意参数并在参数为偶数时返回参数列表。下面是我写的代码
def myfunc(*args):
if args%2==0:
return list(args)
else:
pass
错误是:
unsupported operand type(s) for %: 'tuple' and 'int'
但我在我的代码中找不到错误。
请帮忙!!
定义一个名为 myfunc() 的函数,该函数接受任意参数并在参数为偶数时返回参数列表。下面是我写的代码
def myfunc(*args):
if args%2==0:
return list(args)
else:
pass
错误是:
unsupported operand type(s) for %: 'tuple' and 'int'
但我在我的代码中找不到错误。
请帮忙!!
*args是一个参数元组。您不能直接对其使用模数。此外,如果您返回一些东西,您应该在所有情况下都返回一些东西。
如果传递了偶数个参数,这将返回列表中的参数:
def myfunc(*args):
if len(args) % 2 == 0:
return list(args)
return None
这将只返回偶数的参数:
def myfunc(*args):
return [x for x in args if x % 2 == 0]
如果您需要所有参数是偶数,那么您可以尝试:
def myfunc(*args):
# Check all args are ints. Could allow other types if needed
if not all([isinstance(a, int) for a in args]):
return
if all([a%2 == 0 for a in args]):
return list(args)
return
这给出了以下内容:
myfunc(2,4,'a',8)
> None
myfunc(2,4,6,8)
> [2,4,6,8]
myfunc(2,4,5,8)
> None