Introduction Loops in Python
A concept in Python programming package that allows repetition of certain steps, or printing or execution of the similar set of steps repetitively, based on the keyword that facilitates such functionality being used, and that steps specified under the keyword automatically indent accordingly is known as loops in python. It is acting as a block, with “while” continuing to execute until a certain specified condition is met and “for” executing till the index variable in the specified range of values reaches its final value.
Looping is a common phenomenon in any programming language; From a python perspective, the powerful programming language offers two broad categories of loops.
They are as below:
- While Loops
- For loops
While Loops
The common strategy behind while loops are they execute a set of statements until the given condition is satisfied. The next statement call happens at the instance when the specified condition is satisfied. The use of indented code segments determines the segment or the body of the loop. Indentation starts the loop, and the line from which it starts to be unindented represents the end of the mentioned loop. All non-zero values are interpreted as true here.
Flowchart
Example
Code Snippet
n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
While Loop Example
Python Program for Matching a String
Import Section
- import string
- import random
- import time
Variable section
endeavourNext = ''
completed = False
iterator = 0
Propable Characters to Compare
propableCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' ., !?;:'
String to Be Generated
t = input("Enter the expected string or word : ")
Generate the Initial Random String
endeavourThis = ''.join(random.choice(propableCharacters)
for i in range(len(t)))
Iterate While Completed Is False
Increment the iterator
iterator += 1
endeavourThis = endeavourNext
time.sleep(0.1)
Driver Code
print("Target match found after " +
str(iterator) + " iterators")
For Loops
For traversing a sequential statement set, these loops are implied. The persistence of the loop is passed on pending the last item in the series is executed. While loop here to the content of the loop is separated from the rest of the code by introducing the indentation. As like while loop here to indentation plays an important role in determining the body of the loop involved. Indentation starts the loop, and the line from which it starts to be unindented represents the end of the mentioned loop.
Flowchart
Example
for iterator_var in sequence:
statements(s)
Code Snippet
For Loop Example#1
Python Program Using Turtle Graphing Technique
Import turtle
Function Definition
def border(obj1, panel_x, panel_y):
obj1.penup()
obj1.home()
obj1.forward(panel_x / 2)
obj1.right(90)
obj1.forward(panel_y / 2)
obj1.setheading(180)
obj1.pencolor('red')
obj1.pendown()
obj1.pensize(10)
for distance in (panel_x, panel_y, panel_x, panel_y):
obj1.forward(distance)
obj1.right(90)
obj1.penup()
obj1.home()
def square(obj1, size, color):
obj1.pencolor(color)
obj1.pendown()
for i in range(4):
obj1.forward(size)
obj1.right(90)
def main():
panel = turtle.Screen()
panel.title('Square Demo')
panel_x, panel_y = panel.screensize()
obj1 = turtle.Turtle()
border(obj1, panel_x, panel_y)
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'violet']
obj1.pensize(3)
for i, color in enumerate(colors):
square(obj1, (panel_y / 2) / 10 * (i+1), color)
print('Hit any key to exit')
dummy = input()
Main Program Call
if __name__ == '__main__':
main()
For Loop Example#2
Program to concatenate two LISTS into a dictionary.
Variable declaration
Key_elements=[]
value_elements=[]
Count to be processed
var1=int(input("Count of elements for the dictionry:"))
print (Key Elements)
for x in range(0,var1):
element=int(input("Element item entered" + str(x+1) + ":"))
Key_elements.append(element)
Print (Value Elements)
for x in range(0,var1):
element=int(input("Element item entered" + str(x+1) + ":"))
value_elements.append(element)
d=dict(zip(Key_elements,value_elements))
#Print Section
print("The formulated dictionary is:")
print(d)
Nested loops
Nested looping is the process of looping one loop within the boundaries of others. So when the control flows from the outer loop to the inner loop, it returns back to the outer loop only when the inner loops are completed. Indentation is used to determine the body of the nested loops. Indentation starts the loop, and the line from which it starts to be unindented represents the end of the mentioned loop.
Example
Code:
for iterating_variable#1 in sequence#1:
for iterating_variable#2 in sequence#2:
statements(s)
statements(s)
while expression#1:
while expression#2:
statement(s)
statement(s)
Nested Loop Example
Python Program for File Handling
import os
def listfile(types):
current_path,filename = os.path.split(os.path.abspath(__file__))
Nested Looping Section in The Program
Outer For Loop - - - - - - - - - -#
for path,dir,file in os.walk(current_path):
file_name = str(file)
Inner For Loop
for type in types:
if file_name.endswith(type):
print(file_name)
def deletefile(types):
choice2 = input("Please enter the file to delete : ")
os.remove(choice2)
types = [".txt']",".srt]",".py]"]
Header Area
print(" = = = = = = = = = = = = = = = = = = = = = " )
print(" $$$$$$$$$$$$$ FILE HANDELING $$$$$$$$$$$$ ")
print(" = = = = = = = = = = = = = = = = = = = = = ")
File Listing
File_list = listfile(types)
File Operation
Print( Bye Bye )
exit
else:
Print( Invalid Option )
exit
Python Loop Control Statements
Loops iterate above a block of code pending expression in testis false, but when there is an instance where we need to stop the loop without a check to the condition, that is where the loop control statements come into play. The three major loop control statements in python are as below:
- Break: Terminates the loop and passes the control to the statement after the loop. If a break is mentioned into a nested loop, then it is the innermost loop is where the break will initially terminate.
- Continue: Skips the remaining sentences in the loop and checks the condition posted in the loop.
- Pass: It just passes the execution when reaching a specific statement.
Loop Control Statements example
Python Program Using Loop Control Statements
var_a = 1
var_b = 2
while var_a < var_b:
print(" Code enters while loop ")
var_c = ["SUV","sedan","hatchback","End"]
for iterator in var_c:
if iterator == "SUV":
print("Hyundai creata")
print("Mahindra bolero")
print("---------------")
if iterator == "sedan":
Loop Control Statement: Pass
pass
if iterator =="hatchback":
print("Renault Kwid")
print("suzuki alto")
print("---------------")
if iterator == "End":
Loop Control Statement: Break
break
var_a = var_a+1
Benefits of python Loops: The key advantages of loops are as below:
- Code reduction.
- Reduces code complexity.
- Brings in more stability into coding.
- Code redundancy is greatly resolved.
Conclusion – Loops in Python
The dominance exhibited by any programming language depends on the classified set of coding functionalities. In such instances, python programming’s looping structure is largely stable and flexible to code which stands out to be among the prior reasons which make this language dominate the market.
Recommended Articles
This has been a guide to Loops in Python. Here we discuss what the Loops in Python are, While loops, and much more with appropriate sample code. You can also go through our other suggested articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses