Repeat while something is true
A while loop keeps going as long as its condition is True. Use it when you don't know in advance how many times to repeat.
count = 1
while count <= 5:
print("Count is", count)
count += 1
print("Done!")Output
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5 Done!
Each time round, Python checks count <= 5. When count becomes 6 the condition is False and the loop stops.
Think of it like this: “While the kettle isn't boiling, keep waiting.” You don't know how many seconds it will take – you just keep checking.
A real example: saving money
savings = 0
weeks = 0
while savings < 1000:
savings += 150
weeks += 1
print(f"It takes {weeks} weeks to save {savings} rupees")Output
It takes 7 weeks to save 1050 rupees
Asking until the answer is right
password = ""
while password != "python":
password = input("Password: ")
print("Welcome!")Output (when you type hello, Python, then python)
Password: hello Password: Python Password: python Welcome!
Common mistake: An infinite loop never ends because the condition never becomes False – usually because you forgot to change the variable (like
count += 1). If your program seems stuck, check this first.
Tip: Use
forwhen you know how many times to repeat. Usewhilewhen you repeat “until something happens”.