For Loop
Today, we embark on the exploration of the for loop, a fundamental construct for iteration.
` ˙⋆˖⁺‧₊☽◯☾₊‧⁺˖⋆˙ `
Range Function
The range() function generates a sequence of numbers. It is commonly used in for loops to repeat a block of code a specific number of times.
The syntax for the range() function is:
- • range(stop): generates numbers from 0 to stop (exclusive).
- • range(start, stop): generates numbers from start to stop (exclusive).
- • range(start, stop, step): generates numbers from start to stop (exclusive), incrementing by step.
#Examples of range() function
print(range(5)) # Output: range(0, 5)
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
print(list(range(2, 6))) # Output: [2, 3, 4, 5]
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]
For Loop
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence.
The syntax for a for loop is:
- for variable in sequence:
tab code to execute for each item in the sequence
#Example: For loop
for i in range(5):
print("Iteration:", i)
In this example, the for loop iterates over the sequence generated by range(5) and prints the current iteration number («i» is iterator).
Iterators
An iterator (as «i») is an object that represents a stream of data. It allows you to traverse through all the elements in a collection (such as a list or range) one at a time.
The for loop in Python automatically creates an iterator from the sequence you provide and uses it to loop through each item.
#Example: Iterating through a list
foods = ["Sweet Roll", "Cabbage", "Honey"]
for food in foods:
print("Food:", food)
In this example, the for loop iterates through each item in the foods list and prints the current food.
Practical Application
In the Hall of Repetition, you will master the art of iteration using for loops. This allows you to repeat actions efficiently over sequences.
⋆˖⁺‧₊ Create a list of magical ingredients: "Mandrake Root", "Phoenix Feather", "Dragon Scale". Use a for loop to iterate over the list and print each ingredient. ₊‧⁺˖⋆
Sample Output:
Put: Mandrake Root
Put: Phoenix Feather
Put: Dragon Scale