The 'for' loop in Python is a versatile control flow tool that allows programmers to execute a block of code for a specific number of times. The key purpose of this loop, as the quiz question mentions, is to iterate over a sequence of items. This can include lists, tuples, dictionaries, sets, strings, and more.
Here are a few simple applications of the 'for' loop:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This loop prints every item in the list 'numbers'.
for letter in 'Hello':
print(letter)
This loop prints every character in the string 'Hello'.
for i in range(5):
print(i)
This loop prints numbers 0 through 4. The 'range()' function generates a sequence of numbers, which the for loop then iterates over.
When using 'for' loops in Python, it's good to keep some best practices in mind:
In conclusion, the Python 'for' loop is a fundamental tool for iterating over sequences. It is not used to define functions, create conditional statements, or print text to the console on its own, but it often works together with these other elements to create more complex Python programs.