While Loops

Condition-based iteration

Interview Relevant: Loop control

While Loops

Loop while a condition is true.

Code Examples

While loop patterns.

python
1# Basic while
2count = 0
3while count < 5:
4    print(count)
5    count += 1
6
7# Infinite loop with break
8while True:
9    user_input = input("Enter 'quit' to exit: ")
10    if user_input == 'quit':
11        break
12
13# while with else (rarely used)
14n = 5
15while n > 0:
16    print(n)
17    n -= 1
18else:
19    print("Loop completed normally")
20
21# Reading until EOF
22import sys
23while line := sys.stdin.readline():
24    print(line)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In