Initialization: Start with i
, e.g., initialized to 5, and decrement in each iteration.
Execution: Continues until i
equals 1, thus executing a total of 5 iterations.
General Structure: The syntax follows for variable in container
, where the variable takes on each value in the specified container such as a list or tuple.
Examples:
Iterating Through a List: A for loop can greet each person: for name in [Bill, Nicole, John]
, resulting in "Hi Bill", "Hi Nicole", and "Hi John" consecutively.
Iterating Through Dictionaries: When looping through a dictionary, the variable represents the keys, enabling actions based on key-value pairs. For example: for c in channels
results in statements like "MTV is on channel 35" and "Fox is on channel 11" based on respective keys.
Iterating Through Strings: A for loop can be used to modify strings, such as appending underscores to characters in a string like "TAKE", to potentially produce an output of "T_A_K_E_".
Summation with For Loops: Begin with total = 0
; then, using a loop like for day in revenue_list
, sum values to compute the average by dividing total by the length of the revenue list after the loop completes.
Reversing Lists: Use the reversed()
function, e.g., for name in reversed(names_list)
, to output names in reverse order.
Using Range Function: range()
generates sequences based on specified parameters; for example, range(5)
gives 0 to 4, while range(5, 0, -1)
counts downwards from 5 to 1. This function is commonly used in loops to define the number of iterations.
A nested loop consists of one loop within another, often termed the outer and inner loops. For instance, to create combinations of letters, the outer loop can iterate over A-Z for letter1
, while the inner loop iterates A-Z for letter2
, resulting in combinations like AA, AB, AC, etc.
Break Statement: This statement terminates the loop immediately when encountered, useful in scenarios where a specific condition or result is necessary to exit early from the loop.
Continue Statement: It skips the current iteration and proceeds to the next one without executing any further code in the current loop cycle.
Loop Else Statement: This part of the syntax executes a block of code after a loop finishes normally (not via a break), providing a mechanism to run statements always after the loop completes.
The enumerate()
function allows both indexing and value retrieval from a container during iteration. For instance, using for index, value in enumerate([4, 8, 10])
would yield pairs such as (0, 4), (1, 8), and (2, 10), thereby enabling simultaneous access to both the index and corresponding value of the elements.