Control Flow

While Loop in Python

The while loop executes a block of code while a boolean expression evaluates to true. It terminates as soon as the expression evaluates to false. The boolean expression is evaluated before each iteration.


Syntax
while boolean_expression: 
    #statements to execute while booleanExpression is true

Notes

Because the boolean expression is evaluated before each iteration, the block of code executes ONLY if the boolean_expression evaluates to true. If a guarantee is needed for the block of code to run at least once, use the do-while loop.

boolean_expression results in either a true or false output.

There can also be multiple boolean expressions within the parentheses (booleanExpression). The boolean expressions are connected through logical operators (&&, ||, !).


Example
while distance < 100 :
    print ("You have not finished the race")
    distance += 10

print ("Race has finished!")

< For Loop   |   Ternary Operator >

© 2019 SyntaxDB. All Rights Reserved.