แน่นอน 😎 ผมจะเขียนบทความ สอน Python แบบเป็นบทความ Medium-style มี คำอธิบายทีละขั้นตอน พร้อมตัวอย่างโค้ด ให้คุณอ่านและทดลองได้เลย
✨ Python Basics – เริ่มต้นเขียนโปรแกรมด้วย Python
Python เป็น ภาษาโปรแกรมที่อ่านง่าย เหมาะสำหรับผู้เริ่มต้นและนักพัฒนามืออาชีพ ใช้ทำ Web, Data Science, AI, Automation และอื่น ๆ
1️⃣ การติดตั้ง Python
-
เข้าไปที่ python.org/downloads
-
ดาวน์โหลดเวอร์ชันล่าสุด (แนะนำ Python 3.x)
-
ระหว่างติดตั้ง ติ๊กเลือก “Add Python to PATH” เพื่อให้เรียก
python
จาก Command Line ได้
ตรวจสอบการติดตั้ง:
python --version
ถ้าแสดงเวอร์ชันเช่น Python 3.12.0
แสดงว่าติดตั้งเรียบร้อยแล้ว ✅
2️⃣ เขียนโปรแกรมแรก
สร้างไฟล์ hello.py
:
# hello.py
print("Hello, Python!")
รันโปรแกรม:
python hello.py
ผลลัพธ์:
Hello, Python!
🎉 แค่นี้คุณก็เขียนโปรแกรม Python ตัวแรกสำเร็จ
3️⃣ ตัวแปรและชนิดข้อมูล
Python ไม่ต้องประกาศ type ล่วงหน้า ตัวแปรเกิดเมื่อ assign ค่า
name = "Alice" # str
age = 25 # int
height = 1.68 # float
is_student = True # bool
print(name, age, height, is_student)
ผลลัพธ์:
Alice 25 1.68 True
4️⃣ การทำงานกับ List และ Loop
List คือ array ของ Python:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
ผลลัพธ์:
I like apple
I like banana
I like cherry
5️⃣ Function (ฟังก์ชัน)
ฟังก์ชันช่วยทำให้โค้ด reusable:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
print(greet("Bob"))
ผลลัพธ์:
Hello, Alice!
Hello, Bob!
6️⃣ การใช้ Condition (if / else)
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
ผลลัพธ์:
You are an adult.
7️⃣ การอ่านไฟล์และเขียนไฟล์
# เขียนไฟล์
with open("example.txt", "w") as f:
f.write("Hello, Python File!\n")
# อ่านไฟล์
with open("example.txt", "r") as f:
content = f.read()
print(content)
ผลลัพธ์:
Hello, Python File!
8️⃣ ตัวอย่างโค้ดรวม
โปรแกรม Python แบบครบ ๆ มี List, Function, Loop, Condition:
# โปรแกรมจัดการผลคะแนนนักเรียน
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 72},
{"name": "Charlie", "score": 90}
]
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "D"
for s in students:
print(f"{s['name']} scored {s['score']} → Grade: {grade(s['score'])}")
ผลลัพธ์:
Alice scored 85 → Grade: B
Bob scored 72 → Grade: C
Charlie scored 90 → Grade: A
9️⃣ สรุป
-
Python เป็นภาษา อ่านง่าย, ยืดหยุ่น และ powerful
-
เริ่มจาก variables, list, loops, function, if-else, file I/O
-
ฝึกเขียนโปรแกรมเล็ก ๆ → เพิ่มความเข้าใจ
-
ต่อไปคุณสามารถเรียนรู้เรื่อง Class / OOP, Modules, Libraries เช่น Pandas, NumPy
💡 Tip:
ลองสร้าง Mini Project เช่น:
-
โปรแกรมคำนวณคะแนนนักเรียน
-
โปรแกรมจัดการ To-Do List
-
เว็บเล็ก ๆ ด้วย Flask / FastAPI