📋Lists - ลิสต์
List
ลิสต์ - รายการข้อมูลที่เรียงลำดับและเปลี่ยนแปลงได้
ลิสต์เป็นโครงสร้างข้อมูลที่ใช้เก็บหลายค่าไว้ด้วยกัน สามารถเพิ่ม ลบ หรือแก้ไขข้อมูลได้ ใช้วงเล็บเหลี่ยม [ ]
การสร้างและใช้งาน List
fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม"]
numbers = [1, 2, 3, 4, 5]
mixed = ["ข้อความ", 42, 3.14, True]
print(fruits[0])
print(fruits[-1])
fruits.append("มะม่วง")
fruits.insert(1, "ทุเรียน")
fruits.remove("กล้วย")
deleted = fruits.pop()
for fruit in fruits:
print(f"ผลไม้: {fruit}")
print(len(fruits))
📚Dictionaries - ดิกชันนารี
Dictionary
ดิกชันนารี - ข้อมูลแบบคู่ของ Key และ Value
ดิกชันนารีเก็บข้อมูลเป็นคู่ของ "กุญแจ" (key) และ "ค่า" (value) ทำให้สามารถเรียกข้อมูลด้วยชื่อได้ ใช้ปีกกา { }
การสร้างและใช้งาน Dictionary
student = {
"name":
"สมชาย",
"age":
20,
"grade":
"A",
"subjects": [
"คณิต",
"วิทย์"]
}
print(student[
"name"])
print(student.get(
"age"))
student[
"email"] =
"[email protected]"
student[
"age"] =
21
del student[
"grade"]
for key, value
in student.items():
print(
f"{key}
: {value}
")
if "name" in student:
print(
"มีข้อมูลชื่อ")
🔀If Statements - การตรวจสอบเงื่อนไข
If/Elif/Else
คำสั่งเงื่อนไข - ใช้ตัดสินใจว่าจะทำอะไร
if ใช้ตรวจสอบเงื่อนไข, elif (else if) ใช้ตรวจสอบเงื่อนไขเพิ่มเติม, else ใช้กรณีที่ไม่ตรงเงื่อนไขใดๆ
การใช้งาน If/Elif/Else
age = 18
if age >= 18:
print("คุณเป็นผู้ใหญ่")
else:
print("คุณยังเป็นเด็ก")
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}")
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
count = 1
while count <= 5:
print(f"รอบที่ {count}")
count += 1
number = 0
while True:
number += 1
if number > 10:
break
print(number)
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(f"เลขคี่: {i}")
❌ ระวัง Infinite Loop:
while True:
print("วนไม่หยุด!")
⚙️Functions - ฟังก์ชัน
Function
ฟังก์ชัน - ชุดคำสั่งที่ใช้ซ้ำได้
ฟังก์ชันคือกลุ่มโค้ดที่ทำงานเฉพาะเรื่อง สามารถรับค่าเข้า (parameters) และส่งค่าออก (return) ใช้คำว่า def
การสร้างฟังก์ชัน
def say_hello():
print("สวัสดีครับ")
say_hello()
def greet(name):
print(f"สวัสดี {name}")
greet("สมชาย")
greet("สมหญิง")
def introduce(name, age=18):
print(f"ฉันชื่อ {name} อายุ {age} ปี")
introduce("สมชาย")
introduce("สมหญิง", 25)
⭐ Return Statement - การคืนค่า
✅ ฟังก์ชันควรมี return เสมอ
แม้ว่า Python จะไม่บังคับ แต่การใส่ return ทำให้โค้ดชัดเจนว่าฟังก์ชันส่งอะไรกลับ หากไม่มี return ฟังก์ชันจะส่ง None กลับ
✅ มี Return (แนะนำ)
def add(a, b):
result = a + b
return result
total = add(5, 3)
print(total)
❌ ไม่มี Return
def add(a, b):
result = a + b
print(result)
total = add(5, 3)
print(total)
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 Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.grades = []
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)
student1 = Student("สมชาย", 20)
student2 = Student("สมหญิง", 21)
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}")
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))
print(safe_divide(10, 0))
fruits = ["แอปเปิ้ล", "กล้วย"]
print(get_list_item(fruits, 0))
print(get_list_item(fruits, 10))
ลอง (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
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")
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()
assert calc.add(5) == 5, "เพิ่ม 5 ควรได้ 5"
assert calc.add(3) == 8, "เพิ่ม 3 ควรได้ 8"
assert calc.reset() == 0, "reset ควรได้ 0"
print("✅ Calculator ทำงานถูกต้อง")
test_calculator()
✅ กฎการเขียน Test ที่ดี:
- แต่ละ test ควรทดสอบสิ่งเดียว
- ตั้งชื่อ test ให้บอกว่าทดสอบอะไร
- ทดสอบทั้ง case ปกติและ edge cases
- Test ควร independent - ไม่ขึ้นกับ test อื่น
- เขียน 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 = 10
print(x)
❌ TypeError - ใช้ type ผิด
result = "10" + 5
result = int("10") + 5
result = "10" + str(5)
❌ IndexError - เข้าถึง index ที่ไม่มี
my_list = [1, 2, 3]
print(my_list[5])
if 5 < len(my_list):
print(my_list[5])
else:
print("Index เกินขนาด")
💡 เคล็ดลับการ Debug:
- อ่าน error message ให้ดี มันบอกว่าผิดที่บรรทัดไหน
- ใช้ print() ตรวจสอบค่าตัวแปรในจุดต่างๆ
- แบ่งโค้ดเป็นส่วนเล็กๆ ทดสอบทีละส่วน
- Comment โค้ดออกทีละส่วนเพื่อหาว่าส่วนไหนมีปัญหา
- ใช้ Google หา error message - มักจะมีคนเจอปัญหาเดียวกัน