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.

  • Tourism Trend Prediction

    After tourism was established as a motivator of local economies (country, state), many governments stepped up to the plate.

  • Sentiment Analysis Polarity Detection using pos tag

    Sentiment analysis can determine the polarity of sentiments from given sentences. We can classify them into certain categories.

  • For loop with Dictionary

    Traverse a dictionary with for loop Accessing keys and values in dictionary. Use Dict.values() and Dict.keys() to generate keys and values as iterable. Nested Dictionaries with for loop Access Nested values of Nested Dictionaries How useful was this post? Click on a star to rate it! Submit Rating

  • For Loops with python

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

  • Metrics and terminologies of digital analytics

    These all metrics are revolving around visits and hits which we are getting on websites. Single page visits, Bounce, Cart Additions, Bounce Rate, Exit rate,

  • Hypothesis Testing

    Hypothesis testing is a statistical method for determining whether or not a given hypothesis is true. A hypothesis can be any assumption based on data.

  • A/B testing

    A/B tests are randomly controlled experiments. In A/B testing, you get user response on various versions of the product, and users are split within multiple versions of the product to figure out the “winner” of the version.

  • For Loop With Tuples

    This article covers ‘for’ loops and how they are used with tuples. Even if the tuples are immutable, the accessibility of the tuples is similar to that of the list.

  • Multivariate ANOVA (MANOVA) with python

    MANOVA is an update of ANOVA, where we use a minimum of two dependent variables.

  • Two-Way ANOVA

    You only need to understand two or three concepts if you have read the one-way ANOVA article. We use two factors instead of one in a two-way ANOVA.

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