MASTER YOUR LOGIC BUILDING:Phase 2 - Level 1: Basic Looping

Mastering phase 2 - level 1: basic looping concepts and implementation.

Phase 2 - Level 1: Basic Looping

Why This Matters

Imagine printing "Happy Birthday" on 100 cards. You wouldn't write the same line 100 times — you'd say "repeat this 100 times." That's exactly what a loop does. Loops let your program repeat work without repeating code.

If if statements help programs decide, loops help them repeat. Together, they're the backbone of almost every program.

What You'll Learn

  • The difference between for and while loops
  • How range() generates a sequence of numbers
  • How to accumulate a total (like a running sum)
  • When to use which type of loop

Two Types of Loops

for loop — "Do this N times"

Use when you know how many repetitions you need:

for i in range(1, 11):
    print(i)

This prints 1 through 10. The loop variable i takes each value from the range, one at a time.

while loop — "Keep going while this is true"

Use when you don't know the exact count upfront:

count = 0
while count < 5:
    print(count)
    count += 1

The loop runs as long as the condition is true. Don't forget to update the variable, or you'll loop forever!

Understanding range()

CodeWhat it produces
`range(5)`0, 1, 2, 3, 4
`range(1, 6)`1, 2, 3, 4, 5
`range(0, 10, 2)`0, 2, 4, 6, 8
Remember: range(1, 11) stops before 11. So you get 1 through 10.

Step-by-Step: Sum of 1 to N

Problem: Add 1 + 2 + 3 + … + n.

  1. Create a variable total = 0 (your running sum)
  2. Loop from 1 to n
  3. Add each number to total
  4. Print the result
n = int(input("Enter n: "))
total = 0

for i in range(1, n + 1):
    total += i   # same as: total = total + i

print(f"Sum: {total}")

Think of it like a piggy bank: start with 0, drop in 1, then 2, then 3… and check the total at the end.

Common Mistakes

  • Off-by-one errors — range(1, 10) gives 1–9, not 1–10. Use range(1, 11) for 1–10
  • Forgetting to update the loop variable in `while` — causes an infinite loop
  • Not initializing the accumulator — always set total = 0 before the loop
  • Using `while` when `for` is simpler — if you know the count, use for

Tips

  • Say "for each number from 1 to n" out loud — that maps directly to for i in range(1, n + 1)
  • Trace small examples by hand: what is total after each iteration?
  • Start with printing numbers, then move to summing them

Practice Focus

Work through the examples below:

  • Print numbers 1 to 10 using range()
  • Calculate the sum of the first n natural numbers using an accumulator
  • Try changing the range and predict the output before running your code

Hands-on Examples

Print Numbers 1 to 10

# Print numbers 1 to 10
for i in range(1, 11):
    print(i)

range(1, 11) generates numbers from 1 to 10. The loop variable i takes each value and prints it.