所有数字总是被检测为奇数

  • 本文关键字:数字 python python-3.x
  • 更新时间 :
  • 英文 :

def is_list_even(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 1:
return False
else:
return True
def is_list_odd(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 0:
return False
else:
return True
if __name__ == '__main__':
my_list = [1, 2, 3, 4]
if is_list_even(my_list):
print("all even")
elif is_list_odd(my_list):
print("all odd")
else:
print("not even or odd")

我试图得到特定的输出"不是偶数或奇数"但它只显示为"全是奇数"。我已经看了一段时间了,想知道是否有人能帮我看看我在哪里犯了错误。

你太早回来了:

def is_list_even(my_list):
for i in range(len(my_list)):
if my_list[i] % 2 == 1:
return False
return True  # only once you checked all of them, you know that!

同样,通常不需要使用索引。Python的for循环已经是for-each循环了:

def is_list_odd(my_list):
for x in my_list:
if x % 2 == 0:
return False
return True

用于该短路习惯用法的内置实用程序是anyall:

def is_list_even(my_list):
return not any(x % 2 == 1 for x in my_list)
# return all(x % 2 == 0 for x in my_list)
def is_list_odd(my_list):
return not any(x % 2 == 0 for x in my_list)
# return all(x % 2 == 1 for x in my_list)

最新更新