In any programming language, the for
loop is used to traverse the given object in a sequential manner.
In Python, the for
loop is not like that of other programming languages. It behaves like an iterator method and the difference has been illustrated in one of the examples below. The body of the loop is differentiated from the remaining code by indentation.
for iterator_var in sequence:
loop_statements
To iterate over a sequence some specific times, we use the range()
function, which gives a sequence with a default starting value of 0
. It increments by 1 unless the step size is modified, and ends at the number specified in the arguments.
Suppose the arguments are range(2,14,2)
. The values would be 2,4,6,8,10,12
. Below is an example:
for i in range(2,14,2):print(i)
for
loop with the starting index value, 2
,
and ending value, 14
, of 2
increments every iteration.x
value.Strings can also be used as iterable objects in Python in a for
loop. Below is an example:
for n in range(7):print("value on n is {}" .format(n), end='\n')
for
loop with 0-7
range with 1
increment every iteration.n
value with the string.We can also iterate over elements of a list. Below is an example:
breakfast = ["cereal", "bread", "yogurt"]for x in breakfast:print(x)
breakfast
.for
loop on the list.x
value.Iteration over the sequence in Python involves two types:
Thus, n = 7
will not stop our loop in the code below.
for n in range(7):print("value on n is {}" .format(n), end='\n')n = 7
for
loop with 0-7
range with 1
increment every iteration.n
value with string.n = 7
.Similarly, for
loops can be used to iterate over a tuple, a dictionary, or even a set.
Free Resources