iterative statements
iterative statements
• while loops
• for loops
while (condition){
# Code to be executed while the condition is true
}
• The code block inside the loop is indented and contains the statements to
be executed repeatedly while the condition remains true.
While loops are particularly useful when the number of iterations is uncertain or
dependent on dynamic conditions. They allow for flexible iteration based on
changing circumstances within a program.
Example
i=1
while i < 6:
print(i)
i += 1
With the break statement we can stop the loop even if the while condition is
true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and continue
with the next:
Example
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
With the else statement we can run a block of code once when the condition no
longer is true:
Example
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Syntax:
Example
for x in "banana":
print(x)
With the break statement we can stop the loop before it has looped through all
the items:
Example
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
Example
Example
for x in range(6):
print(x)
Example
The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
The else block will NOT be executed if the loop is stopped by a break statement.
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.
Example