Reference · ติดตั้งเครื่องไม่ได้ก็เล่นได้ในหน้านี้เลย

📖 Python Cheat-sheet

หน้านี้ไม่ใช่ "บทเรียน" — เป็น "ตัวอ้างอิงเร็ว" · เปิดไว้ขณะทำงาน W04–W14 · ทุก example รันได้เลยในเบราว์เซอร์ (กด ▶ Run) · จำไม่ได้เรื่องไหน → กลับมาดูที่นี่

หน้านี้ เสริม ไม่ใช่ แทน เนื้อหาจริงสอนใน W04 (อ่านโค้ด AI) · W05 (แก้) · W06 (เขียน spec) · W08 (ตาราง) · หน้านี้ "ใช้ลืม" — ลืม syntax ไหน → ค้นที่นี่

📑 สารบัญ

  1. ตัวแปร + Type
  2. Operators
  3. Strings + f-string
  4. input() + print()
  5. if / elif / else
  6. for loop
  7. while loop
  8. List
  9. Dict
  10. Tuple + Set
  11. Functions (def)
  12. Import + Modules
  13. อ่าน/เขียน ไฟล์
  14. Try / Except
  15. Built-in Functions
  16. Gotchas ที่เจอบ่อย

1. ตัวแปร + Type

ตัวแปร = "กล่องเก็บค่า" · Python รู้ type อัตโนมัติจากค่าที่ใส่ ไม่ต้องประกาศ

name = "Ploy" # str (string — ข้อความ) age = 20 # int (integer — เลขจำนวนเต็ม) gpa = 3.45 # float (เลขทศนิยม) is_active = True # bool (True / False) nothing = None # None — "ไม่มีค่า" # ตรวจ type ของตัวแปร print(type(name)) # <class 'str'> print(type(age)) # <class 'int'> print(type(gpa)) # <class 'float'> print(type(is_active)) # <class 'bool'> # แปลง type print(int("42")) # 42 (str → int) print(str(42)) # "42" (int → str) print(float("3.14")) # 3.14 (str → float) print(int(3.7)) # 3 (ตัดเศษ — ไม่ปัด)

📚 สอนลึกที่ W04

2. Operators

กลุ่มOperatorตัวอย่าง
Math+ บวก3 + 2 → 5
- ลบ5 - 3 → 2
* คูณ4 * 3 → 12
/ หาร (ทศนิยม)7 / 2 → 3.5
// หารปัดลง7 // 2 → 3
% เศษ (modulo)7 % 2 → 1
** ยกกำลัง2 ** 3 → 8
Compare== เท่ากัน5 == 5 → True
!= ไม่เท่า5 != 3 → True
> มากกว่า5 > 3 → True
< น้อยกว่า5 < 3 → False
>= มากกว่าเท่ากับ5 >= 5 → True
<= น้อยกว่าเท่ากับ3 <= 5 → True
Logicand(5>3) and (2<4) → True
or(5>3) or (2>4) → True
notnot (5>3) → False
Assign=x = 5
+=x += 1 เหมือน x = x + 1
-=x -= 2 เหมือน x = x - 2
*= /= //= %=ทำงานเหมือนกัน
a, b = 7, 2 print(a / b) # 3.5 — หารปกติ print(a // b) # 3 — ปัดลง print(a % b) # 1 — เศษ print(a ** b) # 49 — 7^2 # ลำดับความสำคัญ (precedence) — เหมือนคณิตศาสตร์ print(2 + 3 * 4) # 14 (ไม่ใช่ 20) print((2 + 3) * 4) # 20 — ใช้วงเล็บเปลี่ยนลำดับ # Logic score = 75 print(score >= 50 and score <= 100) # True print(score > 100 or score < 0) # False
กับดักที่เจอบ่อย — = vs == = คือ assign (ใส่ค่า) · == คือ compare (เปรียบเทียบ) · ใน if ใช้ == เสมอ — เขียน if x = 5: จะ SyntaxError

3. Strings + f-string

name = "นัท" score = 85 # 1. ต่อ string ด้วย + (ต้อง str ทั้งคู่) greeting = "สวัสดี " + name print(greeting) # 2. f-string — แทรกตัวแปรในเครื่องหมาย {} print(f"คะแนนของ {name} คือ {score}") # 3. format ตัวเลข pi = 3.14159 print(f"pi = {pi:.2f}") # 2 ตำแหน่งทศนิยม → 3.14 print(f"pi = {pi:.4f}") # 4 ตำแหน่ง → 3.1416 print(f"price = {12345:,}") # ใส่ comma คั่นพัน → 12,345 # 4. string methods ที่ใช้บ่อย s = " Hello World " print(s.strip()) # ตัดช่องว่างหัว/ท้าย → "Hello World" print(s.lower()) # → " hello world " print(s.upper()) # → " HELLO WORLD " print(s.replace("World", "Python")) # → " Hello Python " print("a,b,c".split(",")) # → ['a', 'b', 'c'] print("-".join(["a","b","c"])) # → "a-b-c" # 5. ความยาว + index text = "Python" print(len(text)) # 6 print(text[0]) # 'P' (ตัวแรก = index 0) print(text[-1]) # 'n' (ติดลบ = นับจากท้าย) print(text[0:3]) # 'Pyt' (slice 0–2)

📚 สอนลึกที่ W04 + W05

4. input() + print()

# input() — รับจาก user · คืนค่าเป็น str เสมอ name = input("ชื่อ: ") # ผู้ใช้พิมพ์: Ploy age_str = input("อายุ: ") # ผู้ใช้พิมพ์: 20 # ต้อง convert ถ้าจะคำนวณ age = int(age_str) print(f"{name} อายุ {age} ปี · อีก 5 ปี = {age + 5}") # print() — option useful print("a", "b", "c") # default separator = " " print("a", "b", "c", sep="-") # → "a-b-c" print("no newline", end="") # ไม่ขึ้นบรรทัดใหม่ print(" continue same line")
input() คืน string เสมอ ถ้าจะคำนวณ → ต้องใช้ int() หรือ float() · ไม่งั้น "3" + 5 = TypeError

5. if / elif / else

score = int(input("คะแนน: ")) 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}") # inline if (ternary) — ใช้เมื่อมี 2 ทางเลือกสั้น ๆ status = "ผ่าน" if score >= 50 else "ตก" print(status) # เช็คหลายเงื่อนไขพร้อมกัน age = 22 has_license = True if age >= 18 and has_license: print("ขับรถได้") elif age >= 18 and not has_license: print("รอสอบ") else: print("ยังเด็กเกิน")

📚 ดู flowchart-เทียบ-code ที่ W04

6. for loop

# 1. วน list scores = [85, 72, 45, 91] for s in scores: print(s) # 2. วนช่วงตัวเลข — range() for i in range(5): # 0, 1, 2, 3, 4 print(i, end=" ") print() for i in range(2, 7): # 2, 3, 4, 5, 6 print(i, end=" ") print() for i in range(0, 20, 5): # 0, 5, 10, 15 print(i, end=" ") print() # 3. enumerate — ดู index + ค่า พร้อมกัน fruits = ["apple", "banana", "cherry"] for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # 4. zip — วน 2 list พร้อมกัน names = ["Ploy", "Nat", "Mint"] ages = [20, 22, 19] for name, age in zip(names, ages): print(f"{name} อายุ {age}") # 5. วน string (เป็น char ทีละตัว) for c in "Python": print(c, end=".") print() # break + continue for i in range(10): if i == 3: continue # ข้าม 3 ไป 4 ต่อ if i == 7: break # ออก loop ที่ 7 print(i, end=" ")

7. while loop

attempts = 0 max_attempts = 3 while attempts < max_attempts: password = input("รหัสผ่าน: ") if password == "open-sesame": print("✅ เข้าได้") break attempts += 1 print(f"❌ ผิด ({attempts}/{max_attempts})") else: # else ของ while = ทำเมื่อ loop จบโดยไม่มี break print("🔒 บัญชีถูกล็อค")
ระวัง infinite loop ถ้าตัวแปรในเงื่อนไข "ไม่เปลี่ยน" → loop จะวนตลอดไป · ใน VS Code กด Ctrl + C ใน terminal เพื่อหยุด

8. List

scores = [85, 72, 45, 91] # เข้าถึงด้วย index (เริ่มจาก 0) print(scores[0]) # 85 print(scores[-1]) # 91 (ตัวสุดท้าย) print(scores[1:3]) # [72, 45] — slice # เพิ่ม scores.append(60) # ต่อท้าย → [85, 72, 45, 91, 60] scores.insert(0, 100) # แทรกตำแหน่ง 0 → [100, 85, 72, 45, 91, 60] print(scores) # ลบ scores.remove(72) # ลบค่า 72 (ตัวแรกที่เจอ) del scores[0] # ลบ index 0 last = scores.pop() # ดึง + ลบ ตัวสุดท้าย print(scores, "ดึงออก:", last) # ความยาว + ตรวจสมาชิก print(len(scores)) print(85 in scores) # True # loop + index for i, s in enumerate(scores): print(f"index {i}: {s}") # functions ที่ใช้บ่อย print(sum(scores)) # ผลรวม print(max(scores)) # มากสุด print(min(scores)) # น้อยสุด print(sorted(scores)) # เรียงน้อยไปมาก print(sorted(scores, reverse=True)) # มากไปน้อย # list comprehension — สร้าง list ใหม่จาก list เดิม squares = [x**2 for x in range(5)] print(squares) # [0, 1, 4, 9, 16] evens = [x for x in range(10) if x % 2 == 0] print(evens) # [0, 2, 4, 6, 8]

📚 สอนลึกที่ W08

9. Dict

Dict = ตาราง key → value · เข้าถึงด้วย key ไม่ใช่ index

student = { "name": "Ploy", "id": "640001", "gpa": 3.45, "scores": [85, 72, 91], } # เข้าถึง print(student["name"]) # Ploy print(student["scores"][0]) # 85 # .get() — ปลอดภัยกว่า · ไม่เจอ key → คืน None (ไม่ error) print(student.get("phone")) # None print(student.get("phone", "ไม่มี")) # ค่า default # เพิ่ม / แก้ student["email"] = "ploy@ubu.ac.th" # เพิ่ม student["gpa"] = 3.60 # แก้ del student["id"] # ลบ print(student) # loop key + value for key, value in student.items(): print(f"{key}: {value}") # loop เฉพาะ key for key in student.keys(): print(key) # ตรวจมี key มั้ย print("name" in student) # True print("phone" in student) # False # nested dict — dict ซ้อน dict (ใช้บ่อย) classroom = { "640001": {"name": "Ploy", "gpa": 3.45}, "640002": {"name": "Nat", "gpa": 3.12}, } print(classroom["640001"]["name"]) # Ploy

📚 สอนลึกที่ W08

10. Tuple + Set

# Tuple = list แต่ "แก้ไม่ได้" — ใช้สำหรับค่าที่ไม่อยากให้เปลี่ยน point = (3, 5) print(point[0], point[1]) # point[0] = 10 # ❌ TypeError # unpacking — แยกค่าใส่ตัวแปร x, y = point print(f"x={x}, y={y}") # สลับค่าตัวแปร (Pythonic) a, b = 1, 2 a, b = b, a print(a, b) # 2 1 # Set = list แต่ "ไม่ซ้ำ + ไม่มีลำดับ" scores = [85, 72, 85, 91, 72] unique = set(scores) print(unique) # {72, 85, 91} — ไม่ซ้ำ print(len(unique)) # 3 # union / intersection A = {1, 2, 3} B = {2, 3, 4} print(A | B) # {1, 2, 3, 4} — รวม print(A & B) # {2, 3} — เหมือนกัน print(A - B) # {1} — ใน A แต่ไม่ใน B

11. Functions (def)

# 1. function ง่าย ๆ def greet(name): return f"สวัสดี {name}!" print(greet("Ploy")) # 2. หลาย parameter + default value def calc_grade(score, passing=50): if score >= passing: return "ผ่าน" return "ตก" print(calc_grade(75)) # ผ่าน (passing = 50 default) print(calc_grade(45, 40)) # ผ่าน (override default) # 3. keyword arguments — เรียกใช้ระบุชื่อ def make_user(name, age, role="student"): return {"name": name, "age": age, "role": role} print(make_user(name="Ploy", age=20)) print(make_user("Nat", 30, role="teacher")) # 4. คืน หลายค่า (จริง ๆ คืน tuple) def stats(numbers): return min(numbers), max(numbers), sum(numbers) / len(numbers) lo, hi, avg = stats([85, 72, 91, 60]) print(f"low={lo}, high={hi}, avg={avg:.2f}") # 5. *args (รับ argument กี่ตัวก็ได้) def total(*nums): return sum(nums) print(total(1, 2, 3)) # 6 print(total(1, 2, 3, 4, 5)) # 15 # 6. **kwargs (รับ keyword argument กี่ตัวก็ได้) def describe(**props): for k, v in props.items(): print(f"{k}: {v}") describe(name="Ploy", age=20, gpa=3.45)

📚 สอนลึกที่ W04 + W05 + W11

12. Import + Modules

import math print(math.pi) # 3.141592... print(math.sqrt(16)) # 4.0 print(math.floor(3.7)) # 3 print(math.ceil(3.2)) # 4 # from-import — เอามาเฉพาะตัว from random import randint, choice print(randint(1, 10)) # สุ่ม 1-10 print(choice(["A", "B", "C"])) # สุ่ม element # import + ตั้งชื่อสั้น (มาตรฐาน data science) import numpy as np import pandas as pd arr = np.array([1, 2, 3, 4]) print(arr.mean()) # 2.5 # import file ของตัวเอง # สมมุติมี helpers.py ใน folder เดียวกัน # from helpers import calc_grade # print(calc_grade(75))

📚 สอนลึกที่ W11 (จัดระเบียบ module)

13. อ่าน/เขียน ไฟล์

ตัวอย่างเขียนแล้วอ่านในที่เดียว (ใน Pyodide จะใช้ virtual filesystem):

# เขียน (mode="w" = write, ลบของเก่า) with open("students.txt", "w", encoding="utf-8") as f: f.write("Ploy 85\n") f.write("Nat 72\n") f.write("Mint 91\n") # อ่านทั้งหมด with open("students.txt", "r", encoding="utf-8") as f: content = f.read() print("ทั้งไฟล์:") print(content) # อ่านทีละบรรทัด — วิธีที่ใช้บ่อยสุด print("ทีละบรรทัด:") with open("students.txt", "r", encoding="utf-8") as f: for line in f: line = line.strip() # ตัด \n ทิ้ง name, score = line.split() print(f"{name} ได้ {score}") # เพิ่มต่อท้าย (append) — mode="a" with open("students.txt", "a", encoding="utf-8") as f: f.write("Pim 88\n") # CSV — ใช้ module csv (จะใช้ใน W08) import csv with open("scores.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["name", "score"]) writer.writerow(["Ploy", 85]) writer.writerow(["Nat", 72]) with open("scores.csv", "r", encoding="utf-8") as f: for row in csv.reader(f): print(row)
ทำไม with open(...) Block with ปิดไฟล์ให้อัตโนมัติแม้เกิด error · ไม่ต้องเขียน f.close() เอง · เป็น Python idiom

📚 สอนลึกที่ W08 (CSV) + W10 (real files)

14. Try / Except

def safe_divide(a, b): try: result = a / b except ZeroDivisionError: return "หารด้วย 0 ไม่ได้" except TypeError: return "type ผิด" else: # ทำเมื่อ try สำเร็จไม่ error return result finally: # ทำเสมอ — error หรือไม่ก็ตาม print("(ตรวจสอบเสร็จ)") print(safe_divide(10, 2)) # 5.0 print(safe_divide(10, 0)) # หารด้วย 0 ไม่ได้ print(safe_divide("10", 2)) # type ผิด # จับ exception ทุกชนิด (ระวังใช้ — ปกปิด bug ได้) try: score = int(input("คะแนน: ")) except ValueError as e: print(f"ใส่ตัวเลขสิ — error: {e}") # raise — โยน error เอง def set_age(age): if age < 0: raise ValueError("อายุติดลบไม่ได้") return age try: set_age(-5) except ValueError as e: print(f"ตรวจจับได้: {e}")

📚 สอนลึกที่ W13

15. Built-in Functions ที่ใช้บ่อย

Functionทำอะไรตัวอย่าง
len(x)ความยาวlen("hi") → 2 · len([1,2,3]) → 3
type(x)ดู typetype(42) → int
print(...)แสดงผลprint("hi")
input(prompt)รับจาก username = input("ชื่อ: ")
int(x) / float(x) / str(x) / bool(x)แปลง typeint("42") → 42
range(stop) / range(start, stop, step)ลำดับเลขlist(range(5)) → [0,1,2,3,4]
sum(iterable)ผลรวมsum([1,2,3]) → 6
min(...) / max(...)ค่าน้อย/มากสุดmax([1,5,3]) → 5
abs(x)ค่าสัมบูรณ์abs(-5) → 5
round(x, n)ปัดround(3.567, 1) → 3.6
sorted(iterable)เรียง (คืน list ใหม่)sorted([3,1,2]) → [1,2,3]
reversed(seq)กลับลำดับlist(reversed([1,2,3])) → [3,2,1]
enumerate(iterable)(index, value) คู่ดู section "for"
zip(a, b)จับคู่ 2 listsดู section "for"
any(...) / all(...)มี True ใดมั้ย / True ทุกตัวมั้ยall([True, True, False]) → False
map(f, iter)เรียก f กับทุก elementlist(map(int, ["1","2"])) → [1,2]
filter(f, iter)เก็บเฉพาะที่ f → Truelist(filter(lambda x: x>0, [-1,2,-3])) → [2]
help(x)ดู dochelp(str.split)

16. Gotchas ที่เจอบ่อย

1. Indentation ต้องสม่ำเสมอ

Python ใช้ การย่อหน้า แทน { } · ทุก block ใน if/for/def ต้องเยื้องเท่ากัน (4 ช่องมาตรฐาน) · ห้ามผสม Tab + Space · VS Code แก้ให้ด้วย "Convert Indentation"

2. input() คืน string เสมอ

x = input("ตัวเลข: ") # ❌ ถ้าจะ + 5 จะ error # x + 5 → TypeError: can only concatenate str (not "int") to str # ✅ ถูก: # x = int(input("ตัวเลข: ")) print(type(x)) # str เสมอ

3. = vs ==

= = assign · == = compare · ใน if ใช้ ==

4. Mutable default argument — ระวัง

# ❌ Buggy — default list ใช้ตัวเดียวกันทุกครั้ง def add_score(name, scores=[]): scores.append(name) return scores print(add_score("A")) # ['A'] print(add_score("B")) # ['A', 'B'] ← !! ของเก่ายังอยู่ # ✅ ถูก — ใช้ None แล้วสร้างใหม่ในฟังก์ชัน def add_score_ok(name, scores=None): if scores is None: scores = [] scores.append(name) return scores print(add_score_ok("A")) print(add_score_ok("B"))

5. is vs ==

== = ค่าเท่ากันมั้ย · is = object เดียวกันมั้ย · ใช้ is None เพื่อเช็ค None เสมอ (ไม่ใช่ == None)

6. ลืม return

function ที่ไม่มี return → คืน None โดยอัตโนมัติ · ถ้าได้ None ที่ไม่คาดคิด — ตรวจ return ก่อน

7. Copy list — = ไม่ใช่ copy

a = [1, 2, 3] b = a # ไม่ใช่ copy — ชี้ที่เดียวกัน b.append(4) print(a) # [1, 2, 3, 4] ← a โดนแก้ด้วย # ✅ copy จริง a = [1, 2, 3] b = a.copy() # หรือ b = list(a) หรือ b = a[:] b.append(4) print(a, b) # [1, 2, 3] [1, 2, 3, 4]

8. ลืมรอบ () ของ print ใน Python 3

Python 2: print "hi" · Python 3: print("hi") · คอร์สนี้ใช้ Python 3 ทั้งหมด


🤖 Cheat-sheet + AI = ทรัพย์สมบัติ

หน้านี้ดีกับการ "ลืม syntax" · ของลึก ๆ — ถาม AI · Prompt ที่ใช้ได้:

5 Prompts ที่ใช้ได้ทันที
  • "อธิบาย {code} ทีละบรรทัดในแบบนักศึกษาปี 1"
  • "เปรียบเทียบ list กับ tuple · ตอนไหนใช้แต่ละแบบ"
  • "function นี้คืน None เพราะอะไร · มี return ที่ลืมรึเปล่า?"
  • "แปลง pseudocode นี้ → Python 3.11 ใส่ type hints + docstring"
  • "ทำ trace table ของ for loop นี้ — 1 แถว = 1 รอบ"