Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – ทดสอบสมาชิกคู่ทั้งหมดในช่วงที่กำหนด

เมื่อต้องการทดสอบว่าสมาชิกทุกตัวในช่วงดัชนีที่กำหนดเป็นเลขคู่ทั้งหมดหรือไม่ สามารถใช้ลูป iteration และตัวดำเนินการ modulus ได้

ตัวอย่าง

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 (รวม)

  • ตั้ง flag my_result = True

  • วนลูปดัชนี i ถึง j ตรวจสอบ my_list[index] % 2 ถ้าไม่เท่ากับ 0 (คี่) ตั้ง flag=False break

  • แสดงข้อความตาม flag (ในตัวอย่างมี 61 และ 19 เป็นคี่ จึงไม่ผ่าน)