Learn the basics of for loops in Python.
Loops are one of the fundamental constructs that enable us to control the flow of our program. A for loop is a type of loop that repeats a block of code a specific number of times.
A for
loop in Python follows this structure:
The range()
function has a few default settings:
i
is 0i
is incremented by 1 each time.Take a moment to walk through the slides to see this in action.
Note that the value of i
goes from 0 up to but not including the number in range
.
A cool thing about the range()
function is that you can add parameters to customize your loop:
for i in range(initial, end, increment)
Initial is the starting value, end is the ending value (remember that this number is not included in your loop!), and increment is the amount i
is increased each time.
Take a look at the examples to see how you can use parameters to customize a for
loop.
for
loop to increase by 5 instead of by 2?for
loop to go from 10 to 100?Write a program that prints out the multiples of 5 from 5 to 30. You should use one for
loop with parameters. Your output should look like this: