← Back to Blog

A new kind of loop

The problem...

You know for. It loops through a sequence. It knows exactly how many times it will run before it starts.

But sometimes you don't know how many times you'll need to repeat something. You just know the condition that needs to stay true.

A for loop can't help you here.

The idea!

while repeats a block of code as long as a condition is true. It doesn't count items. It doesn't know when it will stop. It just keeps going — until the condition says otherwise.

The syntax

while condition:
    # runs as long as condition is True

Same rules as always — colon at the end, 4 spaces indent. But no sequence. No counter. Just a condition.

Your first while loop

count = 0

while count < 5:
    print(count)
    count += 1
# 0
# 1
# 2
# 3
# 4

The loop checks the condition before every iteration. As long as count < 5 is true — it runs. When count reaches 5 — condition is false — loop stops.

The update is your responsibility

# Wrong — infinite loop
count = 0

while count < 5:
    print(count)
    # count never changes — condition never becomes False

With for, Python moves through the sequence automatically. With while — you control what changes. Forget to update — loop runs forever.

for vs while

# for — you know how many times
for i in range(5):
    print(i)

# while — you know the condition, not the count
count = 0
while count < 5:
    print(count)
    count += 1

Same result here. But while becomes essential when you can't predict the number of iterations.

A real example

password = "RedHorn"
attempt = ""

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

print("Access granted.")

You don't know how many attempts the user will need. The loop doesn't either. It just keeps asking — until the condition is false.

Heads up!

  • The while line ends with : — same rule as always
  • The condition is checked before every iteration
  • You must update something inside the loop — or it runs forever
  • If the condition is false from the start — the loop never runs

The mindset shift

Stop thinking: "How many times do I repeat this?"

Start thinking: "How long does this condition stay true?"

What you should understand now

  • while repeats as long as a condition is true
  • The condition is checked before every iteration
  • You control what changes inside the loop — Python doesn't do it for you
  • If nothing changes — the loop runs forever
[ login to bookmark ] // copied! 21 views · 2 min
// resources
Code Example while_loops.py
← prev Let Python roll the dice next → More conditions, smarter loop
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.