Python Loop Tutorial – Python For Loop, Nested For Loop

Free Python courses with 57 real-time projects - Learn Python

In this Python Loop Tutorial, we will learn about different types of Python Loop.

Here, we will study Python For Loop, Python While Loop, Python Loop Control Statements, and Nested For Loop in Python with their subtypes, syntax, and examples.

So, let’s start Python Loop Tutorial.

"Python

What is Python Loop?

When you want some statements to execute a hundred times, you don’t repeat them 100 times.

Think of when you want to print numbers 1 to 99. Or that you want to say Hello to 99 friends.

In such a case, you can use loops in python.

Here, we will discuss 4 types of Python Loop:

  • Python For Loop
  • Python While Loop
  • Python Loop Control Statements
  • Nested For Loop in Python

Python While Loop

A while loop in python iterates till its condition becomes False. In other words, it executes the statements under itself while the condition it takes is True.

"Python

When the program control reaches the while loop, the condition is checked. If the condition is true, the block of code under it is executed.

Remember to indent all statements under the loop equally. After that, the condition is checked again.

This continues until the condition becomes false.

Then, the first statement, if any, after the loop is executed.

>>> a=3
>>> while(a>0):
        print(a)
        a-=1

Output

3
2
1

This loop prints numbers from 3 to 1. In Python, a—wouldn’t work. We use a-=1 for the same."Python

1. An Infinite Loop

Be careful while using a while loop. Because if you forget to increment the counter variable in python, or write flawed logic, the condition may never become false.

In such a case, the loop will run infinitely, and the conditions after the loop will starve. To stop execution, press Ctrl+C.

However, an infinite loop may actually be useful. This in cases when a semaphore is needed, or for client/server programming.

A semaphore is a variable used solely for synchronization in accessing shared resources.

2. The else statement for while loop

A while loop may have an else statement after it. When the condition becomes false, the block under the else statement is executed.

However, it doesn’t execute if you break out of the loop or if an exception is raised.

>>> a=3
>>> while(a>0):
        print(a)
        a-=1
else:
    print("Reached 0")

Output

3
2
1
Reached 0

In the following code, we put a break statement in the body of the while loop for a==1.So, when that happens, the statement in the else block is not executed.

>>> a=3
>>> while(a>0):
        print(a)
        a-=1
        if a==1: break;
else:
    print("Reached 0")

Output

3
2

3. Single Statement while

Like an if statement, if we have only one statement in while’s body, we can write it all in one line.

>>> a=3
>>> while a>0: print(a); a-=1;

Output

3
2
1

You can see that there were two statements in while’s body, but we used semicolons to separate them.Without the second statement, it would form an infinite loop

Python For Loop

Python for loop can iterate over a sequence of items. The structure of a for loop in Python is different than that in C++ or Java.

That is, for(int i=0;i<n;i++) won’t work here. In Python, we use the ‘in’ keyword.

Lets see a Python for loop Example

Python Loop Tutorial - Python for Loop

Python Loop Tutorial – Python for Loop

>>> for a in range(3):
        print(a)

Output

0
1
2

If we wanted to print 1 to 3, we could write the following code.

>>> for a in range(3):
        print(a+1)

Output

1
2
3

"Python

1. The range() function

This function yields a sequence of numbers. When called with one argument, say n, it creates a sequence of numbers from 0 to n-1.

>>> list(range(10))

Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We use the list function to convert the range object into a list object.

Calling it with two arguments creates a sequence of numbers from the first to the second.

>>> list(range(2,7))

Output

[2, 3, 4, 5, 6]

You can also pass three arguments. The third argument is the interval.

>>> list(range(2,12,2))

Output

[2, 4, 6, 8, 10]

Remember, the interval can also be negative.

>>> list(range(12,2,-2))

Output

[12, 10, 8, 6, 4]

However, the following codes will return an empty list.

>>> list(range(12,2))

Output

[]

>>> list(range(2,12,-2))

Output

[]

>>> list(range(12,2,2))

Output

[]

2. Iterating on lists or similar constructs

You aren’t bound to use the range() function, though. You can use the loop to iterate on a list or a similar construct.

>>> for a in [1,2,3]:
         print(a)

Output

1
2
3
>>> for i in {2,3,3,4}:
        print(i)

Output

2
3
4

You can also iterate on a string.

>>> for i in 'wisdom':
        print(i)

Output

w
i
s
d
o
m

3. Iterating on indices of a list or a similar construct

The len() function returns the length of the list. When you apply the range() function on that, it returns the indices of the list on a range object.

You can iterate on that.

>>> list=['Romanian','Spanish','Gujarati']
>>> for i in range(len(list)):
        print(list[i])

Output

Romanian
Spanish
Gujarati

4. The else statement for for-loop

Like a while loop, a for-loop may also have an else statement after it.

When the loop is exhausted, the block under the else statement executes.

>>> for i in range(10):
     print(i)
else:
     print("Reached else")

Output

0
1
2
3
4
5
6
7
8
9
Reached else

Like in the while loop, it doesn’t execute if you break out of the loop or if an exception is raised.

>>> for i in range(10):
        print(i)
        if(i==7): break
else: print("Reached else")

Output

0
1
2
3
4
5
6
7

Nested for Loops in Python

You can also nest a loop inside another. You can put a for loop inside a while, or a while inside a for, or a for inside a for, or a while inside a while.

Or you can put a loop inside a loop inside a loop. You can go as far as you want.

>>> for i in range(1,6):
        for j in range(i):
            print("*",end=' ')
        print()

Output

*
* *
* * *
* * * *
* * * * *

Let’s look at some nested while loops to print the same pattern.

>>> i=6
>>> while(i>0):
        j=6
        while(j>i):
            print("*",end=' ')
            j-=1
        i-=1
        print()

Output

*
* *
* * *
* * * *
* * * * *

Loop Control Statements in Python

Sometimes, you may want to break out of normal execution in a loop.

For this, we have three keywords in Python- break, continue, and pass.

Python Loop Tutorial - Loop Control Statements in Python

Python Loop Tutorial –
Loop Control Statements in Python

1. break statement

When you put a break statement in the body of a loop, the loop stops executing, and control shifts to the first statement outside it.

You can put it in a for or while loop.

>>> for i in 'break':
        print(i)
        if i=='a': break;

Output

b
r
e
a

2. continue statement

When the program control reaches the continue statement, it skips the statements after ‘continue’.

It then shifts to the next item in the sequence and executes the block of code for it. You can use it with both for and while loops.

>>> i=0
>>> while(i<8):
        i+=1
        if(i==6): continue
        print(i)

Output

1
2
3
4
5
7
8

If here, the iteration i+=1 succeeds the if condition, it prints to 5 and gets stuck in an infinite loop.

You can break out of an infinite loop by pressing Ctrl+C.

>>> i=0
>>> while(i<8):
      if(i==6): continue
      print(i)
      i+=1

Output

01

2

3

4

5

Traceback (most recent call last):
File “<pyshell#14>”, line 1, in <module>
while(i<8):
KeyboardInterrupt

3. pass statement

In Python, we use the pass statement to implement stubs.

When we need a particular loop, class, or function in our program, but don’t know what goes in it, we place the pass statement in it.

It is a null statement. The interpreter does not ignore it, but it performs a no-operation (NOP).

>>> for i in 'selfhelp':
        pass
>>> print(i)

Output

p

To run this code, save it in a .py file, and press F5. It causes a syntax error in the shell.

Python Interview Questions on Loops

  1. What is Loop in Python? Explain with example.
  2. What is the syntax of for loop in Python?
  3. How do you write a loop in Python?
  4. How many types of loops are there in Python?
  5. What are loops used for in Python?

Conclusion

In this tutorial on Python Loops, we learnt about while and for loops in Python. We also learnt how to nest loops, and use the range() function to iterate through a sequence of items.

Lastly, we learnt about break, continue, and pass statements to control loops. So, try out your own combinations in the shell, and don’t forget to leave your feedback in the comments.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

26 Responses

  1. Akash says:

    How to print
    0
    22
    444
    8888

    • Pavan says:

      import math

      for i in range(1,6):
      if i-1==0:
      print(0)
      continue
      print(str(int(math.pow(2,i-1)))*i)

    • DataFlair Team says:

      Hi Akash,
      Thanks for giving us chance to interact with you through this Python Loops Tutorial. This piece of code can solve your query, try it:
      def evens(n):
      print(0)
      x=2
      for i in range(1,n):
      for j in range(i+1):
      print(x,end=”)
      x*=2
      print()

      n=int(input(“How many lines?”))
      evens(n)

      Now, run this code:

      How many lines?4
      0
      22
      444
      8888

      Make sure to use proper indentation. Happy to help you.
      Regards,
      DataFlair

  2. Osman says:

    Please explain this code in detail. It really confused me. Thanks.
    >>> i=6
    >>> while(i>0):
    j=6
    while(j>i):
    print(“*”,end=’ ‘)
    j-=1
    i-=1
    print(“\n”,end=”)

    • DataFlair says:

      Here variable i is responsible for telling the inner loop how many stars to print and it also tells how many lines we have to print. J is used to print stars.

  3. Frank A Ames says:

    Do not understand the code such that it renders successive lines as * + 1

    >>> i=6
    >>> while(i>0):
    j=6
    while(j>i):
    print(“*”,end=’ ‘)
    j-=1
    i-=1
    print()

  4. Sailesh says:

    How does print(end=” “) work?

    • DataFlair Team says:

      Hi Sailesh,
      The end is an optional keyword argument to the print() function. This denotes the string it appends after the last value. If you do not specify any, it appends a newline after it.- this is the default.
      print(end=”) means we’re trying to append an empty string to whatever we’re trying to print so it doesn’t automatically take it to the next line instead.
      Hope, it helps.
      Keep visiting DataFlair!

  5. santoshpatil says:

    how to print multiple’s of 2,3 and 4

    • DataFlair Team says:

      Hi Santoshpatil,
      for num in range(2,5):
      for multiplier in range(1,11):
      print(f'{num}*{multiplier}={num*multiplier}’)
      print()
      Hope, it helps!

  6. Dexter says:

    Is it possible if the string also contains number like name1 and i want to make it in order for example: name1,name2,name3 and so on ?

  7. hari says:

    for i in range(3):
    for j in range(3):
    if i == j:
    continue
    print(i,j)

    for i in range(3):
    for j in range(3):
    if i == j:
    continue
    print(i,j)
    hey,can i get the explanation for the outputs for the above 2 codes

    • DataFlair says:

      Hi Hari,
      Sure, I will explain the output of the codes. One thing to be mentioned is that both the codes are the same. In the code, we have two for loops, one nested in the other. Both run from 0 to 2 (2 inclusive). Initially, when i=0, the inner for loop runs for j:0 to 2. For i=0, j=0, the if statement gets satisfied, and the continue statement gets executed. So, the values will not be printed. So, we get 0,1; 0,2 printed. In the next iteration when i=1, similarly for all cases except when j=i (the if condition is True), the print executes. And we get 1,0;1,2. And finally, when i=2, the values get printed except when j=2 and the overall output is 0,1 0,2 1,0 1,2 2,0 2,1 Hope you understood the explanation!

  8. cena says:

    for i in range(3):
    for j in range(3):
    if i == j:
    continue
    print(i,j)

    for i in range(3):
    for j in range(3):
    if i == j:
    continue
    print(i,j)

    • DataFlair says:

      Sure
      the output is:
      0 1
      0 2
      1 0
      1 2
      2 0
      2 1

      Your code has two for loops and it prints the value of i and j only if they both are not equal as you can see in the output and in the code also if i and j are equal it executes the continue statement which starts a new iteration with incremented j.

  9. Satheesh M says:

    for a in range(4,17):
    for b in range(a):
    print(a,end=’ ‘)
    print()
    What is the output of this snippet ?

  10. Ankit Minz says:

    How to break through multiple nested for loops in python?

  11. Zareen Sultana says:

    Write a program that will help you to learn multiplication. The program prompts the user to enter a number (between 1 to 100). Then it will printout in a tabular format the multiplication of the given number with numbers from 1 to 10? Make sure that your program will not allow the user to enter values outside the given range.

  12. kenny says:

    the pattern of the output is
    10
    10 9
    10 9 8
    10 9 8 7
    10 9 8 7 6

    pls someone solve this sum,

  13. DataFlair says:

    Hi Kenny,
    We can use nested loops to print this pattern. I am providing the code for this pattern using the for loops: n=5
    for i in range(1,n+1): # running loop to print 5 lines
    for j in range(i): # running loop to print 1 number in 1st line, 2 numbers in 2nd line..
    print(10-j,end=’ ‘)
    print() I hope you understand the above code.

  14. Pema says:

    Example of for loop inside while loop

  15. Hiren Bhavsar says:

    I got a question.
    pass keyword is same like null. It does nothing.
    Then why python uses pass as loop control statement?

    This is the program.

    s = “geeks”

    # Pass statement
    for i in s:
    if i == ‘k’:
    print(‘Pass executed’)
    pass
    print(‘Pass executed1’)
    print(i)

    print()

    # Continue statement
    for i in s:
    if i == ‘k’:
    print(‘Continue executed’)
    continue
    print(i)

    Output:
    g
    e
    e
    Pass executed
    Pass executed1
    k
    s

    g
    e
    e
    Continue executed
    s

    pass has no role..

  16. Ravichandra says:

    adj = [“red”, “big”, “tasty”]
    fruits = [“apple”, “banana”, “cherry”]

    How to get the below O/P using for loop
    red
    apple
    big
    banana
    tasty
    cherry

    • DataFlair Team says:

      adj = [“”red””, “”big””, “”tasty””]
      fruits = [“”apple””, “”banana””, “”cherry””]

      for a, f in zip(adj, fruits):
      print(a)
      print(f)

      OUTPUT
      red
      apple
      big
      banana
      tasty
      cherry

Leave a Reply

Your email address will not be published. Required fields are marked *