for loop: iterate over a sequence For Loop: วนตามลำดับสมาชิก

Use for to walk each item of a list / string / range / enumerate, with break and continue ใช้ for วนทีละสมาชิกของ list / สตริง / range / enumerate พร้อม break และ continue

for variable in sequence: takes each item in turn, puts it in the variable, and runs the indented block. It fits when you know the sequence to walk (a list, a string, or a number range from range).

for ตัวแปร in ลำดับ: จะดึงสมาชิกทีละตัวมาใส่ตัวแปร แล้วรันบล็อกที่ย่อหน้า เหมาะเมื่อรู้ลำดับที่จะวน (list, สตริง, หรือช่วงตัวเลขจาก range)

1 for — repeat over items 1 for — ทำซ้ำหลายครั้ง

Walk each item in a list — the variable after for holds one item per round.

วนทีละสมาชิกใน list — ตัวแปรหลัง for รับค่าสมาชิกในแต่ละรอบ

[1]
[output]
apple
banana
cherry

2 for with a string 2 for กับสตริง

A string is also a sequence — for walks it one character at a time.

สตริงก็เป็นลำดับได้ — for จะวนทีละตัวอักษร

[2]
[output]
h
i

3 range() — counting the rounds for you 3 range() — นับรอบให้

range() generates the numbers for you, so you do not write a list of numbers yourself.

range() สร้างตัวเลขให้เอง ไม่ต้องเขียน list ของตัวเลขเอง

Form Meaningความหมาย
range(n)0 to n-10 ถึง n-1
range(start, stop)start to stop-1start ถึง stop-1
range(start, stop, step)stepping by stepกระโดดทีละ step

3.1 for with range(n)

range(n) gives numbers from 0 to n-1 (not including n).

range(n) ได้ตัวเลขตั้งแต่ 0 ถึง n-1 (ไม่รวม n)

[3]
[output]
0
1
2
3
4

3.2 for with range(start, stop, step)

range(start, stop) starts at start and stops before stop. range(start, stop, step) jumps by step each round, e.g. step=2 gives even numbers.

range(start, stop) เริ่มที่ start ไปจนก่อน stop range(start, stop, step) กระโดดทีละ step ในแต่ละรอบ เช่น step=2 ได้เลขคู่

[4]
[output]
0
2
4
6
8

4 enumerate() — get both the position and the value 4 enumerate() — ได้ทั้งตำแหน่งและค่า

Use enumerate() when you want both the position of an item in a list and its value. The position starts at 0.

ใช้ enumerate() เมื่ออยากรู้ทั้งตำแหน่งของสมาชิกใน list และค่าของมัน ค่าเริ่มต้นของตำแหน่งคือ 0

[5]
[output]
0 red
1 green
2 blue

4.1 enumerate starting from 1 4.1 enumerate เริ่มนับจาก 1

Pass a second argument to enumerate(sequence, start) to begin counting from the number you want, e.g. 1.

ส่งอาร์กิวเมนต์ที่สองให้ enumerate(ลำดับ, start) เพื่อเริ่มนับจากตัวเลขที่ต้องการ เช่น 1

[6]
[output]
1 red
2 green
3 blue

5 break out of the loop 5 break ออกจากลูป

break stops the loop at once — the remaining rounds are not run.

break หยุดลูปทันที — ไม่ทำรอบที่เหลือ

[7]
[output]
0
1

6 continue to skip a round 6 continue ข้ามรอบ

continue skips the rest of the current round and jumps straight to the next round.

continue ข้ามส่วนที่เหลือของรอบปัจจุบัน แล้วไปรอบถัดไปทันที

[8]
[output]
0
2
3

7 Daily sales 7 ยอดขายรายวัน

A for loop is ideal for totals. enumerate(sales, 1) (the second argument is the first number to count from) gives the day number and the amount together; the loop adds each amount to total and remembers the day with the highest sales.

ลูป for เหมาะกับการรวมค่า enumerate(sales, 1) (อาร์กิวเมนต์ตัวที่สองคือเลขที่เริ่มนับ) ให้ทั้งลำดับวันและยอดขายพร้อมกัน ลูปบวกยอดแต่ละวันเข้า total และจำวันที่ขายได้สูงสุด

[9]
[output]
Total: 440
Best day: 3

8 Common mistakes 8 ข้อผิดพลาดที่พบบ่อย

  1. Off-by-one with range(). range(1, 5) stops before 5, so it gives 1, 2, 3, 4. To include 5 write range(1, 6).
  2. ผิดไปหนึ่งค่ากับ range() range(1, 5) หยุดก่อน 5 จึงได้ 1, 2, 3, 4 ถ้าต้องการรวม 5 ให้เขียน range(1, 6)
  3. Changing a list while looping over it. Adding or removing items of the list you are iterating over skips or repeats items. Loop over a copy or build a new list instead.
  4. แก้ list ระหว่างที่วนอยู่ การเพิ่มหรือลบสมาชิกของ list ที่กำลังวนจะทำให้ข้ามหรือซ้ำรายการ ให้วนบนสำเนา หรือสร้าง list ใหม่แทน
  5. break leaves only the innermost loop. In the nested loops below it stops the inner j loop, while the outer i loop keeps going.
  6. break ออกจากลูปในสุดเท่านั้น ในลูปซ้อนด้านล่าง break หยุดลูป j ด้านใน ส่วนลูป i ด้านนอกยังวนต่อ
[10]
[output]
0 0
1 0
2 0

9 Think further 9 แบบฝึกคิดต่อ

Try these yourself in the Run boxes above (or in Google Colab):

ลองทำเองในกล่อง Run ด้านบน (หรือใน Google Colab):

  1. Print the 3 times table (3 x 1 = 3 … 3 x 10 = 30) with range(1, 11).
  2. พิมพ์สูตรคูณแม่ 3 (3 x 1 = 3 … 3 x 10 = 30) ด้วย range(1, 11)
  3. Count the vowels in "education" by looping over the string. Hint: test each letter with in "aeiou".
  4. นับสระใน "education" โดยวนทีละตัวอักษร Hint: ตรวจแต่ละตัวด้วย in "aeiou"
  5. Add up the even numbers from 1 to 10 in two ways: with range(2, 11, 2), and with range(1, 11) plus an if.
  6. รวมเลขคู่ตั้งแต่ 1 ถึง 10 สองวิธี: ใช้ range(2, 11, 2) และใช้ range(1, 11) ร่วมกับ if

Note: Run on this page is a JavaScript simulation, not real Python. For real Python, try Google Colab. หมายเหตุ: การกด Run บนหน้านี้เป็นการจำลองด้วย JavaScript ไม่ใช่ Python จริง หากต้องการทดลอง Python จริง แนะนำ Google Colab

References References / แหล่งอ้างอิง

Sources used for this lesson:

แหล่งที่ใช้ประกอบเนื้อหาในบทนี้:

  1. The for statement — Python Language Reference — for
  2. range — Built-in Types — range
  3. enumerate — Built-in Functions — enumerate

End-of-lesson quizแบบฝึกหัดท้ายบท

ตอบแล้ว 0 / 10

ข้อ 1

1 / 10

In for x in ["a", "b"]:, what is x in the first round?for x in ["a", "b"]: ตัวแปร x ในรอบแรกได้ค่าอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (A) "a""a"

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) "a""a"
    Correct! The first round takes the first item of the list.ถูกต้อง! รอบแรกได้สมาชิกตัวแรกของ list
  • (B) "b""b"
    Wrong: "b" is the item in the second round.ผิด: "b" เป็นสมาชิกในรอบที่สอง
  • (C) 00
    Wrong: for over a list gives the item, not the index automatically.ผิด: for กับ list ได้ค่าสมาชิก ไม่ใช่ดัชนีโดยอัตโนมัติ
  • (D) ["a", "b"]["a", "b"]
    Wrong: you get one item per round, not the whole list.ผิด: ได้ทีละสมาชิก ไม่ได้ทั้ง list ในแต่ละรอบ

ข้อ 2

2 / 10

Which values does range(0, 10, 2) give?range(0, 10, 2) ให้ค่าใดบ้าง?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) 0, 2, 4, 6, 80, 2, 4, 6, 8

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) 0, 1, 2, 3, 4, 5, 6, 7, 8, 90, 1, 2, 3, 4, 5, 6, 7, 8, 9
    Wrong: step=2 jumps by 2, not by 1.ผิด: step=2 จึงกระโดดทีละ 2 ไม่ใช่ทีละ 1
  • (B) 0, 2, 4, 6, 8, 100, 2, 4, 6, 8, 10
    Wrong: the stop value (10) is not included.ผิด: ไม่รวมค่า stop (10)
  • (C) 0, 2, 4, 6, 80, 2, 4, 6, 8
    Correct! Start at 0, step by 2, stop before 10.ถูกต้อง! เริ่มที่ 0 กระโดดทีละ 2 จนก่อน 10
  • (D) 2, 4, 6, 8, 102, 4, 6, 8, 10
    Wrong: it starts at 0 and does not include 10.ผิด: เริ่มที่ 0 และไม่รวม 10

ข้อ 3

3 / 10

What does break do in a for loop?break ใน for ทำอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) Stops the loop immediatelyหยุดลูปทันที

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Skips the current round and goes to the nextข้ามรอบปัจจุบันแล้วไปรอบถัดไป
    Wrong: that is continue.ผิด: นั่นคือ continue
  • (B) Stops the loop immediatelyหยุดลูปทันที
    Correct! break leaves the loop at once.ถูกต้อง! break ออกจากลูปเลย
  • (C) Restarts the loop from the beginningเริ่มลูปใหม่จากต้นเสมอ
    Wrong: it does not restart the whole loop.ผิด: ไม่ได้รีสตาร์ทลูปทั้งก้อนโดยอัตโนมัติ
  • (D) Deletes all variablesลบตัวแปรทั้งหมด
    Wrong: it does not delete variables.ผิด: ไม่ได้ลบตัวแปรใน env

ข้อ 4

4 / 10

In for i, color in enumerate(["red", "green"], 1):, what is i in the first round?จาก for i, color in enumerate(["red", "green"], 1): ค่า i ในรอบแรกคืออะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (D) 11

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) 00
    Wrong: start=1 was passed, so it does not begin at 0.ผิด: ส่ง start=1 จึงไม่เริ่มที่ 0
  • (B) "red""red"
    Wrong: "red" is in color, not i.ผิด: "red" อยู่ในตัวแปร color ไม่ใช่ i
  • (C) 22
    Wrong: the first round starts at the given start, which is 1.ผิด: รอบแรกเริ่มที่ start ที่ส่งเข้าไป คือ 1
  • (D) 11
    Correct! enumerate(..., 1) starts counting from 1.ถูกต้อง! enumerate(..., 1) เริ่มนับตำแหน่งจาก 1

ข้อ 5

5 / 10

What does continue do in a for loop?continue ใน for ทำอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (A) Skips the rest of this round and goes to the nextข้ามส่วนที่เหลือของรอบนี้ แล้วไปรอบถัดไป

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Skips the rest of this round and goes to the nextข้ามส่วนที่เหลือของรอบนี้ แล้วไปรอบถัดไป
    Correct! continue skips the rest of the current round.ถูกต้อง! continue ข้ามที่เหลือของรอบปัจจุบัน
  • (B) Stops the whole loop immediatelyหยุดลูปทั้งหมดทันที
    Wrong: that is break.ผิด: นั่นคือ break
  • (C) Converts for into whileแปลง for เป็น while
    Wrong: it does not change the loop type.ผิด: ไม่ได้เปลี่ยนชนิดลูป
  • (D) Prints the variable automaticallyพิมพ์ค่าตัวแปรอัตโนมัติ
    Wrong: continue does not print anything.ผิด: continue ไม่ได้ print ให้

ข้อ 6

6 / 10

What does for ch in "hi": print(ch) print?for ch in "hi": print(ch) พิมพ์อะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) h then i on separate linesh แล้ว i คนละบรรทัด

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) hi on one linehi ในบรรทัดเดียว
    Wrong: for walks one character at a time, each print on a new line.ผิด: for วนทีละตัวอักษร แต่ละ print ขึ้นบรรทัดใหม่
  • (B) 0 then 10 แล้ว 1
    Wrong: you get the characters, not indexes.ผิด: ได้ตัวอักษร ไม่ใช่ดัชนี
  • (C) h then i on separate linesh แล้ว i คนละบรรทัด
    Correct! A string is a sequence of characters.ถูกต้อง! สตริงเป็นลำดับของตัวอักษร
  • (D) An error, because you cannot loop over a stringError เพราะวนสตริงไม่ได้
    Wrong: for can loop over a string.ผิด: for วนสตริงได้

ข้อ 7

7 / 10

With for i in range(5): if i == 2: break; print(i), what is printed?จาก for i in range(5): if i == 2: break; print(i) พิมพ์อะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) 0, 10, 1

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) 0, 1, 2, 3, 40, 1, 2, 3, 4
    Wrong: break stops the loop at i == 2.ผิด: break หยุดลูปที่ i == 2
  • (B) 0, 10, 1
    Correct! It prints 0 and 1, then breaks at i == 2 (before print).ถูกต้อง! พิมพ์ 0 และ 1 แล้ว break ที่ i == 2 (ก่อน print)
  • (C) 0, 1, 20, 1, 2
    Wrong: break comes before print(i), so 2 is not printed.ผิด: break อยู่ก่อน print(i) จึงไม่พิมพ์ 2
  • (D) Nothingไม่พิมพ์อะไร
    Wrong: rounds i = 0 and 1 print normally.ผิด: รอบ i = 0 และ 1 พิมพ์ปกติ

ข้อ 8

8 / 10

When is enumerate() useful?enumerate() เหมาะกับสถานการณ์ใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (D) When you want both the position and the value of each item in a loopเมื่อต้องการทั้งตำแหน่งและค่าของสมาชิกในลูป

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) When you want to catch an exceptionเมื่อต้องการจับ exception
    Wrong: that is a try/except job.ผิด: งานนั้นใช้ try/except
  • (B) When you want to stop the loop at onceเมื่อต้องการหยุดลูปทันที
    Wrong: stopping a loop uses break.ผิด: การหยุดลูปใช้ break
  • (C) When you want to sort a listเมื่อต้องการเรียงลำดับ list
    Wrong: sorting uses sorted() or .sort().ผิด: การเรียงลำดับใช้ sorted() หรือ .sort()
  • (D) When you want both the position and the value of each item in a loopเมื่อต้องการทั้งตำแหน่งและค่าของสมาชิกในลูป
    Correct! enumerate gives (position, value) pairs.ถูกต้อง! enumerate ให้คู่ (ตำแหน่ง, ค่า)

ข้อ 9

9 / 10

With for i in range(4): if i == 1: continue; print(i), what is printed?จาก for i in range(4): if i == 1: continue; print(i) พิมพ์อะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) 0, 2, 30, 2, 3

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) 0, 1, 2, 30, 1, 2, 3
    Wrong: round i == 1 is skipped past print by continue.ผิด: รอบ i == 1 ถูก continue ข้าม print
  • (B) 0, 2, 30, 2, 3
    Correct! continue skips print only in round i == 1.ถูกต้อง! continue ข้าม print เฉพาะรอบ i == 1
  • (C) 1, 2, 31, 2, 3
    Wrong: 0 still prints; 1 is skipped.ผิด: 0 ยังพิมพ์ ส่วน 1 ถูกข้าม
  • (D) 00
    Wrong: continue skips one round; it does not stop the loop.ผิด: continue ข้ามแค่รอบเดียว ไม่หยุดลูป

ข้อ 10

10 / 10

How many rounds does range(n) run in a for loop?range(n) ในลูป for วนกี่รอบ?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) n rounds (0 to n-1)n รอบ (0 ถึง n-1)

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) n + 1 roundsn + 1 รอบ
    Wrong: range(n) gives 0..n-1 = n values.ผิด: range(n) ได้ 0..n-1 = n ค่า
  • (B) n - 1 roundsn - 1 รอบ
    Wrong: 0 is included, so there are n rounds.ผิด: รวม 0 ด้วย จึงมี n รอบ
  • (C) n rounds (0 to n-1)n รอบ (0 ถึง n-1)
    Correct! range(n) has n values.ถูกต้อง! range(n) มี n ค่า
  • (D) It loops foreverวนไม่รู้จบ
    Wrong: range is finite.ผิด: range มีจำนวนจำกัด