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.

  • ANOVA (Analysis of Variance ) part 1

    A method to find a statistical relationship between two variables in a dataset where one variable is used to group data.

  • Basic plots with Seaborn

    Seaborn library has matplotlib at its core for data point visualizations. This library gives highly statistical informative graphics functionality to Seaborn.

  • Matplotlib in python

    The Matplotlib library helps you create static and dynamic visualisations. Dynamic visualizations that are animated and interactive. This library makes it easy to plot data and create graphs.

  • Plotly with Python and R

    This library is named Plotly after the company of the same name. Plotly provides visualization libraries for Python, R, MATLAB, Perl, Julia, Arduino, and REST.

  • Numpy Array

    Numpy array have functions for matrices ,linear algebra ,Fourier Transform. Numpy arrays provide 50x more speed than a python list.

  • NumPy: Python’s Mathematical Backbone

    Numpy has created a vast ecosystem spanning numerous fields of science.

  • Introduction to Pandas: A Guide

    Pandas is a easy to use data analysis and manipulation tool. Pandas provides functionality for categorical,ordinal, and time series data . Panda provides fast and powerful calculations for data analysis.

  • Pandas Dataframe in brief

    In this tutorial, you will learn How to Access The Data in Various Ways From the dataframe.

  • Exploring the World of Sets in Python

    Understand one of the important data types in Python. Each item in a set is distinct. Sets can store multiple items of various types of data.

  • A Beginner’s Guide to Immutable Tuples

    Tuples are a sequence of Python objects. A tuple is created by separating items with a comma. They are put inside the parenthesis “”(“” , “”)””.

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 !!