Mastering while Loops

While loops execute code repeatedly while a condition remains true. They're ideal for situations where the number of iterations is unknown upfront.

while Loop Structure

# Basic countdown
n = 3
while n > 0:
print(n)
n -= 1
3\n2\n1
Key components:
  • Initial condition: n = 3
  • Loop condition: n > 0
  • Modifier: n -= 1

Controlling Execution

# Break example
while True:
ans = input("Exit? (y/n): ")
if ans.lower() == "y":
break

Use break to exit loops early and continueto skip to next iteration.

Common Pitfalls

# Infinite loop
count = 5
while count > 0:
print(count)
# Forgot to decrement!

Practical Use: Login Attempts

attempts = 3
while attempts > 0:
password = input("Enter password: ")
if password == "secret":
print("Access granted!")
break
attempts -= 1
else:
print("Account locked!")

Your Task: Countdown Generator

Create a countdown from 5 to 1:

  1. Initialize count = 5
  2. Use while loop with condition count > 0
  3. Add count to output string with newline
  4. Decrement count in each iteration

Expected output:
5
4
3
2
1

Section 1/5while Loop Structure

while Loop Structure

Explore this concept

Mastering while Loops

While loops execute code repeatedly while a condition remains true. They're ideal for situations where the number of iterations is unknown upfront.

while Loop Structure

# Basic countdown
n = 3
while n > 0:
print(n)
n -= 1
3\n2\n1
Key components:
  • Initial condition: n = 3
  • Loop condition: n > 0
  • Modifier: n -= 1

Output:

Click "Check" to run your code.