Python - 测试列表中给定范围的所有偶数元素
当需要在给定范围内测试列表中的所有偶数元素时,使用简单的迭代和模运算符。
以下是相同的演示-
示例
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'并且控制中断循环。
根据布尔值,在控制台上显示相关消息。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短