Python | While loop
A Loop is a Sequence of instruction s that is continually repeated until certain condition is satisfied
The While loop is used for iterate the block of code as long as the condition was true , and when the condition is false then it was execute the after loop code
Syntax :
While condition
statement
In python while loop, it will first of check the condition the body of the while loop statements are run if the condition is true, after one iteration again it will check the condition , this process continuously run until the condition was false
Example
x = 0
while x <= 5:
print(x)
x += 1
Output
0
1
2
3
4
5
In this above example, the loop was starting from 0 , and check condition 0 is less than or equal to 5 if yes then execute the statement of while loop ,and increment by 1 , now again python interpreter check the condition at that time x is 1 (one), check condition 1 is less than or equal to 5 if true the again execute the statement
The loop will iterate until the condition is wrong
Break statement
The break statement , it will terminate the iteration at the condition is satisfied
And execute the next statement
Example
x = 0
while x < 6:
print(x)
if x == 3:
break
x += 1
Output
0
1
2
3
Continue statement
A continue statement terminates the current iteration of a loop. Loop control pass from the continue statement and execute the statement
A continue statement is used in both loops for and while
Example
x = 0
while x < 10:
x + = 1
if x == 5:
continue
print(x)
Output
1
2
3
4
6
7
8
9
10