Python for Loops
A for loop in
Python is used to iterate over a sequence such as a list, tuple, set,
dictionary, or string. It allows you to execute a block of code once for
each element in the sequence.
Unlike traditional
for loops in
languages like C or Java, Python’s
for loop
works more like an iterator, automatically moving through each item without
requiring an index variable.
Basic for Loop Example
Example: Loop Through a List
Python automatically assigns each item in the list to the variable
city during
every iteration.
Note: You do not need to create or manage an index variable manually.
Looping Through a String
Strings are also iterable, meaning you can loop through each character one by one.
Example: Iterating Over Characters
Each character in the string is accessed sequentially.
The break Statement
The
break
statement stops the loop immediately, even if there are items left to
iterate over.
Example: Stop When a Condition Is Met
Here, the loop exits as soon as the value 30 is found.
break Before Output
Placing
break before
a print statement prevents the current value from being displayed.
The continue Statement
The
continue
statement skips the current iteration and moves to the next one.
Example: Skip a Specific Value
The loop ignores "cat" and continues with the remaining items.
The range() Function
The
range()
function is used to repeat a block of code a specific number of times.
Example: Basic range()
range() with Start Value
You can define where the sequence should begin.
range() with Step Value
You can also control the increment value.
else with for Loop
The
else block
executes only when the loop completes normally (without hitting
break).
Example: Loop Completion
else Skipped When break Is Used
Nested for Loops
A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Example: Nested Loop
The pass Statement
A for loop
cannot be empty. If you need a loop structure without logic (for future
implementation), use
pass.
This loop does nothing but prevents a syntax error.
