In this tutorial, we will learn about Loops in Python and we will also cover different examples related to Python Loops. And, we will cover these topics.
- Python Loops
- Why do we use loops in python?
- Advantages of loops
- Python for loop
- Nested for loop in python
- Using else statement with for loop
- Python While loop
- Loop Control Statements
- Infinite while loop
- Using else with while loop
Python Loops
The course of Programming is in a sequential manner and when the programmers or the developer’s code there is a need to repeat the upper written code again and again and to solve this we started using the Loops.
The Various types of Loops are provided by the programming languages which is suited to repeating the specific line of code as many times as we want.
How we use the loops can be better understood using the following diagram:
Why do we use loops in python?
Loops are a very important part of Python or in any other language, with the help of loops, we can use the same line of code several times which saves time and also decrease the line of code.
For Example, If we want to print the series of numbers and we use the normal line of code which takes a lot of lines to print the series but if we use the loops we can run the same line of code several times as many as we want to print.
Advantages of loops
Working with loops is having good advantages through which some are given below:
- With the help of loops we can run the same line of code several times.
- It saves the time.
- It makes the code look clean.
The loops are of three types:
- For Loop
- While Loop
- Do-While Loop
Loop statement | Description |
For Loop | For Loop is used for iterating the sequence it executes the set of statements and it is used in list, tuple, and set. |
While Loop | It is used when we don’t know the number of iteration in advance. In this, the code is only executed when the condition is satisfied in the while loop. |
Do-While Loop | The do-while loop is also known as the post-tested loop. It works until the conditions get satisfied. |
Python for loop
The For Loop is used for iterating the sequence it executes the set of statements and it is used in list, tuple, and set.
For Loop Syntax:
for iterating_var in sequence:
statement(s)
For Loop Using the Python and Examples
Example 1: Iterating string using for loop
string = "PythonTpoint"
for i in string:
print(i)
Output:
Example 2: Program to print the table of the given number.
add_list = [1,2,3,4,5,6,7,8,9,10]
n = 15
for i in add_list:
c = n*i
print(c)
Example 3: Program to print the total of the given list.
Code:
py_list = [10,15,23,43,52]
total = 0
for i in py_list:
total = total+i
print("The Total is:",total)
Output:
For loop Using range() function
In Python For loop, we use the Range() function to produce the sequence of the numbers which means if we use the range(10) then it will produce the range from 0 to 9.
Syntax:
range(start,stop,step size)
- Start Represent the beginning of the iteration
- The stop will represent the loop that will iterate till the stop.
- Step size is used to skip the specific number from the iteration.
Python Range() function and its Example
Example 1: Program to print numbers in sequence.
for i in range(10):
print(i,end = ' ')
Output:
Example 2: Program to print table of the given number.
Code:
t = int(input("Enter the number "))
for i in range(1,11):
c = t*i
print(t,"*",i,"=",c)
Output:
Example 3: Program to print even number using step size in range().
Code:
t = int(input("Enter the number "))
for i in range(2,t,2):
print(i)
Output:
Nested for loop in python
In python it allows us to nest any number of loops inside for loop at here the inner loop is executed n number of times after every iteration of the outer loop.
Syntax:
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements
Here are some examples of nested loops which we are going to explain:
Example 1: Nested for loop
Code:
# User input for number of rows
r = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,r+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Example 2: Program to number pyramid.
Code:
r = int(input("Enter the rows"))
for i in range(0,r+1):
for j in range(i):
print(i,end = '')
print()
Output:
Using else statement with for loop
In python it allows us to use the else statement with using the for loop as we do in other languages like c, c++, java, etc. it is only used when all the iterations are finished. We also need to take care of this if inside the code we use the break statement then we won’t be able to execute the else statement.
Revise: Python If-else statements
Example of else without using the break statement.
Code:
for i in range(0,5):
print(i)
else:
print("for loop is exhausted, because of no break statement.")
Example of else using the break statement.
for p in range(0,5):
print(p)
print("The loop is broken due to break statement & came out of the loop")
break;
else:print("for loop is Finished");
Output:
Python While loop
It is used when we don’t know the number of iteration in advance. In this, the code is only executed when the condition is satisfied in the while loop. It is also known as the pre-tested loop.
Syntax:
while expression:
statements
We can better understand with the help of the following flowchart:
Loop Control Statements
In python, we can change the normal sequence of the while loop using the loop control statements. In python, it offers the following loop control statements:
- Continue Statement
- Break Statement
- Pass Statement
Continue Statement
In the Continue Statement when it is encountered, the control is transferred to the beginning of the loop. Let’s better understand with the following example:
Code:
i = 0
str1 = 'pythontpoint'
while i < len(str1):
if str1[i] == 'a' or str1[i] == 't':
i += 1
continue
print('Current Letter :',str1[i])
i += 1
Output:
Break Statement
When the break is encountered the code is taken out from the loop.
Code:
i = 0
string = 'pythontpoint'
while i < len(string):
if string[i] == 't':
i += 1
break
print('Current Letter :', string[i])
i += 1
Output:
Pass Statement
In python, the pass statement is used to declare the empty loop. It is also used to define the empty class, function and control statement. We can better understand with the following example:
Code:
string = 'pythontpoint'
i = 0
while i < len(string):
i += 1
pass
print('Value of i :', i)
Output:
Infinite while loop
In python while loop, if the condition is not false then the infinite loop will occur and it will never stop. now we will discuss more about the infinite loop using some example:
Code:
while (1):
print("Hi! we are inside the infinite while loop")
Output:
Using else with the while loop
In python it allow us to use the else statement with the while loop. It is only executed when the the condition in the while statement is false like for loop in while loop if we use the break statement then it will not execute the else block and exit us from the code. we can better understand with the following example:
p =1
while(p<=5):
print(p)
p=p+1
if(p==3):
break
else:
print("The while loop exhausted")
So, in this tutorial, we discussed Python Loops and we have also covered different examples related to its implementation. Here is the list of examples that we have covered.
- Why do we use loops in python?
- Advantages of loops
- Python for loop
- Nested for loop in python
- Using else statement with for loop
- Python While loop
- Loop Control Statements
- Infinite while loop
- Using else with the while loop
1 thought on “Python Loops”
Comments are closed.