In this part 7 of the Python Basics tutorial, we will learn about how to use loops in python.
Till now, we learnt about variables and conditional statements in python. But, what happens if we want the same line of code (or a block of code) to run repeatedly? We can’t just keep repeating the same lines of code.
In such cases, loops come into the picture.
What are loops in python?
In programming, a loop is a kind of function that executes the same statement (or the same block of code) until the loop condition becomes false.
Now, we will learn about the different kinds of loops used.
Types of loops in python
There are different kinds of loops that can be used depending on the condition or scenario.
- For loop
- While loop
We will study about each of these loops below.
In python, the for keyword works a bit different from other languages. Here, for loop executes a sequence of statements multiple times by iterating over a sequence.
Let’s try to print numbers from 0 to 9 using a for loop.
>>> for i in range(0,10): ... print(i) ... 0 1 2 3 4 5 6 7 8 9 >>>
Here, i is the iterator which iterates over range(0,9).
As we already discussed, for loops in python are iterative. Let’s see how can we print all elements of a list.
Note: Lists will be explained in the next part of the tutorial.
Until then, lists can be thought of as a collection that stores a set of any kind of values.
>>> fruit_list = ['apple','banana','orange','mango'] >>> for fruit in list: ... print(fruit) ... apple banana orange mango >>>
Here, “fruit” is the iterator which iterates over the list “fruit_list”.
With a while loop, we can execute a block of code (or a set of statements) as long as the given condition is true.
Let’s try to print numbers from 0 to 9 (AGAIN!!!??) but this time, using a while loop.
>>> i = 0 >>> while i<10: ... print(i) ... i+=1 ... 0 1 2 3 4 5 6 7 8 9 >>>