For loop is a looping statement that is used when it is known beforehand how many times the loop has to run. Therefore it is already defined the number of times for loop will iterate. The for loop has an ability to iterate over any kind of sequential data types like list or string.
The for loop like the while loop is also an entry controlled loop, the condition is tested before iteration and if the condition is true then for loop executes.
The syntax of the for loop is simple.
for iterating_variable in sequence: loop_body
The given syntax begins with the Python keyword for followed by a variable which will iterate over the list of values is called iterating_variable here. We have in keyword which is an operator to check for membership in the given sequence of values.
The statement has a colon (:) and then followed by the loop body which is indented. The loop body can be a single line statement or it can be a block of code. Indentation of the body will tell python that the block of code is under the loop and it has to be iterated according to the condition.
Python uses indentation as its method or the way of grouping statements. In Python, all the statements which are indented by the same number of spaces after a construct are considered to be a single block of code.
b = [1,2,3,4] for i in b: print(i)
for i in range(0,10): print(i)
b = [“apple”, “mango”, “orange”] for j in b: print(j)
In the first example for loop iterates over a list of values stored in variable b and displays each value using print() built-in function in Python.
In our second example, for loop iterates over a range of values using the python’s built-in function called range(). From the example, it is quite evident that the range() function has two parameters here. The first parameter is the starting value which is inclusive of the range of values to be iterated. The second parameter is the end value until which the loop will iterate. This value is not inclusive in range() hence in range( 0, 10 ) for loop prints value till integer number 9. The function range() also has a third parameter which defines the steps for loop, by default value is 1 but can be changed accordingly. Syntax for range function is
range( n, m, k)
n = initial or starting value
m = the end or the last value
k = steps to skip between each value
So range() will give values like [n, n + k, n + 2k, n + 3k, n + 4k … m-1]
Using else Statement with for loop
Python gives an extra functionality to have an else statement associated with a loop statement. If the else statement is used along with a for loop then the else statement is executed when the loop has exhausted iterating the list.