While statement in python

The "while" statement in python is an important control flow statement that enables repetitive execution of statements.

Syntax of "while" statement in python:

while <Conditional Expression>:
    # While suit
    Python statement1
    Python statement2
    Python statement3
    .
    .
    .
    Python statement n        

else:

    # else suit
    Python statement1
    Python statement2
    Python statement3
    .
    .
    .
    Python statement n    

 


                
Semantics of "while" statement in python:

  • The "while" statement executes a suit of code as long as the conditional expression mentioned in the while statement evaluates to True.
  • The "while" statement terminates its execution when the conditional expression evaluates to False.
  • The "else" suit is executed once the while suit is exited
  • The "else" suit will not be executed if the "while" has exited as a result of a "break" statement.
  • "while" is the only loop control statement that can be controlled by a index variable used as part of its conditional expression.

Example:

index = 0
while (index < 10):
    print("Index Value: {}".format(index))
    index = index + 1 #increment explicitly
else:
    print("Done with printing numbers"

 

Output:

Index Value: 0

Index Value: 1

Index Value: 2

Index Value: 3

Index Value: 4

Index Value: 5

Index Value: 6

Index Value: 7

Index Value: 8

Index Value: 9

Done with printing numbers


Copyright 2024 © pythontic.com