Day - 12
Python-While Loop
A.I. Powered 30 Days Python Micro Course By Satish Dhawale ( Microsoft Certified Trainer )
What is a While Loop?
• A while loop repeats a task as long as a condition is true.
• Example:
“I will keep drinking water while I’m thirsty.”
If the condition becomes false, the loop stops.
• Technical Definition
• A while loop is a control structure that executes a block of code repeatedly
as long as the given condition remains True.
Syntax:
while condition:
# repeated code
Why While Loop is Important?
We do not know how many times the loop should run
Condition-based repetition
Reading data until file ends
Cleaning data until condition is met
Taking user input continuously
Basic Example
i=1
while i <= 5:
print(i)
i += 1
Infinite Loop
x=1
while x < 5:
print("Hello") # x never changes → infinite loop!
Example
Example – Countdown
n=5
while n > 0:
print(n)
n -= 1
Loop Until User Stops :
name = ""
while name == "":
name = input("Enter your name: ")
print("Welcome,", name)
Example – Ask until valid number
num = ""
while not [Link]():
num = input("Enter a number: ")
print("Valid number:", num)
Loop Through List Using While
items = ["Laptop", "Mouse", "Keyboard"]
i=0
while i < len(items):
print(items[i])
i += 1
While Loop with Break
num = 1
while num <= 10:
if num == 5:
break
print(num)
num += 1
While Loop with Continue
x=0
while x < 10:
x += 1
if x % 2 == 0:
continue
print(x)
Password Retry System
password = ""
attempts = 0
while password != "admin123" and attempts < 3:
password = input("Enter password: ")
attempts += 1
if password == "admin123":
print("Login Successful")
else:
print("Account Locked")
Assignments
Basic
Print numbers from 10 to 1
Ask user their favorite color until they enter something
Intermediate
Count vowels in a string using while
Loop through list using while
Advanced
Build a login system with 3 attempts
Ask user to enter prices until they type “STOP”, then calculate total