Notes & software courses · Free to learn
Aph's Blog
On this page

วันที่ 10 — ลูป (Loops)

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

เรียนรู้ 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:

python
  # syntax
while condition:
    code goes here
python
count = 0
while count < 5:
    print(count)
    count = count + 1
#prints from 0 to 4

ใน while loop เราสามารถเพิ่ม else block ที่จะรันเมื่อเงื่อนไขเป็น false:

python
  # syntax
while condition:
    code goes here
else:
    code goes here
python
count = 0
while count < 5:
    print(count)
    count = count + 1
else:
    print(count)

Break และ Continue — ส่วนที่ 1

ถ้าต้องการออกจาก loop ใช้ break:

python
# syntax
while condition:
    code goes here
    if another_condition:
        break
python
count = 0
while count < 5:
    print(count)
    count = count + 1
    if count == 3:
        break

ถ้าต้องการข้ามการทำงาน iteration ปัจจุบันใช้ continue:

python
  # syntax
while condition:
    code goes here
    if another_condition:
        continue
python
count = 0
while count < 5:
    if count == 3:
        count += 1
        continue
    print(count)
    count = count + 1

For Loop

ใช้ for loop ใน sequence (list, tuple, dictionary, set หรือ string) สามารถวน loop ผ่านทุกสมาชิกใน sequence ได้:

python
# syntax
for iterator in lst:
    code goes here
python
numbers = [0, 1, 2, 3, 4, 5]
for number in numbers:
    print(number)

For loop กับ string:

python
# syntax
for iterator in string:
    code goes here
python
language = 'Python'
for letter in language:
    print(letter)

for i in range(len(language)):
    print(language[i])

For loop กับ tuple:

python
# syntax
for iterator in tpl:
    code goes here
python
numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
    print(number)

For loop กับ dictionary — การ loop ผ่าน dictionary จะให้ key:

python
  # syntax
for iterator in dct:
    code goes here
python
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:
    print(key)

for key, value in person.items():
    print(key, value)

For loop กับ set:

python
# syntax
for iterator in st:
    code goes here
python
it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}
for company in it_companies:
    print(company)

Break และ Continue — ส่วนที่ 2

Break ใน for loop:

python
# syntax
for iterator in sequence:
    code goes here
    if condition:
        break
python
numbers = (0,1,2,3,4,5)
for number in numbers:
    print(number)
    if number == 3:
        break

Continue ใน for loop:

python
  # syntax
for iterator in sequence:
    code goes here
    if condition:
        continue
python
numbers = (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 เสมอ:

python
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]
python
# syntax
for iterator in range(start, end, step):
python
for number in range(11):
    print(number)

Nested For Loop

python
# syntax
for x in y:
    for t in x:
        print(t)
python
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:

python
# syntax
for iterator in range(start, end, step):
    do something
else:
    print('The loop ended')
python
for number in range(11):
    print(number)
else:
    print('The loop stops at', number)

Pass

ใน Python เมื่อต้องการ statement แต่ยังไม่ต้องการให้ทำอะไร ใช้ keyword pass:

python
for number in range(6):
    pass

💻 แบบฝึกหัด — วันที่ 10

ระดับ 1

  1. วน loop ตั้งแต่ 0 ถึง 10 ด้วย for loop แล้วทำซ้ำด้วย while loop
  2. วน loop ตั้งแต่ 10 ถึง 0 ด้วย for loop แล้วทำซ้ำด้วย while loop
  3. เขียน loop ที่เรียก print() 7 ครั้งเพื่อให้ได้รูปสามเหลี่ยม:
sh
  #
  ##
  ###
  ####
  #####
  ######
  #######
  1. ใช้ nested loops สร้าง pattern ต่อไปนี้:
sh
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
  1. Print pattern ต่อไปนี้:
sh
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
  1. วน loop ผ่าน list ['Python', 'Numpy','Pandas','Django', 'Flask'] ด้วย for loop แล้ว print แต่ละ item
  2. ใช้ for loop วนจาก 0 ถึง 100 แล้ว print เฉพาะเลขคู่
  3. ใช้ for loop วนจาก 0 ถึง 100 แล้ว print เฉพาะเลขคี่

ระดับ 2

  1. ใช้ for loop วนจาก 0 ถึง 100 แล้ว print ผลรวมของตัวเลขทั้งหมด
sh
The sum of all numbers is 5050.
  1. ใช้ for loop วนจาก 0 ถึง 100 แล้ว print ผลรวมของเลขคู่ทั้งหมดและผลรวมของเลขคี่ทั้งหมด
sh
The sum of all evens is 2550. And the sum of all odds is 2500.

ระดับ 3

  1. ไปที่โฟลเดอร์ data แล้วใช้ไฟล์ countries.py วน loop ผ่านประเทศต่าง ๆ และดึงประเทศที่มีคำว่า 'land'
  2. fruit list นี้ ['banana', 'orange', 'mango', 'lemon'] กลับลำดับโดยใช้ loop
  3. ไปที่โฟลเดอร์ data แล้วใช้ไฟล์ countries_data.py
    1. จำนวนภาษาทั้งหมดในข้อมูลมีเท่าไร
    2. หา 10 ภาษาที่มีคนพูดมากที่สุด
    3. หา 10 ประเทศที่มีประชากรมากที่สุดในโลก