For Loops with python

For loop is one of the most useful methods to reuse a code for repetitive execution.

For loop is one of the most useful methods to reuse code for repetitive execution. This loop is very common in computer languages, but when it comes to Python, there are significant improvements in the for loop more than in other languages. For loops run a code in a loop until given conditions are met.

The basic structure of for loop

In the following code implementation, you can see the basic structure of the for loop. We are iterating through the list “num” from 1 to 10.

Python
Python
Python
num=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in num:
    print(i)
Output
1
2
3
4
5
6
7
8
9
10
Python

If you compare this loop with c++/c/ java languages, you will see one difference that makes these codes more complex and lengthy.

Java implementation of for loop

Python
Python
Python
import java.io.*;
class forward_loop{
    public static void main(String args[])
    {
        int list[]={1,2,3,4,5,6,7,8,9,10};
        int count=0;
        for (int i=0;i<10; i++){
            count=count+1;
            System.out.println(list[i]+" ");
        }
    }
}

C++ Implementation of for-loop

Python
Python
Python
using namespace std;
int main()
    {
        int list[5]={1,2,3,4,5,6,7,8,9,10}
        for (int i=0;i<10;i++)
        {
            cout << list[i] << "\n";
        }
        return 0;
    }

Observe the difference between these codes and Python code. Python code has only 3 lines and is fairly understandable. Java and C++ codes span over 10 lines and may look ambiguous to a newcomer.

Range Function

The range is an independent function, but it is popularly used for loops. It creates an iterable number generator with given parameters.

Range function has 3 arguments ”range (start, stop, step)”. It can operate with 1 stop argument. By giving a stop argument, the range will iterate over 0 to stop.

range(0,10,2)

The range can operate with a minimum of 1 argument. Remember that range does not return a list. It returns numbers per cycle.

Python
Python
Python
list(range(0,10,2))
Output
[0,2,4,6,8]
Python
Python
Python
Python
num=[1,2,3,4,5]
for i in range( 5 ):
    print(num[i])
Output
1
2
3
4
5
Python

It can operate with 2 arguments (start, stop). By giving these arguments, the range will iterate from start to stop.

Python
Python
Python
for i in range(1,5):
    print(i)
Output
1
2
3
4
Python

It can operate with 3 arguments (start, stop, step). By giving these arguments, the range will iterate from start to stop and with skip numbers with each step.

Python
Python
Python
for i in ranage(0,10,2):
    print(i)
Output
0
2
4
6
8
Python

List comprehension with For

Let’s vary the look of the output with simple in changes in print. Using the end parameter cancels out the new line that executes with every print statement.

Python
Python
Python
num=[x for x in range(5)]
for i in num:
    print(i,end=' ')
Output
0 1 2 3 4
Python
Python
Python
Python
num=[x for x in range(5)]
for i in num:
    print(i,end='\t')
Output
0    1    2    3    4
Python

For loop with Strings

Python
Python
Python
string='the quick browm fox jumps over the lazy dog'
for i in string:
    print(i,end='')
Output
the quick browm fox jumps over the lazy dog
Python

Continue Statement

We can use continue to end and start a new iteration in the for loop rather than executing the remaining body of code in the loop.

In the following example, we don’t want to print 4. So we skip if 4 occurs in x by using the continue statement.

Python
Python
Python
even=[x for x in range(10) if x%2==0]
print(even)
for x in even:
    if x==4:
        continue
    print(x)
Output
0
2
6
8
10
12
14
16
18
Python

Pass Statements

We mostly use a pass statement in place of a code for the continuation of execution. If a scope of a function has no statement body, we can use pass in that scope to avoid any errors.

Python
Python
Python
for i in even:
    pass

Observe in the following code there is no statement body of if, by using pass we are continuing to execute for loop.

Python
Python
Python
for i in even:
    if i>0:
        pass
    print(i)
Output
0
2
4
6
8
Python

Nested For loops

Using a loop inside another loop, Scope creates a nested loop. By using nested loops, we can handle problems with complex and multiple recursive operating structures. It also gives the power to operate over matrix-like structures of lists that are Multi-Dimensional lists.

Python
Python
Python
a = [[1,3,5,7],
     [2,4,6,8],
     [8,6,4,2],
     [7,5,3,1]]
for i in a:
    print(i)
Output
[1, 3, 5, 7]
[2, 4, 6, 8]
[8, 6, 4, 2]
[7, 5, 3, 1]
Python

Let’s perform a multiplication operation on a diagonal row in a matrix.

Python
Python
Python
for i in range(len(a)):
    for j in range(len(a[i])):
        if i==j:
            a[i][j]*=20
        print(a[i][j],end=' ')
    print()
Output
20 3 5 7
2 80 6 8
8 6 80 2
7 5 3 20
Python

For loops with Else

The else block in a for-loop executes only if the loop has completed all of its iterations. If the iterations are interrupted in the for-loop, the else block won’t be executed.

no break

Python
Python
Python
for i in range(1,4):
    print(i)
else:
    print("No Break")
Output
1
2
3
No Break
Python

with Break

Python
Python
Python
for i in range(1,4):
    print(i)
    break
else: # Not executed as there is a break
    print("No Break")
Output
1
Python

How useful was this post?

Click on a star to rate it!

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • Manova Quiz

    Solve this quiz for testing Manova Basics

  • Quiz on Group By

    Test your knowledge on pandas groupby with this quiz

  • Visualization Quiz

    Observe the dataset and try to solve the Visualization quiz on it

  • Versions of ANCOVA (Analysis Of Covariance) with python

    To perform ANCOVA (Analysis of Covariance) with a dataset that includes multiple types of variables, you’ll need to ensure your dependent variable is continuous, and you can include categorical variables as factors. Below is an example using the statsmodels library in Python: Mock Dataset Let’s create a dataset with a mix of variable types: Performing…

  • Python Variables

    How useful was this post? Click on a star to rate it! Submit Rating

  • A/B Testing Quiz

    Complete the code by dragging and dropping the correct functions

  • Python Functions

    Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…

  • Python Indexing: A Guide for Data Science Beginners

    Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.

  • Diffusion Models: Making AI Creativity

    Stable Diffusion Models: Where Art and AI Collide Artificial Intelligence meets creativity in the fascinating realm of Stable Diffusion Models. These innovative models take text descriptions and bring them to life in the form of detailed and realistic images. Let’s embark on a journey to understand the magic behind Stable Diffusion in a way that’s…

Leave a Reply

Points You Earned

Untitled design 6
0 distinction_points
Untitled design 5
python_points 0
0 Solver points
Instagram
WhatsApp
error: Content is protected !!