Python Series track

Week 05 · Basic Track

Week 5 — Loops

Automate repetitive tasks with for and while loops. Master range(), break, continue, and the rarely-known loop else clause.

Basic Track3 min readFree lesson

Level: Basic | Prerequisite: Week 4 (Conditional Statements)

Learning Goals

  • Repeat a set number of times with for and range()
  • Repeat while the condition with while is true
  • Control the flow with break and continue
  • Understand nested loops

1. for Loop

Create a sequence of integers with range(start, end, step) and iterate.

for i in range(5):           # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 11):       # 1 ~ 10
    print(i, end=" ")

for i in range(0, 10, 2):    # 0, 2, 4, 6, 8
    print(i)

You can also directly iterate over sequences like lists or strings (next week).

2. while Loop

Keep executing while the condition is True. The termination condition must change.

n = 1
while n <= 5:
    print(n)
    n += 1   #Without this, it's an infinite loop!

Decide termination based on user input:

while True:
    cmd = input("Command (exit with quit):")
    if cmd == "quit":
        break
    print(f"Execute: {cmd}")

3. break and continue

  • break — exit the loop immediately
  • continue — skip this iteration and continue to the next
for i in range(1, 11):
    if i == 5:
        continue   #Skip 5
    if i == 8:
        break      #End at 8
    print(i, end=" ")   # 1 2 3 4 6 7

4. Nested Loops

A loop inside a loop. Often used for multiplication tables and table printing.

for i in range(2, 10):           #2-step~9-step
    for j in range(1, 10):       # ×1 ~ ×9
        print(f"{i} × {j} = {i*j}")
    print()                      #Space between steps

Key Examples (examples/)

File Content
01_for_range.py for + range pattern
02_while.py while loop
03_break_continue.py break, continue
04_nested.py nested loops (multiplication table)

⚠️ Common Mistakes

  1. Infinite Loop
    n = 1
    while n <= 5:
        print(n)
        #n += 1 skipped → prints 1 infinitely
    

→ Force stop with Ctrl+C. Check if the termination condition changes.

  1. Mistake thinking range(1, 10) is 1~10 range(1, 10) is 19 (10 not included). If you want 110, use range(1, 11).

  2. Missing Indentation

    for i in range(5):
    print(i)   # IndentationError
    
  3. Misunderstanding that break exits all loops break only exits the closest loop. For multiple breaks, use a flag variable.

  4. Changing the loop variable inside the loop

    for i in range(5):
        i = 100   #In the next iteration, it goes back to 0, 1, 2...
    

❓ FAQ

Q1. When should we use for or while? A. Use for when the number of iterations is fixed, use while when it depends on a condition to end. Receiving user input is usually while.

Q2. I heard there is a for ... else statement? A. If for completes normally (without break), else will execute. Not often used at the beginner stage.

Q3. Why start from 0? A. It's a convention that computers count indexes from 0. When showing to people, you can start from 1 using enumerate(seq, start=1).

📝 Exercises (exercises/)

  • exercise1.md — Multiplication table (2~9 times)
  • exercise2.md — Star printing (equilateral triangle + inverted triangle)
  • exercise3.md — Number guessing game

Next Week

Week 6. Lists and Tuples — Handling multiple values at once

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_for_range.pyPython
#From 0 to 4
for i in range(5):
    print(i, end=" ")
print()

#From 1 to 10
for i in range(1, 11):
    print(i, end=" ")
print()

#From 0 to 10, increasing by 2
for i in range(0, 11, 2):
    print(i, end=" ")
print()

#Calculate sum
total = 0
for i in range(1, 101):
    total += i
print(f"Sum from 1 to 100: {total}")
examples/02_while.pyPython
#Print 1~5
n = 1
while n <= 5:
    print(n, end=" ")
    n += 1
print()

#Exit with user input
while True:
    cmd = input("Command (exit with quit):")
    if cmd == "quit":
        print("Exiting")
        break
    print(f"Execute: {cmd}")
examples/03_break_continue.pyPython
#Skip 5 out of 1~10, end at 8
for i in range(1, 11):
    if i == 5:
        continue
    if i == 8:
        break
    print(i, end=" ")
print()
#Output: 1 2 3 4 6 7

#Find only the first even number
for n in [3, 7, 11, 4, 9]:
    if n % 2 == 0:
        print(f"First even number: {n}")
        break
examples/04_nested.pyPython
#Multiplication table 2~9
for i in range(2, 10):
    print(f"--- {i} times table ---")
    for j in range(1, 10):
        print(f"{i} × {j} = {i*j}")
    print()

Assignment

Goal

Print multiplication tables from 2 to 9.

Input/Output Example

[2-step]
2 × 1 = 2
2 × 2 = 4
...
2 × 9 = 18

[3-step]
3 × 1 = 3
...

Challenge

  • Receive a number from the user and print only that table

Assignment 2. Star Printing

Goal

Receive height input and print an equilateral triangle and inverted triangle with stars.

Input/Output Example (height = 5)

*
**
***
****
*****

*****
****
***
**
*

Challenge

  • Diamond shape (equilateral triangle + inverted triangle combined, center aligned)

Assignment 3. Number Guessing Game

Goal

The computer sets a random number between 1 and 100, and the user guesses it.

Requirements

  • Give hints each attempt: 'Higher number / Lower number'
  • Count the number of attempts
  • On correct guess, print 'Correct! Number of attempts: N'

Input/Output Example

Enter a number: 50
It's smaller.
Enter a number: 25
It's bigger.
Enter a number: 37
Correct! Number of attempts: 3

Challenge

  • Limit of 7 attempts
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
for i in range(2, 10):
    print(f"[{i} level]")
    for j in range(1, 10):
        print(f"{i} × {j} = {i*j}")
    print()
solution2.pyPython
height = int(input("Height:"))

print("[Equilateral Triangle]")
for i in range(1, height + 1):
    print("*" * i)

print()
print("[Inverted Triangle]")
for i in range(height, 0, -1):
    print("*" * i)
solution3.pyPython
import random

answer = random.randint(1, 100)
tries = 0

while True:
    guess = int(input("Enter number:"))
    tries += 1
    if guess < answer:
        print("It's bigger.")
    elif guess > answer:
        print("It's smaller.")
    else:
        print(f"Correct! Number of attempts: {tries}")
        break

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now