9for Loops

Computers are great for doing the same thing over and over again, which is mindlessly tedious for human beings. That's a big reason why we like using computers so much! In computer programming, a loop is used to create a repeated action, and one such loop is the for loop.

Create a for Loop

Suppose you want to print out each letter in the string Python. You could start by creating a variable and assigning the string Python to the variable. Using print(), you could then print the variable. However, look at what happens when you follow those steps:

>>> language = 'Python'
>>> print(language)
Python

Although the string Python is printed to the console, the goal is to print each letter in the string one by one. To do so, you can use a for loop.

The syntax used to print each letter in the string one by one,  although the string in Python is printed to the console. To do so, you can use a for loop.

A for loop repeats the same steps in your code. The process of repeating is called iterating.

Iterate over a String

When you create a for loop with a string, Python loops through each item in the string. Within the loop, you can specify an action to take on each item. Let's see this in action with the string Python!

Since you previously created a language variable that stores the string Python, use that variable to create a for loop. First, create a for statement that states “for each item in the variable language.”

>>> for item in language:

You can name the item whatever you'd like. However, consider choosing an item name that ...

Get Bite-Size Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.