Courseiva
PCEP-30-02Chapter 9 of 16Objective 3.4

For Loops and the range() Function

A for loop is a way to tell your computer to do the same thing multiple times without you having to write the instruction over and over. It is essential for the PCEP-30-02 exam because you will need to write code that repeats actions a specific number of times or over a sequence of items, and the range() function is the tool that defines that sequence clearly.

12 min read
Intermediate
Updated Jul 24, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture For Loops and the range() Function

The Assembly Line Checker Analogy

An assembly line at a chocolate factory has a conveyor belt. The belt carries a fixed number of chocolate boxes past a quality-check station. The station worker checks each box one at a time, in order. They do not skip a box, and they do not check a box twice. Once they have checked all the boxes on that run, they stop and wait for the next batch.

A for loop works like that assembly line. The 'range()' function is the conveyor belt itself. It creates a numbered sequence — the positions of the empty boxes waiting to be filled. The 'for' keyword is the worker. It picks up each number from the sequence, one by one, and does the task you have given it with that number. For example, 'for i in range(5): print(i)' is like saying: for each box spot numbered 0 through 4 on the belt, write that number on a label. The belt produces five spots: 0, 1, 2, 3, 4. The worker handles each one exactly once. When the belt is empty of those five spots, the worker stops and the programme moves on.

This is specific to for loops and range() because the belt (range()) defines exactly how many items there are and in what order they arrive. A while loop would be like a worker who keeps checking boxes until a red light turns off — they do not know how many boxes there are. The for loop with range() gives you control and certainty about the sequence length, just like the factory manager setting exactly five boxes on the belt.

How It Actually Works

A for loop is a programming structure that repeats a block of code for each item in a sequence. It is one of the two main types of loops in Python, the other being the while loop. The for loop is particularly useful when you know in advance how many times you want to repeat something, or when you have a collection of items (like a list or a string) and you want to process each item one by one. The range() function is a built-in Python tool that generates a sequence of numbers. When you use range() inside a for loop, you create a perfect setup for repeating an action a set number of times.

Here is the basic syntax: for variable_name in range(stop): print(variable_name)

The word 'for' starts the loop. The 'variable_name' is a new name you choose (often 'i' for 'index') that will hold each number from the sequence, one at a time. The 'in' keyword connects the variable to the sequence. The 'range()' function creates the sequence of numbers. The colon (:) at the end tells Python that an indented block of code follows. That indented block is the 'body' of the loop — the instructions that run for each number. A common mistake beginners make is to use the variable name in the loop incorrectly. For example, writing 'for 5 in range(5):' is wrong because the variable must be a name, not a number.

The range() function has three different ways you can use it:

range(stop): Generates numbers from 0 up to, but not including, the stop value. So range(5) gives you 0, 1, 2, 3, 4. It always starts at 0 by default.

range(start, stop): Generates numbers from the start value up to, but not including, the stop value. For example, range(2, 7) gives you 2, 3, 4, 5, 6.

range(start, stop, step): Generates numbers from the start value up to, but not including, the stop value, incrementing by the step value each time. The step can be negative to count downwards. For example, range(10, 0, -2) gives you 10, 8, 6, 4, 2.

Why does this matter? Before for loops existed, programmers had to use goto statements or while loops with manual counters, which were error-prone and hard to read. The for loop combined with range() gives you a clean, readable way to say 'do this N times'. For example, to print 'Hello' five times, you can write: for i in range(5): print('Hello') Notice that you do not even have to use the variable 'i' inside the loop. The loop will still run five times. The variable 'i' is still assigned numbers 0, 1, 2, 3, 4 in turn, but you can ignore it. This is powerful because you can use that variable to do something different on each iteration. For instance: for i in range(1, 6): print(f'This is repetition number {i}') This will print 'This is repetition number 1', then 'number 2', and so on up to 5. The f-string (a way to insert variables into a string) uses the current value of 'i'.

Here is something the PCEP exam loves to test: the number of iterations. How many times does a loop with range(5) run? Exactly 5 times, because it produces 5 numbers (0 through 4). How many times does range(2, 2) run? Zero times, because the start is equal to the stop, so no numbers are generated. How many times does range(10, 5) run? Also zero, because the start is greater than the stop and you have not given a negative step. The default step is +1, so you cannot go from a larger to a smaller number without explicitly setting step to a negative value. This trips up many beginners.

Another key concept is that the loop variable (like 'i') is reassigned each time through the loop. After the loop finishes, the variable retains its last value. For example: for i in range(3): pass print(i) # This prints 2

This can be useful but also a source of confusion. If you use the variable outside the loop, it will have the final value from the last iteration.

The range() function is lazy in Python 3. This means it does not create a list of all the numbers in memory. Instead, it produces each number on demand as the loop iterates. This is efficient for large ranges like range(1000000) because it does not store a million numbers. For the PCEP exam, you do not need to understand the internal mechanism of laziness, but you should know that range() returns an object of type 'range', not a list. You can convert it to a list with list(range(5)), but that is not required for the loop to work.

Finally, remember that the indentation matters in Python. The body of the for loop must be indented, typically by four spaces. Any code at the same indentation level as the 'for' statement will run after the loop completes, not inside it. This is a common point where beginners lose marks on the exam. Always check your indentation carefully.

This diagram shows the flow of control in a for loop with range(): the loop fetches each number from the range sequence, executes the body, and continues until no numbers remain.

Walk-Through

1

Write the 'for' keyword and choose a variable name

Start your loop with 'for' followed by a variable name you choose (commonly 'i', 'j', or 'index'). This variable will store each number from the range sequence one at a time during each iteration.

2

Add the 'in' keyword and call range()

After the variable, write 'in' and then range() with the appropriate arguments. This tells Python where the sequence of numbers comes from. For example, 'for i in range(5):' establishes that i will take values 0,1,2,3,4.

3

End the line with a colon

The for statement must end with a colon. This colon signals that an indented block of code follows. Forgetting the colon is a syntax error and a common exam trap.

4

Indent the loop body

Press Tab or Space to indent the next line(s) by four spaces. All lines you want to repeat must have exactly the same indentation. Python uses indentation to determine what code belongs to the loop.

5

Write the code to execute each iteration

Inside the indented block, write the actions you want to repeat. You can use the loop variable here. For example, 'print(i)' will show the current number. Each iteration, Python executes this block with the next value from range().

6

Run the loop and observe the output

When the programme runs, Python sets the variable to the first number from range(), executes the body, then sets it to the second number, executes the body, and so on until all numbers are used. After the last iteration, the programme moves to any code after the loop.

What This Looks Like on the Job

Consider a small business that sends personalised email reminders to customers. Every morning, an IT worker writes a script to send the first 10 reminder emails from a list of 20. They need the script to handle exactly 10 customers, one after the other, without manual intervention. A for loop with range() is the perfect tool for this task.

Here is how the IT professional would approach it:

They know the customer list is stored in a Python list called 'customers'.

They need to process customers[0] through customers[9] (the first 10).

They write: for i in range(10):

Inside the loop, they use 'customers[i]' to get the current customer's email address.

They then call a function to send the email.

They also log which customer number was processed using the value of 'i'.

The IT worker does not have to write the same email-sending code ten times. The for loop does the repetition automatically. If the manager later says 'We need to process the first 50 customers instead of 10', the IT worker simply changes 'range(10)' to 'range(50)'. That is the power of using range() with a for loop.

Another real-world scenario is data validation. A database administrator has a file with 500 rows of data. Each row must be checked for missing fields. The administrator writes a for loop with range(500) to iterate over each row index. Inside the loop, they check if a certain field is empty. If it is, they add that row's index to an error log. This is far more efficient than manually scanning each row.

For IT professionals who work with automation, for loops and range() appear in tasks like:

Generating test data for a fixed number of test cases

Iterating over a subset of a list (e.g., the first 20 items using range(20))

Performing an action a specific number of times that is determined by user input

Creating a countdown timer using range() with a negative step

The step parameter is particularly useful in data processing. Suppose you have a list of sensor readings taken every minute for an hour, but you only want to process the readings taken at the top of each hour. You could use for i in range(0, 60, 60): which gives only index 0. More practically, to process every third reading, you use for i in range(0, len(readings), 3):. This selective processing is a common requirement in data analytics scripts.

In summary, an IT professional uses for loops with range() daily to automate repetitive tasks that involve a known range of numbers or indices. It is the foundation of iteration control in Python, and mastering it is crucial for the PCEP exam and for real-world scripting.

How PCEP-30-02 Actually Tests This

The PCEP-30-02 exam tests your understanding of for loops and the range() function thoroughly. You will face multiple-choice questions that assess both syntax and logic. Here is exactly what to expect and how to prepare.

The exam focuses on these specific topics:

Correct syntax of the for loop: 'for variable in range(...):' with correct colon and indentation.

The default starting value of range(): 0, not 1.

The exclusive nature of the stop value: range(5) produces 0,1,2,3,4 — it does NOT include 5.

Using range() with two arguments (start, stop) and three arguments (start, stop, step).

The effect of a negative step in range().

How many times the loop body executes given a specific range() call.

What happens when start >= stop with positive step (zero iterations).

Using the loop variable inside the loop body.

The behaviour of the loop variable after the loop ends.

Common traps the exam sets include:

Asking how many times a loop runs: e.g., 'for i in range(2, 2):' runs 0 times. Many beginners guess 1 or 2.

Giving a range() call with a negative step but forgetting to set start > stop: e.g., 'range(5, 1)' runs 0 times because default step is +1. To count down, you need 'range(5, 1, -1)'.

Showing indentation errors in the answer options: only one option will have the colon and proper indentation.

Testing whether the value of 'i' after the loop is the last value or an uninitialised variable. Remember, 'i' retains its last value.

Confusing the number of items produced by range() with the final number itself. For 'range(0, 10, 3)', it produces 0, 3, 6, 9 — that is 4 iterations, not 10.

Key definitions to memorise:

Range: A built-in function that generates a sequence of numbers. It is immutable and efficient.

For loop: A control structure that iterates over a sequence, executing its body once per item.

Iteration: Each single execution of the loop body.

Loop variable: The variable that takes on each value from the sequence in turn.

Exclusive end: The stop value is never included in the sequence.

You should practise writing small loops on paper. The exam may show you a code snippet and ask what it prints. For example: result = 0 for i in range(1, 4): result = result + i print(result) The correct answer is 6 (1+2+3). Show your working. Another common question: 'What does range(5, 0, -1) produce?' Answer: 5, 4, 3, 2, 1. Notice that 0 is excluded because it is the stop value.

Finally, the exam may test your understanding of nested loops (a for loop inside another for loop) but only at a basic level. Focus on the behaviour of range() in single loops first. Nested loops are a separate objective, but understanding the simpler case is essential before attempting the complex one.

Key Takeaways

A for loop repeats a block of code once for each item in a sequence, and range() is the sequence generator for numbers.

range(stop) produces numbers from 0 up to but not including stop, so range(5) gives 0, 1, 2, 3, 4.

range(start, stop) produces numbers from start up to but not including stop with a default step of +1.

range(start, stop, step) produces numbers from start to stop skipping by step, and step can be negative to count down.

If start equals stop with a positive step, the range is empty and the loop body runs zero times.

The loop variable retains its last value after the loop ends and is accessible in the code that follows.

Changing the loop variable inside the loop does not affect the sequence of values from range().

The colon after the for statement and the indented body are required syntax that the exam strictly tests.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

for loop with range()

Used when the number of iterations is known in advance

Sequence is generated automatically by range()

Less risk of infinite loops because the sequence has a fixed end

while loop

Used when the number of iterations depends on a condition

Requires manual counter variable and increment

More risk of infinite loops if the condition never becomes false

range(5)

Produces 0,1,2,3,4

Starts at 0 by default

Often used when indexing a list from the start

range(1, 6)

Produces 1,2,3,4,5

Starts at a specified start value of 1

Often used when counting from 1, like numbering tasks

range(10, 0, -1)

Counts downwards from 10 to 1

Requires a negative step

Produces 10 numbers: 10 to 1

range(0, 10)

Counts upwards from 0 to 9

Uses default positive step of 1

Produces 10 numbers: 0 to 9

Watch Out for These

Mistake

range(5) produces the numbers 1,2,3,4,5

Correct

range(5) produces 0,1,2,3,4

Because many beginners assume counting starts at 1, but Python starts at 0 by default.

Mistake

The loop variable 'i' can be modified inside the loop and that will change the number of iterations

Correct

Changing 'i' inside the loop does not affect the next value assigned to i. The sequence is predetermined by range() at the start.

This happens because beginners think the loop works like a while loop where a counter is manually updated. In a for loop, the range sequence is fixed.

Mistake

range(10, 5) will count backwards and produce 10,9,8,7,6,5

Correct

range(10, 5) with only two arguments defaults to step=+1, so it produces no numbers because start > stop with a positive step.

People assume range() automatically reverses if start is larger than stop, but it requires an explicit negative step.

Mistake

Using range(3) inside a for loop will create a list [0,1,2] in memory

Correct

In Python 3, range() is lazy and does not create a list. It generates each number on demand.

This misconception stems from Python 2, where range() did return a list. Beginners who learn from older resources may carry this confusion.

Mistake

The loop variable 'i' only exists inside the loop, so it cannot be used afterwards

Correct

The loop variable is accessible outside the loop after it completes. It holds the last value from the sequence.

In some other languages, loop variables are scoped only to the loop. Python is different, and this catches newcomers off guard.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

Why does range(5) give me 0,1,2,3,4 instead of 1,2,3,4,5?

Python starts counting at 0 by default because it mimics how computers index memory. If you need to start at 1, use range(1, 6) which gives 1,2,3,4,5.

What happens if I use 'for i in range(10, 5):' with no step?

It produces an empty sequence because the default step is +1, and you cannot go from 10 to 5 going up. The loop runs zero times.

Can I change the loop variable inside the loop to skip an iteration?

No, changing the loop variable does not affect the next value assigned by the loop. The sequence from range() is fixed at the start.

Is range() a list or a tuple?

It is neither. In Python 3, range() returns a range object, which is a lazy sequence. You can convert it to a list with list(range(5)) if needed.

How do I count backwards using range()?

Use a negative step. For example, range(10, 0, -1) gives 10, 9, 8, 7, 6, 5, 4, 3, 2, 1. Remember the stop value is exclusive, so 0 is not included.

What is the difference between a for loop and a while loop?

A for loop is best when you know how many times to iterate (e.g., range(5)), while a while loop runs as long as a condition is true, suitable when you do not know the exact number of iterations in advance.

Terms Worth Knowing

Keep going

You've finished For Loops and the range() Function. Continue through the PCEP-30-02 study guide to build a complete picture of the exam.

Done with this chapter?