Loops in Python
Sometimes, a specific task has to be repeated several times. In such cases, we could use loops. In Python, there are two types of loops, namely the for
loop and while
loop. Let's review them with specific examples.
A for loop
In Python, a for
loop is used to execute a task for n times. A for loop iterates through each element of a sequence. This sequence could be a dictionary, list, or any other iterator. For example, let's discuss an example where we execute a loop:
for i in range(0, 10): print("Loop execution no: ", i)
In the preceding example, the print
statement is executed 10 times:
In order to execute the print
task 10 times, the range()
function (https://docs.python.org/2/library/functions.html#range) was used. The range
function generates a list of numbers for a start and stop values that are passed as an arguments to the function. In this case, 0
and 10
are passed as arguments to the range()
function. This returns a list containing numbers from 0
to 9
. The...