Devdit
 

Python เช็คชนิดตัวแปร ด้วยคำสั่ง type

2.6K

สอนเขียนภาษา Python เพื่อเช็คชนิดตัวแปรว่าตัวแปรดังกล่าวเป็นตัวแปรชนิด หรือประเภทใด เช่น ตัวเลข (Int), ข้อความ (String) เป็นต้น ด้วยคำสั่ง type สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Python เช็คชนิดตัวแปร ด้วยคำสั่ง type

i = 30
print( type(i), i )

s = 'Hello'
print( type(s), s )

b = True
print( type(b), b )

f = 100.93
print( type(f), f )

b = b'\x00\x1e'
print( type(b), b )

ผลลัพธ์

<class 'int'> 30
<class 'str'> Hello
<class 'bool'> True
<class 'float'> 100.93
<class 'bytes'> b'\x00\x1e'
เขียน 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ