Loops
Loops allow you to repeat a block of code multiple times.
They are useful when you want to perform the same action several times without writing the same code over and over again.
The for loop
In Python, a for loop is commonly used to iterate over a sequence of values.
for i in range(5):
print(i)
This will output:
0
1
2
3
4
Explanation
range(5)generates a sequence of numbers from 0 to 4iis the loop variable (it takes each value from the sequence)- the indented block runs once for each value
Using range
The range() function can be used in different ways:
range(5) # 0, 1, 2, 3, 4
range(1, 5) # 1, 2, 3, 4
range(0, 10, 2) # 0, 2, 4, 6, 8
The while loop
A while loop runs as long as a condition is true.
count = 0
while count < 5:
print(count)
count = count + 1
Explanation
- the loop checks the condition
count < 5 - if it is
True, the code runs - after each iteration, the condition is checked again
Infinite loops
Be careful: if the condition never becomes false, the loop will run forever.
while True:
print("This runs forever")
You usually want to avoid this unless you explicitly need it.
Example
for i in range(1, 6):
print(i * 2)
Run this code, modify it and play it with it, in order to understand better how for loops in python behave.
Exercise
Let's practice a bit, shall we? Solve the following tasks:
- Write a program that prints numbers from 1 to 10
- Write a program that prints only even numbers from 1 to 20
- Write a program that counts down from 5 to 1 using a
whileloop
Notes
info
- Use
forloops when you know how many times you want to repeat something - Use
whileloops when the number of iterations depends on a condition - Always make sure your
whileloop will eventually stop