Skip to content · ⁨ข้ามไปยังเนื้อหา⁩
Subjects · ⁨รายวิชา⁩
  • 1 Getting started
    1.1

    Your first program

    English

    Python runs your code one line at a time. Each line is a statement 语句. A program 程序 is just a list of statements that run from top to bottom.

    The print() function shows text on the screen. This is called output 输出. Text inside quotes is a string 字符串.

    • Each print() starts a new line.
    • Quotes can be "double" or 'single' — both make a string.
    • A program does nothing until you run it.
    ไทย

    Python รันโค้ดของคุณทีละบรรทัด แต่ละบรรทัดคือ statement Program ก็แค่รายการของ statements ที่รันจากบนลงล่าง

    ฟังก์ชัน print() แสดงข้อความบนหน้าจอ สิ่งนี้เรียกว่า output ข้อความภายในเครื่องหมายอ้อมคือ string

    print("Hello, world!")
    print("I am learning Python")
    
    • แต่ละ print() เริ่มต้นบรรทัดใหม่
    • Quotes สามารถเป็น "double" หรือ 'single' — ทั้งสองทำให้เป็น string
    • Program จะทำอะไรสักอย่างก็ต่อเมื่อคุณรันมันเท่านั้น
    Source code runs through the interpreter to produce output
    Source code runs through the interpreter to produce output
    1.2

    Comments & code style

    English

    A comment 注释 starts with #. Python ignores everything after the # on that line. Comments explain your code to people; they do not change what the code does.

    Good style makes code easy to read:

    • Use clear names that say what a value means.
    • Put one statement on each line.
    • Do not add spaces at the start of a normal line. In Python, spacing at the start (indentation 缩进) has a special meaning, so a wrong space gives an error 错误.
    ไทย

    Comment เริ่มด้วย # Python จะ ignore ทุกอย่างหลัง # บนบรรทัดนั้น Comment อธิบายโค้ดของคุณให้กับผู้อื่น—they do not change what the code does.

    # This line is a note for humans
    print("Hi")        # you can also comment at the end of a line
    

    Good style makes code easy to read:

    • ใช้ชื่อที่ชัดเจนเพื่อระบุความหมายของค่า
    • วางคำสั่งหนึ่งบรรทัดต่อหนึ่งบรรทัด
    • อย่าเพิ่มช่องว่างที่เริ่มต้นบรรทัดปกติ ใน Python การเว้นวรรคที่ต้นบรรทัด (indentation) มีความหมายพิเศษ ดังนั้นช่องว่างที่ผิดจะทำให้เกิดข้อผิดพลาด
    1.3

    ข้อมูลเข้า, กระบวนการ, ข้อมูลออก

    English

    Many programs follow a simple plan: input 输入 → process → output. You get some data, do something with it, then show a result.

    The input() function reads text that the user types. It always gives back a string.

    • input() waits for the user to type and press Enter.
    • Store the typed text in a variable 变量 so you can use it later.
    • Because input() returns a string, change it with int(...) first if you need a number.

    Common mistakes

    • Forgetting the quotes: print(Hello) looks for a variable named Hello and raises a NameError. Text needs quotes: print("Hello").
    • A stray space at the start of a line: Python reads indentation as structure, so it raises an IndentationError.
    • Assuming input() returns a number. It always returns a string, so wrap it in int(...) before doing any maths.
    ไทย

    โปรแกรมจำนวนมากปฏิบัติตามแผนพื้นฐาน: ข้อมูลเข้า → กระบวนการ → ข้อมูลออก คุณได้รับข้อมูลมา ทำบางอย่างกับมัน แล้วแสดงผลออกมา

    ฟังก์ชัน input() อ่านข้อความที่ผู้ใช้พิมพ์ มันจะให้ค่ากลับเป็น string เสมอ

    name = input("What is your name? ")
    print("Hello, " + name)
    
    • input() รอให้ผู้ใช้พิมพ์และกด Enter
    • เก็บข้อความที่พิมพ์ลงในตัวแปรเพื่อให้สามารถใช้งาน它在ในภายหลังได้
    • เนื่องจาก input()/value return เป็น string ให้แปลงด้วย int(...) ก่อนหากต้องการใช้ตัวเลข

    ข้อผิดพลาดที่พบบ่อย

    • ลืมเครื่องหมายคำพูด: print(Hello) จะมองหาตัวแปรชื่อ Hello และเกิด NameError ข้อความต้องใส่เครื่องหมายคำพูด: print("Hello")
    • ช่องว่างแปลกๆ ที่ ต้น บรรทัด: Python อ่านการเว้นวรรคเป็นโครงสร้าง จึงเกิด IndentationError
    • สมมติว่า input()/value return เป็นตัวเลข มันให้ค่ากลับเป็น string เสมอ ดังนั้นห่อด้วย int(...) ก่อนทำคณิตศาสตร์ใดๆ
  • 2 Variables, types & operators
    2.1

    ตัวแปร & การกำหนดค่า

    English

    A variable 变量 is a name for a value 值. You make one with =, which is called assignment 赋值. The name goes on the left; the value goes on the right.

    Now age holds 17. Use the name anywhere you need the value, and change it later:

    • The = sign does not mean "equal". It means "store the right side under the left name".
    • To test if two values are equal, use == (see below).
    ไทย

    ตัวแปรคือชื่อสำหรับค่า คุณสร้างมันด้วย = ซึ่งเรียกว่า assignment ชื่อไปอยู่ทางซ้าย ค่าไปอยู่ทางขวา

    age = 17
    name = "Mei"
    price = 9.99
    print(age, name, price)
    

    ตอนนี้ age/value holding 17. ใช้ชื่อนี้ได้ทุกที่ที่ต้องการค่า และเปลี่ยน它在ในภายหลัง:

    age = 17
    age = age + 1   # age is now 18
    print(age)
    
    ตัวแปรคือชื่อที่ผูกกับค่าที่จัดเก็บไว้
    ชื่อตัวแปรแต่ละตัวชี้ไปยังค่าในหน่วยความจำ
    • สัญญาณ =/sign ไม่หมายถึง "เท่ากับ" แต่หมายถึง "เก็บด้านขวาล่างชื่อด้านซ้าย"
    • เพื่อทดสอบว่าสองค่าเท่ากันหรือไม่ ให้ใช้ == (ดูด้านล่าง)
    2.2

    จำนวน: int & float

    English

    Python has two main number types. An integer 整数 (int) is a whole number like 17. A float 浮点数 (float) has a decimal point like 9.99.

    These operators 运算符 work on numbers:

    Operator Meaning Example Result
    + add 3 + 2 5
    - subtract 3 - 2 1
    * multiply 3 * 2 6
    / divide (always float) 7 / 2 3.5
    // integer divide 7 // 2 3
    % remainder (modulo) 7 % 2 1
    ** power 2 ** 3 8
    • / always gives a float, so 4 / 2 is 2.0.
    • // and % go together: 17 // 5 is 3, and 17 % 5 is 2.
    ไทย

    Python มีประเภทจำนวนหลัก 2 แบบ Integer (int) คือจำนวนเต็มเช่น 17 Float (float) มีทศนิยมเช่น 9.99

    ตัวดำเนินการเหล่านี้ทำงานกับจำนวน:

    ตัวดำเนินการ ความหมาย ตัวอย่าง ผลลัพธ์
    + บวก 3 + 2 5
    - ลบ 3 - 2 1
    * คูณ 3 * 2 6
    / หาร (ให้เป็น float เสมอ) 7 / 2 3.5
    // หารเอาเศษ (integer divide) 7 // 2 3
    % เศษเหลือ (modulo) 7 % 2 1
    ** ยกกำลัง 2 ** 3 8
    • //operator ให้ผลเป็น float เสมอ ดังนั้น 4 / 2/result คือ 2.0/result
    • // และ % ทำงานคู่กัน: 17 // 5/result คือ 3/result และ 17 % 5/result คือ 2/result
    2.3

    นิพจน์ & การแปลงประเภท

    English

    An expression 表达式 is anything that has a value, like 3 + 4 * 2. Python uses normal maths order (* and / before + and -); add brackets to make the order clear.

    input() gives a string, so convert it before doing maths. Changing a value from one type to another is type conversion 类型转换:

    • int("abc") fails, so only convert text that looks like a number.
    • Mixing types fails too: "age: " + 17 is an error; write "age: " + str(17).
    ไทย

    นิพจน์คือทุกอย่างที่มีค่า เช่น 3 + 4 * 2 Python ใช้ลำดับคณิตศาสตร์ปกติ (* และ / ทำก่อน + และ -); ใส่วงเล็บเพื่อทำให้ลำดับชัดเจน

    input()/value give string ดังนั้นแปลงมันก่อนทำคณิตศาสตร์ การเปลี่ยนค่าจากประเภทหนึ่งไปอีกประเภทหนึ่งคือการแปลงประเภท (type conversion):

    age = int("17")        # text "17" -> number 17
    price = float("9.99")  # text -> 9.99
    label = str(17)        # number -> text "17"
    print(age, price, label)
    
    • int("abc")/expression fails ดังนั้นแปลงเฉพาะข้อความที่ดูเหมือนตัวเลขเท่านั้น
    • การผสมประเภทก็ล้มเหลวเช่นกัน: "age: " + 17/expression เป็น error; เขียน "age: " + str(17)/expression แทน
    2.4

    Boolean & การเปรียบเทียบ

    English

    A Boolean 布尔值 is one of just two values: True or False. A comparison 比较 gives back a Boolean.

    Operator Meaning
    == equal to
    != not equal to
    < > less than / greater than
    <= >= less / greater than or equal to

    Join comparisons with and, or, not:

    Common mistakes

    • / always gives a float, even 4 / 2 is 2.0. Use // when you want a whole number.
    • Using = where you mean ==: = assigns a value, == tests whether two values are equal.
    • Joining a string and a number: "age: " + 5 raises a TypeError. Convert first with str(5).
    • Floats are not exact, so 0.1 + 0.2 is not exactly 0.3 — avoid == on float results.
    ไทย

    Boolean มีเพียงสองค่า: True หรือ False การเปรียบเทียบให้ค่ากลับเป็น Boolean

    ตัวดำเนินการ ความหมาย
    == เท่ากับ
    != ไม่เท่ากับ
    < > น้อยกว่า / มากกว่า
    <= >= น้อยกว่าหรือเท่ากับ / มากกว่าหรือเท่ากับ
    print(7 > 2)        # True
    print(3 == 3.0)     # True
    age = 20
    print(age >= 18)    # True
    

    เชื่อมการเปรียบเทียบด้วย and, or, not:

    age = 20
    print(age >= 13 and age <= 19)   # True only for a teenager
    

    ข้อผิดพลาดที่พบบ่อย

    • //function ให้ผลเป็นfloat เสมอ แม้ 4 / 2/condition จะ 2.0/condition ก็ตาม ใช้ ///function เมื่อต้องการจำนวนเต็ม
    • การใช้ =/assignment แทน ==/comparison: =/symbol assign ค่า, ==/symbol ทดสอบว่าสองค่าเท่ากันหรือไม่
    • การเชื่อม string กับ number: "age: " + 5/expression raise TypeError แปลงก่อนด้วย str(5)/function
    • Floats ไม่ใช่ค่าที่แม่นยำ ดังนั้น 0.1 + 0.2/expression ไม่ใช่ 0.3/value อย่างแท้จริง — หลีกเลี่ยง ==/comparison กับผลลัพธ์ของ float
  • 3 Strings · ⁨สตริง (Strings)⁩
    3.1

    Indexing

    English

    A string 字符串 is text inside quotes. Each character 字符 has a position, called its index 索引. The first index is 0, not 1.

    Read one character with square brackets:

    • Counting starts at 0, so the last index is len(word) - 1.
    • A negative index counts back from the end: word[-1] is the last character.
    • An index that is too large gives an error 错误 (an IndexError).
    ไทย

    String คือข้อความในเครื่องหมายคำพูด แต่ละตัวอักษรมีตำแหน่งเรียก它为 index ตัวแรกคือ 0 ไม่ใช่ 1

    อ่านตัวอักษรหนึ่งตัวด้วยสี่เหลี่ยมเหลี่ยม:

    word = "Python"
    print(word[0])    # P  (the first character)
    print(word[2])    # t
    print(len(word))  # 6  (how many characters)
    
    • การนับเริ่มที่ 0 ดังนั้น index สุดท้ายคือ len(word) - 1
    • Index เชิงลบนับถอยหลังจากท้าย: word[-1] คือตัวอักษรสุดท้าย
    word = "Python"
    print(word[-1])   # n
    print(word[-2])   # o
    
    • Index ที่ใหญ่เกินไปจะทำให้เกิดข้อผิดพลาด (an IndexError)
    s[start:stop] เป็นหน้าต่างครึ่งเปิดของตัวอักษร
    s[start:stop] เป็นหน้าต่างครึ่งเปิดของตัวอักษร
    3.2

    Slicing

    English

    A slice 切片 takes a part of a string. Write word[start:end]. The slice keeps start but stops before end.

    • Leave out start to begin at 0; leave out end to go to the end.
    • A third number is the step 步长. word[::-1] reverses 反转 the string.
    ไทย

    Slice Takes ส่วนหนึ่งของ string เขียน word[start:end] Slice จะเก็บ start แต่หยุด ก่อน end

    word = "Python"
    print(word[0:3])   # Pyt   (positions 0, 1, 2)
    print(word[2:5])   # tho
    
    • ทิ้ง start ไว้เพื่อเริ่มต้นที่ 0; ทิ้ง end ไว้เพื่อไปจนถึงท้าย
    word = "Python"
    print(word[:3])    # Pyt
    print(word[3:])    # hon
    
    • ตัวเลขที่สามคือขั้นตอน. word[::-1] จะกลับลำดับข้อความ.
    print("Python"[::-1])   # nohtyP
    
    3.3

    String methods & ความยาว

    English

    A method 方法 is a function that belongs to a value. You call it with a dot:

    Strings are immutable 不可变: a method returns a new string and never changes the original 原始 one.

    Common methods (each returns a new value):

    Method Meaning Example Result
    .upper() / .lower() change case "Hi".lower() hi
    .strip() remove edge spaces " hi ".strip() hi
    .replace(a, b) swap text "cat".replace("c", "b") bat
    .split(sep) break into a list "a,b".split(",") ['a', 'b']

    Join strings with +. This is called concatenation 拼接:

    ไทย

    Method คือฟังก์ชันที่ติดกับค่า คุณเรียกมันด้วยจุด:

    name = "mei chen"
    print(name.upper())     # MEI CHEN
    print(name.title())     # Mei Chen
    print(len(name))        # 8
    

    Strings เป็น immutable: Method ให้ค่ากลับเป็น string ใหม่ และไม่ pernah เปลี่ยนค่าเดิม

    name = "mei"
    print(name.upper())     # MEI  (the returned value)
    print(name)             # mei  (the original is unchanged)
    

    Methods ปกติ (แต่ละตัวให้ค่าใหม่):

    Method ความหมาย ตัวอย่าง ผลลัพธ์
    .upper() / .lower() เปลี่ยนกรณี "Hi".lower() hi
    .strip() ลบช่องว่างขอบ " hi ".strip() hi
    .replace(a, b) สลับข้อความ "cat".replace("c", "b") bat
    .split(sep) แยกเป็น list "a,b".split(",") ['a', 'b']

    เชื่อม strings ด้วย +. นี้เรียกว่า concatenation:

    first = "Mei"
    last = "Chen"
    print(first + " " + last)   # Mei Chen
    
    3.4

    f-strings

    English

    An f-string 格式化字符串 builds text from values. Put f before the quote, then write {...} around a value.

    • Any expression 表达式 can go inside the braces.
    • {value:.2f} rounds to 2 decimal places 小数位.

    Common mistakes

    • Strings cannot be changed in place: s[0] = "x" raises an error. Build a new string instead.
    • Indexing starts at 0; the last character is s[-1], and s[len(s)] is out of range.
    • A slice s[a:b] includes a but stops before b.
    • String methods return a NEW string: s.upper() does nothing unless you store the result.
    ไทย

    f-string สร้างข้อความจากค่าolumes f หน้าเครื่องหมายคำพูด แล้วเขียน {...} รอบค่า

    name = "Mei"
    age = 17
    print(f"{name} is {age} years old")   # Mei is 17 years old
    
    • นิพจน์อะไรก็ตามสามารถวางภายในวงเล็บปีกกาได้
    • {value:.2f}/format รด down ถึง 2 ตำแหน่งทศนิยม
    price = 9.5
    print(f"Two cost {price * 2}")        # Two cost 19.0
    print(f"Pi is about {3.14159:.2f}")   # Pi is about 3.14
    

    ข้อผิดพลาดที่พบบ่อย

    • Strings ไม่สามารถเปลี่ยนแปลงใน place: s[0] = "x"/operation raise error สร้าง string ใหม่แทน
    • Indexing เริ่มที่ 0; ตัวอักษรสุดท้ายคือ s[-1], และ s[len(s)] out of range
    • A slice s[a:b] includes a แต่หยุด ก่อน b
    • String methods ให้ค่ากลับเป็น NEW string: s.upper()/method ไม่ทำอะไรเลยเว้นแต่คุณ will store ผลลัพธ์
  • 4 Selection · ⁨การคัดเลือก⁩
    4.1

    if / elif / else

    English

    A program chooses what to do with if. It runs an indented 缩进 block only when a condition 条件 is true. The if line ends with a colon 冒号.

    Add elif (else-if) for more cases and else for "anything else". Python runs the first true branch 分支 only, then skips the rest.

    • Compare values with == (equal to), != (not equal to), <, >, <=, >=.
    • A comparison 比较 gives a Boolean 布尔值 — either True or False.
    ไทย

    โปรแกรมเลือกสิ่งที่จะทำกับ if. มันจะรันบล็อกที่เยื้องเฉพาะเมื่อเงื่อนไขเป็นจริง.บรรทัด if ต้องลงท้ายด้วยเครื่องหมายคั่น

    score = 72
    if score >= 60:
        print("pass")
    # pass
    

    เพิ่ม elif (else-if) สำหรับกรณีอื่นๆ และ else สำหรับ "ทุกกรณีที่เหลือ" Python จะรัน สาขาแรก ที่เป็นจริงเท่านั้น แล้วข้ามส่วนที่เหลือ

    score = 72
    if score >= 80:
        print("A")
    elif score >= 60:
        print("B")
    else:
        print("fail")
    # B
    
    • เปรียบเทียบค่าด้วย == (เท่ากับ), != (ไม่เท่ากัน), <, >, <=, >=.
    • การเปรียบเทียบให้ผลลัพธ์เป็น Boolean — คือ True หรือ False เท่านั้น
    if / elif / else: รันเพียงสาขาเดียว
    if / elif / else: รันเพียงสาขาเดียว
    4.2

    การรวมเงื่อนไข

    English

    Join conditions with and, or, not. and needs both sides true; or needs either side true; not flips a Boolean.

    • Use brackets to make the order clear: (a or b) and c.

    Common mistakes

    • Write elif, not else if.
    • Every if / elif / else line ends with a colon :, and its body must be indented.
    • if x = 5: is an error — use == to compare.
    • else takes no condition; only if and elif do.
    ไทย

    เชื่อมเงื่อนไขด้วย and, or, not. and ต้องการให้ ทั้งสอง ด้านเป็นจริง; or ต้องการให้ ด้านใดด้านหนึ่ง เป็นจริง; not กลับค่า Boolean

    age = 16
    has_ticket = True
    if age >= 18 and has_ticket:
        print("entry allowed")
    else:
        print("entry refused")
    # entry refused
    
    • ใช้วงเล็บเพื่อทำให้ลำดับชัดเจน: (a or b) and c.
    temp = 30
    if temp > 25 and not temp > 35:
        print("warm but ok")
    # warm but ok
    

    ข้อผิดพลาดที่พบบ่อย

    • เขียน elif, ไม่ใช่ else if.
    • ทุกบรรทัด if / elif / else ลงท้ายด้วยเครื่องหมายคั่น :, และบอดี้ต้องมีการเยื้อง
    • if x = 5: เป็นข้อผิดพลาด — ใช้ == เพื่อเปรียบเทียบ
    • else ไม่ต้องการเงื่อนไข; เฉพาะ if และ elif ที่ต้องการ
  • 5 Iteration · ⁨การวนซ้ำ⁩
    5.1

    ลูป for และ range

    English

    A loop 循环 repeats code. A for loop repeats once for each item in a sequence 序列. range(n) gives the numbers 0 up to n - 1.

    • range(a, b) goes from a up to (but not including) b.
    • range(a, b, step) adds a step 步长 each time.
    ไทย

    ลูปซ้ำโค้ดลูป for จะซ้ำสำหรับแต่ละรายการในลำดับ range(n) ให้ตัวเลข 0 ถึง n - 1

    for i in range(5):
        print(i)
    # 0, then 1, 2, 3, 4 (each on its own line)
    
    • range(a, b) ไปจาก a ขึ้นไป (แต่ไม่รวม) b
    • range(a, b, step) เพิ่มขั้นตอนในแต่ละครั้ง
    for n in range(2, 11, 2):
        print(n)        # 2 4 6 8 10
    
    for i in range(n): บอดี้รันด้วย i = 0 … n-1
    for i in range(n): บอดี้รันด้วย i = 0 … n-1
    5.2

    รูปแบบตัวสะสม

    English

    To build a result across a loop, start a variable before the loop, then update 更新 it each turn. This is the accumulator 累加器 pattern.

    • The same idea counts how many items match a test.
    ไทย

    การสร้างผลลัพธ์ตลอดการวนลูป ให้เริ่มตัวแปร ก่อน ลูป แล้วอัปเดตมันทุกรอบ นี่คือรูปแบบตัวสะสม

    total = 0
    for n in range(1, 6):
        total = total + n
    print(total)        # 15
    
    • หลักการเดียวกันนี้ใช้นับว่ามีรายการตรงกับการทดสอบกี่รายการ
    count = 0
    for letter in "banana":
        if letter == "a":
            count = count + 1
    print(count)        # 3
    
    5.3

    ลูป while

    English

    A while loop repeats as long as a condition stays true. Change something inside, or it never stops — an infinite loop 无限循环.

    • break leaves the loop straight away.
    ไทย

    ลูป while จะซ้ำ ตราบใดที่ เงื่อนไขยังคงเป็นจริง เปลี่ยนอะไรบางอย่างภายในแล้วจะไม่หยุดเลย — ลูป vô hạn

    n = 1
    while n <= 3:
        print(n)
        n = n + 1
    # 1 2 3
    
    • break ออกจากลูปทันที
    total = 0
    while True:
        total = total + 10
        if total >= 30:
            break
    print(total)        # 30
    
    5.4

    Nested loops

    English

    A loop inside another loop is a nested loop 嵌套循环. The inner loop 内层循环 runs fully for each turn of the outer loop 外层循环.

    Common mistakes

    • range(n) goes from 0 to n - 1, not 1 to n — the classic off-by-one error.
    • Changing a list while looping over it skips items; loop over a copy if you must remove things.
    • Forgetting to change the loop variable in a while makes it run forever.
    • Indentation decides what is inside the loop; a wrongly-indented line runs only once, after the loop.
    ไทย

    ลูปภายในอีกลูปหนึ่งคือลูปซ้อน ลูปภายในจะรันเต็มรูปแบบสำหรับ แต่ละ รอบของลูปภายนอก

    for row in range(3):
        line = ""
        for col in range(3):
            line = line + "*"
        print(line)
    # ***
    # ***
    # ***
    

    ข้อผิดพลาดที่พบบ่อย

    • range(n) ไปจาก 0 ถึง n - 1, ไม่ใช่ 1 ถึง n — ข้อผิดพลาด off-by-one แบบคลาสสิก
    • การเปลี่ยนลิสต์ขณะวนลูปจะทำให้ข้ามรายการ; ให้วนลูปบนสำเนาถ้าคุณจำเป็นต้องลบบางสิ่ง
    • การลืมเปลี่ยนตัวแปรลูปใน while จะทำให้มันรันตลอดกาล
    • การเยื้องกำหนดว่าอะไรอยู่ในลูป; บรรทัดเยื้องผิดจะรันเพียงครั้งเดียว หลังจบลูป
  • 6 Lists & 2-D lists
    6.1

    รายการ

    English

    A list 列表 holds many values in order, inside []. Each item 元素 has an index (from 0).

    • Change an item by its index: scores[1] = 100.
    • A list can grow and shrink; a string cannot.

    The everyday list tools:

    Tool Does
    a.append(x) adds x at the end
    a.insert(i, x) inserts x at position i
    a.remove(x) removes the first x
    a.pop() / a.pop(i) removes and returns the last item / item i
    a.sort() sorts the list in place
    sorted(a) returns a NEW sorted list
    x in a is x in the list?
    len(a), sum(a), max(a), min(a) size and quick maths
    ไทย

    ลิสต์เก็บหลายค่าตามลำดับ ภายใน []. แต่ละรายการมีดัชนี (ตั้งแต่ 0).

    scores = [88, 71, 95]
    print(scores[0])      # 88
    print(len(scores))    # 3
    scores.append(60)     # add to the end
    print(scores)         # [88, 71, 95, 60]
    
    • เปลี่ยนรายการโดยใช้ดัชนี: scores[1] = 100.
    • ลิสต์สามารถขยายและหดได้; สตริงไม่สามารถทำได้

    เครื่องมือลิสต์ในชีวิตประจำวัน:

    เครื่องมือ ทำอะไร
    a.append(x) เพิ่ม x ที่ปลายสุด
    a.insert(i, x) แทรก x ที่ตำแหน่ง i
    a.remove(x) ลบ x ตัวแรกออก
    a.pop() / a.pop(i) ลบและคืนค่ารายการสุดท้าย / รายการ i
    a.sort() เรียงลิสต์ในที่ itself
    sorted(a) คืนค่าลิสต์ที่เรียงลำดับใหม่
    x in a มี x อยู่ในรายการหรือไม่?
    len(a), sum(a), max(a), min(a) ขนาดและการคำนวณเร็ว
    ดัชนีลิสต์เริ่มต้นที่ 0
    ดัชนีลิสต์เริ่มต้นที่ 0
    6.2

    การ traverse ลิสต์

    English

    To traverse 遍历 a list is to visit each item. A for loop does this with no index needed.

    • Use enumerate when you also need the index.
    ไทย

    การ traverse ลิสต์คือการเข้าถึงแต่ละรายการ ลูป for ทำสิ่งนี้ได้โดยไม่ต้องใช้ดัชนี

    scores = [88, 71, 95]
    total = 0
    for s in scores:
        total = total + s
    print(total)          # 254
    
    • ใช้ enumerate เมื่อคุณยังต้องการดัชนีด้วย
    for i, name in enumerate(["a", "b"]):
        print(i, name)    # 0 a  /  1 b
    
    6.3

    ลิสต์ 2 มิติ (ตาราง)

    English

    A 2-D list 二维列表 is a list of lists — a grid 网格 of rows and columns. Use two indexes: grid[row][col].

    • A nested loop 嵌套循环 visits every cell.
    ไทย

    ลิสต์ 2 มิติคือลิสต์ของลิสต์ — ตารางของแถวและหลัก ใช้สองดัชนี: grid[row][col]

    grid = [[1, 2, 3],
            [4, 5, 6]]
    print(grid[0][2])     # 3
    print(grid[1][0])     # 4
    
    • ลูปซ้อนจะเข้าถึงทุกเซลล์
    grid = [[1, 2], [3, 4]]
    for row in grid:
        for value in row:
            print(value, end=" ")
    print()               # 1 2 3 4
    
    6.4

    List comprehensions

    English

    A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].

    • Add if to keep only some items.
    ไทย

    List comprehension สร้างลิสต์ใหม่ในบรรทัดเดียว: [expression for item in sequence]

    squares = [x * x for x in range(5)]
    print(squares)        # [0, 1, 4, 9, 16]
    
    • เพิ่ม if เพื่อเก็บเฉพาะบางรายการ
    evens = [n for n in range(10) if n % 2 == 0]
    print(evens)          # [0, 2, 4, 6, 8]
    
    6.5

    Tuples & sets

    English

    A tuple 元组 is a fixed sequence in round brackets. It cannot be changed after it is made — use one for values that belong together, and unpack 解包 it into names.

    A function that needs to hand back two results returns a tuple:

    A set 集合 stores each value once, with no order. It is perfect for removing duplicates and for fast membership tests 成员测试.

    Common mistakes

    • b = a does not copy a list: both names point to the same list, so changing one changes the other. Use a.copy() or a[:].
    • The last item is a[-1]; a[len(a)] is out of range.
    • append adds ONE item; use extend or + to join another list.
    • Building a grid with [[0]*3]*3 makes three copies of the same row. Build the rows in a loop instead.
    • A tuple with one item needs a comma: (5,), not (5).
    • A set has no order and no duplicates, so you cannot index it with s[0].
    ไทย

    Tuple เป็นลำดับคงที่ในวงเล็บกลม ไม่สามารถเปลี่ยนแปลงได้หลังจากสร้าง — ใช้สำหรับค่าที่เกี่ยวข้องกัน และแยกมันออกมาเป็นชื่อ

    point = (3, 4)
    x, y = point            # unpacking
    print(x, y)             # 3 4
    

    ฟังก์ชันที่ต้องการส่งผลลัพธ์สองค่าจะคืนค่า tuple:

    def min_max(nums):
        return min(nums), max(nums)
    
    lo, hi = min_max([5, 2, 9])
    print(lo, hi)           # 2 9
    

    Set เก็บแต่ละค่าเพียงครั้งเดียว โดยไม่มีลำดับ เหมาะสำหรับการลบค่าซ้ำและการทดสอบความเป็นสมาชิกอย่างรวดเร็ว

    votes = ["red", "blue", "red", "green", "red"]
    colours = set(votes)
    print(len(colours))         # 3  (duplicates removed)
    print("blue" in colours)    # True
    

    ข้อผิดพลาดที่พบบ่อย

    • b = a ไม่ คัดลอกลิสต์: ทั้งสองชื่อชี้ไปยังลิสต์เดียวกัน ดังนั้นการเปลี่ยนอันหนึ่งจะเปลี่ยนอีกอัน ใช้ a.copy() หรือ a[:]
    • รายการสุดท้ายคือ a[-1]; a[len(a)]อยู่นอกช่วงที่ยอมรับได้.
    • append เพิ่ม หนึ่ง รายการ; ใช้ extend หรือ + เพื่อรวมลิสต์อื่น
    • การสร้างตารางด้วย [[0]*3]*3 จะสร้างสำเนา แถวเดียวกัน สาม बार ให้สร้างแถวในลูปแทน
    • Tuple ที่มีรายการเดียวต้องมีลูกน้ำ: (5,), ไม่ใช่ (5)
    • Set ไม่มีลำดับและไม่มีความซ้ำซ้อน ดังนั้นคุณไม่สามารถใช้ดัชนีกับ s[0] ได้
  • 7 Dictionaries
    7.1

    Dictionary

    English

    A dictionary 字典 (dict) stores key 键 → value 值 pairs. You look up a value by its key, not by a number index.

    Add and update

    Assign to a key to add it, or to change an existing one.

    Check and loop

    Use in to test for a key. Loop over the keys, or over .items() to get both key and value.

    • .get(key, default) returns a default 默认值 when the key is missing — no error.

    The classic exam pattern — tally how often each value appears:

    • .get(letter, 0) supplies 0 the first time a key is seen, so there is no KeyError.

    Common mistakes

    • Reading a missing key with d[key] raises a KeyError; use d.get(key) or test if key in d first.
    • Assigning d[key] again overwrites the old value — keys are unique.
    • Keys must be immutable, such as a string or number — a list cannot be a key.
    ไทย

    Dictionary (dict) เก็บคู่ key → value คุณค้นหาค่าโดยใช้ key ไม่ใช่ดัชนีตัวเลข

    student = {"name": "Mei", "score": 88}
    print(student["name"])     # Mei
    print(student["score"])    # 88
    

    เพิ่มและอัปเดต

    กำหนดค่าให้ key เพื่อเพิ่มหรือเปลี่ยนแปลงที่มีอยู่

    student = {"name": "Mei"}
    student["score"] = 88      # add a new key
    student["score"] = 90      # update the value
    print(student)             # {'name': 'Mei', 'score': 90}
    

    ตรวจสอบและวนลูป

    ใช้ in เพื่อทดสอบ presence ของ key. โน้ตผ่าน keys, หรือผ่าน .items() เพื่อรับทั้ง key และ value

    student = {"name": "Mei", "score": 90}
    print("score" in student)  # True
    for key, value in student.items():
        print(key, "=", value)
    # name = Mei
    # score = 90
    
    • .get(key, default) คืนค่า default เมื่อ key หายไป — ไม่มีข้อผิดพลาด
    student = {"name": "Mei"}
    print(student.get("age", 0))   # 0
    

    รูปแบบข้อสอบคลาสสิก — นับว่าแต่ละค่าปรากฏบ่อยแค่ไหน:

    word = "banana"
    counts = {}
    for letter in word:
        counts[letter] = counts.get(letter, 0) + 1
    print(counts)   # {'b': 1, 'a': 3, 'n': 2}
    
    • .get(letter, 0) จัดเตรียม 0 ครั้งแรก中看到 key, ดังนั้นไม่มี KeyError

    ข้อผิดพลาดที่พบบ่อย

    • อ่าน key ที่หายไปด้วย d[key] จะเกิด KeyError; ใช้ d.get(key) หรือทดสอบ if key in d ก่อน
    • การกำหนดค่า d[key] อีกครั้งจะทับค่าเก่า — keys เป็นเอกลักษณ์
    • Keys ต้องเป็น immutable เช่น string หรือ number — list ไม่สามารถเป็น key ได้
    Dictionary map each key to one value
    Dictionary map each key to one value
  • 8 Functions & abstraction
    8.1

    การกำหนดและเรียกใช้ฟังก์ชัน

    English

    A function 函数 is a named block of code you can reuse. Define 定义 it with def, then call 调用 it by name.

    • The code inside runs only when you call the function.
    ไทย

    ฟังก์ชันคือบล็อกโค้ดที่มีชื่อที่คุณสามารถใช้งานซ้ำได้ กำหนดมันด้วย def แล้วเรียกใช้โดยชื่อ

    def greet():
        print("Hello!")
    
    greet()        # Hello!
    greet()        # Hello!
    
    • โค้ดภายในจะรันก็ต่อเมื่อคุณเรียกใช้ฟังก์ชัน
    defiking functions; calling functions; returning values
    def กำหนดฟังก์ชัน; call เรียกใช้; return ส่งค่ากลับ
    8.2

    ค่าที่ส่งกลับ (Return values)

    English

    A function can return 返回 a value with return. The call then stands for that value.

    • return ends the function at once. A function with no return gives None.
    ไทย

    ฟังก์ชันสามารถส่งค่ากลับด้วย return การเรียกใช้จะแทนที่ด้วยค่านั้น

    def square(n):
        return n * n
    
    print(square(5))          # 25
    print(square(3) + 1)      # 10
    
    • return จะหยุดการทำงานของฟังก์ชันทันที ฟังก์ชันที่ไม่มี return จะให้ None
    8.3

    พารามิเตอร์, อาร์กิวเมนต์ & สโคป

    English

    A parameter 形参 is the name in the def. An argument 实参 is the value you pass in.

    A variable made inside a function is local 局部 — it exists only there. That region is its scope 作用域.

    A parameter can have a default value 默认值, used when the caller leaves it out:

    ไทย

    พารามิเตอร์คือชื่อใน def อาร์กิวเมนต์คือค่าที่คุณส่งเข้าไป

    def power(base, exp):         # base, exp are parameters
        return base ** exp
    
    print(power(2, 3))            # 8  (2 and 3 are arguments)
    

    ตัวแปรที่สร้างภายในฟังก์ชันจะเป็น Local — มีอยู่เฉพาะที่นั้น พื้นที่นี้คือสโคปของมัน

    def f():
        x = 10            # local to f
        return x
    
    print(f())            # 10
    # print(x) here would be an error: x is not defined outside f
    

    พารามิเตอร์สามารถมีค่าเริ่มต้นได้ ใช้เมื่อผู้เรียกไม่ระบุ:

    def greet(name, greeting="Hello"):
        return greeting + ", " + name
    
    print(greet("Mei"))              # Hello, Mei
    print(greet("Sam", "Welcome"))   # Welcome, Sam
    
    8.4

    การนามธรรมเชิงขั้นตอน (Procedural abstraction)

    English

    Procedural abstraction 过程抽象 means hiding details behind a name. You use a function by its name and what it does, not by how it works.

    • A good function does one job, has a clear name, and avoids repeating code.
    ไทย

    การนามธรรมเชิงขั้นตอนคือการซ่อนรายละเอียดไว้หลังชื่อ คุณใช้ฟังก์ชันผ่านชื่อและสิ่งที่มันทำ ไม่ใช่ผ่านวิธีทำงาน

    def area_of_rectangle(w, h):
        return w * h
    
    print(area_of_rectangle(4, 5))   # 20
    
    • ฟังก์ชันที่ดีควรทำหน้าที่เดียว มีชื่อชัดเจน และหลีกเลี่ยงการซ้ำซ้อนของโค้ด
    8.5

    โมดูลและการนำเข้า (Modules & imports)

    English

    A module 模块 is a file of ready-made functions. Bring one in with import 导入.

    Common mistakes

    • A function returns None unless you write return. Printing is not the same as returning.
    • Never use a mutable default like def f(x=[]) — the same list is shared between all calls.
    • A variable made inside a function is local and cannot be seen outside it.
    • Run a function with f(); writing f on its own only names it.
    ไทย

    โมดูลคือไฟล์ที่มีฟังก์ชันสำเร็จรูป นำเข้าโดยใช้ import

    import random
    random.seed(0)               # makes the result repeatable
    print(random.randint(1, 6))  # a dice roll
    
    import math
    print(math.sqrt(16))         # 4.0
    

    ข้อผิดพลาดที่พบบ่อย

    • ฟังก์ชันจะคืนค่า None เว้นแต่คุณจะเขียน return การพิมพ์ไม่ใช่การส่งค่ากลับ
    • อย่าใช้ค่าเริ่มต้นแบบ mutable เช่น def f(x=[]) — ลิสต์เดียวกันจะถูกแชร์ระหว่างทุกการเรียกใช้
    • ตัวแปรที่สร้างภายในฟังก์ชันเป็น Local และไม่มองเห็นภายนอกได้
    • เรียกใช้ฟังก์ชันด้วย f(); การเขียน f เพียงอย่างเดียวเป็นการตั้งชื่อเท่านั้น
  • 9 Errors, exceptions & testing
    9.1

    ข้อผิดพลาดและการดีบัก (Errors & debugging)

    English

    Code can fail in three ways. A syntax error 语法错误 breaks Python's rules, so it never runs. A runtime error 运行时错误 happens while running, like dividing by zero. A logic error 逻辑错误 runs but gives the wrong answer.

    • Python prints a traceback 回溯 showing where it failed. Read it from the bottom up.
    ไทย

    โค้ดล้มเหลวได้สามแบบ: Syntax error ฝ่าฝืนกฎ Python จึงไม่รัน Runtime error เกิดขณะรัน เช่น หารด้วยศูนย์ Logic error รันได้แต่ให้คำตอบผิด

    # A runtime error, caught so this block still finishes:
    try:
        print(10 / 0)
    except ZeroDivisionError:
        print("cannot divide by zero")
    # cannot divide by zero
    
    • Python พิมพ์ traceback แสดงตำแหน่งที่ล้มเหลว อ่านจากล่างขึ้นบน
    Error ปกติของ Python: Syntax, Name, Type, Index
    Error ปกติของ Python: Syntax, Name, Type, Index
    9.2

    try / except / raise

    English

    Wrap risky code in try. If it fails, except catches the exception 异常 and handles 处理 it, instead of crashing.

    • Catch a specific type (ValueError, ZeroDivisionError, …).
    • raise makes your own error on purpose.
    ไทย

    ห่อหุ้มโค้ดเสี่ยงไว้ใน try หากล้มเหลว except จะจับ Exception และจัดการแทนการค้าง

    def to_int(text):
        try:
            return int(text)
        except ValueError:
            return 0
    
    print(to_int("42"))    # 42
    print(to_int("abc"))   # 0
    
    • จับประเภทเฉพาะ (ValueError, ZeroDivisionError, …)
    • raise สร้างข้อผิดพลาดของคุณเองโดยเจตนา
    def set_age(age):
        if age < 0:
            raise ValueError("age cannot be negative")
        return age
    
    try:
        set_age(-1)
    except ValueError as err:
        print("error:", err)
    # error: age cannot be negative
    
    9.3

    การทดสอบและความทนทาน (Testing & robustness)

    English

    A test 测试 checks that code gives the right answer. Try normal cases and edge cases 边界情形 — empty input, zero, very large values.

    • Robust 健壮 code does not crash on strange input; it handles it gracefully.

    Common mistakes

    • Do not use a bare except: — catch the specific error, e.g. except ValueError:.
    • A syntax error stops the whole program before it runs, so fix those first.
    • Test the edge cases (empty input, zero, the largest value), not just the easy one.
    ไทย

    การทดสอบตรวจสอบว่าโค้ดให้คำตอบถูกต้อง ลองกรณีปกติ และ กรณีขอบเขต — ข้อมูลว่าง, ศูนย์, ค่ามากพิเศษ

    def average(nums):
        if len(nums) == 0:        # edge case: empty list
            return 0
        return sum(nums) / len(nums)
    
    print(average([2, 4, 6]))     # 4.0
    print(average([]))            # 0
    
    • โค้ดที่ทนทานจะไม่ค้างเมื่อเจอข้อมูลแปลกๆ แต่จะจัดการอย่างเหมาะสม

    ข้อผิดพลาดที่พบบ่อย

    • อย่าใช้ bare except: — จับ Error เฉพาะ เช่น except ValueError:
    • Syntax error หยุดโปรแกรมทั้งหมดก่อนรัน ดังนั้นแก้ไขส่วนนั้นก่อน
    • ทดสอบกรณีขอบเขต (ข้อมูลว่าง, ศูนย์, ค่าสูงสุด) ไม่ใช่แค่กรณีง่าย
  • 10 Files · ⁨ไฟล์⁩
    10.1

    การอ่านและเขียนไฟล์ข้อความ (Reading & writing text files)

    English

    A text file 文本文件 stores text on disk. Open it with open(name, mode) where mode 模式 says read or write. Always use with, which closes the file for you.

    Writing

    Mode "w" writes a new file and erases any old one.

    Reading

    Mode "r" (the default) reads. .read() returns the whole file as one string.

    Line by line

    Loop over the file to get one line at a time. .strip() removes 去除 the newline 换行符 at the end.

    Appending

    Mode "a" appends 追加 — it adds to the end without erasing.

    Mode Meaning
    "r" read (default)
    "w" write (erases first)
    "a" append (add to the end)

    Common mistakes

    • Always close a file, or use with open(...) as f: which closes it for you.
    • read() gives the whole file as one string, and each line still ends with \n.
    • Opening with "w" erases the file first; use "a" to add to the end.
    ไทย

    ไฟล์ข้อความเก็บข้อมูลบนดิสก์ เปิดด้วย open(name, mode) โดย mode บอก read หรือ write ต้องใช้ with ซึ่งปิดไฟล์ให้คุณ

    การเขียน

    Mode "w" เขียนไฟล์ใหม่และลบเก่าออก

    with open("notes.txt", "w") as f:
        f.write("first line\n")
        f.write("second line\n")
    print("saved")            # saved
    

    การอ่าน

    Mode "r" (ค่าเริ่มต้น) อ่าน .read() คืนทั้งไฟล์เป็นสตริงเดียว

    with open("notes.txt", "w") as f:
        f.write("hello\nworld\n")
    with open("notes.txt") as f:
        print(f.read().strip())   # hello / world
    

    อ่านทีบรรทัด

    Loop ผ่านไฟล์เพื่อรับบรรทัดละหนึ่งบรรทัด .strip() ลบ newline ที่ท้ายออก

    with open("data.txt", "w") as f:
        f.write("Mei,88\nSam,71\n")
    with open("data.txt") as f:
        for line in f:
            name, score = line.strip().split(",")
            print(name, "scored", score)
    # Mei scored 88
    # Sam scored 71
    

    การเพิ่มต่อ (Appending)

    Mode "a" เพิ่มต่อ — เพิ่มที่ท้ายโดยไม่ลบ

    with open("log.txt", "w") as f:
        f.write("line 1\n")
    with open("log.txt", "a") as f:
        f.write("line 2\n")
    with open("log.txt") as f:
        print(f.read().strip())   # line 1 / line 2
    
    Mode ความหมาย
    "r" read (ค่าเริ่มต้น)
    "w" write (ลบก่อน)
    "a" append (เพิ่มที่ท้าย)

    ข้อผิดพลาดที่พบบ่อย

    • ปิดไฟล์เสมอ หรือใช้ with open(...) as f: ที่ปิดให้
    • read() ให้ทั้งไฟล์เป็นสตริง และแต่ละบรรทัดยังลงท้ายด้วย \n
    • เปิดด้วย "w" จะลบไฟล์ก่อน; ใช้ "a" เพื่อเพิ่มที่ท้าย
    open → read/write → close (with auto-closes)
    open → read/write → close (with auto-closes)
  • 11 Algorithm design
    11.1

    อัลกอริทึมและการแยกย่อย (Algorithms & decomposition)

    English

    An algorithm 算法 is a clear list of steps that solves a problem. Decomposition 分解 means breaking a big problem into smaller parts you can solve one at a time.

    • Abstraction 抽象 means ignoring detail: you use largest(...) without re-reading how it works.
    ไทย

    อัลกอริทึมคือรายการขั้นตอนที่ชัดเจนแก้ปัญหา Decomposition คือการแบ่งปัญหาย่อยเป็นชิ้นเล็กๆ แก้ทีละส่วน

    # Algorithm: find the largest number in a list
    def largest(nums):
        best = nums[0]
        for n in nums:
            if n > best:
                best = n
        return best
    
    print(largest([3, 9, 2, 7]))   # 9
    
    • Nามธรรมคือการละรายละเอียด: ใช้ largest(...) โดยไม่ต้องอ่านวิธีการทำงานซ้ำ
    11.2

    รหัสเทียมและแผนภาพไหล (Pseudocode & flowcharts)

    English

    Pseudocode 伪代码 is plain, structured English for an algorithm, written before the real code. It is not run.

    A flowchart 流程图 draws the same plan: a box for each step, a diamond for each decision 判断, and arrows for the order.

    ไทย

    รหัสเทียมคือภาษาอังกฤษที่มีโครงสร้างสำหรับอัลกอริทึม เขียนก่อนโค้ดจริง ไม่被执行

    SET best TO first number
    FOR Each number n
        IF n > best
          THEN
            SET best TO n
            OUTPUT best
    

    Flowchart วาดแผนเดียวกัน: กล่องสำหรับแต่ละขั้นตอน, เพชรสำหรับแต่ละการตัดสินใจ, และลูกศรสำหรับลำดับ

    11.3

    การเรียกซ้ำและ Call stack

    English

    Recursion 递归 is when a function calls itself. It needs a base case 基准情形 (a simple input that returns at once) and a recursive case 递归情形 (it calls itself on a smaller input).

    • Each paused call sits on the call stack 调用栈 until the call above it returns.

    Common mistakes

    • Recursion needs a base case, or it calls itself forever and crashes the call stack.
    • Pseudocode is for planning — it need not run, but every step must be unambiguous.
    • Break a big problem into small named steps before you write any code.
    ไทย

    Recursion คือฟังก์ชันเรียกตัวเอง ต้องการ base case (อินพุตง่ายที่คืนค่าทันที) และ recursive case (เรียกตัวเองกับอินพุตเล็กลง)

    Call stack สำหรับ factorial(3): ทุก call รอแล้ว return ตามลำดับย้อนกลับ
    Call stack สำหรับ factorial(3): ทุก call รอแล้ว return ตามลำดับย้อนกลับ
    def fact(n):
        return 1 if n <= 1 else n * fact(n - 1)
    
    print(fact(5))     # 120
    
    • ทุกการเรียกที่ถูกหยุดจะอยู่บน call stack จนกว่าการเรียกด้านบนจะคืนค่า

    ข้อผิดพลาดที่พบบ่อย

    • Recursion จำเป็นต้องมี base case มิฉะนั้นจะเรียกตัวเองตลอดจน call stack ค้าง
    • รหัสเทียมสำหรับการวางแผน — ไม่ต้องรัน แต่ทุกขั้นต้องชัดเจน
    • แบ่งปัญหาย่อยเป็นขั้นเล็กๆ ที่มีชื่อก่อนเขียนโค้ด
  • 12 Data structures
    12.1

    ประเภทข้อมูลนามธรรม (ADTs)

    English

    An abstract data type 抽象数据类型 (ADT) describes some data plus the operations on it, separate from how it is built. You use it through its operations, not through its inner storage.

    ไทย

    Abstract data type (ADT) อธิบายข้อมูลพร้อม operation แยกจากวิธีการสร้าง ใช้ผ่าน operation ไม่ใช่การจัดเก็บภายใน

    # A stack ADT, built on a list
    s = []
    s.append(1)        # add
    s.append(2)
    print(s.pop())     # 2  (remove the most recent)
    
    12.2

    Stack

    English

    A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.

    ไทย

    Stack เป็น Last-in, First-out (LIFO) Push ด้านบน Pop ด้านบน

    Stack ลบจากบน (LIFO); Queue ลบจากหน้า (FIFO)
    Stack ลบจากบน (LIFO); Queue ลบจากหน้า (FIFO)
    stack = []
    stack.append("a")
    stack.append("b")
    print(stack.pop())   # b
    print(stack.pop())   # a
    
    12.3

    Queue

    English

    A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.

    ไทย

    Queue เป็น First-in, First-out (FIFO) Enqueue หลัง Dequeue หน้า

    queue = []
    queue.append("a")     # enqueue
    queue.append("b")
    print(queue.pop(0))   # a  (dequeue the front)
    print(queue.pop(0))   # b
    
    12.4

    Linked lists

    English

    A linked list 链表 is a chain of nodes 节点. Each node holds data and a pointer 指针 to the next node; the last points to None.

    ไทย

    Linked list คือโซ่ของ Node แต่ละ Node เก็บข้อมูลและ Pointer ไป Node ถัดไป ตัวสุดท้ายชี้ None

    Linked list: แต่ละ Node เก็บข้อมูลและ Pointer ไป Node ถัดไป สิ้นสุดที่ None
    Linked list: แต่ละ Node เก็บข้อมูลและ Pointer ไป Node ถัดไป สิ้นสุดที่ None
    n3 = {"data": 3, "next": None}
    n2 = {"data": 2, "next": n3}
    n1 = {"data": 1, "next": n2}
    node = n1
    while node is not None:      # traverse to the end
        print(node["data"])
        node = node["next"]
    # 1 2 3
    
    12.5

    Hash tables

    English

    A hash table 哈希表 maps a key to a slot with a hash function 哈希函数. Two keys can land in the same slot — a collision 冲突. Python's dict is a hash table, so lookup is fast.

    ไทย

    Hash table映射 key กับ slot ด้วย hash function Two keys落地同一slot = Collision Python's dict เป็น hash table ดังนั้นค้นหาเร็ว

    Hash function映射แต่ละkeyสู่slot;สองkeyอาจcollision在同一slot
    ฟังก์ชันแฮชจับคู่คีย์แต่ละตัวเข้ากับช่องเก็บข้อมูล; คีย์สองตัวอาจชนกันอยู่ในช่องเดียวกัน
    table = {}
    table["Mei"] = 88
    table["Sam"] = 71
    print(table["Mei"])   # 88  (fast lookup by key)
    
    12.6

    Binary Search Trees

    English

    A binary search tree 二叉搜索树 (BST) keeps order: every left child is smaller than its node, every right child is larger. Search stays fast.

    ไทย

    ต้นไม้ค้นหาแบบเบย์ (BST) รักษาลำดับ: ลูกทางซ้ายมีค่าน้อยกว่าโหนดเสมอ ลูกทางขวามีค่ามากกว่า โน้ดเสมอ การค้นหาจึงรวดเร็ว

    ต้นไม้ค้นหาแบบเบย์: ค่าที่น้อยกว่าไปทางซ้าย, ค่าที่มากกว่าไปทางขวา
    ต้นไม้ค้นหาแบบเบย์: ค่าที่น้อยกว่าไปทางซ้าย, ค่าที่มากกว่าไปทางขวา
    def insert(root, val):
        if root is None:
            return {"val": val, "left": None, "right": None}
        if val < root["val"]:
            root["left"] = insert(root["left"], val)
        else:
            root["right"] = insert(root["right"], val)
        return root
    
    def inorder(root):
        if root is None:
            return []
        return inorder(root["left"]) + [root["val"]] + inorder(root["right"])
    
    tree = None
    for v in [5, 3, 8, 1, 4]:
        tree = insert(tree, v)
    print(inorder(tree))   # [1, 3, 4, 5, 8]
    
    12.7

    Graphs

    English

    A graph 图 is a set of vertices 顶点 joined by edges 边. An adjacency list 邻接表 — a dict of neighbour lists — is a common way to store one.

    Common mistakes

    • A stack is last-in-first-out; a queue is first-in-first-out. Do not mix them up.
    • Check whether a structure is empty before you pop or dequeue from it.
    • In a linked list, losing the head pointer loses the whole list.
    ไทย

    กราฟคือชุดของจุดยอดที่เชื่อมต่อกันด้วยเส้นเชื่อม วิธีจัดเก็บทั่วไปคือการใช้รายการติด毗邻 — ดิกชันนารีที่มีรายการเพื่อนบ้าน — เป็นวิธีจัดเก็บที่นิยมใช้

    A graph of vertices and edges, with its adjacency-list form
    กราฟของจุดยอดและเส้นเชื่อม พร้อมรูปแบบรายการติด毗邻
    graph = {"A": ["B", "D"], "B": ["A", "C"], "C": ["B", "D"], "D": ["A", "C"]}
    for vertex in graph:
        print(vertex, "->", graph[vertex])
    # A -> ['B', 'D']  (and so on for B, C, D)
    

    ข้อผิดพลาดที่พบบ่อย

    • สแต็กเป็นแบบเข้าหลังออกก่อน; ควูเป็นแบบเข้าก่อนออกก่อน อย่าสับสนกัน
    • ตรวจสอบว่าโครงสร้างนั้นว่างหรือไม่ ก่อนที่จะดึงหรือดีคิวจากมัน
    • ในลิงก์ลิสต์ หากสูญเสียพอยเตอร์ head จะทำให้เสียลิงก์ลิสต์ทั้งหมด
  • 13 Searching, sorting & efficiency
    13.1

    Linear & binary search

    English

    A search 查找 finds where a value is. Linear search 线性查找 checks each item in turn, so it works on any list.

    Binary search 二分查找 is much faster but needs a sorted list. It halves the range each step.

    ไทย

    การค้นหาคือการหาตำแหน่งของค่า การค้นหาเชิงเส้นตรวจสอบแต่ละรายการตามลำดับ ดังนั้นจึงใช้ได้กับทุกชนิดของลิงก์ลิสต์

    def linear_search(items, target):
        for i in range(len(items)):
            if items[i] == target:
                return i
        return -1     # not found
    
    print(linear_search([4, 8, 2, 9], 2))   # 2
    

    การค้นหาแบบเบย์เร็วกว่ามากแต่ต้องใช้ ลิงก์ลิสต์ ที่ เรียงลำดับ แล้ว มันจะแบ่งช่วงครึ่งหนึ่งในแต่ละขั้นตอน

    def binary_search(items, target):
        lo, hi = 0, len(items) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if items[mid] == target:
                return mid
            elif items[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1
    
    print(binary_search([1, 3, 5, 7, 9], 7))   # 3
    
    การค้นหาแบบเบย์แบ่งช่วงครึ่งหนึ่งในแต่ละขั้นตอน — O(log n) บนลิงก์ลิสต์ที่เรียงลำดับแล้ว
    การค้นหาแบบเบย์แบ่งช่วงครึ่งหนึ่งในแต่ละขั้นตอน — O(log n) บนลิงก์ลิสต์ที่เรียงลำดับแล้ว
    13.2

    การจัดอันดับ (บับเบิล & อินเซอร์ชัน)

    English

    To sort 排序 is to put items in order. Bubble sort 冒泡排序 repeatedly swaps 交换 neighbours that are in the wrong order.

    Insertion sort 插入排序 builds a sorted part one item at a time, sliding each new item back into its place:

    • In real code, use Python's built-in sorted():
    ไทย

    การจัดอันดับคือการวางรายการให้อยู่ในลำดับ บับเบิลโซrts ทำการสลับเพื่อนบ้านที่มีลำดับผิดซ้ำๆ

    def bubble_sort(a):
        a = a[:]                          # work on a copy
        for i in range(len(a)):
            for j in range(len(a) - 1 - i):
                if a[j] > a[j + 1]:
                    a[j], a[j + 1] = a[j + 1], a[j]
        return a
    
    print(bubble_sort([5, 2, 4, 1]))      # [1, 2, 4, 5]
    

    อินเซอร์ชันโซrts สร้างส่วนที่เรียงลำดับแล้วทีละรายการ โดยเลื่อนรายการใหม่กลับเข้าไปในตำแหน่งที่เหมาะสม:

    def insertion_sort(a):
        a = a[:]                           # work on a copy
        for i in range(1, len(a)):
            key = a[i]
            j = i - 1
            while j >= 0 and a[j] > key:   # shift bigger values right
                a[j + 1] = a[j]
                j -= 1
            a[j + 1] = key                 # drop key into the gap
        return a
    
    print(insertion_sort([5, 2, 4, 1]))   # [1, 2, 4, 5]
    
    • ในโค้ดจริง ให้ใช้ sorted() ในPython builtin:
    print(sorted([5, 2, 4, 1]))           # [1, 2, 4, 5]
    
    13.3

    ประสิทธิภาพของอัลกอริทึม

    English

    Efficiency 效率 asks how the work grows as the input grows. We describe it with Big-O 大O记号.

    Big-O Name Example
    $O(1)$ constant look up a dict key
    $O(\log n)$ logarithmic binary search
    $O(n)$ linear linear search
    $O(n^2)$ quadratic bubble sort
    ไทย

    ประสิทธิภาพถามว่างานเพิ่มขึ้นอย่างไรเมื่ออินพุตเพิ่มขึ้น เราอธิบาย它以 Big-O

    จำนวนขั้นตอนเพิ่มขึ้นตามขนาดอินพุตสำหรับความซับซ้อนทั่วไป
    จำนวนขั้นตอนเพิ่มขึ้นตามขนาดอินพุตสำหรับความซับซ้อนทั่วไป
    Big-O ชื่อ ตัวอย่าง
    $O(1)$ คงที่ ดูค่าดิกชันนารี
    $O(\log n)$ ลอการิทึม การค้นหาแบบเบย์
    $O(n)$ เชิงเส้น การค้นหาเชิงเส้น
    $O(n^2)$ สี่เหลี่ยม บับเบิลโซrts
    def steps(n):           # how many steps a linear scan takes
        count = 0
        for i in range(n):
            count = count + 1
        return count
    
    print(steps(100))       # 100  -> O(n)
    
    13.4

    ความสุ่มและการจำลอง

    English

    The random module makes random numbers. Use a seed 种子 to make results repeatable. A simulation 模拟 runs many random trials to estimate an answer.

    Common mistakes

    • Binary search only works on a sorted list.
    • Big-O tells you how the time GROWS, not the exact time; an O(n²) method beats O(n) only for tiny inputs.
    • Bubble sort is O(n²) — fine for learning, but slow on large lists.
    ไทย

    โมดูล random ใช้สร้างตัวเลขสุ่ม. ใช้ค่าเริ่มต้น (seed) เพื่อให้ผลลัพธ์ซ้ำกันได้. การจำลองสถานการณ์จะทำการทดลองสุ่มจำนวนมากเพื่อประมาณคำตอบ.

    import random
    random.seed(0)
    rolls = [random.randint(1, 6) for _ in range(1000)]
    print(rolls.count(6))   # about 1/6 of 1000
    

    ข้อผิดพลาดที่พบบ่อย

    • การค้นหาแบบเบย์ใช้ได้เฉพาะกับ ลิงก์ลิสต์ ที่ เรียงลำดับ เท่านั้น
    • Big-O บอกคุณว่าเวลาเพิ่มขึ้นอย่างไร ไม่ใช่เวลาแน่นอน; วิธี O(n²) ดีกว่า O(n) สำหรับอินพุตขนาดเล็กเท่านั้น
    • บับเบิลโซrts เป็น O(n²) — เหมาะสำหรับการเรียนรู้ แต่ช้าสำหรับลิงก์ลิสต์ขนาดใหญ่
  • 14 OOP & paradigms
    14.1

    คลาสและออบเจกต์

    English

    A class 类 is a blueprint. An object 对象 is one thing built from it (an instance 实例). __init__ is the constructor 构造方法 that sets up each object; self is the object itself.

    • name is an attribute 属性 (data on the object); speak is a method 方法 (an action).

    Add __str__ to control what print(obj) shows:

    ไทย

    คลาสคือแบบร่าง ออบเจกต์คือสิ่งหนึ่งสร้างจากมัน (instance) __init__ คือ constructor ที่ตั้งค่าแต่ละออบเจกต์; self คือออบเจกต์เอง

    class Dog:
        def __init__(self, name):
            self.name = name            # an attribute
        def speak(self):
            return self.name + " says woof"
    
    d = Dog("Rex")
    print(d.speak())     # Rex says woof
    
    • name เป็นแอททริบิวต์ (ข้อมูลบนออบเจกต์); speak เป็นเมทอด (การกระทำ)

    เพิ่ม __str__ เพื่อควบคุมสิ่งที่ print(obj) แสดง:

    class Dog:
        def __init__(self, name):
            self.name = name
        def __str__(self):
            return f"Dog named {self.name}"
    
    print(Dog("Rex"))    # Dog named Rex
    
    คลาสคือแบบร่าง; การเรียกใช้มันสร้างออบเจกต์
    คลาสคือแบบร่าง; การเรียกใช้มันสร้างออบเจกต์
    14.2

    การสืบทอด การห่อหุ้ม และความหลากหลาย

    English

    Inheritance 继承 lets a subclass 子类 reuse a superclass 父类. Use super() to call the parent; override 重写 a method to change it.

    Encapsulation 封装 hides data behind methods; a leading underscore marks it private 私有.

    Polymorphism 多态 means one name, many behaviours — the right speak runs for each object.

    ไทย

    การสืบทอดช่วยให้ subclass นำ superclass มาใช้ใหม่ ใช้ super() เพื่อเรียก parent; Overrideメソッドเพื่อเปลี่ยนมัน

    class Animal:
        def speak(self):
            return "some sound"
    
    class Cat(Animal):
        def speak(self):                # override
            return "meow"
    
    print(Cat().speak())   # meow
    

    การห่อหุ้มซ่อนข้อมูลไว้ پشتメソড; Underline นำหน้าบ่งบอกว่าเป็น private

    class Account:
        def __init__(self):
            self._balance = 0           # private
        def deposit(self, n):
            self._balance += n
        def balance(self):
            return self._balance
    
    a = Account()
    a.deposit(50)
    print(a.balance())     # 50
    

    ความหลากหลายหมายถึงชื่อเดียวพฤติกรรมหลายอย่าง —метод speak ที่ถูกต้องจะรันสำหรับแต่ละออบเจกต์

    class Cat:
        def speak(self):
            return "meow"
    
    class Cow:
        def speak(self):
            return "moo"
    
    for animal in [Cat(), Cow()]:
        print(animal.speak())   # meow, then moo
    
    14.3

    แนวคิดการเขียนโปรแกรม

    English

    A paradigm 范式 is a style of writing programs. Procedural 过程式 code is a sequence of steps and functions. Object-oriented 面向对象 code groups data and methods into objects. Declarative 声明式 code says what you want, not how (a list comprehension or SQL).

    Common mistakes

    • Every method needs self as its first parameter.
    • __init__ sets up a new object and runs automatically when you create one.
    • Two objects of the same class have separate attributes; changing one does not change the other.
    ไทย

    Paradigmคือสไตล์การเขียนโปรแกรม โค้ด proceduralคือลำดับขั้นตอนและ functions. โค้ด object-orientedรวม data และメソッドเข้าด้วยกันเป็น objects. โค้ด declarativeบอก what คุณต้องการ ไม่ใช่ how (list comprehension หรือ SQL)

    def total(nums):           # procedural
        t = 0
        for n in nums:
            t += n
        return t
    print(total([1, 2, 3]))    # 6
    
    print(sum([1, 2, 3]))      # 6  (declarative: same result)
    

    ข้อผิดพลาดที่พบบ่อย

    • Everyメ道ต้อง self เป็น first parameter ของมัน
    • __init__ ตั้งค่า new object และรันอัตโนมัติเมื่อคุณสร้างมัน
    • Two objects ของ same class มี separate attributes; เปลี่ยน one ไม่ทำให้ other เปลี่ยน
  • 15 Data representation
    15.1

    บิตและระบบเลขฐานสอง

    English

    A bit 比特 is a single 0 or 1. Binary 二进制 is the base-2 number system: each place is worth twice the one to its right (1, 2, 4, 8, …). Denary 十进制 (base-10) is our normal numbers.

    • 8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.

    Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:

    ไทย

    Bitคือ 0 หรือ 1 เดียว ระบบเลขฐานสองคือระบบเลข base-2: แต่ละตำแหน่งมีค่าเท่าสองเท่าของตำแหน่งทางขวา (1, 2, 4, 8, …) Decimal (base-10) คือตัวเลขปกติของเรา

    ตำแหน่งเลขฐานสอง: 1101 หมายถึง 8 + 4 + 1 = 13
    ตำแหน่งเลขฐานสอง: 1101 หมายถึง 8 + 4 + 1 = 13
    print(bin(13))         # 0b1101
    print(int("1101", 2))  # 13
    
    • 8 bits ทำให้ byte. Width ที่กำหนดสามารถ overflow (wrap around) เมื่อตัวเลขมีค่ามากเกินไป
    x = 250
    x = (x + 10) % 256     # one byte wraps at 256
    print(x)               # 4
    

    Hexadecimal (base 16) เป็นวิธีอ่าน binary แบบกระชับ:的数字หนึ่ง hex ตัวแทนให้สี่ bits พอดี Python เขียน hex ด้วย 0x:

    print(hex(255))        # 0xff
    print(0xFF)            # 255
    print(int("ff", 16))   # 255
    
    15.2

    การบีบอัด

    English

    Compression 压缩 makes data smaller. Lossless 无损 compression keeps every bit, so you rebuild the original exactly. Lossy 有损 compression throws away detail — smaller but not exact — and is used for photos and music.

    Run-length encoding 游程编码 is a simple lossless method: store a run 游程 (a repeat) as a count plus the value.

    Common mistakes

    • n bits store 2**n different values, from 0 up to 2**n - 1.
    • Lossy compression throws away detail and cannot be undone; lossless can be reversed exactly.
    ไทย

    Compressionทำให้ข้อมูลเล็กลง Lossless compressionเก็บทุก bit ดังนั้นคุณจึงสร้างต้นฉบับขึ้นใหม่ได้อย่างแม่นยำ Lossy compressionทิ้งรายละเอียด — เล็กลงแต่ไม่แม่นยำ — และใช้สำหรับรูปถ่ายและเพลง

    Run-length encodingเป็นวิธี lossless ง่าย: เก็บ run (repeat) เป็น count plus ค่า

    def rle(text):
        out = ""
        i = 0
        while i < len(text):
            run = 1
            while i + run < len(text) and text[i + run] == text[i]:
                run += 1
            out += str(run) + text[i]
            i += run
        return out
    
    print(rle("AAAABBBCCD"))   # 4A3B2C1D
    

    ข้อผิดพลาดที่พบบ่อย

    • n บิต สามารถเก็บค่าที่แตกต่างกันได้ 2**n ค่า, ตั้งแต่ 0 ถึง 2**n - 1.
    • Lossy compression ทิ้งรายละเอียดและไม่สามารถย้อนกลับได้; lossless สามารถย้อนกลับได้อย่างแม่นยำ
  • 16 Computing concepts
    16.1

    คอมพิวเตอร์คืออะไรและวงจรการออกแบบ

    English

    Computing 计算 means solving problems with computers: input, process, output. Good software is built in a design cycle 设计循环 — plan, write, test, improve — repeated many times.

    • Break a problem down, build a small part, test it, then add more.
    • Programmers work in teams and reuse each other's code.
    ไทย

    Computingหมายถึงการแก้ปัญหาด้วยคอมพิวเตอร์: input, process, output. Softwareที่ดีสร้างในวงจรการออกแบบ — plan, write, test, improve — ทำซ้ำหลายครั้ง

    • แยกปัญหาออก สร้างส่วนเล็กๆ ทดสอบ แล้วเพิ่มมากขึ้น
    • Programmers ทำงานเป็นทีมและนำโค้ดของผู้อื่นกลับมาใช้ใหม่
    16.2

    อินเทอร์เน็ต

    English

    The Internet 互联网 is a network 网络 of networks. Data is split into packets 数据包 that travel separately and are put back together at the other end. Shared rules called protocols 协议 (such as TCP/IP) make this work. If one path breaks, packets take another route — this is redundancy 冗余, which gives fault tolerance 容错.

    Layer Job
    HTTP request and send web pages
    TCP reliable delivery, in order
    IP addressing and routing
    ไทย

    Internetคือเครือข่ายของเครือข่าย ข้อมูลถูกแบ่งเป็น packets ที่เดินทางแยกต่างหากและประกอบกลับที่另一端 Shared rules called protocols (เช่น TCP/IP) ทำให้สิ่งนี้ทำงานได้ ถ้าเส้นทางหนึ่งล้มเหลว packets จะเลือกเส้นทางอื่น — นี่คือ redundancy ซึ่งให้ความทนทานต่อความผิดพลาด

    แผนที่ Internet: เส้นแต่ละเส้นคือเส้นทางระหว่างสอง networks
    แผนที่ Internet: เส้นแต่ละเส้นคือเส้นทางระหว่างสอง networks
    ชั้น งาน
    HTTP ขอและส่งหน้าเว็บ
    TCP ส่งมอบที่เชื่อถือได้ ตามลำดับ
    IP การกำหนดที่อยู่และการส่งต่อข้อมูล
    16.3

    การประมวลผลแบบขนานและการกระจาย

    English

    Sequential 顺序 code does one step at a time. Parallel 并行 computing does several steps at once on many cores 核心, which can give a speedup 加速. Distributed 分布式 computing spreads the work across many computers, such as a cloud.

    • Not everything can run in parallel: some steps must wait for an earlier result.
    ไทย

    โค้ดแบบลำดับทำงานทีละขั้นตอน การประมวลผลแบบขนานทำหลายขั้นตอนพร้อมกันบนคอร์หลายตัว ซึ่งสามารถเร่งความเร็วได้ การประมวลผลแบบกระจายงานจะแบ่งภาระงานไปทั่วคอมพิวเตอร์หลายเครื่อง เช่น บนคลาวด์

    • ไม่ใช่ทุกอย่างที่รันแบบขนานได้: บางขั้นตอนต้องรอผลลัพธ์จากขั้นตอนก่อนหน้า
    16.4

    ผลกระทบของการประมวลผลข้อมูล

    English

    Computing brings both benefits and harms. The digital divide 数字鸿沟 means not everyone has equal access to it. Software can carry bias 偏见 from the data it learns from. Respect intellectual property 知识产权 (licences), and protect people's personal data 个人数据 and privacy 隐私.

    Common mistakes

    • The Internet and the World Wide Web are not the same: the Web is one service that runs on top of the Internet.
    • More processor cores help only if the work can be split into parts that run at the same time.
    ไทย

    การประมวลผลข้อมูลมีทั้งประโยชน์และโทษ ความเหลื่อมล้ำทางดิจิทัลหมายถึงไม่ทุกคนเข้าถึงได้อย่างเท่าเทียม ซอฟต์แวร์อาจมีอคติจากข้อมูลที่ใช้เรียนรู้ ควรเคารพทรัพย์สินทางปัญญา (ใบอนุญาต) และปกป้องข้อมูลส่วนบุคคลและความส่วนตัวของผู้ใช้

    ข้อผิดพลาดที่พบบ่อย

    • อินเทอร์เน็ตและ World Wide Web ไม่เหมือนกัน: Web เป็นบริการหนึ่ง运行的อยู่บนอินเทอร์เน็ต
    • คอร์โปรเซสเซอร์越多ช่วยได้ก็ต่อเมื่องานสามารถแบ่งเป็นส่วนที่รันพร้อมกันได้เท่านั้น
  • 17 Putting it together · ⁨การรวมกัน⁩
    17.1

    โปรเจกต์ย่อยแบบครบวงจร

    English

    A mini-project 小项目 combines earlier ideas: data in a list, a function with selection inside a loop, and printed output. This is also the shape of the AP Create Performance Task.

    Project: average mark

    Project: count passes

    Project: filter to a new list

    The AP Create Task wants a list, a parameterised procedure 过程 that uses selection 选择 and iteration 迭代, and some input/output. Each project above is exactly that shape — build small pieces, then join them.

    Common mistakes

    • Build in small steps and test each part before moving on — do not write it all at once.
    • Read the whole task first, then plan the input → process → output before you code.
    ไทย

    โปรเจกต์ย่อยรวมแนวคิดเดิมๆ เข้าด้วยกัน: ข้อมูลในลิสต์ ฟังก์ชันที่มีคำสั่งเลือกภายในลูป และการพิมพ์ผลลัพธ์ นี่คือรูปแบบของ AP Create Performance Task

    โปรเจกต์: คำนวณคะแนนเฉลี่ย

    def average(marks):
        if len(marks) == 0:
            return 0
        return round(sum(marks) / len(marks), 1)
    
    print(average([88, 71, 95, 60]))   # 78.5
    

    โปรเจกต์: นับจำนวนผ่านเกณฑ์

    def count_passes(marks, pass_mark=60):
        passes = 0
        for m in marks:                 # iteration
            if m >= pass_mark:          # selection
                passes += 1
        return passes
    
    print(count_passes([88, 50, 95, 60]))   # 3
    

    โปรเจกต์: กรองข้อมูลลงลิสต์ใหม่

    def merit(marks):
        return [m for m in marks if m >= 80]
    
    print(merit([88, 71, 95, 60]))     # [88, 95]
    

    AP Create Task ต้องการลิสต์ กระบวนการที่มีพารามิเตอร์ซึ่งใช้การเลือกและลูป以及一些输入输出。แต่ละโปรเจกต์ข้างต้นมีรูปแบบดังนี้ — สร้างชิ้นส่วนเล็กๆ แล้วนำมารวมกัน

    ข้อผิดพลาดที่พบบ่อย

    • สร้างทีละขั้นและทดสอบแต่ละส่วนก่อนไปต่อ — อย่าเขียนทั้งหมดพร้อมกัน
    • อ่านโจทย์ทั้งหมดก่อน แล้ววางแผนอินพุต → ประมวลผล → เอาต์พุตก่อนเริ่มเขียนโค้ด
    โปรเจกต์ย่อย: ข้อมูล → ฟังก์ชัน → ผลลัพธ์ที่พิมพ์
    โปรเจกต์ย่อย: ข้อมูล → ฟังก์ชัน → ผลลัพธ์ที่พิมพ์

Log in or create account · ⁨เข้าสู่ระบบหรือสร้างบัญชี⁩

IGCSE, A-Level & AP