Menu
Coddy logo textTech

For Loop

Part of the Fundamentals section of Coddy's Python journey — lesson 35 of 77.

Sometimes when programming, it's necessary to perform the same or almost the same operation a couple of times.

To prevent writing the same thing over and over again, we can use loops.

The for loop has the following syntax:

for i in range(start, end):
    code

The range(start, end) determines what is the start value and what is the end value. The i will receive all values from start to end (not including end) sequentially. For example:

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

It will execute the print statement 5 times:

0
1
2
3
4

We can simplify the range(0, 5) to range(5):

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

You can also combine i with other text using an f-string. Place an f before the string and use {i} inside it to insert the value of i:

for i in range(1, 4):
	print(f"Item number: {i}")

This will print:

Item number: 1
Item number: 2
Item number: 3

Loops have many use cases. For example, let's sum all the numbers from 1 to 100:

sum_numbers = 0
for i in range(1, 101):
	sum_numbers += i
print(sum_numbers)

This will first loop through all numbers between 1 and 101 (not including 101) and sum all of them. Then it will print the sum_numbers variable.

challenge icon

Challenge

Beginner

Write a program that prints "Hello Coddy: " and the i value from 3 to 27 (both numbers inclusive), using a for loop.

This means you'll print 25 lines in total, starting from 3 and ending at 27.

The output will look like this:

Hello Coddy: 3
Hello Coddy: 4
...
Hello Coddy: 27

Cheat sheet

The for loop in Python is used to iterate over a sequence:

for i in range(start, end):
    # code to be executed

Key points about range():

  • range(end): Starts from 0, goes up to (but not including) end
  • range(start, end): Goes from start to (but not including) end

Example of a for loop:

for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals