Python คืออะไร?
Python เป็นภาษาโปรแกรมมิ่งระดับสูง (High-level Programming Language) ที่ถูกพัฒนาโดย Guido van Rossum ในปี 1991 Python เป็นภาษาที่เน้นความเรียบง่าย อ่านง่าย และเขียนง่าย ทำให้เป็นภาษาที่เหมาะสำหรับผู้เริ่มต้นเรียนรู้การเขียนโปรแกรม
คุณสมบัติเด่นของ Python:
- เรียบง่าย: ไวยากรณ์ที่เข้าใจง่าย คล้ายภาษาอังกฤษ
- Interpreted: ไม่ต้อง compile ก่อนรัน
- Object-Oriented: รองรับการเขียนโปรแกรมเชิงวัตถุ
- Cross-platform: ทำงานได้บนระบบปฏิบัติการต่างๆ
- Open Source: ใช้งานฟรี มี community ใหญ่
- Library มากมาย: มี package และ library ให้เลือกใช้มากมาย
ข้อมูลน่าสนใจ: ชื่อ "Python" มาจากรายการโทรทัศน์ "Monty Python's Flying Circus" ไม่ใช่งูหลาม และ Python ถูกใช้งานโดยบริษัทใหญ่ๆ เช่น Google, YouTube, Instagram, Spotify
ทำไมต้องเรียน Python?
Python เป็นภาษาที่ได้รับความนิยมสูงสุดในปัจจุบัน มีเหตุผลหลายประการ:
1. เหมาะสำหรับผู้เริ่มต้น
- ไวยากรณ์เรียบง่าย อ่านง่าย
- ไม่ต้องจัดการหน่วยความจำเอง
- Error messages ที่เข้าใจง่าย
- มี tutorial และ documentation ที่ดี
2. ความต้องการในตลาดงาน
- Data Science & AI: Machine Learning, Deep Learning
- Web Development: Django, Flask frameworks
- Automation: การทำงานอัตโนมัติ
- Scientific Computing: การคำนวณทางวิทยาศาสตร์
- Game Development: การพัฒนาเกม
3. Ecosystem ที่แข็งแกร่ง
- PyPI (Python Package Index) มี package มากกว่า 400,000 ตัว
- Library สำคัญ: NumPy, Pandas, Matplotlib, TensorFlow
- Community ใหญ่และช่วยเหลือกัน
- การพัฒนาอย่างต่อเนื่อง
การติดตั้ง Python
Python สามารถติดตั้งได้หลายวิธี:
Windows
# วิธีที่ 1: ดาวน์โหลดจากเว็บไซต์ทางการ
1. ไปที่ https://www.python.org/downloads/
2. ดาวน์โหลด Python เวอร์ชันล่าสุด
3. รันไฟล์ installer
4. ✅ เลือก "Add Python to PATH"
5. คลิก "Install Now"
# วิธีที่ 2: ใช้ Microsoft Store
1. เปิด Microsoft Store
2. ค้นหา "Python"
3. ติดตั้ง Python จาก Python Software Foundation
macOS
# วิธีที่ 1: ดาวน์โหลดจากเว็บไซต์
1. ไปที่ https://www.python.org/downloads/
2. ดาวน์โหลด Python สำหรับ macOS
3. รันไฟล์ .pkg
# วิธีที่ 2: ใช้ Homebrew
brew install python
# วิธีที่ 3: ใช้ pyenv (แนะนำ)
brew install pyenv
pyenv install 3.11.0
pyenv global 3.11.0
Linux
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip
# CentOS/RHEL/Fedora
sudo yum install python3 python3-pip
# หรือ
sudo dnf install python3 python3-pip
# Arch Linux
sudo pacman -S python python-pip
การตรวจสอบการติดตั้ง
# ตรวจสอบเวอร์ชัน Python
python --version
# หรือ
python3 --version
# ตรวจสอบ pip (package manager)
pip --version
# หรือ
pip3 --version
# ผลลัพธ์ที่ควรได้
Python 3.11.0
pip 22.3 from /usr/lib/python3.11/site-packages/pip (python 3.11)
โปรแกรม Python แรก
มาเริ่มต้นด้วยโปรแกรม "Hello, World!" กันเถอะ:
# hello.py
print("Hello, World!")
print("สวัสดี ภาษา Python!")
print("🐍 Python is awesome!")
การรันโปรแกรม
# วิธีที่ 1: บันทึกเป็นไฟล์แล้วรัน
# 1. บันทึกโค้ดเป็น hello.py
# 2. เปิด Terminal/Command Prompt
# 3. รันคำสั่ง
python hello.py
# หรือ
python3 hello.py
# วิธีที่ 2: ใช้ Interactive Mode
python
>>> print("Hello, World!")
Hello, World!
>>> exit()
การใช้ IDE และ Text Editor
# IDE ที่แนะนำ:
1. PyCharm (Professional/Community)
2. Visual Studio Code + Python Extension
3. IDLE (มาพร้อม Python)
4. Jupyter Notebook (สำหรับ Data Science)
5. Sublime Text
6. Atom
# Online Editor:
1. Repl.it
2. CodePen
3. Trinket
4. Python.org Online Console
ไวยากรณ์พื้นฐาน
Python มีไวยากรณ์ที่เรียบง่ายและเข้าใจง่าย:
1. Indentation (การเยื้อง)
# Python ใช้ indentation แทน { }
if 5 > 2:
print("Five is greater than two!") # ต้องเยื้อง
print("This is inside the if block")
# ❌ ผิด - ไม่เยื้อง
if 5 > 2:
print("This will cause an error")
# ✅ ถูก - เยื้องสม่ำเสมอ
if True:
print("First line")
print("Second line")
if True:
print("Nested block")
2. Comments (คอมเมนต์)
# นี่คือคอมเมนต์บรรทัดเดียว
"""
นี่คือคอมเมนต์หลายบรรทัด
ใช้สำหรับอธิบายโค้ดที่ซับซ้อน
หรือเขียน docstring
"""
'''
สามารถใช้ single quote ได้เหมือนกัน
สำหรับคอมเมนต์หลายบรรทัด
'''
print("Hello") # คอมเมนต์ท้ายบรรทัด
3. Case Sensitivity
# Python เป็น case-sensitive
name = "John"
Name = "Jane"
NAME = "Bob"
print(name) # John
print(Name) # Jane
print(NAME) # Bob
# ตัวแปรทั้ง 3 ตัวนี้เป็นคนละตัวกัน
ชนิดข้อมูล
Python มีชนิดข้อมูลพื้นฐานหลายประเภท:
1. Numbers (ตัวเลข)
# Integer (จำนวนเต็ม)
age = 25
population = 1000000
negative = -42
# Float (จำนวนจริง)
height = 175.5
pi = 3.14159
scientific = 1.5e-4 # 0.00015
# Complex (จำนวนเชิงซ้อน)
complex_num = 3 + 4j
# การตรวจสอบชนิดข้อมูล
print(type(age)) #
print(type(height)) #
print(type(complex_num)) #
2. Strings (สตริง)
# การสร้าง string
name = "สมชาย"
message = 'Hello, World!'
multiline = """นี่คือ
string หลายบรรทัด
ใน Python"""
# String operations
first_name = "สม"
last_name = "ชาย"
full_name = first_name + last_name # การต่อ string
# String methods
text = "Python Programming"
print(text.upper()) # PYTHON PROGRAMMING
print(text.lower()) # python programming
print(text.replace("Python", "Java")) # Java Programming
print(len(text)) # 18
# String formatting
age = 25
message = f"ฉันอายุ {age} ปี" # f-string (Python 3.6+)
print(message) # ฉันอายุ 25 ปี
3. Boolean
# Boolean values
is_student = True
is_working = False
# Boolean operations
print(True and False) # False
print(True or False) # True
print(not True) # False
# การแปลงเป็น Boolean
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("Hello")) # True
print(bool([])) # False
print(bool([1, 2, 3])) # True
4. Collections (คอลเลกชัน)
# List (รายการ) - เปลี่ยนแปลงได้
fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "Hello", 3.14, True]
# Tuple (ทูเปิล) - เปลี่ยนแปลงไม่ได้
coordinates = (10, 20)
colors = ("แดง", "เขียว", "น้ำเงิน")
# Dictionary (พจนานุกรม) - key-value pairs
person = {
"name": "สมชาย",
"age": 25,
"city": "กรุงเทพฯ"
}
# Set (เซต) - ไม่มีสมาชิกซ้ำ
unique_numbers = {1, 2, 3, 4, 5}
ตัวแปร
การสร้างและใช้งานตัวแปรใน Python:
1. การสร้างตัวแปร
# Python เป็น dynamically typed
# ไม่ต้องประกาศชนิดข้อมูล
name = "สมชาย"
age = 25
height = 175.5
is_student = True
# การกำหนดค่าหลายตัวแปรพร้อมกัน
x, y, z = 1, 2, 3
a = b = c = 0
# การแลกเปลี่ยนค่า
x, y = y, x
print(f"x = {x}, y = {y}") # x = 2, y = 1
2. กฎการตั้งชื่อตัวแปร
# ✅ ชื่อที่ถูกต้อง
name = "John"
age_in_years = 25
_private_var = "hidden"
firstName = "John" # camelCase
first_name = "John" # snake_case (แนะนำใน Python)
# ❌ ชื่อที่ผิด
# 2name = "John" # ขึ้นต้นด้วยตัวเลข
# first-name = "John" # มี hyphen
# class = "A" # ใช้ keyword
# Keywords ที่ใช้ไม่ได้
import keyword
print(keyword.kwlist)
# ['False', 'None', 'True', 'and', 'as', 'assert', ...]
3. การแปลงชนิดข้อมูล
# Type conversion
age_str = "25"
age_int = int(age_str) # แปลงเป็น integer
age_float = float(age_str) # แปลงเป็น float
# การแปลงต่างๆ
print(str(123)) # "123"
print(int("456")) # 456
print(float("78.9")) # 78.9
print(int(3.14)) # 3 (ตัดทศนิยม)
# การจัดการ error
try:
number = int("abc") # จะ error
except ValueError:
print("ไม่สามารถแปลงเป็นตัวเลขได้")
ตัวดำเนินการ
Python มีตัวดำเนินการหลายประเภท:
1. ตัวดำเนินการทางคณิตศาสตร์
a = 10
b = 3
print(a + b) # 13 (บวก)
print(a - b) # 7 (ลบ)
print(a * b) # 30 (คูณ)
print(a / b) # 3.333... (หาร)
print(a // b) # 3 (หารปัดเศษ)
print(a % b) # 1 (หารเอาเศษ)
print(a ** b) # 1000 (ยกกำลัง)
# การดำเนินการกับ string
text = "Hello" + " " + "World" # "Hello World"
repeat = "Ha" * 3 # "HaHaHa"
2. ตัวดำเนินการเปรียบเทียบ
x = 5
y = 10
print(x == y) # False (เท่ากับ)
print(x != y) # True (ไม่เท่ากับ)
print(x y) # False (มากกว่า)
print(x = y) # False (มากกว่าหรือเท่ากับ)
# การเปรียบเทียบ string
print("apple"
3. ตัวดำเนินการทางตรรกะ
a = True
b = False
print(a and b) # False (และ)
print(a or b) # True (หรือ)
print(not a) # False (ไม่)
# การใช้กับเงื่อนไข
age = 20
if age >= 18 and age 0 and y > 0 and x/y > 1 # ไม่ error เพราะ y > 0 เป็น False
1. การแสดงผลด้วย print()
# การใช้ print() พื้นฐาน
print("Hello, World!")
print("สวัสดี", "ครับ") # พิมพ์หลายค่า
# การจัดรูปแบบ
name = "สมชาย"
age = 25
print(f"ชื่อ: {name}, อายุ: {age} ปี") # f-string
# วิธีอื่นๆ
print("ชื่อ: {}, อายุ: {} ปี".format(name, age)) # .format()
print("ชื่อ: %s, อายุ: %d ปี" % (name, age)) # % formatting
# การควบคุม print()
print("Hello", end=" ") # ไม่ขึ้นบรรทัดใหม่
print("World") # Hello World
print("A", "B", "C", sep="-") # A-B-C
2. การรับข้อมูลด้วย input()
# การรับข้อมูลพื้นฐาน
name = input("กรุณาใส่ชื่อ: ")
print(f"สวัสดี {name}")
# การรับตัวเลข
age_str = input("กรุณาใส่อายุ: ")
age = int(age_str) # แปลงเป็น integer
# หรือแปลงในบรรทัดเดียว
height = float(input("กรุณาใส่ส่วนสูง (ซม.): "))
# การจัดการ error
try:
number = int(input("ใส่ตัวเลข: "))
print(f"คุณใส่: {number}")
except ValueError:
print("กรุณาใส่ตัวเลขเท่านั้น")
โครงสร้างควบคุม
1. If-Elif-Else
# If statement พื้นฐาน
age = 18
if age >= 18:
print("เป็นผู้ใหญ่แล้ว")
# If-else
score = 85
if score >= 80:
print("เกรด A")
else:
print("เกรด B หรือต่ำกว่า")
# If-elif-else
score = 75
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"คะแนน {score} ได้เกรด {grade}")
2. Loops (การวนซ้ำ)
# For loop
fruits = ["แอปเปิ้ล", "กล้วย", "ส้ม"]
for fruit in fruits:
print(f"ผลไม้: {fruit}")
# For loop กับ range()
for i in range(5): # 0, 1, 2, 3, 4
print(f"รอบที่ {i}")
for i in range(1, 6): # 1, 2, 3, 4, 5
print(f"เลข {i}")
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(f"เลขคู่ {i}")
# While loop
count = 0
while count
ฟังก์ชัน
ฟังก์ชันช่วยให้โค้ดเป็นระเบียบและใช้ซ้ำได้:
# การสร้างฟังก์ชัน
def greet(name):
return f"สวัสดี {name}"
# การเรียกใช้ฟังก์ชัน
message = greet("สมชาย")
print(message) # สวัสดี สมชาย
# ฟังก์ชันที่มีหลาย parameter
def calculate_bmi(weight, height):
bmi = weight / (height ** 2)
return bmi
# การใช้งาน
weight = 70 # kg
height = 1.75 # m
bmi = calculate_bmi(weight, height)
print(f"BMI: {bmi:.2f}")
# ฟังก์ชันที่มี default parameter
def introduce(name, age=25):
return f"ชื่อ {name} อายุ {age} ปี"
print(introduce("สมชาย")) # ใช้ age default
print(introduce("สมหญิง", 30)) # กำหนด age เอง
# ฟังก์ชันที่คืนหลายค่า
def get_name_age():
name = input("ชื่อ: ")
age = int(input("อายุ: "))
return name, age
name, age = get_name_age()
print(f"ข้อมูล: {name}, {age}")
ขั้นตอนต่อไป
หลังจากเรียนรู้พื้นฐาน Python แล้ว คุณสามารถศึกษาหัวข้อต่อไปนี้:
- Python คืออะไร? แนะนำเบื้องต้น
- Data Structures (List, Tuple, Dictionary, Set)
- File I/O และการจัดการไฟล์
- Exception Handling
- Object-Oriented Programming (OOP)
- Modules และ Packages
- Regular Expressions
- Working with APIs
- Database Programming
- Web Development (Django/Flask)
- Data Science (NumPy, Pandas, Matplotlib)
- Machine Learning (Scikit-learn, TensorFlow)
เคล็ดลับการเรียนรู้ Python:
- ฝึกเขียนโค้ดทุกวัน แม้แต่โปรแกรมเล็กๆ
- ใช้ Python Interactive Mode สำหรับทดลอง
- อ่าน Python Documentation และ PEP 8 Style Guide
- เข้าร่วม Python Community และ Forums
- ทำโปรเจ็กต์จริงเพื่อฝึกฝน
- ใช้ Git สำหรับ version control
- เรียนรู้ Virtual Environment และ Package Management
ทรัพยากรเพิ่มเติม:
- Python.org - เว็บไซต์ทางการ
- Real Python - บทความและ tutorial คุณภาพสูง
- Python Package Index (PyPI) - repository ของ packages
- Stack Overflow - Q&A community
- GitHub - ดูโค้ดของผู้อื่น
- Jupyter Notebook - สำหรับ Data Science
GlowCode ถูกสร้างโดย Electric Software, Inc. ตั้งแต่ปี 1982
ผู้พัฒนาซอฟต์แวร์ PC และ Windows ที่ได้รับรางวัล
ลิขสิทธิ์ ©1997-2024 Electric Software, Inc.