กลับไปหน้าบทความ

🐍 Python (สอนแบบครบระดับ)

Python อ่านง่าย เขียนเร็ว เหมาะทั้งงาน data, web, automation และงานวิจัย โดยบทความนี้แบ่งเป็น 4 ระดับพร้อมตัวอย่างละเอียด

📋 เนื้อหา (พื้นฐาน)

  • 🧭 Python คืออะไร ใช้ทำอะไร
  • ⚙️ การติดตั้งและรัน
  • 🔤 ตัวแปรและชนิดข้อมูล
  • 🧮 เงื่อนไขและลูป
  • 🧩 ฟังก์ชัน
  • 📦 List/Dict/Set/Tuple
  • 🏁 สรุป
  • 📝 แบบฝึกหัด

🧭 Python คืออะไร ใช้ทำอะไร

ทำไมต้อง Python?

Python เป็นภาษาโปรแกรมแบบ interpreted และ high-level ที่มีไวยากรณ์อ่านง่าย ใกล้เคียงภาษาอังกฤษ ทำให้เหมาะสำหรับผู้เริ่มต้นเรียนเขียนโปรแกรม

  • • อ่านง่าย เขียนง่าย: ไม่ต้องใส่ semicolon ใช้ indentation กำหนดบล็อก
  • • Versatile: ใช้ได้ทั้ง web, data science, AI/ML, automation, scripting
  • • Community ใหญ่: มี library/package มากมายใน PyPI
  • • Cross-platform: รันได้บน Windows, macOS, Linux

Python ใช้ทำอะไรได้บ้าง?

🌐 Web Development

Django, Flask, FastAPI สร้าง web app และ REST API

📊 Data Science

Pandas, NumPy, Matplotlib วิเคราะห์และแสดงผลข้อมูล

🤖 Machine Learning

TensorFlow, PyTorch, scikit-learn สร้างโมเดล AI

🔧 Automation

Selenium, Requests สำหรับ web scraping และ automation

เปรียบเทียบ Python กับภาษาอื่น

# Python - อ่านง่าย กระชับ
def greet(name):
    return f"Hello, {name}!"

print(greet("World"))

# สังเกต: ไม่มี semicolon, ไม่มี curly braces
# ใช้ indentation (ย่อหน้า) กำหนดขอบเขต

⚙️ การติดตั้งและรัน

ติดตั้ง Python

Windows:

  1. ไปที่ python.org/downloads
  2. ดาวน์โหลด Python เวอร์ชันล่าสุด
  3. ติ๊ก "Add Python to PATH" ตอนติดตั้ง

macOS (Homebrew):

brew install python3

Linux (Ubuntu):

sudo apt update
sudo apt install python3 python3-pip python3-venv

ตรวจสอบและรันโปรแกรม

# ตรวจสอบเวอร์ชัน
python --version
# หรือ python3 --version

# รันไฟล์
python main.py

# Interactive mode
python
>>> print("Hello!")
Hello!
>>> 2 + 3
5
>>> exit()

โปรแกรมแรก: Hello World

# hello.py
print("Hello, World!")
print("สวัสดีครับ")

# ใช้ตัวแปร
name = "สมชาย"
print(f"สวัสดี {name}")

# คำนวณ
result = 10 + 20
print(f"10 + 20 = {result}")

🔤 ตัวแปรและชนิดข้อมูล

ตัวแปร (Variables) คืออะไร?

ตัวแปรคือ "กล่องเก็บข้อมูล" ที่มีชื่อ Python เป็นภาษาแบบ dynamically typed ไม่ต้องประกาศ type ล่วงหน้า

# สร้างตัวแปร - ไม่ต้องประกาศ type
name = "สมชาย"        # str (string)
age = 20              # int (integer)
height = 175.5        # float
is_student = True     # bool (boolean)

# ตรวจสอบ type
print(type(name))      # <class 'str'>
print(type(age))       # <class 'int'>
print(type(height))    # <class 'float'>
print(type(is_student)) # <class 'bool'>

กฎการตั้งชื่อตัวแปร

✅ ถูกต้อง

name = "John"
first_name = "John"
name2 = "John"
_private = "secret"

❌ ผิด

2name = "John"     # ขึ้นต้นตัวเลข
first-name = "John" # ใช้ขีด
first name = "John" # มีช่องว่าง

Convention: ใช้ snake_case สำหรับตัวแปร เช่น user_name, total_price

ชนิดข้อมูลพื้นฐาน

# Integer - จำนวนเต็ม
age = 25
negative = -10
big_number = 1_000_000  # ใช้ _ คั่นได้

# Float - ทศนิยม
price = 99.99
pi = 3.14159

# String - ข้อความ
name = "Hello"
message = 'Single quotes work too'
multiline = """This is
a multiline string"""

# Boolean - True/False
is_active = True
is_deleted = False

# None - ไม่มีค่า
result = None

การแปลงชนิดข้อมูล (Type Conversion)

# แปลงเป็น int
int("42")        # 42
int(3.99)        # 3 (ตัดทศนิยม)

# แปลงเป็น float
float("3.14")    # 3.14
float(42)        # 42.0

# แปลงเป็น string
str(42)          # "42"
str(3.14)        # "3.14"

# แปลงเป็น bool
bool(1)          # True
bool(0)          # False
bool("")         # False (string ว่าง)
bool("hello")    # True

f-string (String Formatting)

name = "สมชาย"
age = 20
score = 85.5

# f-string - วิธีที่แนะนำ
print(f"ชื่อ: {name}, อายุ: {age}")

# คำนวณใน f-string
print(f"คะแนน: {score:.1f}")  # 85.5
print(f"อายุปีหน้า: {age + 1}")

# จัดรูปแบบตัวเลข
price = 1234567
print(f"ราคา: {price:,} บาท")  # 1,234,567 บาท

Multiple Assignment

# กำหนดค่าหลายตัวพร้อมกัน
x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3

# สลับค่า (ไม่ต้องใช้ตัวแปรกลาง!)
a, b = 10, 20
a, b = b, a
print(a, b)  # 20 10

# Unpacking
point = (10, 20, 30)
x, y, z = point

# ใช้ * เก็บส่วนที่เหลือ
first, *rest = [1, 2, 3, 4, 5]
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

🧮 เงื่อนไขและลูป

if / elif / else

score = 78

# if-elif-else
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"คะแนน {score} ได้เกรด {grade}")

# Nested if
age = 20
has_id = True

if age >= 18:
    if has_id:
        print("เข้าได้")
    else:
        print("ต้องมีบัตร")
else:
    print("อายุไม่ถึง")

Logical Operators

age = 25
has_license = True

# and - ต้องจริงทั้งคู่
if age >= 18 and has_license:
    print("ขับรถได้")

# or - จริงอย่างน้อยหนึ่งตัว
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
    print("หยุดงาน")

# not - กลับค่า
is_logged_in = False
if not is_logged_in:
    print("กรุณาเข้าสู่ระบบ")

# Chained comparison (Python พิเศษ!)
score = 75
if 60 <= score < 80:
    print("เกรด B หรือ C")

Ternary Operator (Conditional Expression)

age = 20

# แบบปกติ
if age >= 18:
    status = "ผู้ใหญ่"
else:
    status = "เด็ก"

# Ternary - บรรทัดเดียว
status = "ผู้ใหญ่" if age >= 18 else "เด็ก"

# ใช้กับ return
def get_discount(is_member):
    return 0.2 if is_member else 0.0

for Loop

# range(start, stop, step)
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):     # 1, 2, 3, 4, 5
    print(i)

for i in range(0, 10, 2): # 0, 2, 4, 6, 8
    print(i)

for i in range(5, 0, -1): # 5, 4, 3, 2, 1
    print(i)

# วนใน list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# enumerate - ได้ทั้ง index และ value
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# zip - วนหลาย list พร้อมกัน
names = ["Alice", "Bob"]
scores = [85, 90]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

while Loop

# while - วนจนกว่าเงื่อนไขจะเป็น False
count = 0
while count < 5:
    print(count)
    count += 1

# ตัวอย่าง: รับ input จนกว่าจะถูก
while True:
    answer = input("ตอบ 1+1: ")
    if answer == "2":
        print("ถูกต้อง!")
        break
    print("ลองใหม่")

break, continue, else

# break - หยุดลูปทันที
for i in range(10):
    if i == 5:
        break
    print(i)  # 0, 1, 2, 3, 4

# continue - ข้ามรอบนี้ ไปรอบถัดไป
for i in range(5):
    if i == 2:
        continue
    print(i)  # 0, 1, 3, 4

# else - ทำงานเมื่อลูปจบปกติ (ไม่ break)
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            break
    else:
        print(f"{n} เป็นจำนวนเฉพาะ")

🧩 ฟังก์ชัน

ฟังก์ชันพื้นฐาน

# ฟังก์ชันง่ายๆ
def greet():
    print("สวัสดีครับ")

greet()  # เรียกใช้

# ฟังก์ชันที่รับ parameter
def greet_name(name):
    print(f"สวัสดี {name}")

greet_name("สมชาย")

# ฟังก์ชันที่ return ค่า
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # 8

Default Parameters

def calc_vat(price, rate=0.07):
    """คำนวณ VAT"""
    return price * rate

print(calc_vat(1000))       # 70.0 (ใช้ rate default)
print(calc_vat(1000, 0.1))  # 100.0 (ส่ง rate เอง)

# Keyword arguments
def create_user(name, age, city="Bangkok"):
    return {"name": name, "age": age, "city": city}

# เรียกแบบ keyword
user = create_user(name="John", age=25)
user = create_user(age=25, name="John")  # สลับได้

*args และ **kwargs

# *args - รับ arguments หลายตัวเป็น tuple
def summarize(*scores):
    total = sum(scores)
    avg = total / len(scores)
    return total, avg

result = summarize(80, 90, 100, 85)
print(result)  # (355, 88.75)

# **kwargs - รับ keyword arguments เป็น dict
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="John", age=25, city="Bangkok")

# รวมกัน
def flexible(a, b, *args, **kwargs):
    print(f"a={a}, b={b}")
    print(f"args={args}")
    print(f"kwargs={kwargs}")

Return หลายค่า

def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers) / len(numbers)

# Unpack ค่าที่ return
minimum, maximum, average = get_stats([1, 2, 3, 4, 5])
print(f"min={minimum}, max={maximum}, avg={average}")

# หรือรับเป็น tuple
stats = get_stats([1, 2, 3, 4, 5])
print(stats)  # (1, 5, 3.0)

Lambda Functions

# Lambda - ฟังก์ชันสั้นๆ บรรทัดเดียว
square = lambda x: x ** 2
print(square(5))  # 25

add = lambda a, b: a + b
print(add(3, 4))  # 7

# ใช้กับ sort
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78}
]

# เรียงตาม score
students.sort(key=lambda s: s["score"])

# ใช้กับ map และ filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))  # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers))  # [2, 4]

Docstring

def calculate_bmi(weight, height):
    """
    คำนวณค่า BMI (Body Mass Index)
    
    Args:
        weight: น้ำหนักเป็น kg
        height: ส่วนสูงเป็น m
    
    Returns:
        float: ค่า BMI
    
    Example:
        >>> calculate_bmi(70, 1.75)
        22.86
    """
    return weight / (height ** 2)

# ดู docstring
print(calculate_bmi.__doc__)
help(calculate_bmi)

📦 List/Dict/Set/Tuple

List - รายการที่แก้ไขได้

# สร้าง list
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]

# เข้าถึงสมาชิก
print(fruits[0])   # apple
print(fruits[-1])  # orange (ตัวสุดท้าย)
print(fruits[1:3]) # ['banana', 'orange']

# แก้ไข
fruits[0] = "grape"
fruits.append("mango")      # เพิ่มท้าย
fruits.insert(1, "kiwi")    # แทรกตำแหน่ง 1
fruits.extend(["pear", "plum"])  # เพิ่มหลายตัว

# ลบ
fruits.remove("banana")     # ลบตามค่า
del fruits[0]               # ลบตาม index
last = fruits.pop()         # ลบและคืนค่าตัวท้าย
fruits.clear()              # ลบทั้งหมด

# Methods ที่ใช้บ่อย
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.sort()                 # เรียงลำดับ
nums.reverse()              # กลับลำดับ
print(nums.count(1))        # นับจำนวน 1
print(nums.index(5))        # หา index ของ 5
print(len(nums))            # ความยาว

List Comprehension

# แบบปกติ
squares = []
for x in range(5):
    squares.append(x ** 2)

# List comprehension - บรรทัดเดียว
squares = [x ** 2 for x in range(5)]  # [0, 1, 4, 9, 16]

# มีเงื่อนไข
evens = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

# แปลงค่า
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]

# Nested
matrix = [[i * j for j in range(3)] for i in range(3)]

Dictionary - คู่ key-value

# สร้าง dict
profile = {
    "name": "สมชาย",
    "age": 20,
    "skills": ["Python", "SQL"]
}

# เข้าถึงค่า
print(profile["name"])           # สมชาย
print(profile.get("email"))      # None (ไม่ error)
print(profile.get("email", "N/A"))  # N/A (default)

# แก้ไข/เพิ่ม
profile["age"] = 21
profile["email"] = "[email protected]"
profile.update({"city": "Bangkok", "phone": "0812345678"})

# ลบ
del profile["phone"]
email = profile.pop("email")     # ลบและคืนค่า

# วน loop
for key in profile:
    print(key)

for key, value in profile.items():
    print(f"{key}: {value}")

for value in profile.values():
    print(value)

# ตรวจสอบ key
if "name" in profile:
    print("มี key name")

Set - ไม่ซ้ำ ไม่เรียงลำดับ

# สร้าง set
colors = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3}

# เพิ่ม/ลบ
colors.add("yellow")
colors.remove("red")     # error ถ้าไม่มี
colors.discard("pink")   # ไม่ error ถ้าไม่มี

# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # Union: {1, 2, 3, 4, 5, 6}
print(a & b)  # Intersection: {3, 4}
print(a - b)  # Difference: {1, 2}
print(a ^ b)  # Symmetric diff: {1, 2, 5, 6}

# ใช้เอาค่าไม่ซ้ำ
items = ["a", "b", "a", "c", "b"]
unique = list(set(items))  # ['a', 'b', 'c']

Tuple - แก้ไขไม่ได้

# สร้าง tuple (immutable)
point = (10, 20)
rgb = (255, 128, 0)
single = (42,)  # tuple ตัวเดียวต้องมี comma

# เข้าถึง
x, y = point    # unpacking
print(point[0]) # 10

# ใช้เป็น key ใน dict ได้ (list ใช้ไม่ได้)
locations = {
    (0, 0): "Origin",
    (10, 20): "Point A"
}

# Named tuple (อ่านง่ายกว่า)
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y)  # 10 20

🏁 สรุป

  • ✅ Python อ่านง่าย เหมาะกับการเริ่มต้นเรียนเขียนโปรแกรม
  • ✅ ตัวแปรไม่ต้องประกาศ type ล่วงหน้า (dynamic typing)
  • ✅ ใช้ indentation (ย่อหน้า) กำหนดขอบเขตบล็อก
  • ✅ list และ dict เป็นโครงสร้างข้อมูลที่ใช้บ่อยที่สุด
  • ✅ List comprehension ทำให้โค้ดสั้นและอ่านง่าย
  • ✅ ฟังก์ชันช่วยแบ่งงานเป็นส่วนๆ และ reuse ได้
  • ✅ ใช้ f-string สำหรับ format string

📝 แบบฝึกหัด

ระดับง่าย

  1. เขียนโปรแกรมรับชื่อผู้ใช้แล้วแสดงคำทักทาย
  2. เขียนโปรแกรมรับตัวเลข 2 ตัวแล้วแสดงผลบวก ลบ คูณ หาร
  3. เขียนโปรแกรมรับคะแนน แล้วคำนวณเกรด (A/B/C/D/F)
  4. สร้าง list เก็บชื่อเพื่อน 5 คน แล้ววนแสดงทีละคน

ระดับกลาง

  1. เขียนฟังก์ชันหาค่า factorial ของตัวเลข
  2. เขียนฟังก์ชันตรวจสอบว่าเป็นจำนวนเฉพาะหรือไม่
  3. สร้าง dict เก็บข้อมูลนักเรียน 3 คน (ชื่อ, คะแนน) แล้วหาคนที่ได้คะแนนสูงสุด
  4. ใช้ list comprehension สร้าง list เลขคู่ 1-100
  5. เขียนโปรแกรมนับจำนวนตัวอักษรแต่ละตัวในประโยค (ใช้ dict)

ระดับท้าทาย

  1. เขียนโปรแกรมเกม Fizz Buzz (1-100)
  2. เขียนฟังก์ชันหา Fibonacci ตัวที่ n
  3. สร้างระบบเก็บรายชื่อติดต่อ (เพิ่ม/ลบ/แสดง) ใช้ list และ dict
  4. เขียนฟังก์ชันเรียงลำดับ list โดยไม่ใช้ sort()