On this page
วันที่ 10 — ลูป (Loops)
เรียนรู้ while loop และ for loop ใน Python พร้อม break, continue, range และ nested loops
ลูป (Loops)
ในชีวิตประจำวันเราทำงานซ้ำ ๆ หลายครั้ง ใน Python เช่นเดียวกับภาษาโปรแกรมอื่น ๆ ถ้าต้องการทำงานซ้ำ ๆ เราใช้ loop Python มี loop อยู่สองประเภท: while loop และ for loop
While Loop
ใช้ keyword while เพื่อสร้าง while loop เงื่อนไขจะถูกตรวจสอบ ถ้าเป็น true block code จะถูกรัน จนกว่าเงื่อนไขจะเป็น false:
# syntax
while condition:
code goes herecount = 0
while count < 5:
print(count)
count = count + 1
#prints from 0 to 4ใน while loop เราสามารถเพิ่ม else block ที่จะรันเมื่อเงื่อนไขเป็น false:
# syntax
while condition:
code goes here
else:
code goes herecount = 0
while count < 5:
print(count)
count = count + 1
else:
print(count)Break และ Continue — ส่วนที่ 1
ถ้าต้องการออกจาก loop ใช้ break:
# syntax
while condition:
code goes here
if another_condition:
breakcount = 0
while count < 5:
print(count)
count = count + 1
if count == 3:
breakถ้าต้องการข้ามการทำงาน iteration ปัจจุบันใช้ continue:
# syntax
while condition:
code goes here
if another_condition:
continuecount = 0
while count < 5:
if count == 3:
count += 1
continue
print(count)
count = count + 1For Loop
ใช้ for loop ใน sequence (list, tuple, dictionary, set หรือ string) สามารถวน loop ผ่านทุกสมาชิกใน sequence ได้:
# syntax
for iterator in lst:
code goes herenumbers = [0, 1, 2, 3, 4, 5]
for number in numbers:
print(number)For loop กับ string:
# syntax
for iterator in string:
code goes herelanguage = 'Python'
for letter in language:
print(letter)
for i in range(len(language)):
print(language[i])For loop กับ tuple:
# syntax
for iterator in tpl:
code goes herenumbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
print(number)For loop กับ dictionary — การ loop ผ่าน dictionary จะให้ key:
# syntax
for iterator in dct:
code goes hereperson = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
for key in person:
print(key)
for key, value in person.items():
print(key, value)For loop กับ set:
# syntax
for iterator in st:
code goes hereit_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}
for company in it_companies:
print(company)Break และ Continue — ส่วนที่ 2
Break ใน for loop:
# syntax
for iterator in sequence:
code goes here
if condition:
breaknumbers = (0,1,2,3,4,5)
for number in numbers:
print(number)
if number == 3:
breakContinue ใน for loop:
# syntax
for iterator in sequence:
code goes here
if condition:
continuenumbers = (0,1,2,3,4,5)
for number in numbers:
print(number)
if number == 3:
continue
print('Next number should be ', number + 1) if number != 5 else print("loop's end")
print('outside the loop')ฟังก์ชัน Range
ฟังก์ชัน range() ใช้สร้าง list ของตัวเลข range(start, end, step) — default เริ่มที่ 0 และ step เป็น 1 ต้องการ end argument เสมอ:
lst = list(range(11))
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
st = set(range(1, 11))
print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
lst = list(range(0,11,2))
print(lst) # [0, 2, 4, 6, 8, 10]
st = set(range(0,11,2))
print(st) # {0, 2, 4, 6, 8, 10}
lst = list(range(11,0,-2))
print(lst) # [11,9,7,5,3,1]# syntax
for iterator in range(start, end, step):for number in range(11):
print(number)Nested For Loop
# syntax
for x in y:
for t in x:
print(t)person = {
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 250,
'country': 'Finland',
'is_marred': True,
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {
'street': 'Space street',
'zipcode': '02210'
}
}
for key in person:
if key == 'skills':
for skill in person['skills']:
print(skill)For Else
ถ้าต้องการรัน block code เมื่อ loop จบ ใช้ else:
# syntax
for iterator in range(start, end, step):
do something
else:
print('The loop ended')for number in range(11):
print(number)
else:
print('The loop stops at', number)Pass
ใน Python เมื่อต้องการ statement แต่ยังไม่ต้องการให้ทำอะไร ใช้ keyword pass:
for number in range(6):
pass💻 แบบฝึกหัด — วันที่ 10
ระดับ 1
- วน loop ตั้งแต่ 0 ถึง 10 ด้วย for loop แล้วทำซ้ำด้วย while loop
- วน loop ตั้งแต่ 10 ถึง 0 ด้วย for loop แล้วทำซ้ำด้วย while loop
- เขียน loop ที่เรียก print() 7 ครั้งเพื่อให้ได้รูปสามเหลี่ยม:
#
##
###
####
#####
######
#######- ใช้ nested loops สร้าง pattern ต่อไปนี้:
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #- Print pattern ต่อไปนี้:
0 x 0 = 0
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
6 x 6 = 36
7 x 7 = 49
8 x 8 = 64
9 x 9 = 81
10 x 10 = 100- วน loop ผ่าน list ['Python', 'Numpy','Pandas','Django', 'Flask'] ด้วย for loop แล้ว print แต่ละ item
- ใช้ for loop วนจาก 0 ถึง 100 แล้ว print เฉพาะเลขคู่
- ใช้ for loop วนจาก 0 ถึง 100 แล้ว print เฉพาะเลขคี่
ระดับ 2
- ใช้ for loop วนจาก 0 ถึง 100 แล้ว print ผลรวมของตัวเลขทั้งหมด
The sum of all numbers is 5050.- ใช้ for loop วนจาก 0 ถึง 100 แล้ว print ผลรวมของเลขคู่ทั้งหมดและผลรวมของเลขคี่ทั้งหมด
The sum of all evens is 2550. And the sum of all odds is 2500.ระดับ 3
- ไปที่โฟลเดอร์ data แล้วใช้ไฟล์ countries.py วน loop ผ่านประเทศต่าง ๆ และดึงประเทศที่มีคำว่า 'land'
- fruit list นี้ ['banana', 'orange', 'mango', 'lemon'] กลับลำดับโดยใช้ loop
- ไปที่โฟลเดอร์ data แล้วใช้ไฟล์ countries_data.py
1. จำนวนภาษาทั้งหมดในข้อมูลมีเท่าไร
2. หา 10 ภาษาที่มีคนพูดมากที่สุด
3. หา 10 ประเทศที่มีประชากรมากที่สุดในโลก