For Loops

The Basics of: Python For Loops

If you’re a beginner for python and are still trying to master the basics, this tutorial can give you step by step instructions on how to write for loops, and what they’re used for in your programs.

If you’re experienced in other languages, you may already know the basic concept of loops: To repeat a certain event a certain amount of times. A simple example of the for loop in python is this:

Here we take the variable ‘i’ and use it to print the sentence 5 times. As you could tell, the range factor tells the range of how many times the task would be repeated. By default, the first value in the “range” is 0, but if you want, you can change it and instead do something like the following:

When doing this, the task inside the loop will be done 3 times, since the range between 2 and 5 is 3.

For loops can also be used to, for example, read through one at a time a list of words in a list. For example:

For absolute beginners, this might look a little complicated, but whats happening hear, is that by creating this variable ‘i’ for our loop, and saying that it’s representing the values in ‘MyList’, when we come back around in our loop, every time, it moves on to the next value in the list, or adds one.

For loops are used in a variety of complicated programs, and require logic and thinking to understand them, but with practice, the concept of for loops makes for easier and on-point programs.

Close Bitnami banner