Mastering the Python while Loop
Mastering the Python while Loop ๐
The while loop keeps running as long as a specified condition is True. It’s ideal for dynamic scenarios and can be paired with break and continue for more control.
✅ Basic while loop
Print numbers from 1 to 5:
count = 1
while count <= 5:
print("Current number:", count)
count += 1
✅ Skipping values using continue
Print only odd numbers by skipping even ones:
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
print("Odd number:", number)
✅ Looping until correct user input
Ask for a password until the correct one is entered:
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")
With while loops, you gain flexible control over how many times code runs. Just remember to define a proper exit condition to avoid infinite loops!
Loops don't go on forever — unless you forget the exit. Stay in control with CodeVerse ๐
Icons by Flaticon
Comments
Post a Comment