นับประเภทของเครื่องบิน
ในแบบฝึกหัดนี้ มี dictionary ชื่อ aircraft_engines ที่เก็บข้อมูลประเภทเครื่องยนต์ของเครื่องบินพาณิชย์ยอดนิยมหลายรุ่น โดยต้องการนับว่ามีเครื่องบินประเภทเครื่องยนต์ละกี่ลำในชุดข้อมูลนี้ ให้ใช้ทักษะ control flow ของ Python สร้าง for loop ที่มีคำสั่ง if/else เพื่อเพิ่มค่า 1 ให้กับตัวแปร counts สำหรับทุกประเภทเครื่องยนต์ที่พบ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python สำหรับผู้ใช้ MATLAB
คำแนะนำการฝึกหัด
- เขียน for loop เพื่อวนซ้ำผ่านคู่ key:value แต่ละคู่ใน
airplane_types - ในแต่ละรอบของการวนซ้ำ ให้พิมพ์ข้อความว่า "The x airplane has y engines." โดย x คือชื่อเครื่องบิน และ y คือประเภทเครื่องยนต์
- ในแต่ละรอบ ให้เพิ่มค่าของ key engine_type ใน dictionary
counts - สุดท้าย ให้พิมพ์ dictionary "counts" ออกมา
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
counts = {}
# Loop over the key:value pairs in airplane_types
for airplane, engine_type in ____.items():
# Print the aircraft name and engine type of each aircraft
print("The {} airplane has {} engines.".format(____, ____))
# Increment the values of the engine_type key in the counts dictionary
if engine_type in counts:
counts[engine_type] = ____[engine_type] + 1
else:
counts[engine_type] = 1
print(____)