ScanSkill

while loop

while loop is used to execute the block of code repeatedly while the specified condition is True.

Syntax

while condition:
    statement(s)
else:
    statement(s)

Here,

  • while: starts a while loop.
  • condition: Any expression that returns a Boolean value.
  • statement(s): Block of code to be executed when the condition is True
  • else: Optional. Used to indicate the block of code to be executed when loop terminates without break statement.

Note: When looping, while statement provides a condition and the statement(s) are executed repeatedly till the condition evaluates False.

The test on expression takes place before each execution of the statement.

Examples

>>> i = 0
>>> while i <= 3:
...     print(i)
...     i += 1
...
0
1
2
3
>>> key = "Cloudyfox"
>>> user_input = input("Please enter the key: ")
Please enter the key: hello
>>> while user_input != key:
...     user_input = input("Please enter the key: ")
... 
Please enter the key: vertex
Please enter the key: python
Please enter the key: cloudyfox
Please enter the key: Cloudyfox
  • **With else condition(break statement in while loop)
>>> i = 0
>>> while i <= 3:
...     print(i)
...     i += 1
... else:
...     print("break")
... 
0
1
2
3
break
>>> i = 0
>>> while i <= 3:
...     print(i)
...     i += 1
...     break
... else:
...     print("break")
... 
0

Here, since break is used, else will not be executed.