← Back to course

Loops: for and while

Loops: for and while

Welcome back.

In the previous lesson, you learned conditions.

Your programs learned how to make decisions with:

if
else
elif

Very good.

Your program can now choose different paths.

But there is still one big problem.

What if we need to repeat something?

For example:

Print something 10 times.
Ask the user until they type the correct password.
Calculate totals for several products.
Show numbers from 1 to 100.
Process many items one by one.

Without loops, you would write this:

print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")

This works.

But it is ugly.

Very ugly.

Like copying the same message five times because the computer refused to be useful.

Loops solve this.

Loops let your program repeat actions.

Python does the boring repetition.

You keep your sanity.

Mostly.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, your programs will be able to repeat work automatically.

This is a huge step.

Because computers are very good at repetition.

They do not get bored.

They do not complain.

They do not sigh dramatically after the third task.

Unlike humans.

Especially on Monday.

What Is a Loop?

A loop is a way to repeat code.

Instead of writing:

print("Hello")
print("Hello")
print("Hello")

you can write:

for number in range(3):
    print("Hello")

Output:

Hello
Hello
Hello

The code inside the loop runs several times.

This is very useful.

A loop says:

Do this action again and again.

Not forever.

Unless you make a mistake.

Then yes, possibly forever.

We will talk about that.

Very important.

Very slightly terrifying.

Your First for Loop

Create a file:

loops.py

Write:

for number in range(5):
    print("Hello from Python!")

Run it:

python loops.py

or:

python3 loops.py

Output:

Hello from Python!
Hello from Python!
Hello from Python!
Hello from Python!
Hello from Python!

The line:

for number in range(5):

means:

Repeat the indented code 5 times.

The indented line:

    print("Hello from Python!")

belongs to the loop.

So Python runs it 5 times.

Very useful.

Very clean.

Very “finally, the computer is doing computer things”.

Indentation Matters Again

Just like with if, indentation matters in loops.

Correct:

for number in range(3):
    print("Hello")

Wrong:

for number in range(3):
print("Hello")

Python will show:

IndentationError

The code inside the loop must be indented.

Python uses indentation to understand what belongs to the loop.

Your spaces are not decoration.

They are structure.

Tiny architecture.

Again.

Python really loves organized furniture.

The Colon Is Required

A for loop also needs a colon:

for number in range(3):

Wrong:

for number in range(3)
    print("Hello")

Correct:

for number in range(3):
    print("Hello")

The colon tells Python:

A block of repeated code starts here.

Small symbol.

Big responsibility.

The colon is like a tiny door into the loop.

Forget the door, and nobody enters.

Understanding range()

range() creates a sequence of numbers.

Example:

for number in range(5):
    print(number)

Output:

0
1
2
3
4

Important detail:

range(5)

starts at 0 and stops before 5.

So it gives:

0, 1, 2, 3, 4

Not:

1, 2, 3, 4, 5

This surprises many beginners.

Python starts counting from zero.

Computers love zero.

Nobody knows why they are so emotionally attached to it.

Actually, developers know.

But we will not open that cave today.

Counting from 1

If you want to count from 1 to 5, write:

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

Here:

range(1, 6)

means:

Start at 1.
Stop before 6.

So the last number is 5.

Very important.

The second value is not included.

This is common in Python.

At first it feels strange.

Later it becomes normal.

Then you start explaining it to beginners and sound suspiciously calm.

range(start, stop, step)

range() can also use a step.

Example:

for number in range(0, 10, 2):
    print(number)

Output:

0
2
4
6
8

This means:

Start at 0.
Stop before 10.
Move by 2.

Another example:

for number in range(10, 0, -1):
    print(number)

Output:

10
9
8
7
6
5
4
3
2
1

This counts backwards.

Very dramatic.

Like a rocket launch.

But with less fire.

Hopefully.

The Loop Variable

Look at this:

for number in range(5):
    print(number)

The variable number changes each time the loop runs.

First loop:

number = 0

Second loop:

number = 1

Third loop:

number = 2

And so on.

The loop variable stores the current value.

You can name it differently:

for i in range(5):
    print(i)

This works too.

Many developers use i for simple counters.

But clear names are often better:

for product_number in range(5):
    print(product_number)

Use names that make sense.

Your future self is still watching.

And judging.

A little.

Repeat a Message with Numbers

Try:

for number in range(1, 6):
    print(f"Message number {number}")

Output:

Message number 1
Message number 2
Message number 3
Message number 4
Message number 5

Now the loop does not only repeat.

It also uses the current number.

This is very useful.

Loops are not just copy machines.

They can change something each time.

A little.

Like humans learning from mistakes.

But faster.

Simple Sum with a Loop

You can use a loop to calculate a total.

Example:

total = 0

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

print(f"Total: {total}")

Output:

Total: 15

What happens?

Start total at 0.
Add 1.
Add 2.
Add 3.
Add 4.
Add 5.
Print the final total.

This is a very common pattern.

Start with an empty result.

Loop through values.

Update the result.

Print or use the result.

Very useful.

Very programming.

Very “small steps become something bigger”.

Shorter Total Update

This:

total = total + number

can be written as:

total += number

So the program becomes:

total = 0

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

print(f"Total: {total}")

Output:

Total: 15

Both versions are correct.

The shorter version is common.

Use it when you understand what it means.

Do not write short code just to look professional.

Professional code is not code that looks mysterious.

Professional code is code that works and can be understood later.

Very boring.

Very true.

Loop Through Text

You can loop through a string.

Example:

word = "Python"

for letter in word:
    print(letter)

Output:

P
y
t
h
o
n

A string is made of characters.

A loop can go through them one by one.

Here:

letter

stores the current character.

First:

P

Then:

y

Then:

t

And so on.

Python takes the word apart like a polite little machine.

No violence.

Just characters.

Count Letters

Try:

word = input("Enter a word: ")

letter_count = 0

for letter in word:
    letter_count += 1

print(f"The word has {letter_count} letters.")

Example:

Enter a word: Python

Output:

The word has 6 letters.

This counts letters manually.

Later, you will learn easier ways.

But doing it with a loop helps you understand how loops work.

Sometimes we do things the longer way to learn.

Not because Python enjoys watching us suffer.

Probably.

Loop with Conditions

You can use if inside a loop.

Example:

for number in range(1, 11):
    if number % 2 == 0:
        print(f"{number} is even")

Output:

2 is even
4 is even
6 is even
8 is even
10 is even

This line:

number % 2 == 0

checks if the number is even.

The % operator gives the remainder.

If a number divided by 2 has remainder 0, it is even.

Example:

4 % 2 = 0
5 % 2 = 1

Very useful.

Very classic.

Very mathematical but not too scary.

The math dragon is still sleeping.

Even and Odd Numbers

Create a file:

even_odd.py

Write:

for number in range(1, 11):
    if number % 2 == 0:
        print(f"{number} is even")
    else:
        print(f"{number} is odd")

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even

Now the loop repeats.

The condition decides.

Together they make the program more powerful.

Loops and conditions are like a small programming engine.

Not glamorous.

But very strong.

Like an old diesel van that refuses to die.

What Is a while Loop?

A while loop repeats code while a condition is true.

Example:

count = 1

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

Output:

1
2
3
4
5

This means:

While count is less than or equal to 5, repeat the block.

Each time, we increase count by 1.

Eventually, count becomes 6.

Then the condition becomes false.

The loop stops.

Very important.

A while loop must have a way to stop.

Otherwise, it becomes an infinite loop.

And your computer starts looking at you with disappointment.

for vs while

Use for when you know how many times you want to repeat.

Example:

for number in range(5):
    print(number)

Use while when you want to repeat until something changes.

Example:

password = ""

while password != "secret":
    password = input("Password: ")

print("Access granted.")

Simple rule:

for     repeat for a known sequence
while   repeat while a condition is true

This rule is not perfect for every situation.

But it is very good for beginners.

Your First while Loop

Create a file:

while_loop.py

Write:

count = 1

while count <= 5:
    print(f"Count: {count}")
    count += 1

Run it.

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

What happens?

count starts at 1.
Python checks if count <= 5.
If true, it prints.
Then count increases by 1.
Python checks again.
Eventually count becomes 6.
Condition is false.
Loop stops.

This is the basic while pattern.

Start.

Check.

Repeat.

Update.

Stop.

Beautiful.

Like a washing machine with logic.

Infinite Loops

An infinite loop is a loop that never stops.

Example:

count = 1

while count <= 5:
    print(count)

This is dangerous.

Why?

Because count never changes.

It is always 1.

So:

count <= 5

is always true.

The loop runs forever.

Or until you stop the program.

This is called an infinite loop.

Very common beginner mistake.

Very annoying.

Very good way to make your terminal look possessed.

How to Stop an Infinite Loop

If your program gets stuck in an infinite loop, press:

Ctrl + C

This interrupts the program.

The terminal may show something like:

KeyboardInterrupt

That is fine.

It means you stopped the program.

Not elegant.

But effective.

Like pulling the plug on a confused robot.

Avoid infinite loops by making sure the condition can become false.

Very important.

Password Loop

A good use of while is asking until the user gives the correct answer.

Create a file:

password_loop.py

Write:

password = ""

while password != "python123":
    password = input("Enter password: ")

print("Access granted.")

Example:

Enter password: banana
Enter password: hello
Enter password: python123
Access granted.

The loop continues while the password is not correct.

When the user types:

python123

the condition becomes false.

The loop stops.

Then the program prints:

Access granted.

Very useful.

Very simple.

Very bad as real security.

Again, do not protect a bank with lesson 5.

Using break

break stops a loop immediately.

Example:

while True:
    answer = input("Type q to quit: ")

    if answer == "q":
        break

    print(f"You typed: {answer}")

print("Program ended.")

This loop starts with:

while True:

That means:

Repeat forever.

But inside the loop, we use:

break

to stop when the user types "q".

Example:

Type q to quit: hello
You typed: hello
Type q to quit: test
You typed: test
Type q to quit: q
Program ended.

break is useful.

But use it clearly.

A loop with too many secret exits becomes a maze.

And nobody likes debugging a maze.

Except maybe very strange people.

Using continue

continue skips the rest of the current loop and moves to the next iteration.

Example:

for number in range(1, 6):
    if number == 3:
        continue

    print(number)

Output:

1
2
4
5

When number is 3, Python runs:

continue

So it skips:

print(number)

for that iteration.

Then the loop continues with 4.

continue is useful when you want to skip certain cases.

Like saying:

Not this one. Next.

Very practical.

Very slightly rude.

break vs continue

Simple difference:

break      stops the loop completely
continue   skips this round and continues with the next one

Example with break:

for number in range(1, 6):
    if number == 3:
        break

    print(number)

Output:

1
2

The loop stops at 3.

Example with continue:

for number in range(1, 6):
    if number == 3:
        continue

    print(number)

Output:

1
2
4
5

The loop skips 3 but continues.

Small words.

Different behavior.

Do not mix them unless you enjoy surprises.

Common Mistake: Forgetting to Update while Variable

Wrong:

count = 1

while count <= 5:
    print(count)

This never stops.

Correct:

count = 1

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

Always ask:

How will this while loop stop?

If you cannot answer, your loop may become immortal.

Immortal code sounds cool.

It is not.

It is usually a bug wearing a cape.

Common Mistake: Wrong range()

Beginner expectation:

for number in range(5):
    print(number)

Expected by beginner:

1
2
3
4
5

Actual output:

0
1
2
3
4

Remember:

range(5)

starts at 0 and stops before 5.

If you want 1 to 5:

for number in range(1, 6):
    print(number)

This gives:

1
2
3
4
5

Python is not wrong.

It is just Python.

This sentence will become useful many times.

Common Mistake: Bad Indentation

Wrong:

for number in range(3):
print(number)

Correct:

for number in range(3):
    print(number)

The code inside a loop must be indented.

If multiple lines belong to the loop, indent all of them:

for number in range(3):
    print("Current number:")
    print(number)

Both print() lines run inside the loop.

If a line is not indented, it is outside the loop.

Example:

for number in range(3):
    print(number)

print("Done")

Output:

0
1
2
Done

Done prints only once after the loop finishes.

Very important.

Indentation decides ownership.

Like paperwork for code blocks.

Common Mistake: Using while When for Is Simpler

This works:

count = 0

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

But this is simpler:

for count in range(5):
    print(count)

Use for when you know the number of repetitions.

Use while when the loop depends on a condition.

Do not use a screwdriver as a spoon.

It may work.

But people will ask questions.

Mini Program: Multiplication Table

Create a file:

multiplication_table.py

Write:

number = int(input("Enter a number: "))

for i in range(1, 11):
    result = number * i
    print(f"{number} x {i} = {result}")

Example:

Enter a number: 5

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

This is a classic loop program.

Very useful.

Very simple.

Very school, but in a good way.

Mostly.

Mini Program: Sum of Numbers

Create a file:

sum_numbers.py

Write:

limit = int(input("Add numbers from 1 to: "))

total = 0

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

print(f"Total: {total}")

Example:

Add numbers from 1 to: 5

Output:

Total: 15

Because:

1 + 2 + 3 + 4 + 5 = 15

Notice:

range(1, limit + 1)

Why limit + 1?

Because range() stops before the second value.

If the user enters 5, we need:

range(1, 6)

Small detail.

Big importance.

Python loves these little traps.

Educational traps.

Still traps.

Mini Program: Guess the Number

Create a file:

guess_number.py

Write:

secret_number = 7
guess = 0

while guess != secret_number:
    guess = int(input("Guess the number: "))

    if guess < secret_number:
        print("Too low.")
    elif guess > secret_number:
        print("Too high.")
    else:
        print("Correct!")

Example:

Guess the number: 3
Too low.
Guess the number: 10
Too high.
Guess the number: 7
Correct!

This program uses:

Many lessons together.

This is how programming grows.

One idea connects to another.

Like cables.

Hopefully labeled.

Mini Program: Menu Loop

Create a file:

menu.py

Write:

choice = ""

while choice != "q":
    print("----- Menu -----")
    print("1. Say hello")
    print("2. Say goodbye")
    print("q. Quit")

    choice = input("Choose an option: ").lower()

    if choice == "1":
        print("Hello!")
    elif choice == "2":
        print("Goodbye!")
    elif choice == "q":
        print("Exiting...")
    else:
        print("Unknown option.")

This program keeps showing the menu until the user types:

q

Menu loops are very common.

Many terminal programs work like this.

The program asks.

The user chooses.

The program reacts.

Then it asks again.

A tiny command-line application is born.

Very cute.

Very useful.

Do not feed it after midnight.

Practice

Create a file:

practice_loops.py

Write a program that:

Example:

limit = int(input("Enter a number: "))

total = 0

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

    if number % 2 == 0:
        print(f"{number} is even")
    else:
        print(f"{number} is odd")

print(f"Total sum: {total}")

Example output:

Enter a number: 5
1 is odd
2 is even
3 is odd
4 is even
5 is odd
Total sum: 15

This is good practice.

It combines:

Very strong beginner exercise.

Not easy.

But very useful.

Mini Challenge

Create a file:

shopping_total.py

Your program should:

Example solution:

product_count = int(input("How many products? "))

total = 0

for number in range(1, product_count + 1):
    print(f"Product {number}")

    product_name = input("Name: ")
    price = float(input("Price: "))

    total += price

    print(f"Added {product_name}: {price:.2f}")

print("----- Total -----")
print(f"Total price: {total:.2f}")

Example interaction:

How many products? 3
Product 1
Name: Keyboard
Price: 70
Added Keyboard: 70.00
Product 2
Name: Mouse
Price: 25
Added Mouse: 25.00
Product 3
Name: Notebook
Price: 5.5
Added Notebook: 5.50
----- Total -----
Total price: 100.50

This is close to real logic.

A shop.

A list of products.

A total.

No database yet.

No web app yet.

But the idea is real.

Small terminal program.

Big foundation.

Very Python.

Extra Challenge: Password with Attempts

Create a file:

password_attempts.py

Your program should:

Example solution:

secret_password = "python123"
attempts = 0
max_attempts = 3
access_granted = False

while attempts < max_attempts:
    password = input("Password: ")
    attempts += 1

    if password == secret_password:
        access_granted = True
        break
    else:
        print("Wrong password.")

if access_granted:
    print("Access granted.")
else:
    print("Access denied.")

This program uses:

Very good practice.

This is more serious logic.

Still not real security.

But very good learning.

The bank is still not safe.

Please keep the bank away from this lesson.

Beginner Checklist

When your loop does not work, check:

Did I save the file?
Did I use a colon after for or while?
Is the loop body indented?
Does my while loop have a way to stop?
Did I update the counter?
Am I using range() correctly?
Do I need range(1, limit + 1)?
Did I accidentally place code outside the loop?
Did I use break when I wanted to stop?
Did I use continue when I only wanted to skip one round?

Loops are powerful.

But they can create confusing bugs.

Especially while loops.

Always ask:

What changes each time?
When does the loop stop?

If you can answer these two questions, you are much safer.

If not, prepare for chaos.

Educational chaos.

But still chaos.

Summary

Today you learned:

This is a huge step.

Your programs can now repeat work.

They can count.

They can ask again.

They can calculate totals.

They can show menus.

They can process many values.

This is where programming becomes much more powerful.

Because computers love repetition.

And humans love not doing boring repetition manually.

A beautiful partnership.

Mostly.

Next Lesson

In the next lesson, we will learn about lists.

Lists let you store many values in one variable.

Instead of writing:

product1 = "Keyboard"
product2 = "Mouse"
product3 = "Notebook"

you will write:

products = ["Keyboard", "Mouse", "Notebook"]

Then loops and lists will work together.

And that is where Python starts becoming much more useful.

Very strong progress.

Very Python.