Looping in Python (For, While, Nested Loops)

Role of Loops in Python along with its Types: For, While, Nested Loops

We learned about the four different Conditional statements in Python in our previous tutorial.

This tutorial will explain about Looping statements in Python along with its various types and syntax for each type.

The Full Training Series on Python will give you a brief idea of what Python is all about.

Looping_Statements In Python1

Watch the VIDEO Tutorial

Looping Statements In Python:

Looping Statements in Python

Looping statements in python are used to execute a block of statements or code repeatedly for several times as specified by the user.

Python provides us with 2 types of loops as stated below:

  • While loop
  • For loop

#1) While loop:

While loop in python is used to execute multiple statement or codes repeatedly until the given condition is true.

We use while loop when we don’t know the number of times to iterate.

Syntax:

while (expression): block of statements Increment or decrement operator

In while loop, we check the expression, if the expression becomes true, only then the block of statements present inside the while loop will be executed. For every iteration, it will check the condition and execute the block of statements until the condition becomes false.

Example:


number = 5
sum = 0
i = 0

while (i<number):
        sum = sum + i
        i = i+1

print(sum)

Output:

10

while_loop

Output:

while_loop_output

#2) For loop:

For loop in python is used to execute a block of statements or code several times until the given condition becomes false.

We use for loop when we know the number of times to iterate.

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

for_loop

Output:

for_loop_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:


language = [‘Python’, ‘Java’, ‘Ruby’]

for lang in range(len(language)):
      print(“Current language is: “, language[lang])

Output:

Current language is: Python

Current language is: Java

Current language is: Ruby

for_loop_using_range

Output:

for_loop_using_range_output

We are sure that this tutorial would have enriched your knowledge of the various types of Loops in Python.

Check out our upcoming tutorial to know more about Control Statements in Python.

PREV Tutorial | NEXT Tutorial