0
0
Pythonprogramming~5 mins

For loop execution model in Python

Choose your learning style9 modes available
Introduction

A for loop helps you repeat actions easily. It goes through items one by one and does something with each.

When you want to check every item in a list of groceries.
When you need to print each name in a class list.
When you want to add numbers from 1 to 10.
When you want to repeat a task a fixed number of times.
When you want to process each character in a word.
Syntax
Python
for item in collection:
    # do something with item

item is a temporary name for each element as the loop runs.

collection can be a list, string, or any group of items.

Examples
This prints each number in the list one by one.
Python
for number in [1, 2, 3]:
    print(number)
This prints each letter in the word 'cat' on its own line.
Python
for letter in 'cat':
    print(letter)
This prints 'Hello' three times using a range of numbers.
Python
for i in range(3):
    print('Hello')
Sample Program

This program goes through each fruit in the list and prints a sentence saying you like it.

Python
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(f'I like {fruit}')
OutputSuccess
Important Notes

The loop runs once for each item in the collection.

Indentation (spaces before the code inside the loop) is very important in Python.

If the collection is empty, the loop does not run at all.

Summary

A for loop repeats actions for each item in a group.

It helps avoid writing the same code many times.

Use it when you want to work with every item in a list, string, or range.