for loops in Python

A for loop is used to repeat a code over lists, data types, dictionaries, sets, or even strings.

The for loop will go into the specified list and run the code for each item on the list.

Example:

In this example, we are going to use a for loop to print Hello world! 5 times just as we did with the while loop. Copy this code in the Visual studio code:

my_list = [1, 2, 3, 4, 5]
for _ in my_list:
    print ("Hello world!")

This worked, didn’t it?

Code explained: We have a list and there are 5 numbers in the list for the number of times we want the code to repeat. Now, we tell Python that for every character in this list, print Hello world! That means the program will display Hello world 5 times.

How about another example? In this case, we want to explore. We will create a list of all the even numbers between 1 and 10.

Use this code:

even_numbers = []
for i in range (1, 11):
    if i % 2 == 0:
        even_numbers.append(i)
print ("Even Numbers: ", even_numbers)

Code explained: we used the range () function in this code. The work of this function is to return a sequence of items from a list or from math. In this case, the range is from 1 to 10. And you remember how we created the program that returns even numbers and drops the results in a new empty list? There you go.

We can also create an infinite loop with a for loop in Python. Let’s take an example:

number = [0]
for i in number:
    print(i)
    number.append(i+1)

This will continue running forever!

Code explained: We created this infinite loop by using a for loop when we append a new element to the list after every repetition. This means it will continue to add +1 every split second till infinity!

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials