เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Truthy, True, Falsey และ False

การเปรียบเทียบค่าจะตรวจสอบความเป็น truthy แต่การที่ค่าหนึ่งเป็น truthy ไม่ได้หมายความว่ามันคือ True เสมอไป และในทางกลับกัน ค่าที่เป็น falsey ก็ไม่ได้เท่ากับ False เสมอไปเช่นกัน ดังนั้นต้องระมัดระวังให้ดีเมื่อต้องการตรวจสอบว่าค่านั้นคือ True หรือ False จริงๆ หรือแค่เป็น truthy หรือ falsey เท่านั้น ใน Python มีตัวดำเนินการ is สำหรับตรวจสอบว่าสองสิ่งเป็นตัวเดียวกันหรือไม่

คราวนี้จะใช้ dictionary ที่บันทึกข้อมูลเพนกวิน ซึ่งมี key เดียวกับแบบฝึกหัดก่อนหน้า (species, flipper_length, body_mass, sex) พร้อมกับ key tracked ที่มีค่าเป็น boolean

โหลด dictionary ชื่อ penguin_305_details ที่มีข้อมูลของเพนกวินตัวหนึ่งไว้ให้แล้ว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

ประเภทข้อมูลใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ตรวจสอบความเป็น truthy ของ key sex ใน penguin_305_details
    • ถ้าเป็น truthy ให้ตรวจสอบว่า sex คือ True หรือไม่ แล้วเก็บผลลัพธ์ไว้ในตัวแปร sex_is_true
    • แสดงผล key sex และ sex_is_true
  • ตรวจสอบความเป็น truthy ของ key tracked ใน penguin_305_details
    • ถ้าเป็น truthy ให้ตรวจสอบว่า tracked คือ True หรือไม่ แล้วเก็บผลลัพธ์ไว้ในตัวแปร tracked_is_true
    • แสดงผล key tracked และ tracked_is_true

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Check the truthiness of penguin_305_details sex key
if ____["____"]:
	# If true, check if sex is True and store it as sex_is_true
    sex_is_true = penguin_305_details["sex"] ____ ____
    # Print the sex key's value and sex_is_true
    print(f"{____['____']}: {____}")

# Check the truthiness of penguin_305_details tracked key
if ____["____"]:
	# If true, check if tracked is True and store it as tracked_is_true
    tracked_is_true = penguin_305_details["tracked"] ____ ____
    # Print the tracked key and tracked_is_true
    print(f"{____['____']}: {____}")
แก้ไขและรันโค้ด