当需要在给定范围内测试列表中的所有偶数元素时,使用简单的迭代和模运算符。
以下是相同的演示 -
my_list = [32, 12, 42, 61, 58, 60, 19, 16] print("名单是:") 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("结果是:") if(my_result == True): print("All The elements are in the given range") else: print("All The elements are not in the given range")输出结果
名单是: [32, 12, 42, 61, 58, 60, 19, 16] 结果是: All The elements are not in the given range
一个列表被定义并显示在控制台上。
'i' 和 'j' 的值已定义。
变量的值设置为布尔值“True”。
遍历列表,对每个元素使用模运算符来检查它是偶数还是奇数。
如果是偶数,则布尔值设置为 'False' 并且控制中断循环。
根据布尔值,在控制台上显示相关消息。