Understanding Python while Loops: Syntax, Variants, and Control Statements
This article explains Python's while loop syntax, including basic usage, the rarely used while‑else construct, infinite loops, and how break and continue statements affect loop execution, supplemented with clear code examples and a concise summary of loop behavior.
Python provides two loop constructs, for and while ; the while loop repeats a block of statements as long as a given condition evaluates to True .
Basic while syntax :
<code>while <condition>:
# statement block</code>The loop continues while the condition is true; once it becomes false, execution proceeds after the loop.
Example – sum of numbers 1 to 100 :
<code>sum = i = 0
while i <= 100: # loop condition
sum = sum + i
i += 1 # equivalent to i = i + 1
print(sum) # outputs 5050</code>while … else … (rarely used) executes the else block after the loop finishes normally:
<code>while <condition>:
# while block
else:
# else block</code>Example – sum of odd numbers up to 100:
<code>sum = i = 0
while (2 * i + 1) <= 100: # loop condition
sum = sum + 2 * i + 1
i += 1
else:
print('Loop ended')
print(sum)</code>Infinite loops occur when the condition is always true. Example shows reading integers until a negative number is entered:
<code>key = 1
while key >= 0:
key = input('Please enter a positive integer:')
key = int(key)
if key >= 100:
print(key, 'not less than 100')
else:
print(key, 'less than 100')</code>Be careful: an always‑true condition creates a dead loop unless an explicit break is used.
break terminates the loop immediately, while continue skips the rest of the current iteration and proceeds to the next one.
Break example (stops when i == 3 ):
<code>i = 0
while i <= 5: # loop condition
if i == 3:
break # exit loop
print(i)
i += 1</code>Output: 0, 1, 2
Continue example (skips printing when i == 3 ):
<code>i = 0
while i <= 5: # loop condition
i += 1
if i == 3:
continue # skip this iteration
print(i)</code>Output: 1, 2, 4, 5, 6
Summary : The while loop is a condition‑controlled loop that runs while its expression is true; it ends when the expression becomes false. break ends the loop entirely, whereas continue skips the current iteration and proceeds to the next.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.