Automatically translated.View original post

🧮 Daily Python Problem: Let's come to average! 💖

Today, let's practice a very common problem in the Data world. This is the Daily Python Problem: Calculate Average!

Problem: Let us write a function named calculation _ average (number) that receives a list of numbers and returns the average of all the numbers in that list.

⚠️ Don't forget to handle the Edge Case!

The most important thing is the Edge Case or special case. If Input is an empty list [] and we try to divide by 0, our program will Error immediately! 😱

• Requirements: If the list is empty, return 0 (or None, whichever we define)

✨ Let's see two great ways to write.

1.Basic type (check len first):

• Check if len (number) = = 0. If yes, return 0.

• If you are busy, use the sum () function to take the sum and len () to take the number and divide it.

2. Pythonic (use if not numbers):

• This method is shorter and popular in Python because if not numbers: it means checking if len (numbers) = = 0:!

• If the list is busy, then calculate and return in one line. Very short and beautiful!

Example:

• Input: calculated _ average ([1, 2, 3, 4, 5])

• Output: 3.0

Try to practice. Edge Case management is an important skill that good developers need! Keep going. 🥰

# data # python # ai # programmer # learnonlemon8

2025/11/11 Edited to

... Read moreนอกจากวิธีพื้นฐานและวิธี Pythonic ที่แนะนำไปแล้ว การจัดการกับกรณีที่ List ว่างถือเป็นเรื่องสำคัญมากเพราะช่วยป้องกันโปรแกรมหยุดทำงานกลางคันด้วย Error เช่น ZeroDivisionError ที่เกิดจากการหารด้วยศูนย์ ผมเองชอบใช้วิธี if not numbers เพราะทำให้โค้ดสั้นและอ่านง่าย เวลาพัฒนาจริงๆ สิ่งนี้ช่วยให้เขียนฟังก์ชันได้รวดเร็วและลดโอกาสเกิดบั๊ก นอกจากนี้หากต้องการปรับให้ฟังก์ชันยืดหยุ่นขึ้น สามารถเพิ่มพารามิเตอร์เลือกวิธีจัดการกรณีพิเศษ เช่น return None หรือแจ้งเตือนผู้ใช้ก็ได้ สำหรับคนที่เริ่มหัดเขียนโปรแกรม แนะนำให้ลองเล่นกับ input ต่างๆ เช่น List ที่มีเลขลบ หรือตัวเลขจำนวนมาก เพื่อดูผลลัพธ์และทดสอบฟังก์ชันอย่างละเอียด การเข้าใจผลลัพธ์ในกรณีต่างๆ จะช่วยเพิ่มทักษะการเขียนและแก้ปัญหาโค้ดได้ดีขึ้นค่ะ สุดท้าย การฝึกเขียนและทดสอบฟังก์ชันแบบนี้เป็นประจำ จะทำให้คุ้นชินกับการจัดการข้อมูลและเพิ่มความมั่นใจในการพัฒนาซอฟต์แวร์อย่างมืออาชีพเลยครับ