🐍 เรียนรู้การเขียนโปรแกรม PythonLearn Python Programming学习 Python 编程

คู่มือเริ่มต้นสำหรับผู้ที่ต้องการเรียนรู้ Python ตั้งแต่พื้นฐาน

A beginner's guide for anyone who wants to learn Python from the ground up

从零开始学习 Python 编程的入门指南

⌨️แป้นพิมพ์ที่สำคัญสำหรับการเขียน PythonEssential Keyboard Keys for PythonPython 编程必备的键盘按键

ก่อนเริ่มเขียนโค้ด Python คุณควรรู้จักแป้นพิมพ์เหล่านี้ที่จะใช้บ่อยมาก:

Before you start writing Python code, get familiar with these keys — you'll use them constantly:

在开始写 Python 代码之前,先熟悉这些按键——它们会用得非常频繁:

" '
Quote
เครื่องหมายคำพูด
引号
:
Colon
โคลอน
冒号
Tab ↹
Tab
แท็บ (เว้นย่อหน้า)
制表符(缩进)
( )
Parentheses
วงเล็บกลม
圆括号
[ ]
Brackets
วงเล็บเหลี่ยม
方括号
{ }
Braces
ปีกกา
花括号
=
Equals
เท่ากับ
等号
#
Hash
แฮช (สำหรับคอมเมนต์)
井号(注释用)
,
Comma
จุลภาค
逗号
.
Period/Dot
จุด
句点
_
Underscore
ขีดล่าง
下划线
+ -
Plus/Minus
บวก/ลบ
加号 / 减号

📚พื้นฐานการเขียนโปรแกรม PythonPython Programming BasicsPython 编程基础

การแสดงผลข้อความ (Print)Printing Text (Print)打印文本(Print)

ใน Python เราใช้ print() เพื่อแสดงข้อความบนหน้าจอ:

In Python we use print() to display text on the screen:

在 Python 里,我们用 print() 在屏幕上显示文字:

# นี่คือการแสดงข้อความ print("สวัสดีครับ") print("ฉันกำลังเรียน Python") # แสดงตัวเลข print(100) print(3.14)
# This prints text print("Hello!") print("I'm learning Python") # Print numbers print(100) print(3.14)
# 这是打印文本 print("你好!") print("我在学 Python") # 打印数字 print(100) print(3.14)
💡 เคล็ดลับ: เครื่องหมาย # ใช้สำหรับเขียนคอมเมนต์ (comment) โปรแกรมจะไม่ทำงานในบรรทัดที่มี #
💡 Tip: The # symbol starts a comment. Python ignores anything on the line after a # — comments are notes for humans.
💡 小贴士: # 符号用来写注释。Python 会忽略 # 之后的内容——注释是写给人看的笔记。

ตัวแปร (Variables)Variables变量(Variables)

ตัวแปรคือที่เก็บข้อมูล เราใช้เครื่องหมาย = เพื่อกำหนดค่า:

A variable stores a value. Use the = sign to assign one:

变量是用来存值的"容器"。我们用 = 给它赋值:

# สร้างตัวแปร name = "สมชาย" age = 25 height = 175.5 # ใช้ตัวแปร print(name) print("อายุ:", age)
# Create variables name = "Somchai" age = 25 height = 175.5 # Use the variables print(name) print("Age:", age)
# 创建变量 name = "小明" age = 25 height = 175.5 # 使用变量 print(name) print("年龄:", age)

การคำนวณCalculations数学运算

Python สามารถคำนวณเลขได้:

Python can do arithmetic right out of the box:

Python 可以直接做四则运算:

# การบวก ลบ คูณ หาร result = 10 + 5 print(result) # 15 price = 100 * 3 print(price) # 300 average = 50 / 2 print(average) # 25.0
# Add, subtract, multiply, divide result = 10 + 5 print(result) # 15 price = 100 * 3 print(price) # 300 average = 50 / 2 print(average) # 25.0
# 加 减 乘 除 result = 10 + 5 print(result) # 15 price = 100 * 3 print(price) # 300 average = 50 / 2 print(average) # 25.0

📖คำศัพท์สำคัญในการเขียนโปรแกรมImportant Programming Terms编程重要术语

Variable
ตัวแปร
变量
ที่เก็บข้อมูล เปรียบเสมือนกล่องที่ใส่ข้อมูลไว้ และสามารถเปลี่ยนค่าได้
ตัวอย่าง:
A named container that holds a value. Like a labeled box you can put data into — and the contents can change.
Example:
一个有名字的"容器",用来存放数据。就像贴了标签的盒子,里面的东西可以随时换。
例子:
x = 10
String
สตริง (ข้อความ)
字符串(文本)
ข้อมูลประเภทข้อความ ต้องใช้เครื่องหมายคำพูด " " หรือ ' ' ครอบ
ตัวอย่าง: "Hello" หรือ 'สวัสดี'
Text data. Must be wrapped in double quotes " " or single quotes ' '.
Example: "Hello" or 'Hi there'
文本数据,必须用双引号 " " 或单引号 ' ' 包起来。
例子: "Hello"'你好'
Integer
จำนวนเต็ม
整数
ตัวเลขที่ไม่มีทศนิยม
ตัวอย่าง:
A whole number — no decimal point.
Example:
没有小数点的整数。
例子:
1, 100, -50
Float
จำนวนทศนิยม
浮点数(小数)
ตัวเลขที่มีจุดทศนิยม
ตัวอย่าง:
A number with a decimal point.
Example:
带小数点的数字。
例子:
3.14, 2.5, -0.75
List
ลิสต์ (รายการ)
列表
ชุดข้อมูลที่เก็บหลายค่าไว้ด้วยกัน ใช้วงเล็บเหลี่ยม [ ]
ตัวอย่าง: fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม"]
An ordered collection of values, written inside square brackets [ ].
Example: fruits = ["apple", "banana", "orange"]
一组按顺序排列的值,用方括号 [ ] 包起来。
例子: fruits = ["苹果", "香蕉", "橙子"]
Dictionary
ดิกชันนารี (พจนานุกรม)
字典
ชุดข้อมูลที่เก็บเป็นคู่ของ key (กุญแจ) และ value (ค่า) ใช้ปีกกา { }
ตัวอย่าง: person = {"name": "สมชาย", "age": 25}
A collection of key–value pairs, written inside curly braces { }. Look up a value by its key.
Example: person = {"name": "Somchai", "age": 25}
键(key)值(value)成对组成的集合,写在花括号 { } 里。通过键可以查到对应的值。
例子: person = {"name": "小明", "age": 25}
Function
ฟังก์ชัน
函数
ชุดคำสั่งที่ถูกกำหนดไว้ สามารถเรียกใช้ซ้ำได้ ใช้คำว่า def
ตัวอย่าง:
A reusable block of code, defined with the def keyword. Call it whenever you need that behaviour.
Example:
一段可以反复调用的代码块,用 def 关键字定义。需要时再"调用"它即可。
例子:
def say_hello(): print("สวัสดี")
def say_hello(): print("Hello")
def say_hello(): print("你好")

🎯ความสำคัญของ Tab และ Colon (:)Why Tab and Colon (:) MatterTab 和冒号(:)的重要性

1. Colon (:) - โคลอน1. The Colon (:)1. 冒号(:)

ใน Python เครื่องหมาย : ใช้เพื่อบอกว่าจะเริ่มบล็อกของโค้ดใหม่ ใช้กับ:

In Python, the : symbol marks the start of a new block of code. You'll see it after:

在 Python 里,: 用来表示"接下来要开始一个新的代码块"。你会在这些地方看到它:

# ต้องมี : หลัง if if age > 18: print("เป็นผู้ใหญ่") # ต้องมี : หลัง def def greet(): print("สวัสดี") # ต้องมี : หลัง for for i in range(5): print(i)
# Colon required after if if age > 18: print("Adult") # Colon required after def def greet(): print("Hello") # Colon required after for for i in range(5): print(i)
# if 后面必须有 : if age > 18: print("成年人") # def 后面必须有 : def greet(): print("你好") # for 后面必须有 : for i in range(5): print(i)

2. Tab - การเว้นย่อหน้า (Indentation)2. Tab — Indentation2. Tab —— 缩进(Indentation)

Python ใช้ Tab หรือช่องว่าง (spaces) เพื่อกำหนดว่าโค้ดบรรทัดไหนอยู่ภายในบล็อกไหน นี่คือสิ่งที่สำคัญมากใน Python!

Python uses Tab or spaces to decide which lines belong to which block. This isn't just style — it's the syntax itself.

Python 用 Tab 或空格来判断"哪几行属于同一个代码块"。这不只是排版风格——而是语法本身。

⚠️ สำคัญมาก: โค้ดที่อยู่ภายในบล็อก (หลัง :) ต้องเยื้องเข้าไป มิฉะนั้นจะเกิด Error
⚠️ Critical: Code inside a block (after a :) must be indented. Forget the indentation and Python will raise an IndentationError.
⚠️ 非常重要:代码块里的代码(也就是 : 之后的内容)必须缩进,否则 Python 会抛出 IndentationError 错误。
# ✅ ถูกต้อง - มีการเยื้อง (indent) def calculate(): result = 10 + 5 # เยื้องเข้าไป print(result) # เยื้องเข้าไปเท่ากัน # ❌ ผิด - ไม่มีการเยื้อง def wrong(): print("Error!") # จะเกิด IndentationError
# ✅ Correct — properly indented def calculate(): result = 10 + 5 # indented print(result) # same indent level # ❌ Wrong — no indentation def wrong(): print("Error!") # raises IndentationError
# ✅ 正确 —— 有正确的缩进 def calculate(): result = 10 + 5 # 缩进进去 print(result) # 缩进对齐 # ❌ 错误 —— 没有缩进 def wrong(): print("Error!") # 会抛出 IndentationError

🧪 ทดลองเขียนโค้ดTry writing code动手试试

ลองสร้างฟังก์ชันของคุณเอง (พิมพ์ชื่อและอายุ):

Build your own function — enter your name and age:

来写一个属于你自己的函数 —— 输入你的名字和年龄:

ผลลัพธ์จะแสดงที่นี่...Output will appear here...运行结果会显示在这里…

💻ตัวอย่างโค้ดสำหรับฝึกหัดCode Examples for Practice练习用的代码示例

ตัวอย่างที่ 1: สร้างลิสต์และแสดงผลExample 1: Build a list and print it示例 1:创建列表并打印

# สร้างลิสต์ของผลไม้ fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม", "มะม่วง"] # แสดงผลไม้ทั้งหมด print("ผลไม้ที่ฉันชอบ:") for fruit in fruits: print("- ", fruit) # เพิ่มผลไม้ใหม่ fruits.append("ทุเรียน") print("จำนวนผลไม้ทั้งหมด:", len(fruits))
# Create a list of fruits fruits = ["apple", "banana", "orange", "mango"] # Show every fruit print("My favorite fruits:") for fruit in fruits: print("- ", fruit) # Add a new fruit fruits.append("durian") print("Total fruits:", len(fruits))
# 创建一个水果列表 fruits = ["苹果", "香蕉", "橙子", "芒果"] # 把所有水果都打印出来 print("我喜欢的水果:") for fruit in fruits: print("- ", fruit) # 加一个新的水果 fruits.append("榴莲") print("水果总数:", len(fruits))

ตัวอย่างที่ 2: ใช้ Dictionary เก็บข้อมูลExample 2: Store data in a dictionary示例 2:用字典保存数据

# สร้างข้อมูลนักเรียน student = { "name": "สมหญิง", "age": 20, "grade": "A", "subjects": ["คณิตศาสตร์", "วิทยาศาสตร์", "ภาษาอังกฤษ"] } # แสดงข้อมูล print("ชื่อ:", student["name"]) print("อายุ:", student["age"]) print("เกรด:", student["grade"]) print("วิชาที่เรียน:", student["subjects"])
# Create a student record student = { "name": "Somying", "age": 20, "grade": "A", "subjects": ["Math", "Science", "English"] } # Show the data print("Name:", student["name"]) print("Age:", student["age"]) print("Grade:", student["grade"]) print("Subjects:", student["subjects"])
# 创建一条学生记录 student = { "name": "小红", "age": 20, "grade": "A", "subjects": ["数学", "科学", "英语"] } # 显示数据 print("姓名:", student["name"]) print("年龄:", student["age"]) print("成绩:", student["grade"]) print("科目:", student["subjects"])

ตัวอย่างที่ 3: สร้างฟังก์ชันคำนวณExample 3: Build calculation functions示例 3:编写计算函数

# สร้างฟังก์ชันคำนวณพื้นที่สี่เหลี่ยม def calculate_area(width, height): area = width * height return area # เรียกใช้ฟังก์ชัน result = calculate_area(10, 5) print("พื้นที่:", result, "ตารางหน่วย") # ฟังก์ชันตรวจสอบเลขคู่หรือคี่ def check_even_odd(number): if number % 2 == 0: return "เลขคู่" else: return "เลขคี่" print(check_even_odd(7)) # เลขคี่ print(check_even_odd(10)) # เลขคู่
# Function: area of a rectangle def calculate_area(width, height): area = width * height return area # Call the function result = calculate_area(10, 5) print("Area:", result, "square units") # Function: check even or odd def check_even_odd(number): if number % 2 == 0: return "even" else: return "odd" print(check_even_odd(7)) # odd print(check_even_odd(10)) # even
# 函数:计算矩形面积 def calculate_area(width, height): area = width * height return area # 调用函数 result = calculate_area(10, 5) print("面积:", result, "平方单位") # 函数:判断奇偶数 def check_even_odd(number): if number % 2 == 0: return "偶数" else: return "奇数" print(check_even_odd(7)) # 奇数 print(check_even_odd(10)) # 偶数

ตัวอย่างที่ 4: ค้นหาไฟล์ในโฟลเดอร์Example 4: Find a file in your folders示例 4:在文件夹里查找文件

สคริปต์เล็ก ๆ ที่เริ่มจากโฟลเดอร์ปัจจุบัน เดินลงไปในโฟลเดอร์ย่อยทุกชั้น และพิมพ์ path ของไฟล์แรกที่เจอตามชื่อ รองรับ glob เช่น "*.txt" รันด้วย python find_file.py <ชื่อไฟล์>

A tiny script that starts in the current directory, walks every subfolder, and prints the path of the first file matching the name you pass. Glob patterns like "*.txt" work too. Run it with python find_file.py <filename>.

一个小脚本,从当前目录出发,深入每一个子文件夹,把第一个匹配的文件路径打印出来。也支持 "*.txt" 这样的通配符。运行方式:python find_file.py <文件名>

# ค้นหาไฟล์โดยเริ่มจากโฟลเดอร์ปัจจุบัน เดินลงไปทุกโฟลเดอร์ย่อย import os import sys import fnmatch from pathlib import Path # ต้องส่งชื่อไฟล์มา 1 ตัวจาก command line if len(sys.argv) != 2: sys.exit(f"Usage: {Path(sys.argv[0]).name} <filename>") pattern = sys.argv[1] # os.walk เดินลงทุกโฟลเดอร์ย่อยให้เอง for dirpath, _, filenames in os.walk(Path.cwd()): for fn in filenames: if fnmatch.fnmatch(fn, pattern): print(Path(dirpath) / fn) sys.exit(0) # เจอแล้วจบเลย sys.exit(f"Not found: {pattern}")
# Search for a file starting in the current directory, recursing into subfolders import os import sys import fnmatch from pathlib import Path # Expect exactly one filename on the command line if len(sys.argv) != 2: sys.exit(f"Usage: {Path(sys.argv[0]).name} <filename>") pattern = sys.argv[1] # os.walk descends into every subfolder for us for dirpath, _, filenames in os.walk(Path.cwd()): for fn in filenames: if fnmatch.fnmatch(fn, pattern): print(Path(dirpath) / fn) sys.exit(0) # Stop at the first match sys.exit(f"Not found: {pattern}")
# 从当前目录开始查找文件,递归进入每个子文件夹 import os import sys import fnmatch from pathlib import Path # 命令行只接受一个文件名 if len(sys.argv) != 2: sys.exit(f"Usage: {Path(sys.argv[0]).name} <filename>") pattern = sys.argv[1] # os.walk 会自己钻到每一个子文件夹 for dirpath, _, filenames in os.walk(Path.cwd()): for fn in filenames: if fnmatch.fnmatch(fn, pattern): print(Path(dirpath) / fn) sys.exit(0) # 找到第一个就退出 sys.exit(f"Not found: {pattern}")
🎓 เคล็ดลับสำหรับผู้เริ่มต้น:
  • ฝึกพิมพ์โค้ดด้วยตัวเอง อย่าแค่คัดลอก
  • อ่าน Error message เมื่อเกิดข้อผิดพลาด มันจะบอกว่าผิดตรงไหน
  • ใช้ print() เพื่อตรวจสอบค่าของตัวแปร
  • เริ่มจากโค้ดง่ายๆ แล้วค่อยเพิ่มความซับซ้อน
  • อย่าลืมใส่ : (colon) และการเยื้อง (indent) ให้ถูกต้อง
🎓 Beginner tips:
  • Type the code yourself — don't just copy-paste
  • Read the error message carefully when things break — it tells you exactly where the problem is
  • Use print() to peek at variable values while debugging
  • Start small. Get one tiny piece working before adding complexity
  • Don't forget the colon : and the indentation that follows it
🎓 给初学者的小建议:
  • 自己动手敲一遍代码,别只复制粘贴
  • 报错时认真看错误信息(Error message),它会告诉你哪里出问题了
  • print() 来查看变量当前的值,是最简单的调试手段
  • 从最小的代码片段开始跑通,再一点点加复杂度
  • 别忘了写冒号 : 和之后的缩进

🚀ขั้นต่อไป — ดูโค้ดจริงที่ทำงานได้Next Step — See Real Code in Action下一步 —— 看真实代码的运行

เมื่อรู้พื้นฐานแล้ว ลองดูทุกอย่างทำงานจริงใน agent.py — AI agent ขนาดประมาณ 190 บรรทัด ที่ใช้แนวคิดทั้งหมดในหน้านี้: ตัวแปร, ฟังก์ชัน, dictionary, if/else, for loops

Now that you know the basics, watch them work together in agent.py — a real ~190-line AI agent built with everything on this page: variables, functions, dictionaries, if/else, and for loops.

学完基础之后,来看看它们在 agent.py 里一起工作 —— 一个约 190 行的真实 AI 智能体,用到了这一页讲过的所有概念:变量、函数、字典、if/else、for 循环。