While Loop in Python
Loops help us repeat code, but when we don’t know exactly how many times to repeat, the while loop is often the right choice.
For Loop vs While Loop
- A for loop is used when you know in advance how many times you want to run the loop (for example, printing numbers from 1 to 10).
- A while loop is used when the number of iterations is not known in advance, and the loop should continue until a certain condition is True.
In short:
- for → works well for counting or iterating through a sequence.
- while → works well for repeating until a condition changes.
Syntax of While Loop
while condition:
# block of code to execute repeatedly
- condition → The loop keeps running as long as this condition is True.
- If the condition becomes False, the loop stops.
- Proper indentation is required for the loop body.
Basic Examples
1. Counting with while
i = 1
while i <= 5:
print("Number:", i)
i += 1
Output: prints numbers from 1 to 5.
2. Waiting for user input
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted!")
Common Mistakes
-
Forgetting to update the variable:
✅ Fix: Incrementi = 1 while i <= 5: print(i) # ❌ Infinite loop, because i is never updatediinside the loop. -
Using capitalized keyword:
Whileinstead ofwhile→ ❌ SyntaxError. -
Wrong condition:
Example:
while 5:→ Infinite loop, because5is always truthy. Always use a condition that can eventually turnFalse. -
Indentation Errors: forgetting to indent after
whilestatement.
More Use Cases
1. Countdown
count = 5
while count > 0:
print(count)
count -= 1
print("Blast off!")
2. Input validation
number = -1
while number < 0:
number = int(input("Enter a positive number: "))
print("You entered:", number)
๐ก Practice Challenges
- Write a program to print numbers from 1 to 100 using a
whileloop. - Create a simple password checker using
whileuntil the correct password is entered. - Make a countdown timer from 10 to 1 that ends with "Happy New Year!".
- Keep asking the user for input until they type "exit".
What’s Next?
After the while loop, we will learn about break and continue statements, which give us more control inside loops.
No comments:
Post a Comment