Looping Statements in Python

In this tutorial, we would learn about Looping Statements in Python. Looping statements help us to run a block of code for several times. For example, you want to show “Hello World” a hundred times. It means you have to write print(“Hello World”) statement a hundred times. This will be soo boring and time-consuming. But with the help of Loops, we can do this in a few moments and we have to write print(“Hello World”) only once rest of 99 loop will automatically run this line.

In Python, there are three types of loops. We can use a looping statement according to our program requirement. We will learn about each looping statement in detail. Available three looping statements in Python are as follow:

  • for loop
  • while loop
  • nested loop

For Loop:

For loop is used to iterate sequences such as lists, tuple, string and other iterable objects. By default, the loop will only stop from iterating if give sequence will be exhausted.

Syntax of for loop:

for val in sequence:
      Body statements

The val in syntax is just a variable (You can write here any other variable name) which will be replaced with the value which for loop will take from the sequence after every iteration.

Example program:

languages = ['Java','Python','Kotlin'] #List
for fav in languages:       
   print 'Favourite:', fav

Output:

Favourite : Java
Favourite : Python
Favourite : Kotlin

For Loop with if-else:

We can also use if-else and other Conditional statements in loop. Here I will show to check all the even numbers from between 1 to 25.

Numbers = list(range(0,25))
for num in Numbers:
    if(num%2==0):
        print(num)

As you can see in the above example I have used range function to make a list of number from 0 to 25.

While Loop:

While loop iterates the body of loop if the given condition will be true. we can give condition to while loop in form of expression or any non zero value. While loop will stop iterating if the condition becomes false.

Syntax of while loop:

while (condition):
   body of while loop

Example program:

Here we will write code to show number from 1 to 10 using while loop.

num = 1
while(num<=10):
    print(num)
    num+=1

Nested Loop:

When we use a loop inside another loop it is known as Nested Loop. Check out Syntax examples:

for val in sequence:
   for val in sequence:
      body statements
    body statements

Another example with while loop:

while condition:
   while condition:
      statement
    statement

 

Spread the love
Scroll to Top
×