Loop Structures in Python
I. Classification of Loops
whileloopfor-intraversal loop
II. The while Loop
1. Syntax of while
while condition:
# loop body
2. Difference Between if and while
ifevaluates the condition once; if true, executes the block once.whileevaluates the condition n+1 times; if true, executes the block n times.
Example:
print('Using if')
a = 1
if a < 10:
print(a)
a += 1
print('Using while')
a = 1
while a < 10:
print(a, end=" ")
a += 1
Output:

3. Execution Flow (Example: Sum of Numbers 0 to 4)
- Initialize variables:
sum = 0,a = 0 - Condition check:
while a < 5: - Execute loop body:
sum += a - Update variable:
a += 1 - Print result:
print('Sum:', sum)
Tip: The variable used for initialization, condition check, and update must be the same.
4. Example: Sum of Even Numbers from 1 to 100
total = 0
num = 1
while num <= 100:
if num % 2 == 0:
total += num
num += 1
print('Sum of even numbers from 1 to 100:', total)
Important: The increment statement num += 1 must be at the same indentation level as the if statement, not inside it. If placed inside the if, odd values of num would never increment, causing an infinite loop.
Alternatively, the evenness check can be written as:
if not bool(num % 2):
Becuase 0 evaluatse to False, and not False is True.
III. The for-in Loop
1. Syntax of for-in
for variable in iterable:
# loop body
Tip: in sequentially takes values fromm an iterable (e.g., strings, sequences). Iterable objects in Python include strings, lists, tuples, dictionaries, sets, etc.
2. Example
for i in range(10):
print(i, end=" ")
Output:

range() generates a sequence of integers, which is also an iterable.
3. Using Underscore for Unused Variable
If the loop variable is not needed, use an underscore _:
for _ in range(5):
print('Life is short, I use Python')
Output:

4. Common Exercise Examples
(1) Sum of Even Numbers from 1 to 100 using for
total = 0
for num in range(1, 101):
if num % 2 == 0:
total += num
print('Sum of even numbers from 1 to 100:', total)
(2) Find Armstrong Numbers (Narcissistic Numbers) between 100 and 999
An Armstrong number is one where the sum of the cubes of its digits equals the number itself.
for num in range(100, 1000):
units = num % 10
tens = (num // 10) % 10
hundreds = num // 100
if units**3 + tens**3 + hundreds**3 == num:
print(num)