For Loops in Python



Python


In this article, we explain for loops in Python.

There are basically 2 ways to formulate for loops in Python.

There is a for loop that deals with each element of data one by one in succession with no exception with no integer involvement, and there is a for loop that deal with integers.

We will explain this now below.

So let's say you have a list and you want to loop through this list one by one.

Let's say that this is the following list, students=["Tom", "Bill", "Bradley, "Michael"]

Let's say that we just want to print out all of the elements of this list on separate lines.

The following code would do the job.



This for loop just goes through each element of the list and prints out each element of the list.

Notice there is no integer involement.

Now let's say we want to print out the list like this:

Student 1: Tom
Student 2: Bill
Student 3: Bradley
Student 4: Michael


The above for loop wouldn't work, because it has no integer succession.

For this, you would need to modify the for loop.

The for loop would have to include the in range keyword.

This is shown below.



So, this is the for loop we must now use.

When you're using the in range function, the first parameter entered in is number that you want the for loop to begin from. The second parameter is where you want the loop to end. And an optional hird parameter is how much increment or decrement you want in between elements. For example, if you want to count by 2, you would specify a third parameter of 2.

If you're going through every element in a for loop, you always want to begin the for loop with 0. Because the first element in a list is always 0.

If you want to go through the entire loop, you can either manually count all of the elements in the list and place this number as the second parameter of the range() function, or you can just put, len(students). This counts the number of elements in the list. Being that you want to go through each element, we don't specify a third parameter which, by default, is 1.

Realize that in the range() function in Python, the first parameter is inclusive and the second parameter (where the range ends is exclusive.

So, in this case, 0 is inclusive. And the length of the students list, which is 4 is exclusive.

So, the for loops goes from 0 to 1 to 2 to 3. It begins at 0 and ends at 3.

So, we have our list named students.

We then have our for loop.

Based on this for loop, we print out "Students" followed by, str(i+1). What str(i+1) does is start the count at 1, so that we get Student 1: as the first line.

We then add a colon and then we have students[i], which prints out the student names.

So, these are the 2 types of for loops in Python.

These will cover how to loop through all data types in Python.


Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python



HTML Comment Box is loading comments...