Python - Decision control and looping statement - While loop Tutorial
In Python, while loop is used when you exactly don’t know how many times the loop should be executed, the loop execution will automatically stop when the condition becomes false.
Syntax-
while condition:
statements
In the below program, it will print the value of i, until the condition is true. Once the condition becomes false, it will stop printing.
For Example-
i=1
while i<=8:
print(i)
i=i+1
Output-
1
2
3
4
5
6
7
8
- While loop with a break statement
A break statement is used to stop the loop even if the condition is true.
For example-
i=1
while i<=8:
print(i)
if(i==3):
break
i=i+1
Output-
1
2
3
- While loop with continue statement
Continue Statement is used to stop the current iteration and continue with the next iteration.
For example-
i=0
while i<=8:
i=i+1
if(i==3):
continue
print(i)
Output-
1
2
4
5
6
7
8
9
- While loop with else statement
Else statement will run a block of code once when the while condition becomes false.
For example-
i=1
while i<=8:
print(i)
i=i+1
else:
print("Condition becomes false")
Output-
1
2
3
4
5
6
7
8
Condition becomes false