06-while-loops.py
python-for-j277 / control-flow  ·  Lesson 06
Lesson 06 — Control flow

Iteration: While Loops

Repeat code while a condition stays true.

A loop repeats code. A while loop keeps going as long as a condition is true — perfect when you do not know in advance how many times to repeat.

A basic while loop

count.py
count = 1
while count <= 5:
    print(count)
    count = count + 1
print("Done")
Output
1
2
3
4
5
Done
How it works
  • The condition count <= 5 is checked before each repeat.
  • While it is True, the indented lines run.
  • count = count + 1 increases the counter by 1 each time — without this the loop would never stop.
  • Once count reaches 6 the condition is False, so the loop ends and 'Done' prints.

Looping until the user is ready

ready.py
answer = ""
while answer != "yes":
    answer = input("Are you ready? ")
print("Let's go!")
Output
Are you ready? no
Are you ready? maybe
Are you ready? yes
Let's go!
How it works
  • We start answer as an empty string so the condition is True the first time.
  • The loop keeps asking until the user types exactly "yes".
  • Then answer != "yes" becomes False and the loop stops.

Validating input

validate.py
number = int(input("Enter a number 1-10: "))
while number < 1 or number > 10:
    print("That is out of range.")
    number = int(input("Try again: "))
print("Thank you, you chose", number)
Output
Enter a number 1-10: 15
That is out of range.
Try again: 7
Thank you, you chose 7
How it works
  • The loop only runs while the number is outside 1 to 10.
  • A valid number makes the condition False straight away, so the loop is skipped.
  • This is a common pattern for checking that user input is sensible.
Beware the infinite loopAn infinite loop happens when the condition never becomes False. Always make sure something inside the loop can change the condition — usually a counter or new input.
When to use itUse a while loop when you do not know in advance how many repeats you need.

What you have learned

  • A while loop repeats while its condition is True.
  • The condition is checked before each pass.
  • Something inside the loop must eventually make the condition False.
  • Great for input validation and 'keep going until...' situations.