Mastering Loop Structures in Python : Unlocking the Full Potential of Iteration

Mastering Loop Structures in Python : Unlocking the Full Potential of Iteration

A Comprehensive Guide for Understanding Loops in Python

In this article, we'll learn in-depth about conditional statements, the use of for, in, while, break, continue, and pass and their examples in Python programming language. Most applications if not all perform iteration through one or more variables with sequence to ensure proper flow of its functionality.

Check out the previous article titled: Mastering Conditional Statements in Python: A Comprehensive Guide in this Python series.

Loops

To iterate or go over a list of items continuously. It is commonly used in Tech. For example, In our human activities, someone goes over books on the shelf and looks for a book titled "XYZ". That's the same as saying to loop over the books on the shelf to find the book titled "XYZ".

Loops in Python

Loops in Python are done using the keyword for or while in a statement to iterate over a collection of items could be a list, string, dictionary, or tuples. The break, continue and pass keywords can be used within a loop in Python to control the flow of the loop or iteration.

Structure of a loop

for single_item in items:
    #call this line of action...
    . . .

The literal meaning of that statement in English is what Python is doing here. Just like saying for each book in the collections of books check if anyone is published by author X.

For example, the statement above has four words in the first line and the indented code below it.

  • for keyword: marks the beginning of the iteration of the items.

  • single_item ( this could be any name you choose to use to identify a single item in the list while iterating)

  • in keyword: denotes the tagging of an item in the list

  • variable_name containing a sequence of data for example items (the name of the variable that has the items or lists to iterate through.)

  • The next line indented indicates the next line of action. It could be a pass, break, continue, if or nested loop.

Python loops in action

Looping through String

A string in Python is interpreted as a sequence of characters with indexing numbers for each character. Using the for keyword in Python we can loop through the string to perform operations on each character.

name = "Alemsbaja"
for item in name:
    print(item)
  • Output

Looping through the Python List

A list is a data type in Python that holds a sequence of data enclosed within the square bracket. Refer to my previous Python article on data type for clarity.

countries = ["Kenya", "Germany", "Japan", "India", "Nigeria"]
for country in countries:
    print(country)
  • Output

Looping through Python Tuples

Iteration can be performed on tuples that contain a sequence of values enclosed within the parenthesis using Python for keyword.

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for country in countries:
    print(country)
  • output

Looping through Dictionary in Python

The iteration can be done to retrieve the key and value pairs of a dictionary in Python with the items() function appended to the variable name of the dictionary collection.

student_details = {"age" : 10, "name" : "Alemsbaja", "category" : "boarding"}

for key, value in student_details.items():
    print(f"The key is: {key} and the corresponding value is: {value}.")

Python Nested Loops

Just like nested if...elif..else.... Loops can be nested. It can be used for in-depth looping.

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for country in countries:
    print(country)
    for item in country:
        print(item)

Loops using Python range function

The range() is an in-built function in Python that can be used to define the limit or scope of numbers. The range function can take one or three parameters(start, stop, step)

The example below iterates through 1 and stops at 9.

for num in range(1, 10):
    print("Python range in loop", num)
  • output

Demo loop for three parameters in Python range function

This will return the number 5 at first, then add 3 to 5 and will stop at a value less than 10.

for num in range(5, 10, 3):
    print("Python range in loop", num)

#Python range in loop 5
#Python range in loop 8

Another Example:

for num in range(2, 14, 2):
    print("Python range in loop", num)

Returns 2, and keeps adding 2 but must not be equal to 14 or higher than 14.

Let's take a look at one more example of how to use range in a list

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for index in range(len(countries)):
    print("The index position of", countries[index], "in the list is", index)

The range can be used to limit the number of items to access in the list

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for index in range(2):
    print("Accessing item", index, "on the list:", countries[index])

#Accessing item 0 on the list: Kenya
#Accessing item 1 on the list: Germany

while loops in Python

In Python, a code can be executed before the condition is been met using the while keyword. For example, the code below prints the statement until Python is less than or equal to 8. An if statement can be attached as demonstrated in the code below. It's a repetitive test until the condition is been met.

age = 5
while age <= 8:
    print("Enjoying the while loop in python")
    age += 1
    if(age == 7):
        break
#Enjoying the while loop in python

Break in Python Loops

The break is used to stop the iteration before it ends in the for or while loop.

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for index in range(5):
    if countries[index] == "Kenya":
        print("This is", countries[index])
        break
else:
    print("It got here")


#This is Kenya

Once it encounters the match to "Kenya" it stops the iteration.

continue in Python Loops

It continues with the remaining part of the loop even if the condition evaluates to true or false.

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for index in range(5):
    if countries[index] == "Kenya":
        print("This is", countries[index])
        continue
    print("It got here")
  • Output

pass in Python loops

When a program doesn't require any action but a statement is necessary syntactically, the pass statement can be utilized. Just like saying ignore

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for index in range(5):
    pass
print("Passed down here.")

#Passed down here.

For loops with else statement

countries = ("Kenya", "Germany", "Japan", "India", "Nigeria")
for index in range(5):
    if countries[index] == "Kenya":
        print("This is", countries[index])
else:
    print("It got here")

After executing the if statement and nothing else to do it returns the statement in the else section.

#This is Kenya
#It got here

Single-line loops statement in Python

Loops can be written in a line statement.

for i in range(4): print("single line loop statement in Python")

There are lots of use cases where Python loops are applicable or can be used. Please be careful to avoid looping through an infinite value or a condition without a possible outcome.

Conclusion

Loops in Python are pretty easy to understand. The statement syntax and loop keywords are important to note when you want to iterate through a list of items or sequences. The break and continue keywords are applicable in between the iterations when there's a need to halt or skip a particular item or condition during iteration. Handling Loops in Python is better understood when practiced with the examples in the article or other projects.

If you're looking forward to developing applications in Python using the OOP (Object-oriented programming), the major concepts are simplified on my blog here.

Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!