Python Programming - The For Statement

You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.

Python Programming – The For Statement

Python provides for statements as another form for accomplishing control using loops. The for loop statement is used to repeat a statement or a block of statements a specified number of times.
A Python for loop has this general form,
for <var> in <sequence>:
<body>
The body of the loop can be a sequence of Python statements. The start and end of the body can be indicated by its indentation under the loop heading. The variable after the keyword is called the loop index. It takes on each successive value in the sequence, and the statements in the body are executed once for each value.

Usually, the sequence portion is a list of values. You can build a simple list by placing a sequence of expressions in square brackets. Some interactive examples help to illustrate the point:

>>> for i in [ 0 , 1 , 2 , 3 ]:
print ( i )
0
1
2
3
>>> for odd in [ 1 , 3 , 5 , 7 , 9 ] :
print ( odd * odd )
1
9
25
49
81

The for loop specification ends with a colon, and after the colon (:) comes a block of statement which works on the current element. Each statement In the block must be indicated.

>>> little_list = [‘the’ , ‘quick’, ‘brown’ ,’fox’ ]
>>> for the _item in tittle _list:
print (the_item, “*” , end = ” ” )

the * quick * brown * fox *

This example takes each item in little_list one at a time and prints it.

Operation of the for Loop

First, the initialization expression is executed, and then the test condition is examined. If the test expression is false, to begin with, the statements in the body of the loop will not be executed at all. If the condition is true, the statements in the body of the loop are executed and, following that, the increment expression is executed. That is why the first number printed by the program is 0, not 1. Printing takes place before the number is incremented by the increment (++) operator. Finally, the loop recycles, and the test expression is queried again. This continues until the test expression becomes false, and the loop will end.

Leave a Reply

Your email address will not be published. Required fields are marked *