Python for loop
Created By: chatGPT
In Python, a for loop is a versatile tool for iterating over a sequence (like a list, tuple, or string). You can use it to execute a block of code repeatedly for each item in the given sequence. Here’s a basic example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(f'Fruit: {fruit}')
In this example, the variable
fruit
takes on each value from the fruits
list, and the print statement outputs the current fruit to the console. You can also use the range()
function to iterate over a sequence of numbers. Here’s how:for i in range(5):
print(f'Number: {i}')
This loop will print numbers from 0 to 4. The
range(5)
function generates a sequence of numbers starting at 0 and stopping before 5. You can also specify a different starting point and the step value:for i in range(1, 10, 2):
print(f'Odd Number: {i}')
In this last example, the loop starts at 1, goes up to 10 (not inclusive), and increments by 2 each time, resulting in the printing of all odd numbers in that range.
for i in range(1, 10, 2):
print(i)
# Output will be:
# 1
# 3
# 5
# 7
# 9
Moreover, you can use nested loops, where a loop is placed inside another loop. This is useful for working with multi-dimensional data, like a matrix. Here’s an example of a nested loop:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for num in row:
print(num, end=' ')
print()
In this case, the outer loop iterates over each
row
in the matrix
, and the inner loop iterates over each num
in the current row, printing the numbers in a single line. Each row is separated by a new line.# Expected Output:
# 1 2 3
# 4 5 6
# 7 8 9