Loops are used to repeat a block of code multiple times efficiently. Instead of writing the same thing 100 times, you tell Python:
โRun this 100 times!โ and it says โSure!โ.
There are 2 main types of loops in Python:
Loop Type | When to Use |
---|---|
for loop |
When you know how many times to repeat something |
while loop |
When you want to repeat until a condition is false |
for
Loop โ The Repeater You Trustfor i in range(1, 101):
print(i)
range(1, 101)
โ Starts at 1, goes up to but not including 101i
โ Loop variable (think of it as a counter)for i in range(10):
print("Prathamesh")