For loop in python

In this tutorial, you will learn about how work for loops in Python and how to ... Loops can be nested for loop in python as they can with other programming languages. For loop is used for iterating of sequence of list,etc. It is not like for keyword in other programming language. Works as an iterator method found in oop language. By using for loop we can execute set of statements each item in list,etc For using for loop the value range should be given. You probably expect the “for” component in for loop refer that you do something for many times. The loop is programming concept that when implemented it executes a piece of code over again and again for no of times in a sequence. In the for loop variable to be iterated is used in an sequential manner.

 

python for loop syntax :-

For val in sequence:
Body of for
In the above syntax “val” is the variable that takes value of item inside each iteration.
The for loop continues until it reach last statement in program.
Flowchart of for Loop in Python programmingFlowchart:-

 

 

 

 


Example:-
For x in range (4):
 Print(x)
O/p:-
0,1,2,3
The loop will be continued in sequence of values.
In the above example the value of x is 4 so when the for loop start it will start displaying list of numbers from 0, 1, 2 and end at 3 last.

Nested for loop in python :-

If for loop is present Inside another for loop then called as nested for loop.
Loops can be nested as they are present with other programming languages.
During the execution of the nested for loop it will start from first iteration.
Then the first iteration will trigger inner nested loop and runs completion of loop.
Next the program returns to the top of the outer loop, complets the second iteration then trigger the nested loop. The process will be continued until the sequence is complete.
Nesting for loop means simply having a loop outer that has inside its commands inner loop.
The nested loop is also called as a loop inside a loop.
The inner loop will be executed one time each iteration of outer loop.

Nested for loop Syntax :-

For[first variable] in [outer loop]:
[do something]
For[second variable] in [Nested loop]:
[do something]
In the above syntax the first encounter outer loop executes first iteration.
This first iteration trigger inner nested loop which then runs to completion.
Then program again return back to top of the outer loop completions the second iteration and trigger the nested loop.
Again nested loop run to completion and program return back to outer loop in sequence after completion it will break.

 

Nested for loop Example

adj = ["yellow", "small"]
Fruits = ["banana", "apple"]
for x in adj:
for y in fruits:
 print(x, y)

O/p:-


Yellow banana
Yellow apple
small banana
small apple

Additional Services : Refurbished Laptops Sales, Python Classes, Share Market Classes And SEO Freelancer in Pune, India