Skip to content

Variables & Types

ตัวแปร (variable) คือ “กล่องเก็บข้อมูล” ที่เราตั้งชื่อเพื่อเรียกใช้ซ้ำได้ Python มีชนิดข้อมูลพื้นฐาน 4 แบบที่ต้องรู้

ชนิดข้อมูลพื้นฐาน

Section titled “ชนิดข้อมูลพื้นฐาน”
# str — ข้อความ
name = "สมชาย"
product_code = "SKU-001"
# int — จำนวนเต็ม
quantity = 42
year = 2024
# float — ทศนิยม
price = 199.50
tax_rate = 0.07
# bool — True / False
is_active = True
has_discount = False

ตรวจสอบชนิดด้วย type()

Section titled “ตรวจสอบชนิดด้วย type()”
print(type(name)) # <class 'str'>
print(type(quantity)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(is_active)) # <class 'bool'>

f-strings — จัดรูปแบบข้อความ

Section titled “f-strings — จัดรูปแบบข้อความ”
# f-string ใช้ f"..." แล้วใส่ตัวแปรใน {}
message = f"สินค้า {product_code} ราคา {price:.2f} บาท"
print(message)
# สินค้า SKU-001 ราคา 199.50 บาท
# จัดรูปแบบตัวเลข
big_number = 1234567
print(f"{big_number:,}") # 1,234,567
# ใส่ expression ได้เลย
total = quantity * price
print(f"รวม {total:,.2f} บาท") # รวม 8,379.00 บาท
# ใช้ snake_case สำหรับตัวแปรและฟังก์ชัน
user_name = "test" # ดี
userName = "test" # ไม่แนะนำ (camelCase)
# ค่าคงที่ใช้ UPPER_CASE
MAX_RETRIES = 3
API_BASE_URL = "https://api.example.com"