Please enable JavaScript to use CodeHS

For Loops in Python Turtle

Learn the basics of for loops in Python.

By Rachel Devaney

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:

for i in range(COUNT):
    code to execute COUNT number of times
Plain text

The range() function has a few default settings:

  • The initial value of i is 0
  • i 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.


Customize with the Range Function

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.

  • Can you change the for loop to increase by 5 instead of by 2?
  • Can you change the for loop to go from 10 to 100?
  • What happens when you delete the third parameter?
  • Can you have a negative number as an increment?
  • What happens if your end value is smaller than your initial value?

Practice #1

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:

5
10
15
20
25
30
Plain text