Loops execute a block of code repeatedly until a specified end condition is met.
While
for loops are based on iteration over a sequence,
while loops continue executing as long as a specified condition remains True.
for loops are typically used when the number of iterations is known,
whereas
while loops are useful when the number of iterations is not known in advance.
Basic for loop:
for i in range(1, 4):
print(i)
print(i) # Output: 3
Output:
1
2
3
3
Note that the variable "
i" is accessible after the loop finishes.
Note that the indentation is very important to limit the block of the instructions that are part of the loop.
Basic while loop:
i = 1 # initialize the loop variable before the loop
while i <= 3: # check the condition before each iteration
print(i)
i += 1 # update the loop variable to avoid infinite loops
Output:
1
2
3
Continue statement:
The
continue statement skips the rest of the current iteration and jumps to the next iteration of the loop.
i = 0
while i <= 3:
i += 1
if i % 2 == 0: # skip even numbers
continue # if i is even (2), the rest of the code block is skipped (no print)
print(i)
Output:
1
3
Break statement:
The
break statement immediately exits the loop.
i = 0
while True: # infinite loop
i += 1
if i > 3: # break when i bigger than 3
break # exit the loop immediately
print(i)
Output:
1
2
3
Using while-else:
The
else clause executes after the
while loop finishes, but only if the
break statement was not used to exit the loop.
i = 0
while i < 3:
i += 1
print(i)
else:
print("loop completed")
Output:
1
2
3
loop completed