Introduction π
A while loop repeatedly executes a block of code as long as its condition remains True. It is ideal for situations where you don't know in advance how many times the loop should run.
Note
1. Basic While Loop Structure π§±
basic_while.py
i = 1
while i <= 5:
print(i)
i += 1βοΈ The loop starts at i = 1
βοΈ Runs until i <= 5 becomes False
βοΈ Each iteration increases i by 1
2. Infinite Loop β οΈ
A while loop becomes infinite if its condition never becomes False.
infinite_loop.py
while True:
print("This will run forever!")Note
3. Using While Loop With User Input β¨οΈ
while_input.py
password = ""
while password != "admin":
password = input("Enter password: ")
print("Access granted!")4. While Loop With Break π
break stops the loop immediately, even if the condition is still True.
while_break.py
i = 1
while i <= 10:
if i == 5:
break
print(i)
i += 1Note
5. While Loop With Continue π
continue skips the current iteration and moves to the next one.
while_continue.py
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)Note
6. While Loop With Else Block π―
The else block runs when the loop condition becomes False normally (no break).
while_else.py
i = 1
while i <= 3:
print(i)
i += 1
else:
print("Loop completed")7. Nested While Loops πͺ
nested_while.py
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 18. Using While Loop for Menus π
menu_example.py
choice = 0
while choice != 3:
print("1. Say Hello")
print("2. Say Bye")
print("3. Exit")
choice = int(input("Enter option: "))
if choice == 1:
print("Hello!")
elif choice == 2:
print("Bye!")
elif choice == 3:
print("Exiting...")
else:
print("Invalid choice")9. Common Mistakes β οΈ
- Forgetting to update the loop variable (infinite loop).
- Using incorrect conditions.
- Misplacing break or continue.
10. Real-World Example π
real_world_example.py
attempts = 0
while attempts < 3:
pin = input("Enter PIN: ")
if pin == "1234":
print("Login successful!")
break
else:
print("Wrong PIN")
attempts += 1
else:
print("Account locked!")Conclusion π
You now understand Pythonβs while loop thoroughly! Want the next topic? Try For Loop, Range(), Loop Control Statements, or Nested Loops. Just tell me! π