Nested for Loops to Read a Csv File in Python
Introduction to Python Nested Loops
Welcome to another chapter in the Python learning class – Nested Loops. A great way to loop a loop, nested loops have proved their worth in every programming linguistic communication. Today, we volition exist focusing on Python specifically – the types, the syntax, and the examples. And so, let's go started.
Nested Loops
Information technology would be good to briefly touch base of operations upon Nested Loops in full general before proceeding with Python specifically. If a loop exists inside the body of another loop, information technology is termed as Nested Loop. This means that nosotros desire to execute the inner loop code multiple times. The outer loop controls how many iterations the inner loop will undergo. A basic example of a nested for loop is:
for (i=0; i<10; i++)
{
for (j=0; j<10; j++)
{
//This code will execute 100 times.
}
//This lawmaking will execute 10 times.
}
A thing to note here is that any type of loop can be nested inside another loop. For example, a while loop can be nested inside a for loop or vice versa.
Python Nested Loops
Allow us talk over more about nested loops in python.
1) Nested for loop Syntax
The basic syntax of a nested for loop in Python is:
for [iterating_variable_1] in [sequence_1]: #Outer Loop
for [iterating_variable_2] in [iterating_variable_1/sequence_2]: #Inner Loop
[code to execute]
Example:
for i in range(11): #line i
for j in range(i): #line two
print('*', finish='') #line 3
print('') #line 4
Output:
Execution Period
Allow's try to sympathize the execution menses of the above program. In the plan, we used ii iteration variables, i and j, to impress a pattern of stars.
The compiler begins with line 1. Information technology encounters a for loop and a range function. Python's range role outputs an iterable array of integer numbers from 0 to the number specified in the argument. The statement number is excluded from the assortment. In our example, it will generate an assortment [0, 1, 2, 3, 4, 5, 6, 7, 8, nine, 10]. At present, the compiler knows it must execute the next set of statements 10 times.
When it moves to line 2, information technology encounters some other for loop and range function. Note that the argument to this range office is a computed value of our iteration variable i. So, it dynamically generates an array depending on the value of i. When i=0, the array is empty. When i=1, array is [0]. When i=2, the array is [0, 1] and so on.
So, the number of times line three is executed direct depends on the value of i. Notice the part end='' inline 3. This is to prevent Python impress a linefeed after every star. We only want a linefeed at the end of every iteration of the outer loop. Thus, we have explicitly printed a linefeed in line four of our code.
And so now, let u.s. closely examine every iteration of our nested for loop.
Outer Loop Iteration 1
I = 0, j = [], output is a blank line.
Outer Loop Iteration 2
I = 1, j = [0], output = *
Outer Loop Iteration three
I = two, j = [0, one], output = **
Outer Loop Iteration 4
I = 3, j = [0, one, 2], output = ***
.
.
.
Outer Loop Iteration x
I = ix, j = [0, ane, ii, iii, four, 5, 6, seven, 8], output = *********
Outer Loop Iteration 11
I = 10, j = [0, 1, ii, three, four, five, 6, vii, 8, nine], output = **********
2) Nested while loop
Syntax
The syntax for nesting while loop in Python is:
while (expression_1): #Outer loop
[code to execute] #Optional
while (expression_2): #Inner loop
[code to execute]
Unlike the for loop, the while loop doesn't have a precompiled iterable sequence. While loop keeps executing the lawmaking until the expression evaluates to true. So, a developer has to always go on in mind to update the iterating variable/expression, or else the loop will enter infinite execution mode.
Instance
i=1 #line 1
while(i<=5): #line 2
j=5 #line iii
while(j>=i): #line four
impress(j, cease=' ') #line 5
j-=i #line half-dozen
i+=one #line 7
print() #line viii
Output:
Execution Flow
Line 1 of the lawmaking sets the outer loop'due south iterating variable to the initial value. The next line is the beginning of the outer while loop. Information technology has an expression I <=5. This expression is evaluated for true value afterward each iteration. The execution enters the loop just if the status is true. As soon as the condition becomes false, the loop is terminated.
Since the initial value of I is 1, the status in line 2 is true. So, the compiler moves to line 3 and sets our inner loop's iterating variable j to 5. Line 4 once more has a while loop with an expression that evaluates to truthful. And so, the compiler executes line 5 and 6. It and so moves back to line iv and evaluates the status. If the condition is true, it again enters line 5 and vi. If the condition becomes faux, the loop is terminated, and the next lines to execute are line seven and 8. The aforementioned is followed for the outer loop.
Line 6 and 7 are very important every bit they update our iterating variable. Without them, the program flow would enter infinite execution way as the while loop expressions would always consequence in truthy.
Should I suspension, proceed or pass
As with almost all other programming languages, Python has the concept of break and continues. These keywords help finish any loop or skip a particular iteration of the loop. Python also has another keyword – laissez passer. Let's take a expect at these.
1) Break
The break keyword indicates the compiler to spring out of a loop and cease its execution.
Example
for i in range(5):
for j in range(5):
if i == j:
interruption
impress(j, terminate='')
impress('')
Output:
The program to a higher place breaks the inner for loop if the value of I and j are equal. It does not execute further iterations of the loop. This can exist further understood with the continue statement.
2) Continue
The go on keyword indicates the compiler to skip the current iteration of the loop and continue with the side by side iteration.
Example
for i in range(5):
for j in range(five):
if i == j:
continue
print(j, end='')
impress('')
Output:
Notice that the same program, just with a continue argument instead of break, does not terminate the loop execution. It but skips the current iteration.
iii) Laissez passer
The laissez passer keyword is interesting in Python. It simply means do nix. It is used when the code block is needed syntactically, but you lot do not want any control to exist executed. It simply acts equally a placeholder.
Example
for i in range(5):
for j in range(v):
if i == j:
#I am not certain what to do when i equals j, so for now I volition pass.
pass
print(j, end='')
print('')
Output:
Conclusion
Loops are strategically very important to learn to perform a job with minimal lines of code. This is just a basic introduction to loops. It is recommended to play effectually more, go artistic and explore the potential of loops farther.
Recommended Articles
This is a guide to Python Nested Loops. Hither we discuss the Python Nested Loops with the Syntax, Examples, Output and Execution Period in item. You may besides expect at the following article to learn more –
- Python Frameworks
- Install Python
- Loops in Python
- Nested Loop in Java
Nested for Loops to Read a Csv File in Python
Source: https://www.educba.com/python-nested-loops/