Python |
||
For Loop
The "for" loop is a powerful and flexible control structure that allows you to iterate over the elements of a sequence (like a list, tuple, string, or other iterable objects) and perform some operation on each element. The "for" loop is often used when you want to process each item in a collection or repeat a block of code a specific number of times.
The syntax for a "for" loop in Python is as follows:
for variable in iterable: # Code block to execute for each element
Here, the variable represents a temporary name assigned to each element in the iterable as the loop iterates through it. The iterable is a sequence or any other object that can return its elements one at a time. The code block indented under the "for" statement is executed once for each element in the iterable.
During each iteration, the loop assigns the current element from the iterable to the variable. The code block under the "for" statement is then executed with that value. After the code block is executed, the loop proceeds to the next element in the iterable until all elements have been processed.
In addition to looping over sequences, Python's "for" loops can also be used with the built-in range() function. The range() function generates a sequence of numbers, which can be used to repeat a block of code a specific number of times or to iterate over a range of numbers.
Python "for" loops also support the break and continue statements, which provide additional control over the loop execution. The break statement allows you to exit the loop prematurely when a certain condition is met, while the continue statement allows you to skip the rest of the current iteration and proceed to the next one.
Examples
NOTE : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.
< Syntax >
for x in sequence : do_things_on_x
< Example >
|
||