‘For’ loops in Python are used for iterating over a sequence. The sequences can vary from being list, tuple or dictionary. The ‘for’ loop can be used to iterate once for each item of the list, tuple, etc. Indexing is not necessary for any variable in case of the ‘for’ loop.
Here is an example demonstrating the use of the Python.
Program = ["Python", "Ruby", "C"] for x in Program: print(x)
Python Ruby C
If you want enrich your career and become a professional in python, then visit Mindmajix - a global online training platform : "python course" This course will help you to achieve excellence in this domain
‘for’ loop in Python is used for iterating over a sequence or any other objects which are iterable. Whenever the iteration is done over any sequence, the process is called traversal.
Syntax of ‘for’ loop
For val in sequence:
Body of for
In this syntax, ‘val’ is the variable which accesses the value of each item of the sequence. The Looping will be done until all items of the sequence are iterated. Indentation is used to separate the block of code of ‘for’ loop from the rest of the code
As represented by the flowchart, the loop is exited if all the items have been processed. If they are not, then the loop is continued until all the items have been processed.
Example of Python ‘for’ loop
numbers = [5, 2, 3, 7, 1, 9] sum = 2 forval in numbers: sum = sum+val print("The sum is", sum)
Here is an example of the ‘for’ loop.
The sum is 29
[Related Page: Introduction To Python]
The range() function (small description with one example)
Generation of sequence is possible along with the usage of ‘range()’ function. It is also possible to define the stop, start, and step size of this function. The format of specifying them is ‘range(start,stop,step size)’.
Through this, we will simply get the range.
If we require the result in the form of the list, it can be done by forcibly using the list function.
[0, 1, 2, 3, 4]
The ‘else’ block can also be used along with python ‘for’ loop list. This block is optional and is executed only after all the items of the python ‘for’ loop list exhaust.
‘break’ statement is used for disrupting the normal flow of the ‘for’ loop. In this case, the ‘else’ part of the loop will be ignored, and if there will be no break of ‘for’ statement, then the ‘else’ part will execute.
sequence = [0, 1, 2, 3, 4] for i in sequence: print(i) else: print("No element left.")
0 1 2 3 4 No element left.
[Related Article: Regular expression operations]
Break statement is used to disrupt the normal flow of the ‘for’ or ‘while’ loop and in order to exit it.
count = 1 while True: print(count) count += 2 if count >= 5: break
The ‘continue’ statement is used to continue the normal flow of the loop after meeting the argument. The ‘python if’ statement is used to specify the condition.
for i in range(1,10): if i == 3: continue print (i)
1 2 4 5 6 7 8 9
It is also possible to nest loops in Python.
for x in range(1, 5): for y in range(1, 5): print (x, y, x*y)
1 1 1 1 2 2 1 3 3 1 4 4 2 1 2 2 2 4 2 3 6 2 4 8 3 1 3 3 2 6 3 3 9 3 4 12 4 1 4 4 2 8 4 3 12 4 4 16
Recursion is possible in Python, which means that the function can call itself. This is useful when we have the data and we have to loop through it to get the desired result.
deftri_recursion(x): if(x>0): result = x+tri_recursion(x-1) print(result) else: result = 0 return result print("Recursion Example Results") tri_recursion(5)
Recursion Example Results
1 3 6 10 15
The ‘while’ loop in Python is used to iterate some code until the condition remains true. This Loop is helpful when we do not know how long we will have to iterate the block of code.
Syntax of the ‘while’ loop
In the case of ‘while loop in Python’, an expression is defined first. If the expression is found to be true, then only the ‘while’ loop is iterated.
The iteration is continued until the expression is found false.
The syntax of the ‘while’ loop is as follows:
body of while
The body of the ‘while’ loop is defined through an indented block. The first indented block encountered determines the end of the body of the ‘while’ loop.
As you can see in the chart, if the condition is found to be false, then the loop is exited. In case the condition is found to be true, it is executed again and again until the outcome becomes false.
Example: Python while Loop
Here is an example of the usage of ‘while’ loop.
n = 5 sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 print("The sum is", sum)
The sum is 15
Using else statement with while loops (small description with one example)
Just like Python ‘for’ loop, we can also use the ‘else’ block with the ‘while’ loop. The ‘else’ block will be executed only after the condition of the ‘while’ loop is false. Understanding ‘for’ loops in python will help you with other aspects of Python as well.
‘Break’ statement can be used to terminate the ‘while’ loop.
coding = 0 while coding < 3: print("completing loop") coding = coding + 1 else: print("completing else")
completing loop completing loop completing loop completing else
Single statement while the block
If the ‘while’ block consists of a single statement, then the whole loop can be written in a single statement.
count = 0
while (count == 0): print("Python program
It is not beneficial to use this format as it may result in infinite loops and the user may have to forcefully terminate it.
Here is why the loops are used in Python:
if you are interested learn python and build a career in it? Then check out our python training near your cities
These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Microsoft Azure and help you to achieve your dream job.
Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex etc, Connect with him on LinkedIn and Twitter.