While Loops

15 min In Progress

Learning Objectives

  • Repeat code while a condition is true
  • Avoid infinite loops
  • Build interactive programs

Basic while Loop

A while loop repeats as long as its condition remains True.

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

Course Example: Password Check

Keep asking for a password until the correct one is entered.

user_pass = "random"
valid = False
while not valid:
 password = input("please enter your password: ")
 if password == user_pass:
   print("Welcome back user!")
   valid = True
 else:
   print("invalid password, try again... ")

📝 Exercise: Countdown Timer

Write a while loop that counts down from 10 to 1, then prints 'Blastoff!'.

code.py
Output

            
← Back to Chapter