This is another interesting article on Python Programming Language .
Here, you will learn about python for loop with example and the range function in for loop.
What is Python for loop?
In python, for loop is used by the programmers to repeat or iterate over a sequence of elements or others objects which are iterable. Until it reaches the end element in the sequence, the loop continues. Simply, we can say that for loop is used to iterate over a block of code to a fixed number of time. For loop is used to transverse over tuple, list, structure, etc.
Syntax;
for iterating_var in sequence:
statement(s)
Python for loop flowchart
Now let's illustrate Python for loop with the help of following examples.
Simple Python for loop example;
number = [1, 2, 3]for x in number:
print(x)
Output
12
3
Example of Python for loop using a string;
for x in "python":
print(x)
Output
py
t
h
o
n
Example of Python for loop using break statement;
In the below illustrations we will discuss two cases of python for loop using break statement in which loop can be exited in two ways;
Illustration no.1
number = [1, 2, 3]for x in number:
print(x)
if x == 2:
break
Output
1
2
In the above example, you may have noticed that the loop has exited when x is 2.
Illustration no. 2
number = [1, 2, 3]for x in number:
if x == 2:
break
print(x)
Output
1
In the above example, you may have noticed that the loop has exited when x is 2 but this time the break comes before the print.
Example of Python for loop using continue Statement;
number = [1, 2, 3]for x in number:
if x == 2:
continue
print(x)
Output
1
3
For Loop using Range function
The range() function is used by the programmers to generate sequence of numbers. For example if we used range(7), then the number between 0 to 6 will be generated.
Syntax
range(start,stop,step size)
In the syntax, start is used to show the starting of the iteration and the stop shows us the iteration of loop till stop-1. And to skip some numbers in the iteration, step skip is size.
Example of Python for loop using range function;
for x in range(7, 44, 12):
print(x)
Output
719
31
43
For loop with else
In for loop we also have the option of else block. If the items of the sequence in loop exhausts, then the body of else will be executed. And when break statement is used to stop a loop then the the else part will be ignored.
Syntax
for iterating_var in sequence:statement(s)
else:
statement(s)
Example of Python for loop with else;
number = [1, 2, 3]for x in number:
print(x)
else:
print("No extra numbers found!!")
Output
12
3
No extra numbers found!!
Conclusion
Above we have discussed about python for loop with example and the range function in for loop. In python, for loop is used by the programmers to repeat or iterate over a sequence of elements or others objects which are iterable. Simply, we can say that for loop is used to iterate over a block of code to a fixed number of time.