while
KeywordPython 2.0+Beginner
Starts a loop that repeats as long as its condition is true
Quick Info
- Documentation
- Official Docs
- Python Version
- 2.0+
Learn by Difficulty
Quick Example
python
count = 0 while count < 5: print(count) count += 1 # Sum until threshold total = 0 n = 1 while total < 100: total += n n += 1 print(f"Sum reached {total} after adding {n-1} numbers")
while repeats its body as long as the condition is True. Make sure the condition eventually becomes False or you get an infinite loop.
Try in PlaygroundTags
languagesyntaxcorecontrol-flowloop
Related Items
for
Keyword
Starts a loop that iterates over a sequence or iterable
break
Keyword
Exits the nearest enclosing for or while loop immediately
continue
Keyword
Skips the rest of the current loop iteration and moves to the next
pass
Keyword
A no-op placeholder; does nothing, used where syntax requires a statement
else
Keyword
Catch-all branch when preceding if/elif conditions are all false