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.