Junior — Middle
Could you explain the use and operation of the for loop in programming?
sobes.tech AI
Answer from AI
The for loop in programming is used to repeat a block of code a certain number of times or to iterate over elements of a collection.
In Python, for is often used to iterate over lists, strings, ranges, and other iterable objects.
Example of iterating over a list:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(f'I love {fruit}')
Example with a range of numbers:
for i in range(5):
print(i)
Here, the loop will run 5 times, printing numbers from 0 to 4.