Tutorial: The Basics of Python "For Loop".

Tutorial: The Basics of Python "For Loop".

In this tutorial, we will learn about Python's for loop and different simple statements and functions that generally use in for loop.

The looping simplifies complex problems. Instead of writing the same code, again and again, we can repeat the same code a finite number of times using loops. When you're working with data in Python, for loop can be a powerful tool.

In this tutorial, we will learn about Python's for loop and different simple statements and functions that generally use in the for loop.

What are For Loops?

A for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly.

In the context of most data science, the for loop is used to iterate over the elements of iterable objects (such as a string, tuple, or list). and perform some action for each entry. for example, a for loop would iterate through a list, performing some action on each item in the list.

An iterable object is any Python object that we can iterate through, or "loop" through, and return a single element at a time.

You can create a for loop by using the following syntax:

for var in sequence:
    statements

Here, 'var' is a variable that is used for iterating over a sequence. it takes the value of the item inside the sequence on each iteration. This variable can actually be called almost anything. Python will interpret any variable name we put in that spot as referring to each list entry in sequence as the loop executes.

Loop continues until it reaches the last element in the sequence.

Let's look at a quick example: if we had a list of numbers stored in Python, we could use a for loop to iterate through that list, printing each number until it reaches the end of the list.

Let's create a list of numbers and then use for loop that iterates through it and prints each entry on the list in sequence.

number_list = [1, 2, 3, 4, 5]
for num in number_list:
      print(num)

Output

1
2
3
4
5

So, in the code above:

num points to 1 on the first iteration of the loop.. then 2 on the second iteration of the loop.. and so on. Note that the iterable object in the above code example is a list object, but it could be any other iterable object such as a string.

For example:

string = 'Python'
for char in string:
     print(char)

Output

P
y
t
h
o
n

So, in the above example, we could see that we can use the same for loop to iterate through each character in a string.

Other Useful Statements: Range, Break, and Continue

range() function

For loops can be used with Python’s range() function to iterate through each number in a specified range.

For example:

for i in range(1, 5):
     print(i)

Output

1
2
3
4

Python doesn't include the maximum value of a range count, which is why the number 5 doesn't print in the above code.

The range creates a range object and this must be converted to a list if you want to use it as one.

when the range is called with two arguments as range(start, stop), it produces an object with the values from start to stop -1.

if you called range with just one argument, Let's consider it n, then it will return an object with the values from 0 to n-1.

for i in range(3):
     print(i)

Output

0
1
3

You can even add a third argument to the range() function to specify the step between two numbers. As you can see the default value is 1, but if add the third argument of 2, for example:

for i in range(1,10, 2):
      print(i)

Output

1
3
5
7
9

Break

By default, a Python for loop will loop through each possible iteration of the iterable object you've assigned it. But sometimes we may want to stop the loop if a certain condition is met. In that circumstances, the break statement is very useful.

The break statement terminates the loop containing it. Control of the program moves out of the for a loop once the break statement executed. Program counter will point towards the statements immediately after the for a loop.

If the break statement is inside a nested loop, the break will terminate the innermost loop.

For example:


for num in number_list:
      if num == 3:
          break
      print(num)

Output

1
2

In the above program, for loop runs and print the value of i until the i is not equal to 3, as soon as the value of i is equal to 3, which makes if condition True then if block executes the break statement making program counter moves out of the loop.

continue Statement

Another statement that can be used within loops is continue. A continue statement skips the remaining lines of code inside a loop and starts the next iteration. Unlike break, continue jumps back to the top of the loop, rather than stopping it.

for num in number_list:
    if num == 3:
        continue
    print(num)

Output

1
2
4
5

In the above code, When Python sees continue while executing a for loop on a list, it stops at that point and moves on to the next item on the list. Hence, we see in the output that all the numbers except 3.

The difference between break and continue is :

  • break ends the loop entirely. When Python executes break, the for loop is over.

  • continue ends a specific iteration of the loop and moves to the next item in the list. When Python executes continue it moves immediately to the next loop iteration, but it does not end the loop entirely.

Hopefully, this tutorial helps you to understand for loops in Python. for loop can be useful for common data science tasks like data cleaning, data preparation, and data analysis.

Thank you for reading, See you in my next blog :)

Did you find this article valuable?

Support Madhuri's blog by becoming a sponsor. Any amount is appreciated!