주어진 범위에 대해 목록의 모든 짝수 요소를 테스트해야 하는 경우 간단한 반복 및 모듈러스 연산자가 사용됩니다.
아래는 동일한 데모입니다 -
예시
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'의 값이 정의됩니다.
-
변수 값은 Boolean 'True'로 설정됩니다.
-
목록은 반복되고 모듈러스 연산자는 각 요소에 사용되어 짝수인지 홀수인지 확인합니다.
-
짝수이면 Boolean 값이 'False'로 설정되고 컨트롤이 루프에서 벗어납니다.
-
Boolean 값에 따라 콘솔에 해당 메시지가 표시됩니다.