CodingNic

Loops and Iteration

While Loops

Loops and Iteration 20 min read

While Loops

While Loops

Sometimes we want code to keep running until something changes.

For example:

  • Keep asking for a password until it is correct
  • Keep counting until you reach a number
  • Keep showing a menu until the user exits

A while loop helps us do this.

What Is a While Loop?

A while loop repeats code while a condition is true.

This means Python checks a question first.

If the answer is true, the code runs.

If the answer is false, the loop stops.

python
count = 1

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

How This Example Works

Let’s go step by step:

  • count starts at 1
  • Python checks: is count <= 3?
  • Yes, so it prints 1
  • Then count += 1 changes count to 2
  • Python checks again
  • The loop continues until count becomes 4

Then the condition is false, so the loop stops.

Output

text
1
2
3

Why We Change the Value

Inside many while loops, something must change.

If nothing changes, the condition may stay true forever.

That creates an infinite loop.

python
number = 1

while number <= 3:
    print(number)
    number += 1

Another Example

python
password = ""

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

print("Access granted")

The program keeps asking until the correct password is entered.

Using While to Repeat Messages

python
times = 1

while times <= 4:
    print("Welcome")
    times += 1

Code Along

python
age = 1

while age <= 3:
    print("Age:", age)
    age += 1

Mini Challenge

Build a counter.

Steps:

  • Create a variable called number and set it to 1
  • Use a while loop
  • Print numbers from 1 to 5
  • Increase the number each time

Real World Use Case

Programs use while loops in games, login systems, timers, and menus that keep running until the user stops them.

Quiz

  1. What does a while loop do?
  2. When does a while loop stop?
  3. Why do we change the variable inside the loop?
  4. What is an infinite loop?

Assignment

Create a program that prints Hello five times using a while loop.

Summary

You learned that a while loop repeats code while a condition is true and stops when the condition becomes false.