A while loop repeatedly executes a block of indented statements as long as its condition evaluates to true. Once the condition becomes false, execution proceeds beyond the loop.
counter = 1
# Execute body while counter does not exceed 100
while counter <= 100:
print('ok')
counter += 1
# Both print and increment share indentation, controlled by the loop
The loop condition must yield a Boolean value (True or False). When true, the indented suite runs; when false, control passes to the next statement after the loop. All statements in side the loop maintain uniform indentation to signify they belong to the same logical block.
# General form
while condition:
# repeated statements
Loops may contain any valid statements, including nested conditionals. Tracking the loop variable helps observe progress and produce specific output sequences.
Example: Print odd numbers below 100
Approach one uses arithmetic progression: the i-th odd number equals 2*i - 1. Generating the first 50 terms yields all odd under 100.
idx = 1
while idx <= 50:
print(2 * idx - 1)
idx += 1
Approach two checks each integer from 1 to 100 for an odd remainder when divided by 2.
num = 1
while num <= 100:
if num % 2 == 1:
print(num)
num += 1
# Increment is mandatory to avoid infinite looping
Exercise 1: Reverse digits of a positive integer
Reverse the digit order, discarding any leading zeros in the result. For instance, reversing 380 produces 83.
value = int(input())
rev = 0
while value > 0:
rev = rev * 10 + value % 10
value //= 10
print(rev)
Exercise 2: List proper factors of a positive integer
Output all divisors of a given number except the number itself.
x = int(input())
divisor = 1
while divisor < x:
if x % divisor == 0:
print(divisor)
divisor += 1