Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Data Types และ Type Conversion: คู่มือครบวงจร

Python มี Built-in Data Types หลากหลาย การเข้าใจแต่ละประเภทและการแปลงชนิดข้อมูล (Type Conversion) จะช่วยเขียนโค้ดได้มีประสิทธิภาพขึ้น

Python Built-in Data Types

CategoryTypeคำอธิบายตัวอย่าง
Textstrข้อความ (Unicode)"hello", 'world'
Numericintจำนวนเต็ม (ไม่จำกัดขนาด)42, -10
floatทศนิยม3.14, -0.5
complexจำนวนเชิงซ้อน3+4j
Sequencelistลำดับ มีออเดอร์ แก้ไขได้ Duplicate ได้[1, 2, 3]
tupleลำดับ มีออเดอร์ แก้ไขไม่ได้ Immutable(1, 2, 3)
MappingdictKey-Value Pair ไม่มีออเดอร์ (Python 3.7+ มีออเดอร์){"name": "John"}
SetsetUnique elements ไม่มีออเดอร์{1, 2, 3}
BooleanboolTrue / FalseTrue, False
BinarybytesImmutable bytesb"hello"
bytearrayMutable bytesbytearray(5)

การสร้างตัวแปรแต่ละประเภท

# Text
text = "Hello World"
text2 = str("Hello World")

# Numeric
num_int = 42
num_float = 3.14
num_complex = 3 + 4j

# Sequence
my_list = [1, 2, 3, "four"]
my_tuple = (1, 2, 3, "four")

# Mapping
my_dict = {"name": "John", "age": 30}
my_dict2 = dict(name="John", age=30)

# Set
my_set = {1, 2, 3, 3, 2}  # {1, 2, 3} - duplicate ถูกลบอัตโนมัติ
my_set2 = set([1, 2, 3])

# Boolean
flag = True
flag2 = bool(1)  # True

# Binary
byte_data = b"hello"
byte_arr = bytearray(b"hello")

เช็ค Type ของตัวแปร: type()

x = [1, 2, 3]
print(type(x))        # 
print(type(x).__name__) # 'list'

# isinstance() - แนะนำกว่า type() ==
print(isinstance(x, list))  # True
print(isinstance(x, (list, tuple)))  # True

Type Conversion (Type Casting)

Numeric Conversions

# int → float
x = 5
y = float(x)    # 5.0

# float → int (ปัดทิ้งทศนิยม)
x = 5.9
y = int(x)      # 5 (ไม่ปัดเศษ!)

# int → complex
x = 5
y = complex(x)  # (5+0j)

# String → Numeric
int("42")       # 42
float("3.14")   # 3.14
complex("3+4j") # (3+4j)

Sequence Conversions

# String → List/Tuple/Set
s = "hello"
list(s)   # ['h', 'e', 'l', 'l', 'o']
tuple(s)  # ('h', 'e', 'l', 'l', 'o')
set(s)    # {'h', 'e', 'l', 'o'} - unique only

# List ↔ Tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)  # (1, 2, 3)
back_to_list = list(my_tuple)  # [1, 2, 3]

# List → Set (ลบ duplicate)
my_list = [1, 2, 2, 3, 3, 3]
my_set = set(my_list)  # {1, 2, 3}

Dict Conversions

# List of tuples → Dict
pairs = [("a", 1), ("b", 2)]
my_dict = dict(pairs)  # {'a': 1, 'b': 2}

# Dict → List of keys/values/items
list(my_dict.keys())   # ['a', 'b']
list(my_dict.values()) # [1, 2]
list(my_dict.items())  # [('a', 1), ('b', 2)]

Implicit vs Explicit Conversion

# Implicit (Python ทำให้อัตโนมัติ)
result = 5 + 3.0  # 8.0 (int → float อัตโนมัติ)

# Explicit (โปรแกรมเมอร์ระบุเอง)
result = int(5.9)  # 5

Common Pitfalls

  • float → int ตัดทิ้งทศนิยม ไม่ได้ปัดเศษ: int(5.9) == 5
  • String → int ต้องเป็นตัวเลขเท่านั้น: int("3.14") → ValueError
  • Bool conversion: bool([]) == False, bool([1]) == True, bool("False") == True (non-empty string เป็น True)

บทความเกี่ยวข้อง