🚀 โครงสร้างโปรแกรม Python

เรียนรู้การใช้ Lists, Dictionaries, Functions, Classes และการจัดการข้อผิดพลาด

📋Lists - ลิสต์

List
ลิสต์ - รายการข้อมูลที่เรียงลำดับและเปลี่ยนแปลงได้
ลิสต์เป็นโครงสร้างข้อมูลที่ใช้เก็บหลายค่าไว้ด้วยกัน สามารถเพิ่ม ลบ หรือแก้ไขข้อมูลได้ ใช้วงเล็บเหลี่ยม [ ]

การสร้างและใช้งาน List

# สร้าง list fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม"] numbers = [1, 2, 3, 4, 5] mixed = ["ข้อความ", 42, 3.14, True] # เข้าถึงข้อมูล (index เริ่มที่ 0) print(fruits[0]) # แอปเปิ้ล print(fruits[-1]) # ส้ม (ตัวสุดท้าย) # เพิ่มข้อมูล fruits.append("มะม่วง") fruits.insert(1, "ทุเรียน") # แทรกที่ตำแหน่งที่ 1 # ลบข้อมูล fruits.remove("กล้วย") deleted = fruits.pop() # ลบตัวสุดท้าย # วนลูปใน list for fruit in fruits: print(f"ผลไม้: {fruit}") # ตรวจสอบความยาว print(len(fruits)) # จำนวนข้อมูลใน list

🧪 ทดลองใช้ List

ลิสต์ว่างเปล่า: []

📚Dictionaries - ดิกชันนารี

Dictionary
ดิกชันนารี - ข้อมูลแบบคู่ของ Key และ Value
ดิกชันนารีเก็บข้อมูลเป็นคู่ของ "กุญแจ" (key) และ "ค่า" (value) ทำให้สามารถเรียกข้อมูลด้วยชื่อได้ ใช้ปีกกา { }

การสร้างและใช้งาน Dictionary

# สร้าง dictionary student = { "name": "สมชาย", "age": 20, "grade": "A", "subjects": ["คณิต", "วิทย์"] } # เข้าถึงข้อมูล print(student["name"]) # สมชาย print(student.get("age")) # 20 # เพิ่มหรือแก้ไขข้อมูล student["email"] = "[email protected]" student["age"] = 21 # ลบข้อมูล del student["grade"] # วนลูป for key, value in student.items(): print(f"{key}: {value}") # ตรวจสอบว่ามี key หรือไม่ if "name" in student: print("มีข้อมูลชื่อ")

🔀If Statements - การตรวจสอบเงื่อนไข

If/Elif/Else
คำสั่งเงื่อนไข - ใช้ตัดสินใจว่าจะทำอะไร
if ใช้ตรวจสอบเงื่อนไข, elif (else if) ใช้ตรวจสอบเงื่อนไขเพิ่มเติม, else ใช้กรณีที่ไม่ตรงเงื่อนไขใดๆ

การใช้งาน If/Elif/Else

# If statement พื้นฐาน age = 18 if age >= 18: print("คุณเป็นผู้ใหญ่") else: print("คุณยังเป็นเด็ก") # If/Elif/Else หลายเงื่อนไข score = 75 if score >= 80: grade = "A" elif score >= 70: grade = "B" elif score >= 60: grade = "C" elif score >= 50: grade = "D" else: grade = "F" print(f"เกรดของคุณคือ: {grade}") # เงื่อนไขซับซ้อน (and, or, not) temperature = 28 is_raining = False if temperature > 30 and not is_raining: print("อากาศร้อนและไม่มีฝน") elif temperature <= 30 or is_raining: print("อากาศเย็นหรือมีฝน")
⚠️ อย่าลืม: หลังเงื่อนไข if, elif ต้องมีเครื่องหมาย : เสมอ และโค้ดด้านในต้องเยื้อง (indent)

🔄While Loops - การวนลูปแบบมีเงื่อนไข

While Loop
วนลูปแบบ While - ทำซ้ำจนกว่าเงื่อนไขจะเป็นเท็จ
While loop จะทำซ้ำตราบใดที่เงื่อนไขยังเป็นจริง ต้องระวังไม่ให้เกิด infinite loop (วนซ้ำไม่รู้จบ)

การใช้งาน While Loop

# While loop พื้นฐาน count = 1 while count <= 5: print(f"รอบที่ {count}") count += 1 # เพิ่มค่า count ไป 1 # ใช้ break เพื่อหยุดลูป number = 0 while True: number += 1 if number > 10: break # หยุดลูป print(number) # ใช้ continue เพื่อข้ามรอบนั้น i = 0 while i < 10: i += 1 if i % 2 == 0: continue # ข้ามเลขคู่ print(f"เลขคี่: {i}")
❌ ระวัง Infinite Loop:
# ❌ อันตราย - วนซ้ำไม่รู้จบ while True: print("วนไม่หยุด!") # ไม่มี break หรือเงื่อนไขหยุด

⚙️Functions - ฟังก์ชัน

Function
ฟังก์ชัน - ชุดคำสั่งที่ใช้ซ้ำได้
ฟังก์ชันคือกลุ่มโค้ดที่ทำงานเฉพาะเรื่อง สามารถรับค่าเข้า (parameters) และส่งค่าออก (return) ใช้คำว่า def

การสร้างฟังก์ชัน

# ฟังก์ชันพื้นฐาน def say_hello(): print("สวัสดีครับ") say_hello() # เรียกใช้ฟังก์ชัน # ฟังก์ชันที่รับ parameters def greet(name): print(f"สวัสดี {name}") greet("สมชาย") greet("สมหญิง") # ฟังก์ชันที่มี default value def introduce(name, age=18): print(f"ฉันชื่อ {name} อายุ {age} ปี") introduce("สมชาย") # ใช้ค่า default age=18 introduce("สมหญิง", 25) # ระบุ age=25

⭐ Return Statement - การคืนค่า

✅ ฟังก์ชันควรมี return เสมอ
แม้ว่า Python จะไม่บังคับ แต่การใส่ return ทำให้โค้ดชัดเจนว่าฟังก์ชันส่งอะไรกลับ หากไม่มี return ฟังก์ชันจะส่ง None กลับ

✅ มี Return (แนะนำ)

def add(a, b): result = a + b return result total = add(5, 3) print(total) # 8

❌ ไม่มี Return

def add(a, b): result = a + b print(result) # ไม่มี return total = add(5, 3) print(total) # None
# ตัวอย่างฟังก์ชันที่มี return ที่ดี def calculate_area(width, height): """คำนวณพื้นที่สี่เหลี่ยม""" area = width * height return area def is_even(number): """ตรวจสอบว่าเป็นเลขคู่หรือไม่""" if number % 2 == 0: return True return False def get_grade(score): """คำนวณเกรดจากคะแนน""" if score >= 80: return "A" elif score >= 70: return "B" elif score >= 60: return "C" else: return "F" # การใช้งาน my_area = calculate_area(10, 5) print(f"พื้นที่: {my_area}") if is_even(4): print("เป็นเลขคู่") student_grade = get_grade(85) print(f"เกรด: {student_grade}")

🏗️Classes - คลาส

Class
คลาส - พิมพ์เขียวสำหรับสร้างวัตถุ (Object)
คลาสคือแม่แบบสำหรับสร้าง object ที่มีคุณสมบัติ (attributes) และพฤติกรรม (methods) ช่วยจัดระเบียบโค้ดแบบ Object-Oriented Programming (OOP)

การสร้างและใช้งาน Class

# สร้าง class class Student: # Constructor - ฟังก์ชันเริ่มต้น def __init__(self, name, age): self.name = name # attribute self.age = age self.grades = [] # Method - ฟังก์ชันภายใน class def introduce(self): return f"ฉันชื่อ {self.name} อายุ {self.age} ปี" def add_grade(self, grade): self.grades.append(grade) return f"เพิ่มเกรด {grade} แล้ว" def get_average(self): if len(self.grades) == 0: return 0 return sum(self.grades) / len(self.grades) # สร้าง object จาก class student1 = Student("สมชาย", 20) student2 = Student("สมหญิง", 21) # ใช้งาน methods print(student1.introduce()) student1.add_grade(85) student1.add_grade(90) student1.add_grade(78) print(f"คะแนนเฉลี่ย: {student1.get_average()}")
💡 ทำไมต้องใช้ self?
self หมายถึง object ตัวนั้นๆ ทำให้แต่ละ object มีข้อมูลของตัวเองที่แยกกัน

🛡️Error Handling - การจัดการข้อผิดพลาด

Try/Except/Finally
Try/Except - จัดการข้อผิดพลาดไม่ให้โปรแกรมหยุดทำงาน
Try ใช้ลองรันโค้ดที่อาจเกิด error, Except จับ error ที่เกิดขึ้น, Finally รันโค้ดไม่ว่าจะมี error หรือไม่

การใช้ Try/Except

# ตัวอย่างพื้นฐาน try: number = int(input("ใส่ตัวเลข: ")) result = 100 / number print(f"ผลลัพธ์: {result}") except ValueError: print("❌ กรุณาใส่ตัวเลขเท่านั้น") except ZeroDivisionError: print("❌ ไม่สามารถหารด้วย 0 ได้") except Exception as e: print(f"❌ เกิดข้อผิดพลาด: {e}") # ใช้ Finally try: file = open("data.txt", "r") content = file.read() print(content) except FileNotFoundError: print("❌ ไม่พบไฟล์") finally: if 'file' in locals(): file.close() print("✅ ปิดไฟล์แล้ว")

ฟังก์ชันที่มีการจัดการ Error

def safe_divide(a, b): """หารเลขอย่างปลอดภัย""" try: result = a / b return result except ZeroDivisionError: print("❌ ไม่สามารถหารด้วย 0") return None except TypeError: print("❌ กรุณาใส่ตัวเลข") return None def get_list_item(items, index): """เข้าถึง list อย่างปลอดภัย""" try: return items[index] except IndexError: print(f"❌ ไม่มี index {index} ใน list") return None except TypeError: print("❌ index ต้องเป็นตัวเลข") return None # การใช้งาน print(safe_divide(10, 2)) # 5.0 print(safe_divide(10, 0)) # None + warning fruits = ["แอปเปิ้ล", "กล้วย"] print(get_list_item(fruits, 0)) # แอปเปิ้ล print(get_list_item(fruits, 10)) # None + warning
ลอง (Try)
เกิด Error?
จัดการ (Except)
จบ (Finally)

🧪Testing - การทดสอบโปรแกรม

Unit Testing
การทดสอบหน่วย - ทดสอบฟังก์ชันแต่ละตัว
Unit testing คือการเขียนโค้ดเพื่อทดสอบว่าฟังก์ชันทำงานถูกต้องหรือไม่ ช่วยตรวจจับ bug ก่อนเข้า production

การเขียน Test ด้วย assert

# ฟังก์ชันที่จะทดสอบ def add(a, b): return a + b def multiply(a, b): return a * b def is_positive(number): return number > 0 # เขียน test cases def test_add(): """ทดสอบฟังก์ชัน add""" assert add(2, 3) == 5, "2+3 ควรได้ 5" assert add(-1, 1) == 0, "-1+1 ควรได้ 0" assert add(0, 0) == 0, "0+0 ควรได้ 0" print("✅ test_add ผ่านทุก test") def test_multiply(): """ทดสอบฟังก์ชัน multiply""" assert multiply(2, 3) == 6 assert multiply(5, 0) == 0 assert multiply(-2, 3) == -6 print("✅ test_multiply ผ่านทุก test") def test_is_positive(): """ทดสอบฟังก์ชัน is_positive""" assert is_positive(5) == True assert is_positive(-5) == False assert is_positive(0) == False print("✅ test_is_positive ผ่านทุก test") # รัน tests def run_all_tests(): print("🧪 เริ่มทดสอบ...") test_add() test_multiply() test_is_positive() print("🎉 ผ่านทุก test!") run_all_tests()

การทดสอบ Class

class Calculator: def __init__(self): self.result = 0 def add(self, value): self.result += value return self.result def reset(self): self.result = 0 return self.result def test_calculator(): """ทดสอบ Calculator class""" calc = Calculator() # ทดสอบ add assert calc.add(5) == 5, "เพิ่ม 5 ควรได้ 5" assert calc.add(3) == 8, "เพิ่ม 3 ควรได้ 8" # ทดสอบ reset assert calc.reset() == 0, "reset ควรได้ 0" print("✅ Calculator ทำงานถูกต้อง") test_calculator()
✅ กฎการเขียน Test ที่ดี:
  1. แต่ละ test ควรทดสอบสิ่งเดียว
  2. ตั้งชื่อ test ให้บอกว่าทดสอบอะไร
  3. ทดสอบทั้ง case ปกติและ edge cases
  4. Test ควร independent - ไม่ขึ้นกับ test อื่น
  5. เขียน test ก่อนแก้ bug จะช่วยป้องกันไม่ให้ bug กลับมา

🐛Debugging - การแก้ไขข้อผิดพลาด

Debugging
ดีบัก - การหาและแก้ไขข้อผิดพลาด (Bug)
Debugging คือกระบวนการหาสาเหตุของข้อผิดพลาดและแก้ไข ใช้เทคนิคต่างๆ เช่น print, breakpoint, หรือ debugger

เทคนิคการ Debug

1. ใช้ print() ตรวจสอบค่า

def calculate_average(numbers): print(f"🔍 Debug: รับ numbers = {numbers}") total = 0 for num in numbers: print(f"🔍 Debug: กำลังบวก {num}, total = {total}") total += num print(f"🔍 Debug: total สุดท้าย = {total}") count = len(numbers) print(f"🔍 Debug: จำนวน = {count}") average = total / count print(f"🔍 Debug: ค่าเฉลี่ย = {average}") return average result = calculate_average([10, 20, 30]) print(f"ผลลัพธ์: {result}")

2. ตรวจสอบ Type และ Value

def debug_variable(var, name="variable"): """แสดงข้อมูลของตัวแปร""" print(f"\n=== Debug {name} ===") print(f"Type: {type(var)}") print(f"Value: {var}") print(f"Length: {len(var) if hasattr(var, '__len__') else 'N/A'}") print("=================\n") # ตัวอย่างการใช้ my_list = [1, 2, 3] my_dict = {"name": "สมชาย", "age": 25} my_string = "Hello" debug_variable(my_list, "my_list") debug_variable(my_dict, "my_dict") debug_variable(my_string, "my_string")

3. Common Errors - ข้อผิดพลาดที่พบบ่อย

❌ IndentationError - การเยื้องผิด
# ❌ ผิด def hello(): print("สวัสดี") # ไม่ได้เยื้อง # ✅ ถูก def hello(): print("สวัสดี")
❌ NameError - ใช้ตัวแปรที่ไม่มี
# ❌ ผิด print(x) # x ยังไม่ได้ถูกสร้าง # ✅ ถูก x = 10 print(x)
❌ TypeError - ใช้ type ผิด
# ❌ ผิด result = "10" + 5 # ไม่สามารถบวก string กับ number # ✅ ถูก result = int("10") + 5 # แปลง string เป็น int ก่อน result = "10" + str(5) # หรือแปลง number เป็น string
❌ IndexError - เข้าถึง index ที่ไม่มี
# ❌ ผิด my_list = [1, 2, 3] print(my_list[5]) # มีแค่ index 0-2 # ✅ ถูก - ตรวจสอบก่อน if 5 < len(my_list): print(my_list[5]) else: print("Index เกินขนาด")
💡 เคล็ดลับการ Debug:
  • อ่าน error message ให้ดี มันบอกว่าผิดที่บรรทัดไหน
  • ใช้ print() ตรวจสอบค่าตัวแปรในจุดต่างๆ
  • แบ่งโค้ดเป็นส่วนเล็กๆ ทดสอบทีละส่วน
  • Comment โค้ดออกทีละส่วนเพื่อหาว่าส่วนไหนมีปัญหา
  • ใช้ Google หา error message - มักจะมีคนเจอปัญหาเดียวกัน

🎮ทดลองเขียนและทดสอบ

สร้างฟังก์ชันคำนวณเกรด

ลองสร้างฟังก์ชันที่รับคะแนนและคืนเกรด:

พิมพ์คะแนนแล้วกดปุ่ม...