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 ให้ตรวจสอบว่า
- ตรวจสอบความเป็น truthy ของ key
trackedในpenguin_305_details- ถ้าเป็น truthy ให้ตรวจสอบว่า
trackedคือTrueหรือไม่ แล้วเก็บผลลัพธ์ไว้ในตัวแปรtracked_is_true - แสดงผล key
trackedและtracked_is_true
- ถ้าเป็น truthy ให้ตรวจสอบว่า
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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"{____['____']}: {____}")