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 till the condition is true. So the basic structure of python while loop is:
CopyWhile condition : #Start of the statements Statement . . . . . . . Statement #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 idea about while loop. In this example, we are printing numbers from 1 to 4 inside loop and 5 in outside of the loop
Copycnt=1 #this is the initial variable while cnt < 5 : #inside of while loop print (cnt), print ("This is inside of while loop") cnt+=1; else : #this statement will be printed if cnt is equals to 5 print (cnt), print("This is outside of while loop")
In the example of for loop tutorial we print each letters from words. We can implement that code use while loop. The following code will show you that.
Copyword="anaconda" pos=0 #initial position is zero while pos < len(word) : print (word[pos]) #increment the position after printing the letter of that position pos+=1
An interesting fact about loop is if you implement something using for loop, you can implement that in while loop too. Try to implement examples shown in for loop tutorial in 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 3
1 2 3 4
1 2 3 4 5
The following code will illustrate how to implement that using nested while loop.
Copyline=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 else: #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 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.
Copyvar = 100 while var == 100 : # an infinite loop data = input("Enter something:") print ("You entered : ", data) print ("Good Bye Friend!")
If you run above program, it will never end and you will have to kill it using Ctrl+C keyboard command.
Copy>>> ================= RESTART: /Users/pankaj/Desktop/infinite.py ================= Enter something:10 You entered : 10 Enter something:20 You entered : 20 Enter something: Traceback (most recent call last): File "/Users/pankaj/Desktop/infinite.py", line 3, in <module> data = input("Enter something:") KeyboardInterrupt >>>
That’s all about python while loop example tutorial. For any queries please comment below.