Nested loops & 2-D lists
A loop inside a loop
- You can put one loop inside another loop.
- For every pass of the outer loop, the inner loop runs fully.
- So an outer of 2 and an inner of 3 runs the body 2 × 3 = 6 times.
ลูปในลูป
- คุณสามารถวางลูปหนึ่ง อยู่ข้างใน ลูปอีกวงหนึ่ง
- สำหรับทุกครั้งที่วนรอบลูปภายนอก ลูปภายในจะทำงาน ครบถ้วน
- ดังนั้นลูปนอกขนาด 2 และลูปในขนาด 3 จะวนโค้ด 2 × 3 = 6 รอบ
for row in range(2):
for col in range(3):
print(row, col)
A list of lists
- A 2-D list is a list whose items are themselves lists.
- It models a grid or table: rows of columns.
- Reach one cell with two indexes:
grid[row][col].
รายการของรายการ
- 2-D list คือรายการwhoseitemsเป็นรายการอื่นๆ ด้วย
- มันจำลองตารางหรือตาราง: แถวของคอลัมน์
- เข้าถึงเซลล์หนึ่งด้วยดัชนีสองตัว:
grid[row][col]
grid = [[1, 2], [3, 4]]
print(grid[0][1])
print(grid[1][0])
Loop over a grid
- Use a nested loop to visit every cell.
- The outer loop walks the rows; the inner loop walks the columns.
for row in grid:gives one row (a list) at a time.
ลูปผ่านตาราง
- ใช้ nested loop เพื่อเข้าถึงทุกเซลล์
- ลูปภายนอกเดินผ่าน แถว; ลูปภายในเดินผ่าน คอลัมน์
for row in grid:ให้แถวหนึ่ง (list) พร้อมกัน
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value)
In Cambridge pseudocode
- A 2-D list is the exam's 2-D array, written
ARRAY[1:rows, 1:cols].
ใน伪代码 Cambridge
- 2-D list คือ 2-D array ของข้อสอบ เขียน
ARRAY[1:rows, 1:cols]
DECLARE grid : ARRAY[1:2, 1:3] OF INTEGER
FOR r ← 1 TO 2
FOR c ← 1 TO 3
OUTPUT grid[r, c]
NEXT c
NEXT r
Common mistakes
- The inner loop finishes all its turns for each single turn of the outer loop.
- Index a grid row first, then column:
grid[row][col].
ข้อผิดพลาดที่พบบ่อย
- ลูปภายในจะทำงานครบทุกรอบสำหรับแต่ละรอบของลูปภายนอก
- ใช้ดัชนีเพื่อเข้าถึงแถวก่อน แล้วจึงถึงคอลัมน์:
grid[row][col]
Now you try
- Use a nested loop in each task.
- Press Check answer to test your code.
ลองดูเลย
- ใช้ลูปซ้อนกันในแต่ละงาน
- กด Check answer เพื่อทดสอบโค้ดของคุณ
A 2-D list is a grid
A 2-D list is rows of columns; reach a cell with grid[row][col]. · รายการ 2-D คือแถวและหลัก; เข้าถึงเซลล์ด้วย **grid[row][col]**
Use a nested loop to print a 3-by-3 square of stars: three lines, each with three * characters. · ใช้ ลูปซ้อน (nested loop) เพื่อพิมพ์ตารางดาวขนาด 3×3: สามบรรทัด แต่ละบรรทัดมี * ตัวอักษรสามตัว
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Add up every number in the 2-D list grid with a nested loop. Store the total in total (the answer is 21). · รวม ทุกตัวเลขใน 2-D list grid ด้วยลูปซ้อน เก็บผลรวมไว้ใน total (คำตอบคือ 21)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Count how many cells in the 2-D list grid are equal to 0. Store the count in count (the answer is 3). · นับว่าใน 2-D list grid มีเซลล์ใดบ้างที่เท่ากับ 0 เก็บจำนวนนับไว้ใน count (คำตอบคือ 3)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่