Python for Beginners

For loop in Python

Lesson 8 introduces the for loop in Python: range() in its three forms, iterating over strings with enumerate, comparing for and while, and criteria for choosing the most suitable loop in each situation.

joao • 01 Nov 2026 • 6 min read • 117 • 0
For loop in Python | Usando Python
Publicidade

By the end of this lesson, you should understand the for loop, be able to use range() in its three forms, iterate over strings and other iterables, and know how to choose between for and while according to the situation.

1. The for loop

for is the most used loop in Python. Its purpose is different from while: instead of repeating while a condition is true, it walks through a sequence of values, running the block once for each item.

The syntax is:

for item in sequence:
    block_of_code

On each iteration, the variable item receives the next value from the sequence. When the sequence ends, the loop stops automatically. There is no condition to check manually, which reduces the chance of errors.

An example with a string:

for letter in "Python":
    print(letter)

The output will be:

P
y
t
h
o
n

Here the sequence is the string itself, and for walks through each character. This behavior is called iteration, and objects that can be traversed this way are called iterables. Strings, lists, tuples and dictionaries are iterables; isolated numbers are not.


2. range()

To repeat a block a specific number of times, Python offers the range() function. It generates a sequence of numbers that for walks through.

Form 1 — range(end)

Produces a sequence that starts at 0 and ends before the given value:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

The number 5 does not appear. range(n) generates the numbers from 0 to n - 1, totaling n items. This behavior is a common source of confusion: range(5) repeats the block five times, with values 0 to 4.

Form 2 — range(start, end)

Allows you to define where the sequence starts:

for i in range(2, 6):
    print(i)

Output:

2
3
4
5

The start is included; the end is excluded. As in the previous form, the final value does not appear.

Form 3 — range(start, end, step)

Adds a step, which defines the increment between values:

for i in range(0, 10, 2):
    print(i)

Output:

0
2
4
6
8

The step 2 generates only the even numbers. It is also possible to use a negative step to count backwards:

for i in range(5, 0, -1):
    print(i)

Output:

5
4
3
2
1

Summary of the three forms

FormExampleSequence generated
range(end)range(4)0, 1, 2, 3
range(start, end)range(2, 5)2, 3, 4
range(start, end, step)range(1, 6, 2)1, 3, 5

Note: range() is not a list

In Python 3, range() returns a special object that generates numbers on demand, not a complete list. This means it is efficient even for huge intervals:

for i in range(1_000_000):
    if i == 3:
        break

The loop stops at i == 3, without generating a million numbers at once. If you need to see the contents as a list, use list(range(5)), which returns [0, 1, 2, 3, 4].

3. Iterating strings

We have already seen that for walks through strings character by character. This opens the door to several useful manipulations.

Counting vowels

word = "programming"
vowels = 0

for letter in word:
    if letter in "aeiou":
        vowels += 1

print(f"The word has {vowels} vowels.")

On each iteration, for hands a character to the variable letter. The if checks whether it is in the set of vowels, and the counter advances.

Iterating with an index

Often it is not enough to know the character, but also its position. For this, use enumerate():

word = "Python"

for index, letter in enumerate(word):
    print(f"{index}: {letter}")

Output:

0: P
1: y
2: t
3: h
4: o
5: n

enumerate() returns pairs (index, value) on each iteration. This avoids the temptation of writing for i in range(len(word)), which is less readable and more error-prone.

Iterating over a list of words

fruits = ["apple", "banana", "grape"]

for fruit in fruits:
    print(fruit.upper())

Lists will be covered in detail in the next lessons, but it is already possible to see that for works the same way: it hands over one item at a time.

4. for vs while: when to use each

Both loops solve the same basic problem — repeating code — but in different contexts.

Use for when:

  • You know how many times the block should run (for i in range(10)).

  • You need to walk through a known sequence (string, list, tuple).

  • The repetition has a clear and finite structure.

Use while when:

  • You do not know how many times the block will run.

  • The stop depends on a dynamic condition, such as user input.

  • The loop needs to continue until something external happens.

Practical comparison

The same problem solved in both ways:

Counting from 1 to 5 with for:

for i in range(1, 6):
    print(i)

Counting from 1 to 5 with while:

i = 1
while i <= 5:
    print(i)
    i += 1

The for version is shorter and does not require the programmer to remember to increment i. The while version makes the condition explicit, but it also leaves room for errors such as forgetting the increment.

Asking for a password until it is correct — while is more natural:

correct_password = "python123"

while True:
    attempt = input("Password: ")
    if attempt == correct_password:
        print("Access granted.")
        break
    print("Incorrect password, try again.")

Here there is no way to know how many attempts the user will make. A for would require an arbitrary maximum number, which does not match the problem.

Rule of thumb

  • If the repetition depends on a sequence, use for.

  • If the repetition depends on a condition, use while.

When in doubt, prefer for. It is harder to get wrong, because it does not require you to manually manage the control variable.

Lesson wrap-up

In this lesson, you learned the for loop, saw the three forms of range() and how Python treats the upper bound (exclusive), iterated over strings with and without an index, and compared for and while to know when each one is more appropriate.

for is, in practice, the most used loop in daily work. It eliminates an entire class of common while errors — such as forgetting to increment the control variable or getting the stop condition wrong. Whenever the repetition involves a sequence, start by thinking of for.

In the next lesson, we will look at lists, the most used data structure in Python, and how to combine them with for to process collections of values.

Suggested exercise

Write a program that:

  1. Asks the user for a word.

  2. Uses for to walk through the word and count how many consonants it has (consider only letters, ignoring numbers and symbols).

  3. Also displays the word reversed, built character by character inside the loop, not using [::-1].

Hint: create an empty string before the loop and concatenate each character at the beginning of it. To count consonants, check whether the letter is in the alphabet and is not in the set of vowels.

📄 Copyright: Unless otherwise noted, all articles are original. Please cite the source when sharing.

🔗 Link: http://usandopy.com/en/python-para-iniciantes/for-e-range-loop-em-python/

Publicidade
Você ainda não está logado, por favor faça login ou registre-se para comentar
    0 pessoas participaram | 0 comentários
    Ainda não há comentários, fique à vontade para conversar!