Programming
Python ยังคงเป็นภาษาโปรแกรมอันดับ 1 ของโลกในปี 2026 ด้วยเหตุผลหลายประการ:
python --version เพื่อตรวจสอบ# ติดตั้งผ่าน Homebrew (แนะนำ)
brew install python3
# ตรวจสอบเวอร์ชัน
python3 --version
# อัพเดตระบบ
sudo apt update && sudo apt upgrade -y
# ติดตั้ง Python
sudo apt install python3 python3-pip python3-venv -y
# ตรวจสอบ
python3 --version
pip3 --version
| IDE | ข้อดี | เหมาะกับ |
|---|---|---|
| VS Code | ฟรี, เบา, Extension เยอะ | ทุกระดับ |
| PyCharm | ฟีเจอร์ครบ, Debug ดี | มืออาชีพ |
| Jupyter Notebook | รันทีละ cell, เห็นผลทันที | Data Science |
| Thonny | เรียบง่ายมาก | เด็กและมือใหม่มาก |
ดูวิดีโอเพิ่มเติมเกี่ยวกับPython สำหรับมือใหม่ เริ่มเรียนเขียนโปรแ:
# โปรแกรมแรก — Hello World!
print("สวัสดีครับ! ยินดีต้อนรับสู่โลกของ Python 🐍")
# รับ input จากผู้ใช้
name = input("คุณชื่ออะไรครับ? ")
print(f"สวัสดีครับ คุณ{name}! ยินดีที่ได้รู้จัก")
# ตัวแปร (Variables) — ไม่ต้องประกาศ type
name = "สมชาย" # str (ข้อความ)
age = 25 # int (จำนวนเต็ม)
height = 175.5 # float (ทศนิยม)
is_student = True # bool (จริง/เท็จ)
skills = ["Python", "SQL", "Git"] # list (รายการ)
info = {"name": "สมชาย", "age": 25} # dict (พจนานุกรม)
# ตรวจสอบ type
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(skills)) # <class 'list'>
# คณิตศาสตร์
print(10 + 3) # 13 (บวก)
print(10 - 3) # 7 (ลบ)
print(10 * 3) # 30 (คูณ)
print(10 / 3) # 3.333... (หาร)
print(10 // 3) # 3 (หารปัดลง)
print(10 % 3) # 1 (เศษ)
print(10 ** 3) # 1000 (ยกกำลัง)
# เปรียบเทียบ
print(10 == 10) # True
print(10 != 5) # True
print(10 > 5) # True
# ตรรกศาสตร์
print(True and False) # False
print(True or False) # True
print(not True) # False
# if/elif/else
score = 85
if score >= 80:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(f"คะแนน {score} ได้เกรด {grade}")
# for loop
fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม", "มะม่วง"]
for i, fruit in enumerate(fruits, 1):
print(f"{i}. {fruit}")
# while loop
count = 0
while count < 5:
print(f"นับ: {count}")
count += 1
# List Comprehension (เทคนิคขั้นเทพ!)
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Filter ด้วย comprehension
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
# สร้างฟังก์ชัน
def greet(name, greeting="สวัสดี"):
"""ทักทายผู้ใช้"""
return f"{greeting}ครับ คุณ{name}!"
print(greet("สมชาย"))
print(greet("สมหญิง", "หวัดดี"))
# ฟังก์ชันที่ return หลายค่า
def calculate(a, b):
return a + b, a - b, a * b, a / b
add, sub, mul, div = calculate(10, 3)
print(f"บวก={add}, ลบ={sub}, คูณ={mul}, หาร={div:.2f}")
# Lambda (ฟังก์ชันสั้นๆ)
double = lambda x: x * 2
print(double(5)) # 10
# *args และ **kwargs
def flexible(*args, **kwargs):
print(f"args: {args}")
print(f"kwargs: {kwargs}")
flexible(1, 2, 3, name="Python", year=2026)
# Import modules
import os
import json
from datetime import datetime
from pathlib import Path
# ใช้งาน
now = datetime.now()
print(f"วันที่: {now.strftime('%d/%m/%Y %H:%M')}")
# สร้าง module ของตัวเอง — สร้างไฟล์ myutils.py
# แล้ว import ใช้: from myutils import my_function
class Employee:
"""คลาสพนักงาน"""
company = "SiamCafe" # Class variable
def __init__(self, name, position, salary):
self.name = name # Instance variable
self.position = position
self.salary = salary
def introduce(self):
return f"สวัสดีครับ ผม{self.name} ตำแหน่ง{self.position} ที่{self.company}"
def annual_salary(self):
return self.salary * 12
def __str__(self):
return f"{self.name} ({self.position})"
# Inheritance (การสืบทอด)
class Developer(Employee):
def __init__(self, name, salary, languages):
super().__init__(name, "Developer", salary)
self.languages = languages
def code(self):
langs = ", ".join(self.languages)
return f"{self.name} เขียนได้: {langs}"
# ใช้งาน
dev = Developer("สมชาย", 50000, ["Python", "JavaScript", "Go"])
print(dev.introduce())
print(dev.code())
print(f"รายได้ต่อปี: {dev.annual_salary():,} บาท")
# เขียนไฟล์
with open("data.txt", "w", encoding="utf-8") as f:
f.write("สวัสดี Python!\n")
f.write("บรรทัดที่ 2\n")
# อ่านไฟล์
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# JSON
import json
data = {
"name": "SiamCafe",
"articles": 544,
"categories": ["Network", "Security", "AI", "Programming"]
}
# เขียน JSON
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# อ่าน JSON
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"]) # SiamCafe
# CSV
import csv
with open("employees.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["ชื่อ", "ตำแหน่ง", "เงินเดือน"])
writer.writerow(["สมชาย", "Developer", 50000])
writer.writerow(["สมหญิง", "Designer", 45000])
# pip install flask
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>สวัสดี SiamCafe Blog!</h1>"
@app.route("/api/articles")
def articles():
return jsonify({
"total": 544,
"categories": ["Network", "Security", "AI"]
})
if __name__ == "__main__":
app.run(debug=True, port=5000)
# pip install fastapi uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Article(BaseModel):
title: str
category: str
content: str
@app.get("/")
def read_root():
return {"message": "สวัสดี SiamCafe API!"}
@app.post("/articles/")
def create_article(article: Article):
return {"status": "created", "title": article.title}
# รัน: uvicorn main:app --reload
# pip install pandas numpy matplotlib
import pandas as pd
import numpy as np
# สร้าง DataFrame
data = {
"เดือน": ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค."],
"รายได้": [50000, 55000, 48000, 62000, 58000],
"ค่าใช้จ่าย": [30000, 32000, 28000, 35000, 31000]
}
df = pd.DataFrame(data)
df["กำไร"] = df["รายได้"] - df["ค่าใช้จ่าย"]
print(df)
print(f"\nกำไรเฉลี่ย: {df['กำไร'].mean():,.0f} บาท")
print(f"กำไรสูงสุด: {df['กำไร'].max():,.0f} บาท")
# NumPy
arr = np.array([1, 2, 3, 4, 5])
print(f"Mean: {arr.mean()}, Std: {arr.std():.2f}")
# ตัวอย่าง: ดาวน์โหลดข้อมูลจากเว็บ
import requests
response = requests.get("https://api.github.com/users/python")
data = response.json()
print(f"Python GitHub: {data['public_repos']} repos")
# ตัวอย่าง: ส่ง Email อัตโนมัติ
import smtplib
from email.mime.text import MIMEText
def send_email(to, subject, body):
msg = MIMEText(body)
msg["Subject"] = subject
msg["To"] = to
# ต้องตั้งค่า SMTP server
print(f"ส่ง email ถึง {to}: {subject}")
# ตัวอย่าง: จัดการไฟล์อัตโนมัติ
from pathlib import Path
import shutil
def organize_downloads(folder):
"""จัดระเบียบไฟล์ในโฟลเดอร์ Downloads"""
extensions = {
"รูปภาพ": [".jpg", ".png", ".gif", ".webp"],
"เอกสาร": [".pdf", ".doc", ".docx", ".xlsx"],
"วิดีโอ": [".mp4", ".avi", ".mkv"],
"โค้ด": [".py", ".js", ".html", ".css"],
}
for file in Path(folder).iterdir():
if file.is_file():
for category, exts in extensions.items():
if file.suffix.lower() in exts:
dest = Path(folder) / category
dest.mkdir(exist_ok=True)
shutil.move(str(file), str(dest / file.name))
print(f"ย้าย {file.name} → {category}/")
break
| ระดับ | โปรเจกต์ | สิ่งที่ได้เรียนรู้ |
|---|---|---|
| 🟢 ง่าย | เครื่องคิดเลข | ตัวแปร, ฟังก์ชัน, input/output |
| 🟢 ง่าย | เกมทายตัวเลข | random, loop, condition |
| 🟡 กลาง | To-Do List CLI | File I/O, CRUD, list |
| 🟡 กลาง | Web Scraper | requests, BeautifulSoup, data |
| 🟡 กลาง | REST API ด้วย Flask | Web, JSON, HTTP methods |
| 🔴 ยาก | Chat Bot ด้วย AI | API, NLP, async |
| 🔴 ยาก | Dashboard ด้วย Streamlit | Data viz, pandas, deployment |