You are on page 1of 3

ทบทวนประเภทของตัวแปร

Name Type Details

Integers int Whole numbers: 1 20 23 56 2020

Floating point float Decimal points: 1.2 4.56 2020.0

Complex numbers complex Complex numbers: 3.0+2.0j, -1.0j, where j = √−1

Strings str sequence of charaters or sentences: 'A', 'hello world', "Bangkok KMUTT"

Lists list Order sequence of anything: [10, 'Non, str ,float, function]

Tuples tup immutable sequence of anything (10, 'Non, str ,float, function)

Dictionaries dict Key:Values pairs: {'key1':'values1', 'key2':'values2', ...}


Name Type Details

Sets set Unordered non-repeatable set {10, 'Non, str ,float, function}

Booleans bool Logical True or False

ตัวแปรประเภท Tuple
คือตัวแปรแบบเรียงลำดับที่ไม่สามารถเปลี่ยนรูปหรือแก้ไขค่า
ของข้อมูลได้ (immutable and unchangeable)
In [1]: mytuple = ('A', "B", 1.0)

In [2]: type(mytuple)

tuple
Out[2]:

ตรวจสอบขนาดของข้อมูลหรือความยาวของ tuple

In [3]: len(mytuple)

3
Out[3]:

In [4]: List = ['Ant', 'Bird', 'Cat', 'Dog']

Tuple1 = ('Ant', 'Bird', 'Cat', 'Dog')

Tuple2 = (3.14, "Non", "Non", 1, True, False, 22/7)

In [5]: print(len(Tuple1))

print(len(Tuple2))

In [ ]: type(Tuple1)

In [6]: List[0] = "Art"

print(List)

['Art', 'Bird', 'Cat', 'Dog']

ตัวแปร tuple เมื่อประกาศค่าแล้ว ไม่สามารถเปลี่ยนแปลงแก้ไขค่าของข้อมูลได้

In [7]: Tuple1[0] = "Art"

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-7-657a680fb7bf> in <module>()

----> 1 Tuple1[0] = "Art"

TypeError: 'tuple' object does not support item assignment

หากต้องการเปลี่ยนแปลงข้อมูลใน tuple ต้องประกาศค่าของตัวแปรขึ้นมาใหม่


In [8]: Tuple1 = ('Art', 'Bird', 'Cat', 'Dog')

In [9]: print(Tuple1[2])

print(Tuple1[2:])

print(Tuple2[:3])

print(Tuple2[4:])

Cat

('Cat', 'Dog')

(3.14, 'Non', 'Non')

(True, False, 3.142857142857143)

ตัวแปรประเภท Set
ชุดของข้อมูลแบบไม่เรียงลำดับ ไม่สามารถแก้ไขค่าได้ และไม่มีดัชนีในการเรียกข้อมูล (unordered,
unchangeable, and unindexed).

In [10]: Set1 = {2,3,3,3,4,1,2,5,6,3,1}

print(Set1)

print(len(Set1))

{1, 2, 3, 4, 5, 6}

In [11]: Set2 = {"B","D","C","A","D","C"}

print(Set2)

print(len(Set2))

{'C', 'D', 'B', 'A'}

ไม่สามารถเรียกข้อมูลใน set โดยใช้ดัชนีได้

In [12]: Set1[0]

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-12-25c87e89cfea> in <module>()

----> 1 Set1[0]

TypeError: 'set' object is not subscriptable

ไม่สามารถรวมตัวแปรประเภท set สองตัวแปรเข้าด้วยกันได้

In [14]: Set1 + Set1

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-14-10c0d018f856> in <module>()

----> 1 Set1 + Set1

TypeError: unsupported operand type(s) for +: 'set' and 'set'

You might also like