ตัวแปรและประเภทข้อมูล
เก็บค่าและรู้จักชนิดข้อมูลพื้นฐานใน Python
ตัวแปรใน Python — ง่ายกว่าที่คิด
ใน JS ต้องใช้ let หรือ const
แต่ Python ไม่ต้องใช้คำสั่งประกาศ — กำหนดค่าได้เลย:
name = "สมชาย"
age = 25
print(name)
print(age)
name= ชื่อตัวแปร== กำหนดค่า"สมชาย"= ค่า
💡 ไม่ต้องบอกชนิดข้อมูลล่วงหน้า — Python เดาเองได้ (เรียกว่า dynamic typing)
เปลี่ยนค่าได้ตลอด
score = 10
print(score) # 10
score = 20
print(score) # 20
score = "ดี" # เปลี่ยนจากตัวเลขเป็นข้อความก็ได้
print(score) # ดี
ชนิดข้อมูลพื้นฐาน
1. int — จำนวนเต็ม
age = 25
count = -10
2. float — ทศนิยม
price = 99.50
pi = 3.14
3. str — ข้อความ (string)
name = "สมชาย"
greeting = 'Hi' # ใช้ ' ก็ได้
msg = f"ชื่อ {name}" # f-string (เหมือน template literal ใน JS)
💡 f-string เป็นวิธีแทรกค่าในข้อความที่สะอาดที่สุด:
f"...{ตัวแปร}..."
4. bool — จริง/เท็จ
is_logged_in = True
has_error = False
⚠️ Python ใช้
True/Falseตัวใหญ่นำหน้า (ไม่ใช่true/falseแบบ JS!)
ตรวจสอบชนิด: type()
print(type(25)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
แปลงชนิดข้อมูล
# string → int
age_text = "25"
age = int(age_text)
print(age + 5) # 30
# int → string
num = 100
text = str(num)
# string → float
price = float("99.5")
⚠️ ถ้ารับค่าจาก
input()(ผู้ใช้พิมพ์) จะได้เป็น string เสมอ ต้องแปลงก่อนคำนวณ
รับข้อมูลจากผู้ใช้: input()
name = input("ชื่ออะไร? ")
print("สวัสดี " + name)
age_text = input("อายุเท่าไหร่? ")
age = int(age_text)
print(f"ปีหน้าคุณจะอายุ {age + 1}")
ตั้งชื่อตัวแปร
Python นิยมรูปแบบ snake_case (ตัวเล็ก คั่นด้วย underscore):
# ✅ ดี (Python style)
user_age = 25
total_price = 1500
is_logged_in = True
# ❌ ไม่ตามธรรมเนียม Python
userAge = 25
กฎ:
- ใช้ได้: ตัวอักษร, ตัวเลข,
_ - ตัวแรกห้ามเป็นตัวเลข
- ตัวพิมพ์เล็ก/ใหญ่ ต่างกัน (
Ageกับageคนละตัว)
การตั้งค่าหลายตัวพร้อมกัน (Python เพ้อเลอะ)
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
a = b = c = 0 # ทั้งสามเท่ากับ 0
ลองทำจริง
product_name = "กาแฟ"
quantity = 2
price_per_item = 80.0
total = quantity * price_per_item
print(f"สินค้า: {product_name}")
print(f"จำนวน: {quantity}")
print(f"รวม: {total} บาท")
สรุป
| แนวคิด | สรุป |
|---|---|
| ประกาศตัวแปร | ไม่ต้องมีคำสั่ง กำหนดค่าได้เลย |
int / float | จำนวนเต็ม / ทศนิยม |
str | ข้อความ (ใช้ f"..." แทรกค่า) |
bool | True / False (ตัวใหญ่!) |
type() | ตรวจสอบชนิด |
int() / str() / float() | แปลงชนิด |
บทหน้า: เรียน เงื่อนไข (if/elif/else) ใน Python 🔀
อ่านจบแล้ว? ทำเครื่องหมายว่าเสร็จเพื่อบันทึกความคืบหน้า
แบบทดสอบ
ตอบให้ครบแล้วกด “ตรวจคำตอบ” เพื่อเช็คความเข้าใจ
1. ใน Python ต้องใช้คำสั่งใดประกาศตัวแปร?
2. ตัวเลขที่มีทศนิยมใน Python เป็นชนิดใด?
3. ฟังก์ชันใดใช้ตรวจสอบชนิดของข้อมูลใน Python?
กำลังโหลด…