Python Loop Structures: Basics, Syntax, Control Flow, and Helper Tools
while Loop Fundamentals
Syntax Guidelines
While loops execute a code block repeatedly as long as a specified boolean condition evaluates to True. Key requirements include:
- A boolean expression that resolves to True/False
- Consistent 4-space indentation for the loop body
- A well-defined exit condition to avoid infinite execution
# Calculate product of integers from 1 to 10
factorial_result = 1
current_num = 2
while current_num <= 10:
factorial_result *= current_num
current_num += 1
print(f"10! is: {factorial_result}")
Print Formatting Extras
Unbroken Output
Add end='' to the print() function to prevent automatic line breaks.
Tab Alignment
Insert \t in strings to align content horizontally, equivalent to pressing the Tab key.
for Loop Fundamentals
Syntax Overview
For loops iterate over iterable objects (like strings, lists, or range sequences) and process each element individually. Important notes:
- No explicit boolean loop condition; iteration stops when the iterable is exhausted
- Indentation rules apply identical to while loops
# Iterate over a greeting string and count vowels
greeting = "bonjour"
vowel_count = 0
for char in greeting:
if char.lower() in {'a', 'e', 'i', 'o', 'u'}:
vowel_count += 1
print(f"Vowels in '{greeting}': {vowel_count}")
range() Sequence Generator
Functionality and Syntax
range() creates a memory-efficient iterable numeric sequence, commonly used with for loops. It supports three syntax variants:
range(end): Generates integers starting at 0, up to but not includingendrange(start, end): Generates integers starting atstart, up to but not includingendrange(start, end, step): Generates integers with a custom intervalstepbetween values
# Iterate over even numbers from 20 down to 2
for even_val in range(20, 0, -2):
print(even_val, end=' ')
For Loop Temporary Variable Scope
Temporary variables used in for loops are technically accessible outside the loop, but this violates Python coding conventions. To safely reference the varible after iteration, initialize it explicitly before the loop starts.
# Explicitly initialize index variable before loop
final_index = -1
for final_index in range(7):
pass
print(f"Last loop index value: {final_index}")
Loop Control Statements
contineu and break
Both control statements modify loop execution flow and work identically in while and for loops, affecting only the innermost loop they appear in:
continue: Skips the remaining code in the current iteration and proceeds to the nextbreak: Terminates the entire current loop immediately
# Skip numbers divisible by 3 and stop at 17
for num in range(10, 25):
if num == 17:
break
if num % 3 == 0:
continue
print(num, end=' | ')