ประเภทข้อมูลหลาม
ชนิดข้อมูลในตัว
ในการเขียนโปรแกรม ประเภทข้อมูลเป็นแนวคิดที่สำคัญ
ตัวแปรสามารถจัดเก็บข้อมูลประเภทต่างๆ และประเภทต่างๆ สามารถทำสิ่งต่างๆ ได้
Python มีประเภทข้อมูลในตัวตามค่าเริ่มต้นในหมวดหมู่เหล่านี้:
ประเภทข้อความ: | str |
ประเภทตัวเลข: | int , float ,
complex |
ประเภทลำดับ: | list , tuple ,
range |
ประเภทการทำแผนที่: | dict |
ประเภทชุด: | set ,frozenset |
ประเภทบูลีน: | bool |
ประเภทไบนารี: | bytes , bytearray ,
memoryview |
รับประเภทข้อมูล
คุณสามารถรับชนิดข้อมูลของวัตถุใด ๆ โดยใช้type()
ฟังก์ชัน:
ตัวอย่าง
พิมพ์ชนิดข้อมูลของตัวแปร x:
x = 5
print(type(x))
การตั้งค่าประเภทข้อมูล
ใน Python ชนิดข้อมูลจะถูกตั้งค่าเมื่อคุณกำหนดค่าให้กับตัวแปร:
Example | Data Type | Try it |
---|---|---|
x = "Hello World" | str | |
x = 20 | int | |
x = 20.5 | float | |
x = 1j | complex | |
x = ["apple", "banana", "cherry"] | list | |
x = ("apple", "banana", "cherry") | tuple | |
x = range(6) | range | |
x = {"name" : "John", "age" : 36} | dict | |
x = {"apple", "banana", "cherry"} | set | |
x = frozenset({"apple", "banana", "cherry"}) | frozenset | |
x = True | bool | |
x = b"Hello" | bytes | |
x = bytearray(5) | bytearray | |
x = memoryview(bytes(5)) | memoryview |
การตั้งค่าประเภทข้อมูลเฉพาะ
ถ้าคุณต้องการระบุชนิดข้อมูล คุณสามารถใช้ฟังก์ชันตัวสร้างต่อไปนี้:
Example | Data Type | Try it |
---|---|---|
x = str("Hello World") | str | |
x = int(20) | int | |
x = float(20.5) | float | |
x = complex(1j) | complex | |
x = list(("apple", "banana", "cherry")) | list | |
x = tuple(("apple", "banana", "cherry")) | tuple | |
x = range(6) | range | |
x = dict(name="John", age=36) | dict | |
x = set(("apple", "banana", "cherry")) | set | |
x = frozenset(("apple", "banana", "cherry")) | frozenset | |
x = bool(5) | bool | |
x = bytes(5) | bytes | |
x = bytearray(5) | bytearray | |
x = memoryview(bytes(5)) | memoryview |