For loop in python

problem

We wish to repeat actions/ commands. One way is by using the built-in loop mechanisms of Python. In this post we will use the well-known for loop.

SOLUTION

The for-loop is usually preferable when we know exactly how many times we wish to iterate. For example, we want to iterate 5 times and print a number each time. For example:

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

				
			
running

In a terminal, issue the following command:

				
					python3 for_loop.py
				
			
output
				
					0
1
2
3
4
				
			

In the example above we used the range function in order to generate a range of numbers, hence the name. The range can be used in various ways.

iterating over a list

Let’s suppose we a list of numbers and we wish to print each item. We can easily plug the list in the for loop. For example:

				
					    numbers = [2, 11, -23, 89, 0, 466, 90]

    for x in numbers:
        print(x)

				
			
output
				
					2
11
-23
89
0
466
90
				
			
print only even numbers by iterating over a list

Now, let’s extend the example above and print only the even numbers from the list. Remember an even number is a number that can be exactly divided by 2 (no remainder).

For example:

				
					    numbers = [2, 11, -23, 89, 0, 466, 90]

    for x in numbers:
        if x % 2 == 0: # check if even
            print(x)

				
			
output
				
					2
0
466
90
				
			

By simply adding an if statement in the loop’s body, we can now print only the even numbers from the list.

conclusion

In this post we saw how we can simply use the built-in for-loop mechanism of Python and how to iterate over a range of numbers or a given list of numbers. Pretty cool! 🧑🏻‍💻🇵‌🇾‌🐍

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

Posted on: October 21, 2022
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x