Home Python How to Loop in Python

How to Loop in Python

Python is not just any programming language; it is general-purpose, high-level, and interpreted. Many coding enthusiasts and developers are turning to Python because of its remarkable design philosophy. It strongly purports code readability through its significant use of notable whitespace. This article seeks to explore the effectiveness of the Python programming language in looping useful code.

The world of computing defines a loop as a controlled flow of iterations. It enables a specific code statement or statements to execute repeatedly concerning certain conditions in play.

Loops in Python

Python programming language offers several interesting loops that will help your code meet its targeted looping requirements. The effectiveness and usefulness of these Python-supported loops are in their execution algorithms. The methodologies through which these loops execute tend to lead to a common algorithmic outcome; however, the operable distinguishing factor is in the implemented loop syntax.

Python While Loop

The Python definition of a While Loop depicts it as a useful way of executing a code block or code statements only when certain set conditions are fulfilled. Therefore, if the executing code does not meet or satisfy the conditions in play, the loop does not execute and transfers the execution power to the line of code or code statement that immediately succeeds it. The Syntax for a While Loop is straightforward, as depicted below.

while Expression:
	statement(s) 
    

You should also note the use of indentation by Python statements. Each programming construct follows a specific number of character spaces. These character spaces are inclusive of every code block that is defined on a programmable space. Python’s unique approach to consider code or character spacing through indentation helps it organize and group code blocks or statements.

Consider the following Python While Loop code example.

# an illustration of a Python While Loop Program
count = 2
while (count < 5):
	count = count + 1
	print("Hello CodeUnderscored Learner")
    

The execution of the above code will produce an output similar to the following.

Hello CodeUnderscored Learner
Hello CodeUnderscored Learner
Hello CodeUnderscored Learner

While Loop with An Else Statement

We already discussed that a While Loop would execute a code block or statements until its set conditions are fulfilled or completely satisfied. A false condition on a loop scheduled to execute forces it to transfer the program’s execution power to the statements or code block succeeding it. We can achieve this transfer of execution power through implementing an else statement into our code. The else code clause executes because the conditioned loop did not meet the needed execution criteria. However, if the conditioned While Loop meets the set execution criteria and an Else statement is also in play, the statement will be last to execute. The syntax for a While Loop with the Else Statement is as follows.

While condition:
	#statements to execute
else:     
	#statements to execute
    

Therefore, if we implement our previously created example code with the an Else Statement, it will look as follows.

# an illustration of a Python While Loop Program with an Else statement
count = 2
while (count < 5):
	count = count + 1
	print("Hello CodeUnderscored Learner")   
else:
	print("End of Learning!")
    

Executing this program should present an output like the following:

Hello CodeUnderscored Learner
Hello CodeUnderscored Learner
Hello CodeUnderscored Learner
End of Learning!

Single Statement While Block

There are cases where a While Loop code block will only accommodate a single line of code or statement. Under such circumstances, you do not need to waste too much space on your code script. A single line of code or statement is sufficient to handle the entire loop. Consider the implementation of this concept in the following code example.

# an illustration of a single While block statement through a Python program
count = 3
while count == 3: print("Hello CodeUnderScored Learner")
  

Despite the code simplicity and management of this While Loop type, we strongly discourage its usage in critical real-life code applications. Reason? You might have noticed that if the While Loop condition is met or is true, there is no way we can end the execution of the Python program other than forcefully unplugging our compiler or using a break statement. Therefore, you would not want an infinitely running program on a user-centered system or application.

Python For in Loop

This type of Python Loop is effective in implementing sequential traversal. A practical example of its implementation is traversing an array, a string, or a list in a Python program. Python implements the For Loop, which is different from the traditional C-style type of For Loop, where a loop condition can be represented like for (n=0; n<m; n++). The Python way of implementing this type of loop is through the for in loop. This implementation has some similarities to the other programming languages’ use of for each loop. Time to understand the implementation of sequential traversals through Python’s for in loop. The for in loop syntax is as follows.

for iterator_variable in sequence:
	executable statement(s)
    

This iteration takes place within a defined range. The example code below expounds on this explanation.

# an illustration of a for in loop iteration within the range 0 to x-1 through a Python program
x = 7
for y in range (4, x):
	print (y)
    

The expected output from executing this Python code is:

3
4
5
6

We can also demonstrate the use of for in loop to iterate a list, tuple, string, and dictionary through the following code examples.

# Python program illustrating iteration over a list 
print ("\nPython For Loop List Iteration")
l = ["Code","Under","Scored"]
for x in l:
    print (x)
# Python program illustrating iteration over a tuple or immutable
print ("\nPython For Loop Tuple/Immutable Iteration")
t = ("Code","Under","Scored")
for x in t:
    print (x)
# Python program illustrating iteration over a String
print ("\nPython For Loop String Iteration")
s = "CodeUnderUnderscored"
for x in s:
    print (x)
# Python program illustrating iteration over a Dictionary
print ("\nPython For Loop Dictionary Iteration") 
d = dict()
d['Code'] = 11
d['Under'] = 22
d['Scored'] = 33
for x in d:
    print ("%s %d" %(x, d[x]))
    

The output of the above programs executions is as follows:

Python For Loop List Iteration
Code
Under
Scored

Python For Loop Tuple/Immutable Iteration
Code
Under
Scored

Python For Loop String Iteration
C
o
d
e
U
n
d
e
r
U
n
d
e
r
s
c
o
r
e
d

Python For Loop Dictionary Iteration
Code 11
Under 22
Scored 33

For In Loop Iteration Through the Index of Sequences Approach

We also can implement a For Loop sequence using the index of elements to perform our loop iterations. We first need to calculate and determine the length of the list used in this loop. This list length will serve as the range parameter of Python’s For Loop through which an iteration will take place. The example Python code below provides a better preview of this explanation.

# an illustration of iteration by index through a Python program   
my_list = ["Code", "Under", "Scored"]
for index in range (len(my_list)):
	print (my_list[index])
    

Running the above Python program should yield the following results.

Code
Under
Scored

Executing For In Loops with Else Statements

The same way we demonstrated with the While Loop is the same methodology or approach we can use to integrate an else statement inside a for in loop‘s Python code block. Since Python’s for in loop is not conditional like the While Loop, the code segment for the For Loop executes first, and afterward, the execution of the else statement follows suite. The code example below gives a better visual preview of this concept.

# an illustration of how to combine an else statement with a for in loop through a Python program
my_list = ["Code","Under","Scored"]
for index in range (len(my_list)):
	  print (my_list[index])
else:
	print ("\nGoodbye CodeUnderScored Learner!")
    

The execution of this Python program yields the following results:

Code
Under
Scored

Goodbye CodeUnderScored Learner!

Nested Python Loops

Like many other programming languages, Python caters to the nesting of several loops. Loop nesting is using one loop inside the executable code block of another loop. The following for in loop syntax gives a better preview and illustration of this concept.

for iterator_variable_one in sequence:
	for iterator_variable_two in sequence:
		executable statement(s)
		executable statement(s)
        

This nesting concept is also achievable through the While Loop and we can highlight its syntax as follows.

while expression_one:
	while expression_two:
		executable statement(s)
		executable statement(s)
        

It is also important to note that Python nested loops do not have to restrict themselves to a single loop type like a While Loop that only nests other While Loops code or a For in Loop that only nests other For in Loops code. Their applicability on a program code can be dynamic whereby a nested While Loop can contain a For In Loop and vice versa.

# an illustration of a nested for in loop through a Python program
for x in range (1, 7):
	for y in range (x):
		print (x, end = ' ')
	print ()
    

The output of the above code execution will yield the following result:

1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 
6 6 6 6 6 6 

The following example caters to Python’s nested While Loop.

# an illustration of a nested While Loop through a Python program 
x = 2
while (x < 30):
	z = 2
	while (z <= (x/z)):
		if not (x%z): break
		z = z + 1
	if (z > x/z): print (x, "is a prime number")
	x = x + 1
print ("\nEnd of the Prime Numbers Lesson!") 

The above nested While Loop code prints prime numbers between 2 and 30. The expected output from its execution is as follows:

2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number

End of the Prime Numbers Lesson!

The following Python program example code depicts how a nested loop combines both the For In Loop and the While Loop.

# an illustration of nested While and For In Loop through a Python program 
x = 12
while (x < 30):
    for z in range (0, x):
        print(z)
    print ("\n These printed numbers conquer with the While Loop's (x < 30) set condition!") 
    break
    

We took some creative approach to fuse the While Loop and the For in Loop together and for the program code to be as logical as possible. The output from executing this code is as follows:

0
1
2
3
4
5
6
7
8
9
10
11

 These printed numbers conquer with the While Loop's (x < 30) set condition!
  

Python’s Loop Control Statements

You might have noticed that the last few code examples have implemented the use of the break statement. It is useful in ending a code’s execution to prevent a program from running infinitely or indefinitely. A break statement gives us the controlling power to break out of a running loop to be safe from a continually executing loop. Consider this example code:

# python code implementation of a break statement
for letters in 'CodeUnderScored':
    #use the break statement to end this loop is
    if letters == 'r' or letters == 'U':
        break
print ('First Captured Letter is:', letters) 

The expected output from the execution of this code is:

First Captured Letter is: U
  

Apart from the break statement, we also have the continue statement, whose contribution in Loop control statements is essential in altering a Python program code’s normal execution sequence. Such statements destroy the automated program objects that were active with a defined loop. Therefore, while a break statement breaks out of an active loop, a continue statement takes this control back to where the defined loop started its execution. The following code example regarding the continue statement captures this explanation better.

# Python code implementation of a continue statement
# This program prints all the letters in the word CodeUnderScored except letters U and d
for letters in 'CodeUnderScored':
	if letters == 'U' or letters == 'd':
		continue
	print (letters, 'is one of the remaining letters')
	var = 10
    

Executing this code will yield an output similar to the following:

C is one of the remaining letters
o is one of the remaining letters
e is one of the remaining letters
n is one of the remaining letters
e is one of the remaining letters
r is one of the remaining letters
S is one of the remaining letters
c is one of the remaining letters
o is one of the remaining letters
r is one of the remaining letters
e is one of the remaining letters

Python also implements the use of a pass statement in its loops. The common usage of a pass statement is in defining and executing an empty loop. However, if we are creative enough in its usage, it can be useful in Python classes, functions, and empty control statements. Consider the implementation of the pass statement in the following code example.

# an empty loop Python program
for letters in 'CodeUnderScored':
	pass
print ('The last letter of the word CodeUnderscored is: ', letters)  

Upon the execution of this code, you should get an output similar to the following:

The last letter of the word CodeUnderscored is:  d
  

The Internal Operability of Python’s For Loop

This section of the article requires that you know the usefulness of iterators in a Python loop. Lucky enough, we have scratched the surface of this concept from the previously covered steps in this tutorial. A simple For Loop code example should get us started in this section.

# demonstrating For Loop Iteration through a Python Program
fruits = ["Mangoes", "Avocados", "Tomatoes"]
for my_fruit in fruits:
	print (my_fruit)
    

Because this Python code structure is pretty straight forward, you can expect an output like the following:

Mangoes
Avocados
Tomatoes

The above example code defines a list object called fruits with three predefined fruit object elements the list object holds. Therefore, examples of official iterable objects known to Python are Lists, Sets, and Dictionaries. It would be best if you never depicted an integer object to be an iterable object. Iterable objects permit Python’s Loops like the For Loop to iterate over them or perform a repeatable action through them. Strings and Tuples also qualify as iterable objects.

The above code example and its succeeding contextual explanation regarding Python iterators have created the perfect foundation for us to grasp better the concept of Python’s For Loop’s internal Operability. Therefore, to fulfill the objective of this final section of our article, we need to be procedural in accomplishing the following 4 steps.

Step 1: Make use of the inter () function to turn or transform a Python list into an iterable object.

Step 2: Implement an executable infinite While loop which should only break when a StopIteration exception is raised.

Step 3: Make use of the next () function within a try code block to retrieve the next element in line on a defined list object.

Step 4: The final step after the successful retrieval of the defined list elements is to finalize the iteration operation by printing out the retrieved list elements.

The following Python code example is the perfect implementation of the four steps discussed above.

# An illustration of the internal operability of Python's For Loop
# Here, we define and initialize an iterable called fruits with some iterable elements
fruits = ["Mangoes", "Avocados", "Tomatoes"] 
# Here, we reference the already created iterable and then create an iterator object
iter_obj =  iter(fruits)
# Create an infinite While Loop
while True:
	try:
		#retrieve one item after another from the fruits list in a successive order
		my_fruit = next(iter_obj)
		print (my_fruit)
	except StopIteration:
		#we check for the validity of the raised StopIteration instance before proceeding to 
        #break the execution of the loop.
		break

The expected output is as follows:

Mangoes
Avocados
Tomatoes

Final Thoughts

If you have managed to consume all the content of this article’s tutorial, you should consider yourself a master of the Python Loops. This Python Loops’ foundation should brace you to starting thinking in line with practical, real-world challenges. You are now better equipped to maneuver around or bypass the hurdles you might face concerning Python Loops’ usage in dynamic Python programs or projects.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More