Python – 在给定范围内针对列表中的所有偶数元素进行测试


当需要测试给定范围内的列表中的所有偶数元素时,将使用简单的迭代和取模运算符。

以下是同样的演示 -

示例

 在线示例

my_list = [32, 12, 42, 61, 58, 60, 19, 16]

print("The list is :")
print(my_list)

i, j = 2, 7

my_result = True
for index in range(i, j + 1):

   if my_list[index] % 2 :
      my_result = False
      break

print("The result is :")

if(my_result == True):
   print("All The elements are in the given range")
else:
   print("All The elements are not in the given range")

输出

The list is :
[32, 12, 42, 61, 58, 60, 19, 16]
The result is :
All The elements are not in the given range

解释

  • 在控制台上定义并显示一个列表。

  • 定义 ‘i’ 和 ‘j’ 的值。

  • 将变量的值设置为布尔值 ‘True’。

  • 对列表进行迭代,并在每个元素上使用取模运算符来检查它是偶数还是奇数。

  • 如果是偶数,则布尔值将设置为 ‘False’,并且控制会退出循环。

  • 根据布尔值,在控制台上显示相关消息。

更新于: 06-9 月-2021

126 次浏览

开启你的 职业生涯

完成课程认证

开始
广告
© . All rights reserved.