PART 2 โ€ข LEVEL 05

๐Ÿ” Loops & Patterns

Repeat instructions efficiently, control each iteration and turn simple loop logic into useful number and symbol patterns.

โฑ 90โ€“105 minutes๐Ÿ“š 8 concepts๐Ÿ’ป 5 programs๐Ÿง  6-question quiz
learning_streak.pyPython 3
total = 0

for day in range(1, 6):
    total += day
    print(f"Day {day}: total = {total}")

print("Streak complete!")
FINAL OUTPUTDay 5: total = 15
Streak complete!

By the End of This Level

You will be able to choose, trace and control Python loops confidently.

01

Generate reliable sequences using range().

02

Use for and while for suitable repetition tasks.

03

Apply break, continue and nesting correctly.

04

Construct number and symbol patterns systematically.

01

Loop Mental Model

A loop repeats a block of code. Each repetition is called an iteration, and a correct loop must know what to repeat and when to stop.

Instead of writing the same statement many times, define one loop body and let Python execute it for a controlled sequence or while a condition remains true.

Iteration

One complete execution of the statements inside a loop body.

1InitializePrepare values
โ†’
2CheckItem or condition
โ†’
3ExecuteRun loop body
โ†’
4UpdateMove forward
02

The range() Function

range() generates an arithmetic sequence of integers. Its stop value is always excluded.

FormMeaningGenerated values
range(5)Start at 0, stop before 50, 1, 2, 3, 4
range(2, 6)Start at 2, stop before 62, 3, 4, 5
range(2, 11, 2)Increase by 22, 4, 6, 8, 10
range(5, 0, -1)Decrease by 15, 4, 3, 2, 1
Remember

The step cannot be zero. A negative step requires the start value to be greater than the stop value.

03

The for Loop

Use for when iterating over a known sequence or a predictable number of values.

EXAMPLE 1

Sum from 1 to 5

total = 0

for number in range(1, 6):
    total += number

print("Sum =", total)
OUTPUT
Sum = 15
Accumulator pattern

Initialize an accumulator such as total before the loop, update it during every iteration, then use the completed value after the loop.

04

The while Loop

Use while when repetition depends on a changing condition and the number of iterations is not naturally known in advance.

EXAMPLE 2

Count the Digits

number = 50821
count = 0

while number > 0:
    count += 1
    number //= 10

print("Digits =", count)
OUTPUT
Digits = 5
FOR LOOP
for attempt in range(3):
    print(attempt)

Use it for a known sequence or count.

WHILE LOOP
while balance > 0:
    balance -= payment

Use it while a changing condition remains true.

05

break, continue and pass

๐Ÿ›‘

break

Stops the nearest loop immediately.

โญ๏ธ

continue

Skips the rest of the current iteration.

๐Ÿงฉ

pass

Does nothing; it is a valid placeholder statement.

๐ŸŽฏ

Nearest Loop

Inside nested loops, control affects only the innermost loop.

EXAMPLE 3

Skip and Stop

for number in range(1, 10):
    if number == 3:
        continue
    if number == 7:
        break
    print(number)
OUTPUT
1
2
4
5
6
06

Nested Loops

For every iteration of the outer loop, the inner loop completes all of its iterations.

EXAMPLE 4

Coordinate Pairs

for row in range(1, 3):
    for column in range(1, 4):
        print(row, column)
OUTPUT
1 1
1 2
1 3
2 1
2 2
2 3
Iteration count

If the outer loop runs 2 times and the inner loop runs 3 times for each outer iteration, the inner body runs 2 ร— 3 = 6 times.

07

Pattern Construction

Treat every pattern as a collection of rows. Decide what changes in each row, then build or print that row inside the loop.

EXAMPLE 5

Growing Star Triangle

stars = ""

for row in range(1, 5):
    stars += "*"
    print(stars)
OUTPUT
*
**
***
****
STEP 2

Find row content

Determine how many symbols or numbers belong in that row.

STEP 3

Verify the change

Compare consecutive rows and confirm the intended growth or reduction.

Common Loop Mistakes

Infinite Loop
while count < 5:

Update count so the condition can eventually become false.

Off by One
range(1, 5)

The stop value is excluded, so this produces 1 through 4.

Wrong Scope
total = 0

Initialize accumulators before the loop, not again during every iteration.

Indentation
print(total)

Its indentation decides whether it runs every iteration or once after the loop.

Debug loops:1. Write the starting state2. Test the condition or range3. Trace one iteration4. Confirm the update5. Verify termination
QUICK REVISION

๐Ÿ“Œ Loops & Patterns โ€” Quick Revision

Review these rules before attempting the quiz and programming problems.

01

One repetition of a loop body is an iteration.

02

range() excludes its stop value.

03

for is natural for sequences and known counts.

04

while repeats while its condition is true.

05

A while loop must move toward termination.

06

break exits the nearest loop.

07

continue skips to the next iteration.

08

pass is a placeholder and performs no action.

09

Nested-loop work multiplies across loop counts.

10

Patterns become easier when designed row by row.

Level 5 Quick Quiz

Select one answer for every question, then check your score.

6 Questions
1What values does range(2, 6) generate?
2Which loop is usually best when the repetition count is unknown?
3What does break do?
4How many times does for i in range(5): run?
5What must a safe while loop eventually do?
6An outer loop runs 3 times and its inner loop runs 4 times. How often does the inner body run?

PRACTICE

๐ŸŽฏ 5 Programming Problems โ€” Loops & Patterns

Follow the CodeBhavya pattern: understand the task, inspect the sample, use the editor, run, check, then compare with the official program.

๐Ÿ“ˆ Loops Practice Progress
Solved0 / 5
Completed with Solution0
Total Score0 / 500
Completion0%

A problem counts as Solved when its output passes before the official solution is opened.

1. Sum of First N Numbers

Read N and calculate the sum from 1 through N.

Sample input: 10Expected output: Sum = 55
2. Multiplication Table

Read a number and display its multiplication table from 1 through 10.

Sample input: 7Expected output: Ten lines from 7 x 1 = 7 to 7 x 10 = 70
3. Count Digits

Read a positive integer and count its digits using a while loop.

Sample input: 50821Expected output: Digits = 5
4. Factorial

Read a non-negative integer and calculate its factorial.

Sample input: 5Expected output: Factorial = 120
5. Growing Star Pattern

Read the number of rows and display a left-aligned growing star triangle.

Sample input: 4Expected output: Four rows from * through ****
KEY TAKEAWAY

๐ŸŽฏ Every Loop Needs Progress

1Initialize

Prepare counters and accumulators.

โ†’
2Control

Define the range or condition.

โ†’
3Repeat

Perform one clear iteration.

โ†’
4Terminate

Reach a reliable stopping point.

A strong loop is easy to trace: its starting state is known, every iteration makes progress, and its stopping point is guaranteed.

INTERACTIVE LEARNING

๐ŸŽฌ A for Loop โ€” Visual Flow

Watch for number in range(1, 4) select values, execute the body and stop after the sequence is exhausted.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” Accumulator Loop

Trace three iterations and observe how the loop variable, total and output change.

INTERVIEW PREPARATION

๐ŸŽค Loops & Patterns โ€” Interview Questions

Answer aloud before opening each explanation.

1.

What is the difference between for and while?

2.

Why is the stop value excluded from range()?

3.

What causes an infinite loop?

4.

How do break and continue differ?

5.

What is an accumulator?

6.

What is the time complexity of two loops that run n times each when one is nested inside the other?

EXTRA TIPS

๐Ÿ’ก Loops & Patterns โ€” Extra Tips

  • 01

    Trace the first two iterations manually before trusting a complex loop.

  • 02

    Give counters and accumulators descriptive names instead of using every letter.

  • 03

    Check the first value, last included value and excluded stop value of every range.

  • 04

    Update a while loop's controlling state visibly inside its body.

  • 05

    Avoid unnecessary nesting when one clear condition or formula can solve the task.

  • 06

    For patterns, write the expected rows on paper and identify what changes.

EXTRA PRACTICE

โœ๏ธ Loops & Patterns โ€” Extra Practice Questions

  1. Display all even numbers from 2 through 100 using range().
  2. Calculate the sum of digits of a positive integer using a while loop.
  3. Reverse a positive integer without converting it to text.
  4. Check whether a number is prime using loop termination when a divisor is found.
  5. Display the first N terms of the Fibonacci sequence.
  6. Count how many values from 1 through 50 are divisible by both 3 and 5.
  7. Build a descending star triangle with five rows.
  8. Build the number pattern 1, 12, 123, 1234.
  9. Use nested loops to display a 3 ร— 3 coordinate grid.
  10. Trace a deliberately infinite loop and explain the exact missing update.

Loops & Patterns Complete

When you can select the right loop, prove its termination and solve all five programs without help, mark this level complete and continue.