Generate reliable sequences using range().
๐ Loops & Patterns
Repeat instructions efficiently, control each iteration and turn simple loop logic into useful number and symbol patterns.
total = 0
for day in range(1, 6):
total += day
print(f"Day {day}: total = {total}")
print("Streak complete!")Streak complete!
By the End of This Level
You will be able to choose, trace and control Python loops confidently.
Use for and while for suitable repetition tasks.
Apply break, continue and nesting correctly.
Construct number and symbol patterns systematically.
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.
One complete execution of the statements inside a loop body.
The range() Function
range() generates an arithmetic sequence of integers. Its stop value is always excluded.
| Form | Meaning | Generated values |
|---|---|---|
range(5) | Start at 0, stop before 5 | 0, 1, 2, 3, 4 |
range(2, 6) | Start at 2, stop before 6 | 2, 3, 4, 5 |
range(2, 11, 2) | Increase by 2 | 2, 4, 6, 8, 10 |
range(5, 0, -1) | Decrease by 1 | 5, 4, 3, 2, 1 |
The step cannot be zero. A negative step requires the start value to be greater than the stop value.
The for Loop
Use for when iterating over a known sequence or a predictable number of values.
Sum from 1 to 5
total = 0
for number in range(1, 6):
total += number
print("Sum =", total)Sum = 15
Initialize an accumulator such as total before the loop, update it during every iteration, then use the completed value after the loop.
The while Loop
Use while when repetition depends on a changing condition and the number of iterations is not naturally known in advance.
Count the Digits
number = 50821
count = 0
while number > 0:
count += 1
number //= 10
print("Digits =", count)Digits = 5
for attempt in range(3):
print(attempt)Use it for a known sequence or count.
while balance > 0:
balance -= paymentUse it while a changing condition remains true.
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.
Skip and Stop
for number in range(1, 10):
if number == 3:
continue
if number == 7:
break
print(number)1 2 4 5 6
Nested Loops
For every iteration of the outer loop, the inner loop completes all of its iterations.
Coordinate Pairs
for row in range(1, 3):
for column in range(1, 4):
print(row, column)1 1 1 2 1 3 2 1 2 2 2 3
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.
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.
Growing Star Triangle
stars = ""
for row in range(1, 5):
stars += "*"
print(stars)* ** *** ****
Count rows
Use the outer loop to choose the current row.
Find row content
Determine how many symbols or numbers belong in that row.
Verify the change
Compare consecutive rows and confirm the intended growth or reduction.
Common Loop Mistakes
while count < 5:Update count so the condition can eventually become false.
range(1, 5)The stop value is excluded, so this produces 1 through 4.
total = 0Initialize accumulators before the loop, not again during every iteration.
print(total)Its indentation decides whether it runs every iteration or once after the loop.
๐ Loops & Patterns โ Quick Revision
Review these rules before attempting the quiz and programming problems.
One repetition of a loop body is an iteration.
range() excludes its stop value.
for is natural for sequences and known counts.
while repeats while its condition is true.
A while loop must move toward termination.
break exits the nearest loop.
continue skips to the next iteration.
pass is a placeholder and performs no action.
Nested-loop work multiplies across loop counts.
Patterns become easier when designed row by row.
Level 5 Quick Quiz
Select one answer for every question, then check your score.
๐ฏ 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.
A problem counts as Solved when its output passes before the official solution is opened.
Read N and calculate the sum from 1 through N.
10Expected output: Sum = 55total at zero and add every value in range(1, n + 1).Python Code Editor
Program Output
Run your program to see the output.
Test Case
n = int(input())
total = 0
for number in range(1, n + 1):
total += number
print("Sum =", total)Read a number and display its multiplication table from 1 through 10.
7Expected output: Ten lines from 7 x 1 = 7 to 7 x 10 = 70Python Code Editor
Program Output
Run your program to see the output.
Test Case
number = int(input())
for multiplier in range(1, 11):
print(number, "x", multiplier, "=", number * multiplier)Read a positive integer and count its digits using a while loop.
50821Expected output: Digits = 5Python Code Editor
Program Output
Run your program to see the output.
Test Case
number = int(input())
count = 0
while number > 0:
count += 1
number //= 10
print("Digits =", count)Read a non-negative integer and calculate its factorial.
5Expected output: Factorial = 120n.Python Code Editor
Program Output
Run your program to see the output.
Test Case
n = int(input())
factorial = 1
for current in range(1, n + 1):
factorial *= current
print("Factorial =", factorial)Read the number of rows and display a left-aligned growing star triangle.
4Expected output: Four rows from * through ****stars string, add one star each iteration and print the updated row.Python Code Editor
Program Output
Run your program to see the output.
Test Case
rows = int(input())
stars = ""
for row in range(1, rows + 1):
stars += "*"
print(stars)๐ฏ Every Loop Needs Progress
Prepare counters and accumulators.
Define the range or condition.
Perform one clear iteration.
Reach a reliable stopping point.
๐ฌ A for Loop โ Visual Flow
Watch for number in range(1, 4) select values, execute the body and stop after the sequence is exhausted.
๐ How Python Runs a for Loop
1. Create the Sequence
range(1, 4) prepares the values 1, 2 and 3.
๐ Program Tracing โ Accumulator Loop
Trace three iterations and observe how the loop variable, total and output change.
Click Next to begin tracing.
โ
๐ค Loops & Patterns โ Interview Questions
Answer aloud before opening each explanation.
What is the difference between for and while?
A for loop iterates through a sequence. A while loop repeats while a condition remains true and requires deliberate state updates.
Why is the stop value excluded from range()?
The half-open design makes counts and boundaries predictable: range(n) produces exactly n values starting at zero.
What causes an infinite loop?
An infinite loop occurs when its stopping condition never becomes false or no terminating control statement is reached.
How do break and continue differ?
break exits the nearest loop completely. continue skips the remaining statements in the current iteration and moves to the next one.
What is an accumulator?
An accumulator stores a running result, such as a sum or product, and is updated during each relevant iteration.
What is the time complexity of two loops that run n times each when one is nested inside the other?
The inner body runs n ร n times, giving quadratic time complexity: O(nยฒ).
๐ก 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
whileloop'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.
โ๏ธ Loops & Patterns โ Extra Practice Questions
- Display all even numbers from 2 through 100 using
range(). - Calculate the sum of digits of a positive integer using a
whileloop. - Reverse a positive integer without converting it to text.
- Check whether a number is prime using loop termination when a divisor is found.
- Display the first
Nterms of the Fibonacci sequence. - Count how many values from 1 through 50 are divisible by both 3 and 5.
- Build a descending star triangle with five rows.
- Build the number pattern
1,12,123,1234. - Use nested loops to display a 3 ร 3 coordinate grid.
- 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.
