Contents:
- Introduction
- General Format of while Loop
- else Clause in while Loop in Python
- while Loop Working
- Example
Introduction
A loop is a programming construct that allows a block of code to be executed repeatedly until a certain condition is met. Python supports two main types of loops: for loops and while loops.
General Format of while Loop
while test: # Loop header line with test expression
. . . .statements # Loop body containing indented statements
else: # Optional else
. . . .statements # Run if loop didn’t exit with break statement
In its most complex form, the while statement consists of a header line with a test expression, a body of one or more normally indented statements, and an optional else part that is executed if control exits the loop without a break statement being encountered. Here, body of the the loop has one or more than one indented statements. The indented statement means, extra blank spaces(typically 4 spaces) added at the beginning of line of code. So, to represent block of statements in python line indention is used unlike other languages where curly brackets({, }) are used to represent block of code.
else Clause on while Loop
Unlike other popular programming languages (C, C++, and Java), Python uses an optional else clause on loops. If the loop finishes without executing the break, the else clause executes. In either kind of loop, the else clause is not executed if the loop was terminated by a break.
while Loop Working
Python while loop repeatedly executes an associated block of statements as long as a test expression at the top keeps evaluating to a true value. When the test expression does become false, control passes to the statement that follows the while block. Here, test expression can be implicitly evaluated as True or False in boolean context such as:
- Any non-empty object or non-empty number is true.
- Zero numbers, empty objects, and the special object None are considered false.
Example:
x=5
y=2
while(y<=x):
print(y)
y=y+1
Output:
2
3
4
5
Explanation: Here variable x refers to the object 5 and variable y refers to the object 2. The while loop test expression y<=x checks whether the value of y is less than or equal to the value of x or not. This time, y is less than x, the boolean value True is returned and hence value of y gets printed on screen and the value of y gets incremented by 1. Again, the control goes to header of the loop at test expression to check it out whether to execute the loop or not. It follows the same process, evaluates the test expression and decides whether to execute the block of statements or not. This way, while loop works and whenever False value is returned by test expression, while loop gets terminated and control goes to execute the instruction following the while loop.
🙂 Happy Learning !