Loops
A loop in Python lets you repeat a block of code multiple times, this reduces the amount of code we need to write and also improves efficiency. Loops also allows us to run code specific number of times or forever.
Types of Loops:
In Python we have 2 types of loops
For - To repeat something a certain amount of Times
While - As long as it's true, which can mean forever or as long as the program is running.
Example of For Loop:
for i in range(1, 6): #Iterate from 1-5, 6 is excluded.
print(i)Output:
1
2
3
4
5How does this work?
This loop creates a range between 1-5 and displays the output instantly. We could slow down the program by adding a time delay.
Last updated