Variables & Types
ตัวแปรและ Dynamic Typing
หัวข้อที่มีชื่อว่า “ตัวแปรและ Dynamic Typing”ใน Python คุณกำหนดค่าให้กับชื่อตัวแปรได้เลย — ไม่ต้องประกาศชนิดข้อมูล ชนิดของตัวแปรถูกกำหนดโดยออบเจกต์ที่อ้างถึงในขณะนั้น ไม่ใช่โดยการประกาศ
x = 10 # x อ้างถึง intx = "hello" # x อ้างถึง str แล้ว — ถูกต้องสมบูรณ์x = [1, 2, 3] # x อ้างถึง list แล้วนี่เรียกว่า dynamic typing ชนิดข้อมูลติดอยู่กับออบเจกต์ ไม่ใช่กับชื่อตัวแปร
ชนิดข้อมูล Scalar พื้นฐาน
หัวข้อที่มีชื่อว่า “ชนิดข้อมูล Scalar พื้นฐาน”Python มีชนิดข้อมูล scalar สี่ชนิดที่คุณจะใช้ในทุกโปรแกรม:
| ชนิด | ตัวอย่างค่า | หมายเหตุ |
|---|---|---|
int | 42, -7, 0 | ความแม่นยำไม่จำกัด — ไม่มี overflow |
float | 3.14, -0.5 | ทศนิยม IEEE 754 double precision |
str | "hello", 'world' | ลำดับ Unicode ที่เปลี่ยนแปลงไม่ได้ |
bool | True, False | subclass ของ int; True == 1, False == 0 |
ยังมี None — singleton ที่แทนการขาดค่า
None มีชนิดข้อมูลของตัวเอง คือ NoneType และมี None เพียงออบเจกต์เดียวในกระบวนการ Python ทั้งหมด
ทดสอบด้วย is None เสมอ ไม่ใช่ == None
การตรวจสอบชนิดข้อมูลขณะรันไทม์
หัวข้อที่มีชื่อว่า “การตรวจสอบชนิดข้อมูลขณะรันไทม์”type() คืนชนิดที่แน่นอนของออบเจกต์
isinstance() ทดสอบว่าออบเจกต์เป็น instance ของชนิดนั้นหรือ subclass ของตัวเอง
age = 30print(type(age)) # <class 'int'>print(isinstance(age, int)) # Trueprint(isinstance(True, int)) # True — bool เป็น subclass ของ intการแปลงชนิดข้อมูล
หัวข้อที่มีชื่อว่า “การแปลงชนิดข้อมูล”Python ไม่แปลงชนิดข้อมูลโดยอัตโนมัติ คุณต้องแปลงอย่างชัดเจนโดยใช้ชื่อชนิดข้อมูลเป็นฟังก์ชัน:
n = int("42") # str -> intf = float("3.14") # str -> floats = str(100) # int -> strb = bool(0) # int -> bool -> Falseถ้าแปลงไม่ได้ Python จะ raise ValueError:
int("hello") # ValueError: invalid literal for int()Truthiness
หัวข้อที่มีชื่อว่า “Truthiness”ออบเจกต์ Python ทุกชิ้นมีการตีความเป็น boolean ที่ใช้ใน if และ while
ค่าต่อไปนี้เป็น falsy — ค่าอื่นๆ ทั้งหมดเป็น truthy:
False,None- ศูนย์:
0,0.0,0j - container ว่างเปล่า:
"",[],{},(),set()
name = ""if name: print("has name")else: print("name is empty") # branch นี้ทำงานDemo ที่รันได้จริง
หัวข้อที่มีชื่อว่า “Demo ที่รันได้จริง”age: int = 30price: float = 9.99greeting: str = "Hello"active: bool = Truenothing = None
print(type(age))print(type(price))print(type(greeting))print(type(active))print(type(nothing))
x = int("42")y = float("3.14")z = str(100)print(x, y, z)
falsy_values = [0, "", None, False, [], 0.0]for v in falsy_values: print(f"bool({v!r}) = {bool(v)}")Loading Python runtime (first run only)…