The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by suriyan, 2022-09-17 23:25:38

139_1-Python-Book-2022-Edit_share

139_1-Python-Book-2022-Edit_share

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอยา่ งที่ 4.1 ให้พมิ พ์รายการที่ 2 ของ Lists:
thislist = ["Sit", "Jan","Ton", " Leo", " Ang ", " Pu ", "Kaew"," Prim " ]
print(thislist[1])
Output
Jan

1.4 การเปลยี่ นค่าของ List (Change List Items)
▪ การเปล่ยี นคา่ Lists
ตวั อย่างที่ 4.2 การเปลยี่ น Lists ที่ 2:

thislist = ["Sit", "Jan","Ton", " Leo", " Ang ", " Pu ", "Kaew"," Prim " ]
thislist[1] = ["Dang"]
print(thislist[1])
Output
Dang

▪ การเปลยี่ นช่วงค่าของ Lists
ตวั อย่างที่ 4.3 การเปลีย่ นชว่ งคา่ ของ Lists:
thislist = ["Sit", "Jan","Ton", " Leo", " Ang ", " Pu ", "Kaew"," Prim " ]
thislist[1:3] = ["black", "melon"]
print(thislist)
Output
['Sit', 'black', 'melon', ' Leo', ' Ang ', ' Pu ', 'Kaew', ' Prim ']

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 93

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

1.5 การเพ่มิ Lists (Add List Items)
▪ การเพ่มิ Lists ดว้ ยเมธอด append

ตัวอยา่ งท่ี 4.4 เมธอด append() แทรกรายการท่ีดชั นีทีร่ ะบุ:
thislist = ["Sit", "Jan","Ton", " Leo", " Ang ", " Pu ", "Kaew"," Prim " ]
thislist.append("Aey")
print(thislist)
output
['Sit', 'Jan', 'Ton', ' Leo', ' Ang ', ' Pu ', 'Kaew', ' Prim ', 'Aey']

▪ การแทรก Lists ด้วยเมธอด insert
ในการแทรก Lists ใหม่โดยไม่ตอ้ งแทนทค่ี า่ ใด ๆ ท่ีมอี ยู่เราสามารถใชเ้ มธอด insert()

ตวั อย่างที่ 4.5 เมธอด insert() แทรกรายการที่ดชั นีที่ระบ:ุ
thislist = ["Sit", "Jan","Ton", " Leo", " Ang ", " Pu ", "Kaew"," Prim " ]
thislist.insert(2,"Kim")
print(thislist)
output
['Sit', 'Jan', 'Kim', 'Ton', ' Leo', ' Ang ', ' Pu ', 'Kaew', ' Prim ']

▪ การขยาย List ดว้ ยเมธอด extend
ในการผนวกองคป์ ระกอบจากรายการอน่ื ไปยังรายการปัจจบุ นั ใหใ้ ชเ้ มธอด extend()

ตวั อยา่ งท่ี 4.6 ใชเ้ พิ่มรายการ thislist2 ลง thislist :
thislist = ["Sit", "Jan","Ton", " Leo", " Ang ", " Pu ", "Kaew"," Prim " ]
thislist2 = ["Lin","Pin","Fin"]
thislist.extend(thislist2)
print(thislist)
output
['Sit', 'Jan', 'Ton', ' Leo', ' Ang ', ' Pu ', 'Kaew', ' Prim ', 'Lin', 'Pin', 'Fin']

94 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

1.6 การลบ Lists (Remove List Items)
▪ ลบรายการทร่ี ะบดุ ้วยเมธอด remove()

ตวั อย่างที่ 4.7 การลบ "banana" :
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
output
["apple","cherry"]

▪ ลบดัชนีที่ระบดุ ว้ ยเมธอด pop()

ตัวอยา่ งที่ 4.8 การลบ List ที่ 2 :
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
output
["apple","cherry"]

หมายเหตุ หากไม่ระบุดัชนี เมธอดจะลบรายการสุดทา้ ย

▪ การลบดว้ ยคำหลัก Del

ตวั อยา่ งท่ี 4.9 การลบ List ดัชนี 0 :
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
output
["banana", "cherry"]

ตัวอยา่ งท่ี 4.10 การลบ List ทั้งหมด :
thislist = ["apple", "banana", "cherry"]
del thislist

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 95

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

▪ การลา้ ง Lists ดว้ ย clear()
Lists ยงั คงอยูแ่ ต่ไมม่ ีเน้ือหา

ตัวอย่างที่ 4.11 การลา้ ง Lists :
thislist = ["apple", "banana", "cherry"]
thislist.clear
print(thislist)
output
[]

2. รายการข้อมลู แบบทเู พลิ (Tuples)

2.1 ทำความรจู้ กั ทเู พลิ
• ทเู พลิ คือ ชุดของวตั ถุทเี่ รยี งลำดบั และไม่เปล่ยี นรูป Tuples เป็นลำดับ เชน่ เดยี วกับ

List ความแตกต่างระหว่างทูเปิลและลิสต์ คือ ทูเปิลไมส่ ามารถเปลย่ี นแปลงไดต้ ่างจากลสิ ต์ และทู
เพิลใช้วงเลบ็ (…) ในขณะทล่ี ิสต์ใช้วงเล็บเหลีย่ ม[…]

• ทูเพลิ ถูกจดั ทำดัชนีรายการแรกมีดัชนี [0] รายการท่ีสองมีดชั นี [1]
• ทูเพิลไมส่ ามารถเปล่ียนแปลงได้ซ่ึงหมายความว่าเราไม่สามารถเปลยี่ นแปลงเพ่ิม หรอื
ลบรายการหลงั จากสรา้ งทเู ปลิ แล้ว
• การสร้างทูเปิลทำไดง้ ่ายเพียงแคใ่ ส่คา่ ตา่ งๆทีค่ ่ันด้วยจลุ ภาค สามารถเลือกทจี่ ะใสค่ า่ ที่
คน่ั ด้วยเครือ่ งหมายจุลภาคระหวา่ งวงเล็บไดด้ ว้ ย ตัวอยา่ งการสรา้ งทูเพลิ เชน่

thistuple = ("apple", "banana", "cherry")
print(thistuple)

▪ อนญุ าตรายการที่ซำ้ กนั เน่อื งจากทูเปลิ ถูกจดั ทำดัชนที ูเปลิ จงึ มไี อเทม็ ท่ีมีค่าเดยี วกันได้:

ตวั อยา่ งที่ 4.12 ทูเพิลอนุญาตให้มคี า่ ซำ้ กันได้
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Output
('apple', 'banana', 'cherry', 'apple', 'cherry')

96 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ความยาวทเู พลิ หากตอ้ งการแสดงจำนวนขอ้ มลู ท่ที ูเพลิ ให้ใช้ฟังก์ชนั len():

ตัวอยา่ งท่ี 4.13 พิมพ์จำนวนรายการในทเู พลิ :
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Output
3

สรา้ งทูเพิลดว้ ยรายการเดยี ว ในการสร้างทเู พลิ ที่มีเพียงรายการเดียวต้องเพิม่ ลกู น้ำ(,)
หลงั รายการมิฉะน้ันไพทอนจะไมร่ ับรวู้ า่ เป็นทเู ปลิ

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
output
<class 'tuple'>
<class 'str'>

Tuple Items – ประเภทขอ้ มลู
รายการ Tuple สามารถเป็นประเภทขอ้ มูลใดกไ็ ด:้

ตัวอยา่ งที่ 4.14 ชนิดขอ้ มูลสตริง จำนวนเตม็ และบูลนี :
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male")

print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
output
('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)
('abc', 34, True, 40, 'male')

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 97

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอยา่ งที่ 4.15 ทูเพลิ ท่ีมสี ตริงจำนวนเต็มและคา่ บูลีน:
tuple4 = ("abc", 34, True, 40, "male")
print(tuple4)
output
('abc', 34, True, 40, 'male')

2.2 การเขา้ ถงึ ค่าในทเู พิล
หากตอ้ งการเขา้ ถงึ ค่าในทเู ปิลให้ใช้วงเล็บเหล่ียมสำหรบั การแบ่งส่วนพร้อมกบั ดชั นีหรอื ดัชนี

เพอ่ื รบั คา่ ท่ีมีอยู่ในดัชนนี น้ั ตัวอยา่ งเชน่ -
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
output
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

2.3 การอัปเดตทูเพลิ (Update Tuples)
▪ เปลย่ี นคา่ ทเู พิล(Change Tuple Values)
เมื่อสร้างทเู ปลิ แลว้ จะไมส่ ามารถเปลยี่ นค่าได้ ทูเปลิ ไมส่ ามารถเปล่ียนแปลงไดห้ รือไมเ่ ปล่ียน

รูปตามทเ่ี รยี ก
แตม่ ีวิธีแกป้ ัญหาคือ สามารถแปลงเปน็ ลสิ ต์ เปล่ียนลสิ ต์ และแปลงลิสต์กลับเปน็ ทเู ปลิ ได้

ตัวอยา่ งที่ 4.16 แปลงทเู พลิ เป็นลสิ ตเ์ พอ่ื ให้สามารถเปลยี่ นแปลงได:้
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)
output
("apple", "kiwi", "cherry")

98 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

▪ วนลปู ผ่านทเู พลิ (Loop Tuples)
สามารถวนลปู เพื่อเข้าถึงข้อมูลทูเพลิ โดยการใช้ลูป for

ตวั อยา่ งท่ี 4.17 วนซำ้ รายการและพิมพค์ า่ :
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
output
apple
banana
cherry

▪ วนซำ้ หมายเลขดชั นี
สามารถวนซ้ำรายการทูเปิลได้โดยอ้างถงึ หมายเลขดัชนี ใชฟ้ งั กช์ นั range()และlen()เพ่ือ
สร้างการทำซ้ำท่เี หมาะสม

ตวั อย่างท่ี 4.18 พิมพร์ ายการทั้งหมดโดยอ้างถึงหมายเลขดัชน:ี
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
output
apple
banana
cherry

▪ วนลปู (While)
สามารถวนรอบรายการโดยใชก้ าร while วนซ้ำ ใชl้ en()ฟังกช์ ันเพอ่ื กำหนดความยาวของทู
เปิลจากนั้นเรม่ิ ตน้ ท่ี 0 และวนซำ้ ไปตามรายการทเู ปลิ โดยอา้ งถงึ ดัชนี อยา่ ลมื เพ่มิ ดชั นที ลี ะ 1
หลงั จากการทำซ้ำแตล่ ะครง้ั

ตวั อย่างที่ 4.19 วนลูป
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 99

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

Output
apple
banana
cherry

2.4 การรวมทเู พลิ (Join Tuples)
การรวมทูเพลิ โดยใชต้ วั ดำเนินการ +

ตัวอย่างที่ 4.20 การรวมทูเพิล
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
output
('a', 'b', 'c', 1, 2, 3)

การคณู ทเู พิล การคูณเน้ือหาของทเู พลิ ตามจำนวนครงั้ ทกี่ ำหนดสามารถใชต้ ัว * ดำเนินการ:

fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2

print(mytuple)
output
('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')

2.5 เมธอดและฟงั ก์ชนั ท่ใี ชง้ านกบั ชนิดข้อมูลทูเพิล
ชนดิ ข้อมลู ทูเพลิ เกบ็ ชนดิ ข้อูลไดห้ ลากหลายประเภท เช่นจำนวนเตม็ ทศนิยม สตรงิ ลสิ ต์

เป็นต้น ภาษาไพทอนได้ตรียมเมธอดและฟงั ก์ชันไว้ให้เรยี กใชง้ านดังต่อไปนี้

ตารางที่ 17 เมธอดและฟังกช์ นั ทใ่ี ช้งานกับชนดิ ข้อมลู ทเู พิล

เมธอด ความหมาย รูปแบบการใชง้ าน
index() ใช้สำหรบั แสดงตำแหนง่ ข้อมูล tub.index()
count() ใช้สำหรับนับจำนวนขอ้ มลู tub.count(x)
len() ฟงั ก์ชนั ใช้สำหรบั แสดงจำนวนข้อมูลทีอ่ ยใู่ นทู len(tub)
เพลิ

หมายเหตุ tub คือ ตัวแปรชนดิ ทูเพลิ , x คอื คา่ ข้อมูลใดๆ

100 ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอย่างที่ 4.21 ใหแ้ ปลงเลขอารบิคเป็นเลขไทยและแสดงคำอ่านแบบเรียงคำ โดยเกบ็
รายการเลขไทยแบบทเู พิล จากนัน้ นำเลขอารบิคแตล่ ะตัวมาใชเ้ ป็นลำดับในการอา่ นขอ้ มูลจากทเู พิล
เพ่อื ให้ได้ค่า ท่ีตรงกัน

tp_thai_digits = ('๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙')
tp_digit_words = ('ศนู ย'์ , 'หนง่ึ ', 'สอง', 'สาม', 'สี่', 'หา้ ', 'หก', 'เจ็ด', 'แปด', 'เก้า')

number = input('กำหนดตวั เลขอาราบิคเปน็ จำนวนเตม็ บวก >>')
number = tuple(number) #ไมต่ ้องมบี รรทดั นี้เลยกไ็ ด้
thai_digit = ''
thai_word = ''

for n in number: #วนลูปตามจำนวนตัวเลข

n = int(n)

thai_digit += tp_thai_digits[n] #ใชต้ ัวเลขนน้ั เป็นลำดบั ในการอ่านคา่ จากทูเพลิ

thai_word += tp_digit_words[n]

print('เลขไทย:', thai_digit)
print('คำอา่ น:', thai_word)

3. รายการขอ้ มูลแบบเซต (Sets)

myset = {"apple", "banana", "cherry"}
• เซต ใช้เพือ่ เกบ็ หลายรายการในตัวแปรเดยี ว
• เซต เป็นหน่ึงใน 4 ประเภทขอ้ มูลในตัวในไพทอนท่ใี ช้ในการจดั เก็บคอลเลคชันข้อมูลอกี
3 ประเภท คอื List , Tuple และDictionary ซ่ึงทัง้ หมดมคี ุณภาพและการใช้งานท่ี
แตกต่าง
• เซต ไม่มลี ำดับในการจัดเกบ็ ท่ีแนน่ อน ดงั นน้ั จึงไมส่ ามารถเขา้ ถงึ สมาชิกตวั ใดตัวหน่ึงแบบ
เจาะจงด้วยเลขลำดับเหมือนลสิ ต์หรือทเู พลิ
• เซต จะเขียนดว้ ยวงเล็บปีกกา(curly brackets) {}

ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 101

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตวั อยา่ งท่ี 4.22 การสร้างเซต
thisset = {"apple", "banana", "cherry"}
print(thisset)
output
{'cherry', 'apple', 'banana'}

หมายเหตุ เซตไมเ่ รยี งลำดบั หมายความวา่ รายการจะเรียงลำดับแบบสุ่ม

ตัวอยา่ งท่ี 4.23 ค่าทซี่ ำ้ กนั จะถูกละเวน้ :
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
output
{ "banana", "cherry", "apple"}

ตัวอยา่ งท่ี 4.24 นับจำนวนรายการในเซต:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
output
3

#ชนิดข้อมลู สตริง จำนวนเต็ม และบูลีน
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

#ชดุ ทมี่ ีสตรงิ จำนวนเต็มและค่าบูลนี :
set1 = {"abc", 34, True, 40, "male"}

3.1 การเขา้ ถงึ เซต ( Access Set Items)
ไม่สามารถเขา้ ถงึ รายการในเซตได้โดยอ้างถึงดชั นีหรือคีย์ แต่สามารถวนซำ้ รายการชุดโดย

ใช้การ for วนซ้ำหรือถามว่ามคี า่ ทร่ี ะบุอยใู่ นเซตหรอื ไมโ่ ดยใชค้ ำสำคัญ in

102 ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอย่างท่ี 4.25 การเขา้ ถึงเซต
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
output
cherry
banana
apple

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)
output
True

3.2 การเพม่ิ รายการเซต
เม่อื สร้าง set แล้วจะไมส่ ามารถเปลีย่ นรายการได้ แต่สามารถเพม่ิ รายการใหมไ่ ด้

หากต้องการเพ่ิมหน่งึ รายการในชุดให้ใช้ เมธอด add()
▪ Add Set Items

ตัวอยา่ งท่ี 4.26 เพิม่ รายการ(item) ลงในเซตโดยใช้เมธอด add():
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")

print(thisset)
output
{'orange', 'banana', 'cherry', 'apple'}

▪ Add Sets
หากต้องการเพิม่ เซตจากชดุ อน่ื ลงในเซตปจั จุบันใหใ้ ช้เมธอด update():

ตวั อย่างท่ี 4.27 Add elements from tropical and thisset into newset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)

print(thisset)

ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 103

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

Output
{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}

▪ เพ่ิมรายการทที่ ำซ้ำได้ (Add Any Iterable)
อ็อบเจก็ ต์ใน เมธอด update() ทไ่ี ม่มีเซตสามารถเป็นออ็ บเจก็ ต์ทท่ี ำซ้ำได้ (ทเู ปิล, ลสิ ต์

พจนานกุ รม และอ่ืน ๆ )

ตวั อยา่ งท่ี 4.28 เพ่มิ รายการทำซ้ำ update()
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)

print(thisset)
output
{'banana', 'cherry', 'apple', 'orange', 'kiwi'}

3.3 Remove Set Items
หากตอ้ งการลบรายการในชุดใหใ้ ช้เมธอด remove() หรอื discard()

ตัวอย่างที่ 4.29 ลบ "banana" โดยใช้ remove() method:
#เมธอด remove()
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")

print(thisset)
output
{'apple', 'cherry'}

หมายเหต:ุ หากไม่มรี ายการที่จะลบremove()จะทำใหเ้ กดิ ขอ้ ผิดพลาดขน้ึ

ตัวอยา่ งที่ 4.30 ลบ "banana" โดยใช้ discard() method:
#เมธอด discard()
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
output
{'cherry', 'apple'}

หมายเหต:ุ หากไม่มรี ายการที่จะลบdiscard()จะ ไมท่ ำใหเ้ กดิ ข้อผดิ พลาด

104 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

สามารถใชp้ op() method ลบรายการได้ แตว่ ธิ นี ้จี ะลบรายการสดุ ท้าย โปรดจำไว้ว่าset ไม่
เรียงลำดบั ดังนั้นจะไมท่ ราบว่ารายการใดถูกลบออกไป

คา่ ที่ส่งคืนของpop() methd คือ รายการทถ่ี ูกลบออก

ตวั อยา่ งที่ 4.31 ลบรายการสดุ ทา้ ยโดยใช้ pop() method:
#ลบรายการสดุ ทา้ ยโดยใชเ้ มธอด pop()
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
output
apple
{'cherry', 'banana'}

ตวั อยา่ งที่ 4.32 clear() method จะทำให้เซตวา่ ง:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
output
set()

ตวั อยา่ งที่ 4.33 คยี ์เวริ ์ด del จะลบเซตได้สมบรู ณ์:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
output
Traceback (most recent call last):
File "C:\Users\HPSurajak\AppData\Local\Temp\Rar$DIa20196.49467\
del_set.py", line 5, in <module>

print(thisset)
NameError: name 'thisset' is not defined

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 105

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

3.4 Loop Sets
สามารถวนซ้ำรายการทก่ี ำหนดไดโ้ ดยใช้ลูป for :

ตัวอยา่ งท่ี 4.34 วนรอบเซต และพมิ พ์คา่ :
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
output
banana
cherry
apple

3.5 Join Sets
มหี ลายวิธใี นการรวมสองเซตขน้ึ ไปในไพทอนซง่ึ สามารถใชเ้ มธอด union() ทสี่ ง่ คนื เซตใหมท่ ่ี

มีรายการท้งั หมดจากท้ังสองชดุ หรือ update() วิธที ่แี ทรกรายการท้งั หมดจากชุดหนึ่งไปยังอกี ชดุ หนงึ่ :

ตวั อยา่ งท่ี 4.35 เมธอด union() สง่ กลบั เซตใหม่กับรายการทง้ั หมดจากทงั้ 2 เซต:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
output
{'a', 2, 'c', 3, 1, 'b'}

ตวั อยา่ งที่ 4.36 เมธอด update() แทรกรายการใน set2 ลง set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
output
{3, 2, 'b', 'a', 'c', 1}

หมายเหตุ: ทง้ั สอง union() และ update() จะไม่รวมรายการท่ซี ้ำกนั

106 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

3.6 Set Methods

ตารางท่ี 18 เมธอดและคำอธิบาย

เมธอด คำอธบิ าย

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or

more sets

difference_update() Removes the items in this set that are also included in

another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in

other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

4. รายการข้อมูลแบบดกิ ชนั นารี (Dictionaries)

4.1 เกย่ี วกบั ดกิ ชนั นารี

• ดกิ ชนั นารี คือ การจดั เกบ็ ข้อมูลแบบรายการทีส่ มาชิกแต่ละตวั มีองคป์ ระกอบ 2 อย่าง คือ
key และ value

• ดิกชนั นารี ใชเ้ พ่ือเกบ็ ค่าข้อมูลใน key : value

• ดกิ ชนั นารี คอื คอลเล็กชันทไ่ี ม่มีการเรียงลำดับเปลีย่ นแปลงไดแ้ ละไม่อนุญาตให้มกี ารทำซำ้

• ดกิ ชนั นารี เขียนด้วยวงเล็บปกี กา { } และมีคียแ์ ละคา่ ดังน้ี

key value
Red แดง
Green เขียว
blue นำ้ เงิน
Pink ชมพู

ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 107

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

▪ Dictionary Items

ตัวอยา่ งที่ 4.37 สร้างและพิมพ์ dictionary:
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
print(thisdict)
Output
{'brand': 'Toyota', 'model': 'Fortuner', 'year': 2020}

ตวั อย่างที่ 4.38 พมิ พ์ "brand" ค่าใน dictionary:
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020,
}
print(thisdict["brand"])
Output
Toyota

▪ ไม่เรียงลำดบั (Unordered)
เม่ือเราบอกวา่ พจนานกุ รมไมเ่ รียงลำดบั หมายความวา่ รายการนัน้ ไมม่ ีลำดบั ที่กำหนดไวไ้ ม่

สามารถอ้างถงึ รายการโดยใชด้ ชั นไี ด้
▪ เปลย่ี นแปลงได้ (Changeable)
พจนานุกรมสามารถเปลีย่ นแปลงได้ซง่ึ หมายความว่าเราสามารถเปลยี่ นแปลงเพ่ิมหรือลบ

รายการตา่ งๆได้หลงั จากสร้างพจนานุกรมแล้ว
▪ ไม่อนุญาตใหท้ ำซำ้ (Duplicates Not Allowed)
พจนานุกรมไมส่ ามารถมสี องรายการทีม่ ีคีย์เดียวกัน

ตัวอย่างท่ี 4.39 ค่าทซี่ ำ้ กันจะเขียนทับคา่ ที่มอี ยู่:
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020,
"year": 2021
}

108 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

print(thisdict)
Output
{'brand': 'Toyota', 'model': 'Fortuner', 'year': 2021}

4.2 การเขา้ ถึงสมาชกิ ของดกิ ชันนารี
สามารถเขา้ ถึงรายการของพจนานกุ รมโดยอ้างถงึ ช่ือคยี ภ์ ายในวงเล็บ [ ]

ตวั อย่างท่ี 4.40 รับคา่ ของคีย์ "model":
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
x = thisdict["model"]
print(x)
Output
Fortuner

ตวั อยา่ งที่ 4.41 รบั ค่าของคยี ์ "model": นอกจากนี้ยงั ใช้ เมธอด get() จะใหผ้ ลลพั ธ์
เดยี วกัน:
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
x = thisdict.get("model")
print(x)
Output
Fortuner

เมธอด keys() จะกลบั รายการของคียท์ ้ังหมดในพจนานุกรม

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 109

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอยา่ งที่ 4.42 เมธอด keys()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020}
x = thisdict.keys()

print(x)
Output
dict_keys(['brand', 'model', 'year'])

4.3 การเปลย่ี นรายการดกิ ชนั นารี
สามารถเปล่ียนค่าของรายการเฉพาะได้โดยอา้ งถึงชือ่ คยี ์:

ตวั อยา่ งที่ 4.43 เปลย่ี นค่า
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
thisdict["year"] = 2021
print(thisdict)

Output
{'brand': 'Toyota', 'model': 'Fortuner', 'year': 2021}

เมธอด update() สามารถปรบั ปรงุ dict ทม่ี ีรายการจากอารก์ ิวเมนตท์ ก่ี ำหนด
อาร์กวิ เมนตต์ ้องเปน็ dict หรือ object ท่ที ำซำ้ ไดซ้ ง่ึ มี key: value

ตวั อย่างที่ 4.44 อปั เดต "ปี" ของรถโดยใช้ เมธอด update()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
thisdict.update({"year": 2018})
print(thisdict)

110 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

Output
{'brand': 'Toyota', 'model': 'Fortuner', 'year': 2018}

4.4 การเพิ่มรายการดิกชนั นารี
การเพิ่มรายการลงใน dictionary ทำไดโ้ ดยใชค้ ียด์ ชั นใี หม่และกำหนดคา่ ใหก้ บั dict:
ตวั อยา่ งที่ 4.46 การเพ่มิ รายการ

thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020}
thisdict["color"] = "red"
print(thisdict)
Output
{'brand': 'Toyota', 'model': 'Fortuner', 'year': 2020, 'color': 'red'}

ตวั อยา่ งท่ี 4.47 การเพิม่ รายการด้วย update()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020}
thisdict.update({"color": "red"})
print(thisdict)
Output
{'brand': 'Toyota', 'model': 'Fortuner', 'year': 2020, 'color': 'red'}

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 111

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

4.5 การลบรายการดิกชนั นารี
มหี ลายวิธีในการลบรายการออกจากดิกชันนารี

ตวั อยา่ งท่ี 4.48 pop()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
thisdict.pop("model")
print(thisdict)

Output
{'brand': 'Toyota', 'year': 2020}

ตวั อย่างท่ี 4.49 popitem()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
thisdict.popitem()
print(thisdict)

Output
{'brand': 'Toyota', 'model': 'Fortuner'}

ตวั อย่างที่ 4.50 คีย์เวริ ด์ del เลือกลบบางรายการ
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
del thisdict["model"]
print(thisdict)

112 ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

Output
{'brand': 'Toyota', 'year': 2020}

ตวั อย่างท่ี 4.51 คีย์เวิรด์ del ลบทัง้ หมด
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
del thisdict
print(thisdict)
#จะทำใหเ้ กิดขอ้ ผิดพลาดเนอ่ื งจากไม่มี "thisdict" อกี ต่อไป

ตัวอยา่ งท่ี 4.52 clear()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
thisdict.clear
print(thisdict)
Output
{}

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 113

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

4.6 การวนซำ้ ดกิ ชันนารี (Loop Dictionaries)
• สามารถวนผา่ นพจนานุกรมไดโ้ ดยใช้ for วนซ้ำ
• เม่อื วนลปู ผ่านพจนานุกรมคา่ ทสี่ ่งคนื เปน็ คียข์ องพจนานุกรม แต่กม็ วี ิธีการคนื ค่าเชน่ กนั

ตัวอย่างท่ี 4.53 พมิ พช์ อ่ื dict ท้ังหมด
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
for x in thisdict:
print(x)
Output
brand
model
year

ตวั อยา่ งที่ 4.54 พมิ พท์ ุก value ใน dictionary
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
for x in thisdict:
print(thisdict[x])
Output
Toyota
Fortuner
2020

114 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตวั อยา่ งที่ 4.55 ใชm้ ethod values() คืนค่า value ใน dictionary:
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
for x in thisdict.values():
print(x)

Output
Toyota
Fortuner
2020

ตัวอยา่ งท่ี 4.56 ใช้ keys() method คนื key ใน dictionary:
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
for x in thisdict.keys():
print(x)

Output
brand
model
year

ตัวอย่างท่ี 4.57 วนซ้ำทงั้ key และ value โดยใช้ items()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
for x,y in thisdict.items():
print(x,y)

ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 115

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

Output
brand Toyota
model Fortuner
year 2020

4.7 การคัดลอกดิกชันนารี (Copy Dictionaries)
ไพทอนไม่สามารถทำการคดั ลอก dictionary ดว้ ยการพิมพ์ dict2 = dict1, เพราะว่า :

dict2 จะอา้ งองิ ถึง dict1, and และทำการเปลีย่ น dict1 โดยอัตโนมัตใิ น dict2 ทั้งนเ้ี ราสามารถทำ
การสำเนาโดยใช้ built-in Dictionary เมธอด copy()

ตวั อยา่ งท่ี 4.58 ทำสำเนาดกิ ชนั นารดี ้วย เมธอด copy()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
mydict = thisdict.copy()
print(mydict)

อีกวธิ ีหน่งึ ในการทำสำเนา คือ การใช้ฟังกช์ ัน dict()

ตัวอยา่ งท่ี 4.59 คำส่งั ฟงั กช์ ัน dict()
thisdict = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
mydict = dict(thisdict)
print(mydict)

4.8 ดิกชันนารีทีซ่ อ้ นกัน (Nested Dictionaries)

116 บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอย่างที่ 4.60 Nested Dictionaries ซอ้ นกัน 3 ชดุ
myfamily = {
"child1" : {

"name" : "COM",
"year" : 2010
},
"child2" : {
"name" : "EDU",
"year" : 2015
},
"child3" : {
"name" : "KSU",
"year" : 2020
}
}

print(myfamily)

หรือ สามารถ add 3 dictionaries ลง new dictionary กไ็ ด:้

ตวั อย่างที่ 4.61 สร้าง 3 dictionaries จากน้ันสร้าง dictionary เพอื่ เก็บ 3
dictionaries:

child1 = {
"name" : "COM",
"year" : 2010
}

child2 = {
"name" : "EDU",
"year" : 2015
}

child3 = {
"name" : "KSU",
"year" : 2020

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 117

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)

.

4.9 เมธอดของดิกชันนารี (Dictionary Methods)
Python มชี ุดของ built-in methods ทส่ี ามารถใช้ร่วมกบั dictionaries.

ตารางที่ 19 ชดุ ของ built-in methods

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

ตวั อยา่ งที่ 4.62 clear()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

118 ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

car.clear()

print(car)
output
{}

ตวั อยา่ งท่ี 4.63 copy()
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020}
}
x = car.copy()
print(x)

output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

ตัวอยา่ งท่ี 4.64 fromkeys()
x = ('key1', 'key2', 'key3')
y=0
thisdict = dict.fromkeys(x, y)
print(thisdict)

output
{'key1': 0, 'key2': 0, 'key3': 0}

ตวั อยา่ งที่ 4.65 get()

car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020}
x = car.get("price", 15000)

บี ที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 119

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

print(x)

output
15000

ตวั อยา่ งท่ี 4.66 items()
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
x = car.items()
car["year"] = 2018
print(x)

dict_items([('brand', 'Toyota'), ('model', 'Fortuner'), ('year', 2018)])

ตัวอยา่ งที่ 4.67 keys()

car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
x = car.keys()
car["color"] = "white"
print(x)

output
dict_keys(['brand', 'model', 'year', 'color'])

ตัวอย่างที่ 4.68 pop()
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}

120 ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

x = car.pop("model")
print(x)

output
Fortuner

ตวั อยา่ งที่ 4.69 popitem()
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
x = car.popitem()
print(x)

output
('year', 2020)

ตัวอย่างที่ 4.70 setdefault()
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
x = car.setdefault("color", "white")
print(x)

output
White

ตวั อยา่ งที่ 4.71 update()

car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}

ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 121

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

car.update({"color": "White"})
print(car)

output
{'brand': 'Toyota', 'model': 'Fortuner', 'year': 2020, 'color': 'White'}

ตัวอย่างท่ี 4.72 values()
car = {
"brand": "Toyota",
"model": "Fortuner",
"year": 2020
}
x = car.values()
car["year"] = 2018
print(x)

output
dict_values(['Toyota', 'Fortuner', 2018])

5. สรุปทา้ ยบท

การรวบรวมข้อมลู 4 ประเภทในภาษาโปรแกรมไพทอน:
• Lists คือ ข้อมลู ชนดิ ลำดบั รายการและเปลย่ี นแปลงได้ อนุญาตใหส้ มาชกิ ซำ้ กนั
• Tuple ข้อมลู ชนดิ ลำดับรายการและไม่สามารถเปลีย่ นแปลงได้ อนุญาตใหส้ มาชกิ ซำ้ กนั
• Set คือ คอลเลก็ ชนั ทไี่ ม่มีการเรียงลำดบั และไมไ่ ดจ้ ัดทำดัชนี ไมม่ ีสมาชกิ ซ้ำกนั
• Dictionarie คอื คอลเลก็ ชันทีไ่ ม่เรียงลำดบั และเปล่ียนแปลงได้ ไมม่ สี มาชกิ ซ้ำกนั

เมอ่ื เลือกประเภทคอลเลกชนั จะเปน็ ประโยชนใ์ นการทำความเข้าใจคณุ สมบัตขิ องประเภท
น้นั ๆ การเลอื กประเภทท่เี หมาะสมสำหรับชุดข้อมลู หน่งึ ๆ อาจหมายถงึ การคงความหมาย
ไวแ้ ละอาจหมายถึงการเพ่ิมประสิทธิภาพหรือความปลอดภยั

6. กิจกรรม

1. ใหร้ บั ค่าปี พ.ศ. เขา้ มา แล้วคำนวณวา่ ปีนั้นตรงกบั ปนี ักษัตรใด โดยท่ี
• เก็บชอ่ื ปนี ักษัตรไวใ้ นแบบลสิ ต์ เชน่ constellation = [ ‘ชวด’, ‘ฉล’ู ,…,‘กนุ ’]
• โดยสูตรคำนวณหานกั ษตั รแบบง่าย เพอ่ื ใชก้ บั ลิสต์โดยหาค่าทเ่ี หลอื จากการหารดงั นี้
คา่ ทเ่ี หลือ = (ปี พ.ศ. + 5) % 12

122 ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

• นำค่าที่เหลอื ไปใชเ้ ปน็ เลขลำดบั ในการอา่ นชอื่ ปีนกั ษัตรจากลิสตท์ ไ่ี ดส้ ร้างไว้ เช่น ถ้าได้
ค่าทเ่ี หลอื เปน็ 1 แสดงว่าตรงกับ ‘ฉล’ู เป็นตน้

constellations = ['ชวด', 'ฉล'ู , 'เถาะ', 'ขาล', 'มะโรง', 'มะเสง็ ',
'มะเมยี ', 'มะแม', 'วอก', 'ระกา', 'จอ', 'กนุ ']

print('ถา้ ตอ้ งการหยุด ใหใ้ สค่ ่านอ้ ยกว่า 1');

while True:
year = int(input('ปี พ.ศ. >> '))
if year < 1:
break

x = (year + 5) % 12
c = constellations[x]
print('ตรงกับปนี กั ษตั ร:', c)
print()

2. เก็บรายชื่อวันสำคญั ของเดือนต่างๆ ในแบบลิสต์ 2 มติ ิ จากน้ันวนลปู เพอื่ ตรวจสอบว่าใน
แตล่ ะเดอื นน้นั มวี ันสำคัญอะไรบ้าง แลว้ แสดงผลออกมา ผลลพั ธด์ งั น้ี

#ให้เดือนแรกเปน็ ชอ่ งวา่ ง เพอื่ ใชแ้ ทนเดอื นลำดบั ท่ี 0
#ดังน้นั ลำดบั ของเดือนมกราคมกจ็ ะเปน็ 1 ตามท่ีเราเข้าใจ
months = [' ', 'มกราคม', 'กมุ ภาพันธ'์ , 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน',

'กรกฎาคม', 'สงิ หาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม']

#สร้างลสิ ต์วา่ งแบบ 2 มติ ิ
days = []
for m in range(13): #[[เดือน 0], [เดอื น 1], [เดือน 2], ...[เดือน 12]]

days.append([])
for d in range(32): #[[วันท่ี 0, วันที่ 1, วันที่ 2, ..., วนั ท่ี 31], [วนั ท่ี 0, วนั ที่ 1, วนั ที่ 2,
..., วนั ที่ 31], ...]

days[m].append('')

days[1][1] = 'วนั ขน้ึ ไปใหม่'
days[1][16] = 'วันคร'ู
days[2][14] = 'วันวาเลนไทน'์
days[4][6] = 'วนั จักร'ี

ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 123

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

days[4][13] = 'วนั สงกรานต์'
days[7][28] = 'วนั เฉลมิ พระชนมพรรษา ร.10'
days[8][12] = 'วันแม'่
days[10][23] = 'วันปิยมหาราช'
days[12][5] = 'วันพ่อ'
days[12][10] = 'วนั รฐั ธรรมนญู '
days[12][25] = 'วนั คริสต์มาส'
days[12][31] = 'วันส้นิ ป'ี

print('วันสำคญั ในเดอื นต่างๆ')

for m in range(len(days)): # วนลูปตามจำนวนเดอื น (0 - 12)
important_days = ''

for d in days[m]: # วนลูปตามจำนวนวนั ท่ขี องแต่ละเดอื น

if d != '':

if important_days != '':

important_days += ', '

important_days += d

#ถา้ เดือนนน้ั มีวนั สำคญั กใ็ หแ้ สดงออกไป
if important_days != '':

print(f'เดอื น {months[m]} : {important_days}')

124 ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

7. แบบฝึกหดั ท้ายบท

1. จงเขียนโปรแกรมเพอื่ เก็บช่ือและสขี องวนั ทงั้ 7 ในรอบสปั ดาห์ดว้ ยลิสตห์ รือทเู พิล 2 มติ ิ
แล้วใชล้ ูป for เพอ่ื อา่ นคา่ มาแสดงผล

2. จงเขียนโปรแกรมรับข้อมูลทางคยี บ์ อร์ด แลว้ นำมากำหนดเปน็ ลิสต์ จากนนั้ ให้
เรยี งลำดับจากนอ้ ยไปหามาก (สามารถใชฟ้ งั ก์ชนั sort) และจากมากไปหาน้อย (กรณนี ต้ี ้องนำ
ลิสตท์ ่ีเรียงลำดบั จากนอ้ ยไปหามากเอาไวแ้ ลว้ มาเรยี งแบบย้อนกลับ)

3. จงเขยี นโปรแกรมเพ่อื รับขอ้ มูลจากคียบ์ อรด์ เปน็ คะแนนของนกั เรียนจำนวนหน่งึ จากนัน้
พิจารณาให้เกรดโดยยดึ เอาผู้ไดค้ ะแนนสูงสดุ (top) เป็นเกณฑ์ดังน้ี

• ไดเ้ กรด A ถ้าคะแนน >= top-10
• ไดเ้ กรด B ถา้ คะแนน >= top-20
• ไดเ้ กรด C ถา้ คะแนน >= top-30
• ไดเ้ กรด D ถา้ คะแนน >= top-40
• ได้เกรด F ถ้าคะแนน < top-40

ีบที ีทีี4ีีขีอีมีลีแีบีบีลีาีดีบีรีาียีกีาีร 125

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

บทที่ 5
คำส่ังควบคุมทิศทางการทำงานของโปรแกรม

ในบทน้ี จะได้เรียนรคู้ ำสง่ั วนซ้ำในภาษาไพทอน ซ่ึงจะพดู ถึงการควบคมุ การทำงานโดยการใช้
คำสง่ั ท่ีสามารถควบคุมโปรแกรมใหท้ ำงานซ้ำๆ ในเงอ่ื นไขท่ีกำหนดและเพม่ิ ความสามารถของการ
เขียนโปรแกรม ตัวอย่างของการทำงานซำ้ ๆ นั้นพบเห็นได้ทัว่ ไปในชวี ิตประจำวัน เช่น โปรแกรม
พยากรณ์สภาพอากาศที่เกิดขน้ึ ในทกุ ๆ วนั ดังนน้ั แนวคดิ เหลา่ น้จี งึ ถูกนำมาใชก้ บั การเขยี นโปรแกรม
ในการเขยี นโปรแกรม สามารถกำหนดการทำงานของโปรแกรมได้โดยใช้ คำสงั่ ควบคุมทิศทางการ
ทำงานของโปรแกรมซง่ึ มี 3 รปู แบบ คอื

1. คำสัง่ ควบคุมแบบลำดบั (Sequence Control Statement)
2. คำสั่งควบคุมแบบมีเงอ่ื นไข(Condition Control Statement)
3. คำสัง่ ควบคุมแบบทำซำ้ (Interation Control Statement)

ภาพท่ี 4 แสดงผงั งานรูปแบบคำสัง่

1. คำสงั่ ควบคุมแบบลำดับ

การเขยี นโปรแกรมควบคุมการทำงานแบบลำดบั เปน็ ลักษณะการเขยี นคำสั่งให้โปรแกรม
ทำงานแบบทำงานจากบนลงล่าง โดยทำงานจากคำสง่ั ที่ 1 คำสั่งท่ี 2 คำสัง่ ที่ 3 ไปเรอื่ ยๆ จนครบ
ทุกคำส่ัง ไมม่ กี ารตดั สินใจ ไมม่ ีการทำซำ้ และไมม่ คี ำส่งั กระโดดข้าม ดงั ตัวอย่าง

ตัวอย่างที่ 5.1 คำนวณพ้นื ท่ีส่เี หล่ยี ม
x = float(input(“กรณุ าป้อนความยาว = ”))
y = float(input(“กรณุ าป้อนความกวา้ ง = ”))
z=x*y

บี ที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 126

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

print(“พน้ื ทส่ี ่เี หล่ียมผนื ผา้ = ”, z)

ตวั อยา่ งที่ 5.2 คำนวณรายไดส้ ทุ ธิ
name = str(input("ชื่อพนกั งาน = "))
salary = int(input("เงนิ เดอื น = "))
OT = int(input("จำนวนชว่ั โมงท่ีทำงานล่วงเวลา = "))
cal_ot = OT * 20
bonus = salary * 0.5
ot_bonus = cal_ot + bonus
salary_total = salary + ot_bonus
print ("ค่าทำงานล่วงเวลา %d * 20 = %.2f" %(OT,cal_ot), "บาท")
print ("ค่า bonus %d * 0.5 = %.2f" %(salary,bonus), "บาท")
print ("รวม OT และ bonus %.2f + %.2f = %.2f" %(cal_ot,bonus,ot_bonus),"บาท")
print ("รายไดส้ ุทธิ %d + %.2f = %.2f" %(salary,ot_bonus,salary_total), "บาท")

2. คำส่งั ควบคุมแบบมเี ง่อื นไข(Condition Control Statement)

▪ คำสงั่ if
รูปแบบ

if เง่อื นไข:
คำสงั่ ต่างๆ

บี ที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 127

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอย่างท่ี 5.3 if statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
output
b is greater than a

ในตัวอยา่ งนี้เราใชต้ ัวแปรสองตวั คอื a และ b ซ่งึ ใช้เปน็ สว่ นหนึ่งของคำสัง่ if เพ่อื ทดสอบว่า
bมากกว่า a หรือไม่ เม่ือ a เปน็ 33 และ b คือ 200 เรารวู้ า่ 200 มคี ่ามากกว่า 33 ดังนน้ั เราจงึ พิมพ์
วา่ "b มากกว่า a"

ตัวอยา่ งท่ี 5.4 if statement:
var = 100
if ( var == 100 ) :

print ("Value of expression is 100")
print ("Good bye!")
output
Value of expression is 100
Good bye!

ตัวอยา่ งท่ี 5.5 รับค่าตัวเลขมา 2 คร้งั แลว้ ตรวจสอบว่าเปน็ เลขคู่หรือเลขคี่ (ถ้าหาร 2 ลงตวั
แสดงว่าเป็นเลขค่)ู :
odd = 'เลขค่ี'
even = 'เลขค'ู่

n = int(input('จำนวนท่ี #1: '))
s = odd
if n % 2 == 0:

s = even

print(f'{n} เป็น {s}')

128 ีบีทีทีี5ีคี ีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

n = int(input('\nจำนวนท่ี #2: '))
s = odd
if n % 2 == 0:

s = even
print(f'{n} เปน็ {s}')
คำสง่ั if…else

คำสง่ั if…else ควบคมุ การทำงานแบบมีเง่ือนไข 2 ทศิ ทาง

If เงอื่ นไข:
คำส่ังต่างๆ ถา้ ตรงกับเงื่อนไขทก่ี ำหนด

else:
คำส่งั ตา่ งๆ ถ้าตรงกับเงอ่ื นไขไม่ตรงที่กำหนด

ภาพที่ 5 แสดงผังงานคำสัง่ if - else

ตวั อยา่ งที่ 5.6 เปรียบเทยี บคา่ ตัวแปร a และ b
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
output
b is not greater than a

บี ที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 129

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตวั อยา่ งท่ี 5.7 รับข้อมลู Password และ Confirm Password แล้วตรวจสอบวา่ ตรงกนั
หรอื ไม่
pw1 = input('Password: ')
pw2 = input('Confirm Password: ')

if pw1 != pw2:
print('Password not match!')

else:
print('\nPassword OK')

Output

ภายในบล็กคำส่งั if หรือ else ตอ้ งมีอย่างน้อย 1 คำสัง่ แตห่ ากยังมพ่ รอ้ มท่จี ะกำหนดคำส่ังใดๆ
ในขณะนั้น เชน่ อย่รู ะหวา่ งทดสอบ ก็อาจใชค้ ยี เ์ วิร์ด pass เพ่ือขา้ มบลอ็ กคำสัง่ นั้นไปกอ่ น เช่น
x = -1
if x >= 0:

print ('OK')
else:

pass

▪ คำส่งั if…elif…else
ถ้าเง่อื นไขท่ีเราต้องการสรวจสอบสามารถแยกไดห้ ลายกรณี แตม่ เี พียงกรณเี ดียวเท่านั้นทถี่ ูกเลอื ก

เพอื่ ดำเนินการ ลักษณะเช่นน้ีสามารถตรวจสอบดว้ ยคำสงั่ elif ร่วมกบั if ได้ดงั รปู แบบต่อไปน้ี

If เงอ่ื นไขท่ี 1:
คำสง่ั ต่างๆ ถ้าตรงกบั เงอ่ื นไขท่ี 1

elif เงื่อนไขท่ี 2:
คำสง่ั ตา่ งๆ ถา้ ตรงกับเงอ่ื นไขท่ี 2


elif เง่ือนไขที่ n:

คำสง่ั ตา่ งๆ ถา้ ตรงกบั เงือ่ นไขท่ี n

130 บี ีทีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตวั อย่างท่ี 5.8 รบั ตวั เลขทางคียบ์ อร์ดเป็นตัวเลข 0-4 แล้วใช้ if…elif…else ตรวจสอบแล้ว
แสดงผล
print("Please enter the values from 0 to 4")
x=int(input("Enter a number: "))
if x==0:

print("You entered:", x)
elif x==1:

print("You entered:", x)
elif x==2:

print("You entered:", x)
elif x==3:

print("You entered:", x)
elif x==4:

print("You entered:", x)
else:

print("Beyond the range than specified")
Output
Please enter the values from 0 to 4
Enter a number: 4
You entered: 4

ตวั อย่างท่ี 5.9 รับตัวเลขทางคีย์บอรด์ เปน็ จำนวนประตู ทมี เจา้ บา้ นและทีมเยอื น แล้วใช้
if…elif ตรวจสอบว่าใครเป็นผชู้ นะ
home_goals = int(input('ประตทู ่ที มี เจา้ บา้ นทำได:้ '))
guest_goals = int(input('ประตทู ่ที ีมเยอื นทำได:้ '))

if home_goals > guest_goals:
print('ผล: ทีมเจา้ บ้านชนะ')

elif home_goals < guest_goals:
print('ผล: ทีมเยอื นชนะ')

elif home_goals == guest_goals:
print('ผล: เสมอกนั ')

ีบที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 131

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

เปล่ียนหน่วยขนาดไฟล์ใหเ้ หมาะสม โดยรบั ข้อมูลเขา้ มาในหน่วย ไบต์ แลว้ เปรยี บเทยี วว่า
สามารถเปลีย่ นเป็นหน่วยใหญ่ทีส่ ดุ ใดได้ โดยจำนวนไบตข์ องแต่ละหนว่ ยเป็นดังตาราง

หนว่ ย จำนวนไบต์
KB 1,024
MB 1,048,576
GB 1,073,741,824
TB 1,099,511,627,776

ตวั อย่างที่ 5.10 รับคา่ จากคียบอรด์ แล้วแปลงหน่วยขอ้ มูล

size = float(input('ขนาดของไฟล์ (ไบต์) >> '))
unit = ''

if size >= 1_099_511_627_776: #ถา้ ขนาด 1, 099, 511, 627, 776 ขนึ้ ไป ให้แปลงเปน็

หนว่ ย TB

size /= 1_099_511_627_776

unit = 'TB'

elif size >= 107_3741_824: #ถา้ ขนาด 107, 3741, 824 ขนึ้ ไป ให้แปลงเป็นหน่วย GB

size /= 1_073_741_824

unit = 'GB'

elif size >= 1_048_576: #ถ้าขนาด 1, 048, 576 ขึ้นไป ให้แปลงเปน็ หนว่ ย MB

size /= 1_048_576

unit = 'MB'

elif size >= 1_024: #ถา้ ขนา ด 1,024 ขึ้นไป ใหแ้ ปลงเปน็ หนว่ ย KB

size /= 1_024

unit = 'KB'

elif size < 1_024: #ถ้าขนาดนอ้ ยกว่า 1,024 ใหเ้ ป็นหนว่ ย Byte เช่นเดมิ

unit = 'Byte(s)'

print(f'แปลงเป็นหน่วยท่ีเหมาะสมไดป้ ระมาณ: {format(size, ".2f")} {unit}')

132 ีบีทที ีี5ีคี ีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

3. คำสงั่ ควบคุมแบบทำซำ้ (Interation Control Statement)

ในภาษาไพทอน มีคำสง่ั ทำซำ้ อยู่ 2 คำส่งั คอื while loops และ for loops

ภาพที่ 6 แสดงผงั งานคำสัง่ แบบทำซำ้
3.1 คำสงั่ วนซ้ำด้วย while loop

While loop เราสามารถเรียกใช้ชดุ คำสงั่ ได้ตราบเท่าท่ีเงอ่ื นไขเป็นจรงิ
while เงือ่ นไข:

คำส่งั ต่างๆ

ตัวอยา่ งที่ 5.11 คำสง่ั ทำซำ้ แบบ While
i=1
while i < 6:
print(i)
i += 1
output
1
2
3
4
5

ีบที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 133

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

▪ The break Statement

ตวั อย่างที่ 5.12 คำสั่ง break เราสามารถหยุดลปู ไดแ้ มว้ า่ เงื่อนไข while จะเปน็ จรงิ :
i=1
while i < 6:
print(i)
if i == 3:

break
i += 1
output
1
2
3

▪ The continue Statement
continue statement สามารถหยุดการวนซ้ำ และดำเนินการต่อในขนั้ ตอนตอ่ ไป:

ตวั อยา่ งท่ี 5.13 ทำซ้ำตอ่ ไปถา้ ค่า i = 3
i=0
while i < 6:
i += 1
if i == 3:

continue
print(i)
output
1
2
4
5
6

134 ีบีทที ีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

▪ The else Statement
คำส่งั else สามารถเรยี กใช้บล็อกโคด้ เมอ่ื เงือ่ นไขไมเ่ ป็นจรงิ :

ตัวอยา่ งท่ี 5.14 พมิ พ์ขอ้ ความเม่อื เงอ่ื นไขเป็นเทจ็ :
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
output
1
2
3
4
5
i is no longer less than 6

3.2 คำสงั่ วนซำ้ ดว้ ย for loop

ตัวอย่างท่ี 5.15 พิมพ์ fruit ใน fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
output
apple
banana
cherry

บี ที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 135

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

▪ Looping Through a String

ตัวอยา่ งที่ 5.16 วนลูปสตริง
for x in "banana":
print(x)
output
b
a
n
a
n
a

▪ The break Statement

ตวั อย่างท่ี 5.17 break Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":

break
output
apple
banana

ตัวอยา่ งท่ี 5.18 break Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":

break
print(x)
output
apple

136 บี ีทที ีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

▪ The continue Statement

ตัวอยา่ งท่ี 5.19 continue
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":

continue
print(x)
output
apple
cherry

▪ The range() Function
ในการวนซ้ำชุดรหสั ตามจำนวนครั้งทก่ี ำหนดเราสามารถใช้ฟงั ก์ชนั range() ส่งคนื ลำดบั

ของตวั เลขโดยเร่ิมจาก 0 ตามคา่ เริ่มตน้ และเพม่ิ ขน้ึ ทลี ะ 1 (โดยคา่ เรม่ิ ตน้ ) และส้ินสดุ ทต่ี วั เลขท่ี
ระบุ

ตัวอย่างท่ี 5.20 ใชฟ้ งั ก์ชัน range()
for x in range(6):
print(x)
output
0
1
2
3
4
5

หมายเหตุ: ชว่ ง (6)ไมใ่ ชค่ า่ 0 ถึง 6 แตเ่ ปน็ ค่า 0 ถึง 5
ฟังกช์ นั range () มีค่าเร่ิมตน้ เปน็ 0 เป็นคา่ เร่ิมตน้ อยา่ งไรก็ตามสามารถระบุค่า

เร่ิมตน้ ไดโ้ ดยการเพ่มิ พารามเิ ตอร:์ range (2, 6)ซึง่ หมายถงึ ค่าต้งั แต่ 2 ถงึ 6 (แตไ่ ม่รวม 6):

ีบที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 137

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

ตัวอยา่ งที่ 5.21 ใช้พารามิเตอรเ์ ริม่ ต้น:

for x in range(2, 6):
print(x)
output
2
3
4
5
ฟงั กช์ นั range () มีค่าเริม่ ต้นทจี่ ะเพมิ่ ลำดับทลี ะ 1 อยา่ งไรก็ตามสามารถระบุค่าสว่ นเพ่มิ ได้โดย
การเพมิ่ พารามเิ ตอรท์ ส่ี าม: range (2, 30, 3 ) :

ตวั อยา่ งท่ี 5.22 เพ่ิมลำดับดว้ ย 3 (คา่ เรมิ่ ต้นคือ 1):
for x in range(2, 30, 3):
print(x)
output
2
5
8
11
14
17
20
23
26
29

▪ Else in for Loop
คำหลัก else ใน for loop ระบุบลอ็ กของรหัสทจ่ี ะดำเนนิ การเม่อื loop เสรจ็ สนิ้ :

ตวั อย่างที่ 5.23 พมิ พต์ วั เลขตั้งแต่ 0 ถงึ 5 และพิมพ์ข้อความเมอื่ การวนซำ้ ส้ินสดุ ลง:
for x in range(6):
print(x)
else:
print("Finally finished!")

138 บี ีทที ีี5ีคี ีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

output
0
1
2
3
4
5
Finally finished!

▪ Nested Loops
ลูปทซ่ี อ้ นกนั คือ การวนซำ้ ภายในลปู "วงใน" จะดำเนินการหนง่ึ คร้งั สำหรบั การวนซำ้

ของ "วงนอก" แต่ละครัง้ :

ตัวอยา่ งที่ 5.24 Nested Loops
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:

print(x, y)
Output
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

ีบที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 139

ีกาีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

4. กิจกรรม

4.1 ให้ตรวจสอบวา่ จะต้องสุม่ ก่คี รง้ั จึงจะได้เลขท่มี คี ่าตง้ั แต่ 0.9 ขนึ้ ไป

import random

x=0
times = 0

while x < 0.9: #ถา้ ไดค้ ่าทน่ี อ้ ยกว่า 0.9 ต้องวนลปู ตอ่ ไป
x = random.random() #เลขส่มุ ทีไ่ ด้จาก random() จะอยรู่ ะหว่าง 0 - 1
times += 1

print(f'ต้องสมุ่ ทงั้ หมด {times} ครงั้ เพื่อให้ไดค้ า่ ตง้ั แต่ 0.9 ข้ึนไป')

4.2 เขยี นโปรแกรมเพือ่ รับคา่ รหสั จากผใู้ ช้ ถา้ รหสั คอื 1234 ด้วยฟังกช์ ัน input() หากใสร่ หัสผิด
ให้ใสใ่ หม่จนกว่าจะถูกตอ้ ง โดยใช้ลปู while ในการรับขอ้ มูล
validCode = False

while not validCode: #ถา้ ตวั แปร validCode ยงั เปน็ false กใ็ ห้วนลูปตอ่ ไป
code = input('กรณุ ใสร่ หัส >> ')
if code == '1234':
validCode = True #ถา้ ใส่รหสั ถกู เปลี่ยนคา่ validCode เปน็ true เพ่ือออกจากลูป

while

print('คณุ ใส่รหัสถูกต้อง')

140 ีบีทที ีี5ีคี ีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

4.3 แยกตวั เลขออกมาทลี ะตัว เชน่ 2520 แยกเปน็ 2,5,2,0
n = int(input('กรุณาใส่ตัวเลขจำนวนเต็ม >> '))
remain = n
digit = 0
result = ''

#จะใช้เทคนิคการนำตวั เลขที่คัดแยกในลูปกอ่ นๆ น้ี
#มาวางต่อท้ายเลขท่คี ัดแยกได้ในลปู น้ี โดยค่นั ด้วยเครื่องหมาย ','
while remain != 0:

digit = remain % 10
if result == '':

result = str(digit)
else:

result = str(digit) + ', ' + result

remain = remain // 10

print('ตวั เลขท่แี ยกได้คอื : ', result)

4.4 สร้างเกมทายตวั เลข

- เม่ือเร่มิ เกมใหส้ มุ่ ตัวเลข 0-99
- ใชl้ oop while หรอื for กไ็ ด้ เพ่ือแสดง input ให้ผูเ้ ลน่ ทายตัวเลขทีต่ ้องการทาย
- ถ้าผู้เลน่ ใส่เลขท่มี ากกว่าคา่ ท่สี ุ่ม ให้แจ้งวา่ น้อยกว่านี้
- ถา้ ผูเ้ ล่นใสเ่ ลขท่นี อ้ ยกวา่ คา่ ท่สี มุ่ ใหแ้ จง้ ว่า มากกว่านี้
- ทายได้ไม่เกนิ 7 คร้ัง วนลปู ไปจนกวา่ จะชนะ ทายครบยงั ไม่ถกู ถอื วา่ แพ้

import random
win = False
number = random.randint(0, 100)
count = 1
max_guess = 7
message = ''

ีบที ีทีี5ีีคีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม 141

กี าีีรีเีขียีนีโีปีรีแีกีรีมีภีาีษีาีไีพีทีอีนีี(Python Programming)

while not win:
guess_num = int(input(
f'ทายคร้งั ท่:ี {count} กรณุ าใส่ตวั เลข 0 - 99 >> '))
if guess_num > number:
message = 'น้อยกวา่ น'ี้
elif guess_num < number:
message = 'มากกวา่ น'ี้
elif guess_num == number:
message = '\nถูกตอ้ ง'
win = True
print(message)
if (not win) and (count == max_guess):
print(f'\nคณุ ทายครบ {max_guess} ครั้งแล้ว\nเกมถกู ยกเลิก')
break
count += 1

4.5 ใชล้ ปู for วนรบั ตวั เลข 4 จำนวนจากผู้ใช้ พร้อมหาผลรวมและคา่ เฉลยี่
sum = 0
for i in range(1, 5):

num = int(input(f'จำนวนที่ {i}: '))
sum += num

print('ผลรวม:', sum)
print('ค่าเฉล่ยี :', sum / 4)

142 ีบีทที ีี5ีคี ีาีสีงีคีวีบีคีมีทีศีทีาีงีกีาีรีทีาีงีาีนีขีอีงีโีปีรีแีกีรีม


Click to View FlipBook Version