Please enable JavaScript to use CodeHS

Python Tutorial

For Loops in Python

Loops let you repeat code without copying and pasting it. Master the for loop and the range() function, then learn to loop over strings and lists like a pro.

python ~20 min Beginner friendly
The Big Idea

What is a for loop?

Loops are one of the fundamental constructs that let us control the flow of a program. A for loop repeats a block of code a specific number of times - so instead of writing print("hip hip hooray!") a hundred times, you write it once and tell Python to repeat it.

A for loop in Python follows this structure:

main.py
for i in range(COUNT):
    # code to execute COUNT number of times

The range() function has a few default settings:

  • The initial value of i is 0
  • i is increased by 1 each time the loop repeats

Heads up: the value of i goes from 0 up to but not including the number in range. So range(3) gives you 0, 1, 2 - three values, but no 3!

Interactive

Step through a loop

The best way to understand a loop is to watch it run one step at a time. Press Step to walk through each moment of this program, and watch i change:

for i in range(3):    print("i is", i)print("Done!")
–
current value of i
Console
The loop hasn't started yet.

Level Up

Customize with the range() function

A cool thing about range() is that you can add parameters to customize your loop:

main.py
for i in range(initial, end, increment):

Initial is the starting value, end is the ending value (remember, this number is not included in your loop!), and increment is the amount i increases each time.

Here's an example that counts by 2s, then press Run:

main.py
for i in range(2, 10, 2):
    print(i)
Console
2
4
6
8

Now experiment yourself. Change the three numbers and watch which values of i your loop visits. Try: counting by 5s, going from 10 to 100, or even a negative increment counting down!

range() playground
for i in range(, , ):

Your Turn

Practice: multiples of 5

1

Multiples of 5

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:

Expected output
5
10
15
20
25
30
solution.py
# Start at 5, stop before 31, count by 5
for i in range(5, 31, 5):
    print(i)

Why 31 and not 30? Because the end value is not included. Using range(5, 30, 5) would stop at 25. Anything from 31 to 35 works here - 31 makes your intent clear.


More Power

Looping over strings, lists, and more

As you can see, for loops make life much easier by repeating code a specific number of times. But there's so much more they can do!

In Python, we can use for loops to loop over strings, lists, tuples, and dictionaries. This comes in handy when we have data structures containing hundreds, or even thousands, of items. This code loops over each letter in the string "karel" and each item in a list of famous programmers:

main.py
# Loop over a string
my_string = "karel"
for letter in my_string:
    print(letter)

# Loop over a list
my_list = ["Lovelace", "Babbage", "Hopper"]
for item in my_list:
    print(item)
Console
k
a
r
e
l
Lovelace
Babbage
Hopper

Good to know: the loop variable name is up to you. letter and item are just descriptive names - the loop works exactly the same if you call it x. Descriptive names make your code easier to read.

Your Turn

Practice: sandwich shop

2

Sandwich Shop Speller

You work at a sandwich shop. For each order, you ask the customer for their name and spell it back to them to make sure it's right. It turns out you are an excellent speller and get it right every time!

Write a program that uses a for loop to print out each letter of the customer's name. Create a variable for the name - or jazz it up with input() to ask for it.

solution.py
name = input("What's your name? ")

print("Let me spell that back to you:")
for letter in name:
    print(letter)
Console (if the customer types "Ada")
What's your name? Ada
Let me spell that back to you:
A
d
a

Combine and Conquer

Beyond the basics

You've now got the basics of for loops - congratulations! But don't stop here. You can combine loops with other control structures, like if statements, to build more powerful programs.

This program loops over a string and counts how many vowels it has - similar to the letter-frequency analysis used to crack secret codes:

main.py
text = "Ada Lovelace is considered the first programmer."
num_vowels = 0

for letter in text:
    if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u":
        num_vowels = num_vowels + 1

print("There are " + str(num_vowels) + " vowels.")
Console
There are 15 vowels.

Think about it: the capital A in "Ada" is not counted, because the program only checks lowercase letters. How would you change the code to count capital vowels too?

Try the same loop on your own text. The widget below runs the same algorithm on whatever you type (counting capitals too), and highlights each vowel the loop finds:



The loop found 4 vowels.

Code

A loop example

For loops repeat code for each item in a sequence. This program uses two kinds of for loops.


Check Yourself

Quick quiz

1. What does for i in range(4): print if the loop body is print(i)?

2. Which loop prints the numbers 10, 20, 30, 40?

3. How many times does this loop print?

word = "pizza"
for letter in word:
    print("yum")

Keep learning Python

For loops repeat code a set number of times. Next, learn while loops, which repeat as long as a condition is true, or explore the lists you just learned to loop over.