Day 12: Nested Loops

Day 12: Loops inside loops for grids! Outer for i in range(1, 6): sets rows (1-5). Inner for j in range(1, 6): sets columns, running fully for each i. Inside inner: print(i, "x", j, "=", i * j) calculates and prints (e.g., 1 x 1 = 1). After inner loop, print() adds a blank line for readability.

Run: Prints a 5x5 table. Nested loops are for 2D tasks like matrices. In time, make it 1-10 or add formatting. Indentation is key—inner under outer. This scales Week 1 loops!

Create a multiplication table: Use nested for loops to print tables from 1 to 5 (e.g., 1x1=1 up to 5x5=25). (Concepts: nested loops, range)

Example Code:

for i in range(1, 6):
    for j in range(1, 6):
        print(i, "x", j, "=", i * j)
    print()  # New line after each row

Key Concepts:

  • Nested Loops: A loop inside another loop; the inner runs completely for each outer iteration.
  • range(a, b): (Repeated from Day 5) Generates numbers from a to b-1, used here for both loops.
  • Multiplication Operator (*): (Repeated from Day 2) Multiplies numbers.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top