Definition
Python while loop is used to execute a block of code until the given condition is True.
Syntax
while condition:# block of code# to be executed# until the condition is True
Examples
Example1
i = 5while i>0:print(i)i = i - 1
Output
54321
Example2
# printing table for any numbernumber = int(input("Enter number:"))i = 1while i!=11:print(number, "X", i, "=", i*number)i=i+1
Output
Enter number:1010 X 1 = 1010 X 2 = 2010 X 3 = 3010 X 4 = 4010 X 5 = 5010 X 6 = 6010 X 7 = 7010 X 8 = 8010 X 9 = 9010 X 10 = 100
Example3
# infinite while loopwhile True:print("This line will print infinite times")
Output
This line will print infinite timesThis line will print infinite timesThis line will print infinite timesThis line will print infinite timesThis line will print infinite times.........
break statement
We can use break statement if we want to exit the while loop.
Generally, we use break statements in while loop when we have some specific conditions to exit the while loop.
Example1
i = 0while True:print(i)if i==5:breaki = i + 1
Output
012345
Example2
# printing tablei = 1number = 10while True:if i==11:breakprint(f"{number} X {i} = {number*i}")i = i + 1
Output
10 X 1 = 1010 X 2 = 2010 X 3 = 3010 X 4 = 4010 X 5 = 5010 X 6 = 6010 X 7 = 7010 X 8 = 8010 X 9 = 9010 X 10 = 100
If you have any confusion in the 7th line about f, then click here. Scroll down on that page and read fast string concepts.
continue statement
Unlike the break statement, continue statement skips one step of the loop and continues with the next step.
Example1
i = 0while i<6:i=i+1if i==2:continueprint(i)
Output
13456
Example2
# skipping every stepi = 0while i<6:i=i+1continueprint(i)
Program outputs nothing
while… else…
In python, we can use else statement with while loop.
Block of else statement will be executed every time unless the while loop is terminated with a break statement.
Example1
i = 0while i<6:i=i+1print(i)else:print(i)
Output
1234566
Example2
i = 0while i<6:i=i+1print(i)if i==4:breakelse:print(i)
Output
1234