🐍 บทที่ 4: ตัวแปรและประเภทข้อมูลใน Python
📌 ตัวแปรคืออะไร?
ตัวแปร (Variable) คือค่าที่สามารถเก็บข้อมูลได้ในหน่วยความจำของคอมพิวเตอร์ ใน Python สามารถสร้างตัวแปรได้โดยไม่ต้องกำหนดชนิดข้อมูลล่วงหน้า
ตัวอย่างการสร้างตัวแปรใน Python:
name = "Jhon"
age = 21
score = 95.5
print(name) # Jhon
print(age) # 21
print(score) # 95.5
📌 กฎการตั้งชื่อตัวแปรใน Python
- ✅ ต้องขึ้นต้นด้วยตัวอักษรหรือเครื่องหมาย `_` (underscore)
- ✅ ห้ามใช้ตัวเลขเป็นตัวอักษรตัวแรก เช่น `1name` ❌
- ✅ สามารถใช้ตัวเลขและอักขระ `_` ได้ เช่น `name_1` ✅
- ✅ ห้ามใช้คำสงวนของ Python เช่น `if`, `else`, `while`, `def`
ตัวอย่างชื่อที่ถูกต้อง:
my_name = "Jhon"
_age = 25
score1 = 90
📌 ประเภทข้อมูลใน Python
Python รองรับประเภทข้อมูลหลัก ๆ ดังนี้:
- 🔢 **จำนวนเต็ม (Integer - `int`)** เช่น `10`, `-5`, `1000`
- 📏 **จำนวนจริง (Floating Point - `float`)** เช่น `10.5`, `3.14`, `-2.8`
- 🔡 **สตริง (String - `str`)** เช่น `"Hello"`, `'Python'`
- ✅ **บูลีน (Boolean - `bool`)** เช่น `True`, `False`
- 📦 **ลิสต์ (List - `list`)** เช่น `[1, 2, 3]`, `["apple", "banana"]`
- 📦 **ทูเพิล (Tuple - `tuple`)** เช่น `(1, 2, 3)`, `("a", "b")`
- 📦 **ดิกชันนารี (Dictionary - `dict`)** เช่น `{"name": "Jhon", "age": 21}`
💻 ตัวอย่างการใช้ประเภทข้อมูลใน Python
# จำนวนเต็ม (int)
num1 = 10
# จำนวนจริง (float)
num2 = 3.14
# ข้อความ (string)
text = "Hello, Python!"
# บูลีน (bool)
status = True
# ลิสต์ (list)
fruits = ["apple", "banana", "cherry"]
# ทูเพิล (tuple)
days = ("Monday", "Tuesday", "Wednesday")
# ดิกชันนารี (dict)
person = {"name": "Jhon", "age": 21}
# แสดงผลข้อมูลทั้งหมด
print(num1, num2, text, status)
print(fruits)
print(days)
print(person)
🔄 การแปลงชนิดข้อมูล (Type Conversion)
Python อนุญาตให้แปลงชนิดข้อมูลระหว่าง `int`, `float`, `str` ได้
# แปลงจำนวนเต็มเป็นสตริง
num = 100
text_num = str(num)
print(text_num) # "100"
# แปลงสตริงเป็นจำนวนเต็ม
text = "50"
num_text = int(text)
print(num_text + 10) # 60
# แปลงจำนวนเต็มเป็นจำนวนจริง
num = 20
float_num = float(num)
print(float_num) # 20.0
🖥️ ตรวจสอบชนิดของตัวแปร
ใช้ฟังก์ชัน `type()` เพื่อตรวจสอบชนิดข้อมูลของตัวแปร
num = 100
text = "Python"
pi = 3.14
print(type(num)) #
print(type(text)) #
print(type(pi)) #
📌 สรุป
- ✅ Python ใช้ตัวแปรโดยไม่ต้องกำหนดชนิดข้อมูล
- ✅ ตัวแปรต้องมีชื่อที่ถูกต้องตามกฎของ Python
- ✅ รองรับประเภทข้อมูลต่าง ๆ เช่น `int`, `float`, `str`, `bool`, `list`, `tuple`, `dict`
- ✅ สามารถแปลงชนิดข้อมูลระหว่าง `int`, `float`, `str` ได้
- ✅ ใช้ `type()` เพื่อตรวจสอบชนิดของตัวแปร