Python while loop

Filed Under: Python

In this tutorial we will cover basics of python while loop. In the previous tutorial, we learned about Python for loop.

Python while loop

Python while loop is used to repeatedly execute some statements until the condition is true. So the basic structure of python while loop is:

While condition :
	#Start of the statements
	. . . . . . .
	#End of the Statements
else :
	#this scope is optional
        #This statements will be executed if the condition
	#written to execute while loop is false

For example, the following code will give you some ideas about the while loop. In this example, we are printing numbers from 1 to 4 inside loop and 5 in outside of the loop

cnt=1 #this is the initial variable
while cnt < 5 :
        #inside of while loop
        print (cnt,"This is inside of while loop")
else :
        #this statement will be printed if cnt is equals to 5
        print (cnt, "This is outside of while loop")

python while loop

In the example of for loop tutorial, we print each letter from words. We can implement that code use while loop. The following code will show you that.

pos=0 #initial position is zero
while pos < len(word) :
	print (word[pos])
	#increment the position after printing the letter of that position

python while loop example

An interesting fact about the loop is if you implement something using for loop, you can implement that in a while loop too. Try to implement examples shown in for loop tutorial in a while loop.

Python Nested while loop

You can write while loop inside another while loop. Suppose you need to print a pattern like this

    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5

The following code will illustrate how to implement that using nested while loop.

line=1 #this is the initial variable
while line <= 5 :
        pos = 1
        while pos < line:
                #This print will add space after printing the value
                print pos,
                #increment the value of pos by one
                pos += 1
                #This print will add newline after printing the value
                print pos
        #increment the value of line by one
        line += 1

Python while loop infinite problem

Since the while loop will continue to run until the condition becomes false, you should make sure it does otherwise program will never end. Sometimes it can come handy when you want your program to wait for some input and keep checking continuously.

var = 100
while var == 100 :  # an infinite loop
   data = input("Enter something:")
   print ("You entered : ", data)

print ("Good Bye Friend!")

If you run the above program, it will never end and you will have to kill it using the Ctrl+C keyboard command.

================= RESTART: /Users/pankaj/Desktop/ =================
Enter something:10
You entered :  10
Enter something:20
You entered :  20
Enter something:
Traceback (most recent call last):
  File "/Users/pankaj/Desktop/", line 3, in <module>
    data = input("Enter something:")

That’s all about python while loop example tutorial. For any queries please comment below.


  1. Minh says:

    Does the “else” branch in while loop have the same properties like “else” in for loop?
    I mean that if while loop does not end normally, it will not go to “else” branch, doesn’t it?

  2. Jason says:

    There is a slight error in the first example. I think you are going for the following as oppose to what you currently have:

    print(cnt, “This is inside of while loop”)
    print(cnt, “This is outside of while loop”)

    Additionally, you have typo in the following, I think it was an oversight while creating these awesome tutorials:

    1. Pankaj says:

      Ah, thanks for the comment and let me know about these subtle errors. I have fixed them in the code.

  3. Anil says:

    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5
    Can you share me logic for above with WHILE loop please

    1. Jason says:

      The logic above doesn’t output the accurate result. Here is how I got the desired result:
      line = 1

      while line <= 5:
      pos = 1
      output = ""

      while pos <= line:
      output += str(pos) + " "
      pos += 1

      line += 1

      Let me know if this helped.

Leave a Reply

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

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages