3. Python supports to have an else statement associated with a loop
statement
If else statement is used with a while loop, the else statement is
executed when the condition becomes false
Using else statement with a while loop
while condition:
# Code to be executed when the condition is True
else:
# Code to be executed when the condition becomes False
Syntax
4. Introduction to while loop
A while loop allows general repetition based upon the repeated
testing of a Boolean condition
Where, loop body contain the single statement or set of statements
(compound statement) or an empty statement.
A while loop is used to execute a set of statements as long as
condition is true
A loop statement allows us to execute a statement multiple times
5. Syntax How the While Loop
Works
1 Initialization
Set the initial state of the loop
variables.
2 Condition Check
Evaluate the condition expression to
determine if the loop should
continue.
3 Code Execution
Execute the code block within the
loop.
while(condition):
#code
#Initialization
7. 05
Examples
i = 0 # Initialize a variable
while i < 5: # While the variable is
print(i) less than 5
i+=1 print the variable and
increment it by 1
# The loop will stop when i is equal to 5
# Initialize a list
nums = [1, 2, 3, 4, 5]
# Iterate over the list and print each element
i = 0
while i < len(nums):
print(nums[i])
i += 1
# The loop will stop when i is equal to the length of the list