counter = 0
while counter < 5:
print(counter)
counter+=10
1
2
3
4
Link to the Google Colaboratory notebook: 7-Loops
Python has two primitive loop commands:
while loopsfor loopsWith the while loop we can execute a set of statements as long as a condition is true.
Be careful not to forget the incremental conditions, otherwise the program will not stop.
With the break statement we can stop the loop even if the while condition is true:
With the continue statement we can stop the current iteration, and continue with the next:
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
apple
banana
cherry
With the break statement we can stop the loop before it has looped through all the items:
With the continue statement we can stop the current iteration of the loop, and continue with the next:
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
We can also specify the start, end and the step:
A nested loop is a loop inside a loop.
The “inner loop” will be executed one time for each iteration of the “outer loop”:
One can loop through the element of a list AND the indexes it goes through.