In this article, you’ll learn to iterate over a sequence of elements using the different variations of for loop.
loops in python
- Python programming language provides following types of loops to handle looping requirements. Python provides three ways for executing the loops.
- While all the ways provide similar basic functionality, they differ in their syntax and condition checking time
Why we use loops in python?
- The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times.
- For example, if we need to print the first 10 natural numbers then, instead of using the print statement 10 times, we can print inside a loop which runs up to 10 iterations.
Advantages of loops
There are the following advantages of loops in Python.
- It provides code re-usability.
- Using loops, we do not need to write the same code again and again.
- Using loops, we can traverse over the elements of data structures (array or linked lists).
Python programming language provides following types of loops to handle looping requirements.
Sr.No. | Loop Type & Description |
---|---|
1 | while loopRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. |
2 | for loopExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
3 | nested loopsYou can use one or more loop inside any another while, for or do..while loop. |
Python While Loop
- While loop is used to iterate over a block of code repeatedly until a given condition returns false. In the last tutorial, we have seen for loop in Python, which is also used for the same purpose.
- The main difference is that we use while loop when we are not certain of the number of times the loop requires execution, on the other hand when we exactly know how many times we need to run the loop, we use for loop.
Syntax of while loop
while condition:
#body_of_while
The body_of_while is set of Python statements which requires repeated execution. These set of statements execute repeatedly until the given condition returns false.
While loop Flowchart
Flow of while loop
- First the given condition is checked, if the condition returns false, the loop is terminated and the control jumps to the next statement in the program after the loop.
- If the condition returns true, the set of statements inside loop are executed and then the control jumps to the beginning of the loop for next iteration.
- These two steps happen repeatedly as long as the condition specified in while loop remains true.
Python – While loop example
- Here is an example of while loop. In this example, we have a variable num and we are displaying the value of num in a loop, the loop has a increment operation where we are increasing the value of num.
- This is very important step, the while loop must have a increment or decrement operation, else the loop will run indefinitely, we will cover this later in infinite while loop.
- num = 1
- # loop will repeat itself as long as
- # num < 10 remains true
- while num < 10:
- print(num)
- #incrementing the value of num
- num = num + 3
Output:
1
4
7
For loop in Python
- For loop in Python is used to iterate over a sequence of numbers, a string, a list, a tuple or a dictionary. The working of theforloop remains the same in all programming languages.
- However, the syntax is what differs. In this article, we will discuss Python for loop with several examples.
Why do we need a for loop?
- For loop in Python is used to traverse sequentially through lists, tuples, strings, dictionary, and sets. Using the for looping technique, we can execute a set of statements once for each item in the sequence.
- The statements inside the for loop are separated from the rest of the code using indentation (Here is how to indent it the right way!)
Flowchart of for loop in Python
Here is the execution flow of a for loop in Python programming.
Syntax:
for var in sequence: Block of code
Here var will take the value from the sequence and execute it until all the values in the sequence are done.
Example:
- language = [‘Python’, ‘Java’, ‘Ruby’] for lang in language:
- print(“Current language is: “, lang)
Output:
- Current language is: Python
- Current language is: Java
- Current language is: Ruby
Output:
For loop using range () function:
Range () function is used to generate a sequence of numbers.
For Example, range (5) will generate numbers from 0 to 4 (5 numbers).
Example:
Output:
- Current language is: Python
- Current language is: Java
- Current language is: Ruby
Output:
We are sure that this tutorial would have enriched your knowledge of the various types of Loops in Python.
Nested Loops
- In some script you may want to use nested loops.
- A nested loop is a loop inside a loop.Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times for every iteration of the outer loop. The syntax is given below.
Syntax
- for iterating_var1 in sequence: #outer loop
- for iterating_var2 in sequence: #inner loop
- #block of statements
- #Other statements
Example- 1: Nested for loop
- # User input for number of rows
- rows = int(input(“Enter the rows:”))
- # Outer loop will print number of rows
- for i in range(0,rows+1):
- # Inner loop will print number of Astrisk
- for j in range(i):
- print(“*”,end = ”)
- print()
Output:
Enter the rows:5
*
**
***
****
*****