while Loop in Python
The while loop in Python, used to execute some block of code, multiple times. I've included all version of the loop. That is, this article deals with:
- Example of while loop
- while loop as infinite loop
- How to stop the infinite execution of while loop
- while loop with break keyword
- while loop with continue keyword
- while loop with pass keyword
- while loop with list
- while loop with else block
- while loop in single line
- And at last, the nested while loop
Python while Loop Syntax
The syntax to use while loop in Python is:
while expression: statement(s)
where expression refers to the conditional expression. The expression can also be used either with True or False directly. Or with any conditional expression that must returns the result in True/False.
If the conditional expression evaluates to be True, then the program flow goes inside the while loop's block and executes all the statement(s) available in its body. Otherwise, if the condition evaluates to be False. Then the program flow does not executes its statement(s) and execution of the whole while loop stops.
After executing all the statements available in the body of while loop. The conditional expression of the loop again gets evaluated. This process continues until the conditional expression evaluates to be False. Now let's understand while loop practically with the help of example programs given below.
Python while Loop Example
Let's create one of the simplest program of Python, that uses while loop. That is, the program given below demonstrates while loop in python:
i=1 while i <= 10: print(i) i = i+1
Here is the sample output produced by above python program:
The dry run of above program goes like:
- Since the first statement of the program is,
i=1. Therefore, initially 1 gets initialized to a variable i. So i=1
- Now the execution of second statement or the execution of while loop, begins
- That is, the condition i <= 10 or 1 <= 10 evaluates to be True. Therefore program flow goes inside the loop
- Inside the loop, there are two statements. Therefore both the statements gets executed one by one
- That is, the statement
print(i)prints the value of i. That is, 1 gets printed on output
- And using the second statement, the value of i gets incremented by 1. So i=2 now
- Since all the statements of while loop, gets executed. Therefore program flow again evaluates the conditional expression of the loop with new value of i
- That is, the expression i <= 10 or 2 <= 10 again evaluates to be True
- Therefore program flow again goes inside the loop.
- So 2 gets printed on output and the value of i gets incremented using the second statement of the while loop. Now i=3
- The conditional expression of while loop again gets evaluated. That is, i <= 10 or 3 <= 10 evaluates to be True, the third time
- This process continues, until the condition evaluates to be False
Important - Don't forget to update (increment/decrement) the loop variable from inside the body of the while loop. Otherwise, the loop continue its execution forever.
Here is another example on while loop. This program receives an input from user. And the program continues receiving input from user until user enters learning python as input:
print("Hey! Welcome") print("What are you doing here ?") what = input() while what != "learning python": what = input("What ?\n") print("Right.")
Here are some sample runs of the above while loop example in Python. Here is the initial output produced by above program:
Now type your answer say i don't know, and press
ENTER key to store the input in what variable.
Now the input using what variable gets compared with string learning python. If the value of the what does
not equals to this string, then program flow goes inside the loop, and receives another input. Here is the output:
Since, i don't know is not equal to learning python. Therefore another input() statement gets executed, that receives another input from user. Here is another sample run with user input learning on codescracker:
As again the second input too is not equal to the string provided in while loop's conditional expression. Therefore program again will receive the input. Here is the third sample run. But this time with required input, that is learning python:
while Loop as Infinite Loop
If the conditional expression of the while loop always evaluates to be True, then the loop goes for infinite execution. For example,
while True: statement(s)
while 0<10: statement(s)
while "codescracker" == "codescracker": statement(s)
etc. Since the first loop uses True keyword itself, therefore the loop goes for its forever execution. In the second while loop's conditional expression, the condition 0<10 always evaluates to be True. Therefore this loop always continues its execution infinitely. Similar thing goes for the third while loop.
Both expressions, that is, 0<10 and "codescracker" == "codescracker" refers to True indirectly. Because these two conditional expression always evaluates to be True.
How to Stop Infinite Execution of while Loop ?
To stop the infinite execution of while loop, we need to either update the loop variable, or use the break keyword, from inside the body of the loop. Let's see how.
while Loop with break Keyword
The break keyword is used to exit from the loop. Or it can be used to skip the remaining execution of the loop.
i = 1 while True: val = 2*i print(val) i = i+1 if i>10: break
The output produced by above program is shown in the snapshot given below:
The above program of while loop is created in a way that, the loop continues its execution, until the condition of the if, that is i>10 evaluates to be True. That is, if the condition evaluates to be True, therefore program flow goes inside its block or if's body, and the break statement gets executed that stops remaining execution of the while loop.
while Loop with continue Keyword
The continue keyword is used to jump for the next iteration, skipping the execution of the remaining statement(s) of the loop's body, if available after the keyword.
i = 9 while i<=20: i = i+1 if i%2 != 0: continue print(i)
This program prints all the even numbers from 10 to 20 (including both numbers, if even). The snapshot given below shows the sample output produced by above program:
while Loop with pass Keyword
The pass keyword does nothing. It can be used as a placeholder for the code or block of code, that has to be implement in future.
mystr = "codescracker" count = 0 while count < len(mystr): count = count+1 pass print("Length of String =", count)
Here is the output produced by above program:
However, the above program can also be written without pass, the output will be same. Here is the same program without pass:
mystr = "codescracker" count = 0 while count < len(mystr): count = count+1 print("Length of String =", count)
I've provided all the details about pass in separate tutorial. Also compared pass with continue in another separate tutorial.
while Loop with List
The program given below uses list as conditional expression of the while loop.
mylist = ['p', 'y', 34.5, 't', 2, 'codescracker', True] while mylist: print(mylist.pop())
The output produced by above program is shown in the snapshot given below:
In above program, the pop() method is used to pop or delete list element from the end.
Here is another program, uses while loop to implement list. This program receives the size and elements of the list. And then prints the list elements back on the output screen, using while loop:
print("Enter the Size: ", end="") tot = int(input()) i = 0 mylist = list() print("Enter", tot, "Numbers: ", end="") while i<tot: val = int(input()) mylist.insert(i, val) i = i+1 i = 0 print("\n-------The List is-------") while i<tot: print(mylist[i], end=" ") i += 1
Here is its sample run with user input 6 as size and 23, 24, 25, 26, 39, 40 as six elements:
while Loop with else Block
The while loop with else statement, is used to execute statement(s) using else, after completing the execution of the loop. For example:
i = 9 while i<=20: i = i+1 if i%2 != 0: continue print(i) else: print("All even numbers from 10 to 20 are given above")
Here is the output produced by this Python program, that shows the use of else statement with while loop:
while Loop in Single Line
The while loop in Python can also be written in single line. Here is an example uses the loop in single line:
i = 1 while i <= 10: print(5 * i); i += 1
The output produced by above program, is:
5 10 15 20 25 30 35 40 45 50
Nested while Loop
Just like for loop, while loop can also be nested inside another while loop. Here is an example, demonstrates the use of nested while loop in Python:
print("Enter any Number: ") n = int(input()) print("Enter Number of Rows: ") no_of_rows = int(input()) i = 0 j = 0 while i<no_of_rows: while j<i+1: print(n, end=" ") j = j+1 j = 0 i = i+1 print()
Here is the initial output produced by above program:
Now enter a number say 1 and then enter the number of rows say 5 to print 1 in five rows in a way that one "1" at first row, two "1" at second row, three "1" at third row, four "1" at fourth row, and five "1" at fifth row, as shown in the snapshot given below:
- Print Multiplication Table
- Print Prime Numbers
- Find Factorial of a Number
- Matrix Multiplication Program
« Previous Tutorial Next Tutorial »