How To Make the For Loop In Python

In this tutorial, you will learn how to create and use for loops in Python. For loops are an essential part of programming, especially when you need to iterate through a sequence of elements or run a block of code a specific number of times. Python makes it easy to work with for loops, so let’s dive right in!

Step 1: Understand the Basic Structure of a For Loop

In Python, a for loop is created using the following syntax:

An iterable in Python can be any object capable of returning its elements one at a time, such as lists, strings, tuples, or dictionaries.

Let’s break down the components of this syntax:

  1. for – The keyword that begins the for loop.
  2. variable – A placeholder for the current element in the iterable during each iteration.
  3. in – The keyword to specify the iterable.
  4. iterable – The sequence of elements that will be iterated through.
  5. : – A colon to signify the beginning of the block of code that will be executed for each item in the iterable.
  6. The block of code – The indented block of code that will be executed for each item in the iterable.

Step 2: Write a Basic For Loop

As a simple example, let’s iterate through a list of numbers and print each number:

In this code, numbers is iterable (a list), and num is the variable that takes the value of each element in numbers. In each iteration of the loop, the value of num is printed.

Output:

1
2
3
4
5

Step 3: Use the Range() Function

Sometimes, you might want to iterate over a range of numbers. The range() function can be helpful in such cases:

Output:

0
1
2
3
4

The range(5) function generates a sequence of numbers from 0 to 4 (5 numbers in total). Note that the ending number (5) is not included in the range.

You can also specify a start and end number, and even a step, like this:

Output:

1
3
5

This code iterates through a range of numbers starting from 1 and ending at 6, with a step of 2.

Step 4: Iterate Through Other Types of Iterables

It isn’t just lists and ranges that you can iterate through. You can also use for loops to iterate through strings, tuples, and dictionaries.

Here’s how you iterate through a string:

Output:

H
e
l
l
o
,

w
o
r
l
d
!

Here’s how you iterate through a tuple:

Output:

apple
banana
cherry

And here’s how you iterate through a dictionary:

Output:

Alice - 90
Bob - 85
Charlie - 95

Full Code

Conclusion

In this tutorial, you have learned how to create and use loops in Python. You now know how to iterate through lists, ranges, strings, tuples, and dictionaries. Python’s for loop syntax is simple and easy to understand, making it a versatile and powerful tool in your programming toolkit.