While loop in Python is used to execute statements repeatedly until a condition is satisfied. The condition is followed by
boolean expression.Following is the syntax of a while loop:
while boolean_expression: statements
Observe the following in the above code
- After the while keyword there is a colon (:) .The colon is used to introduce a block in Python.
- We have specified the statements in the while loop after whitespaces. This is a convention in Python to follow the block statements after indentation of 4 whitespaces.
Note that we have not used brackets in while loop.
In the following example we are setting the value of variable a as 1.Then we are incrementing the value of a and printing it till it is less than 10.So this loop will execute 10 times
a=1 while a<10: a+=1 print(a)
break is used exit the while block.So if you use the break keyword then the execution exits the while block.In the following example we are using the break keyword for exiting the while loop if the the value of variable a becomes equal to 5.
while a<10: a+=1 if(a==5): break print(a)
Leave a Reply