Python
|
Loops
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:
Output:
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:
Output:
Continue statement:
The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop.
Output:
Break statement:
The break statement immediately exits the loop.
Output:
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.
Output: