Contents:
- Introduction
- General Format of for Loop
- for Loop Working
- Example
Introduction
The for statement in Python differs a bit from what you may be used to in C or Pascal. Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. The for loop is a generic iterator in Python: it can step through the items in any ordered sequence or other iterable object.
General Format of for Loop
for target in object: # Assign object items to target
. . . . statements # Repeated loop body: use target
else: # Optional else
. . . . statements # Run if didn’t exit loop body with break
The Python for loop begins with a header line that specifies an assignment target (or targets), along with the object you want to step through. The header is followed by a block of (normally indented) statements that you want to repeat.
for Loop Working
When Python runs a for loop, it assigns the items in the iterable object(An iterable object is an object contains a countable number of values capable of returning one value at a time.) to the target one by one and executes the loop body for each. The loop body typically uses the assignment target to refer to the current item in the sequence. The for statement also supports an optional else block, which works exactly as it does in a while loop—it’s executed if the loop exits without running into a break statement (i.e., if all items in the sequence have been visited).
Example:
X = ‘hack’
for item in X:
print(item, end=’ ‘)
Output:
h a c k
Explanation: Here, a string object ‘hack’ is referred by a variable X. The string object is an iterable object. First, for loop assigns the character h to item variable and then the body of the loop executes, printing h on computer screen. The same process of item assignment and loop body execution continues till all the items of iterable object get assigned to target variable. Finally, we get the output on computer screen: h a c k
🙂 Happy Learning !