Introduction
In this article, I will explain the while loop in Python. In this loop, an announcement is run once if its condition evaluates to True, and never runs if it evaluates to False. A while statement is similar, except it can be run one or more times. The statements inside it are time and again executed, as long as the circumstance holds. Once False, the next code will be executed.
- SyntaxWhile expression:
- print (while statement)
Example
Simple program for a while loop:
- i = 1
- while i < 10:
- print(i)
- i += 1
Output
Remember that i's value is 10, so the block of code will be executed 10 times.
While Loop and Break Statement
We can stop the loop with the break declaration although the while condition is true.
Syntax
- While expression:
- if condition:
- break
Example
Here's a simple program for the while loop and break statement.
- i = 1
- while i < 10:
- print(i)
- if (i == 5):
- break
- i += 1
Output
Note that after number 5, there's no display in the output screen.
While Loop and Continue Statement
The continue statement is used to leave a sum statement and it continues with the next statement.
- SyntaxWhile expression:
- if condition:
- continue
Example
Simple program for a while loop and condition statement.
- i = 0
- while i < 10:
- i += 1
- if i == 5:
- continue
- print(i)
Output
Note that the number 5 is missing in the output.
While Loop and Pass Statement
The pass statement is used to write an empty loop statement. Pass is also used for empty control statements.
Syntax
- While expression:
- if condition:
- pass
Example
Here's a simple program for a while loop and pass statement.
- i = 0
- while i < 10:
- i += 1
- if i == 5:
- pass
- print(i)
Output
The pass statement does not change anything.
While Loop and Else Statement
In the else statement, we will run a block of code once while the condition false.
- SyntaxWhile expression:
- print (while statement)
- else:
- print (else statement)
Example
Simple program for a while loop and else statement.
- i = 1
- while i < 10:
- print(i)
- i += 1
- else:
- print ("i is less than 10")
Output
Prints a message one time while the condition is false.
Conclusion
In this article, we have seen the while loop in Python. I hope this article was useful to you. Thanks for reading!