Contents

Mastering Python Loops: A Comprehensive Guide

A Complete Guide to Python Loops, Statements, and Functions

Website Visitors:

What is a loop

In computer programming, a loop is a control structure that allows a sequence of instructions to be executed repeatedly until a certain condition is met. Python, being a powerful and easy-to-learn programming language, provides several loop constructs to enable iterative execution of code blocks.

In this article, we will discuss Python loops in detail, including for loops, while loops, and do-while loops. We will also cover the use of break and continue statements, and how to use the enumerate() function to get the index.

Python For Loop

The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. The syntax of the for loop is:

1
2
for variable in sequence:
    statement(s)

Here, variable is a temporary variable that takes on the value of each element in the sequence one by one, and statement(s) is the code block that is executed each time through the loop.

Example 1: Iterate over a list

1
2
3
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

1
2
3
apple
banana
cherry

Example 2: Iterate over a string

1
2
for letter in "Python":
    print(letter)

Output:

1
2
3
4
5
6
P
y
t
h
o
n

Example 3: Iterate over a range

1
2
3
for x in range (5,10):
    print (x)
    x=x+1

Output:

1
2
3
4
5
5
6
7
8
9

Example 4: Iterate over custom value

1
2
for i in range(1,100,10):
    print(i)

Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
1
11
21
31
41
51
61
71
81
91

Here, we are running a for loop but at interval of 10. For loop stops if the value is equal to or more than 100.

Example 5: Iterate over a collection

1
2
3
days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
for day in days:
    print ("Day is ", day)

Output:

1
2
3
4
5
6
7
Day is  Mon
Day is  Tue
Day is  Wed
Day is  Thu
Day is  Fri
Day is  Sat
Day is  Sun

Example 6: Iterate over list in for loop directly

1
2
for x in [25]:
    print(x):

Output: 25 Above value in for loop is a list. So it goes in that list one by one and prints it. As there is only one value, it will print it and stop.

Python While Loop

The while loop is used to repeatedly execute a block of code as long as a specified condition is true. The syntax of the while loop is:

1
2
while condition:
    statement(s)

Here, condition is the expression that is evaluated each time the loop is run, and statement(s) is the code block that is executed as long as the condition is true.

Example 3: Iterate with a while loop

1
2
3
4
count = 0
while count < 5:
    print(count)
    count += 1

Output:

1
2
3
4
5
0
1
2
3
4

If you provide one word or one value in a for loop, it will pick each letter and process it. If you want to perform an action on each value, then send it as a list. In below example, when the friends list is passed into the function, it will output as Hi Lisa, and Hi Chris. But when only one value is passed into the function and for loop, it takes that value and processes it letter by letter.

1
2
3
4
5
6
7
8
def greeting(friends):
    for i in friends:
        print("Hi " + i)
    
    
friends = ["Lisa", "Chris"]
greeting(friends)
greeting("John")

Output:

1
2
3
4
5
6
7
Hi Lisa
Hi Chris

Hi J
Hi o
Hi h
Hi n

Python Do-While Loop

Python does not have a built-in do-while loop construct like some other programming languages, but we can emulate it using a while loop and a break statement. The basic structure of the do-while loop is:

1
2
3
do:
    statement(s)
while condition

Example 4: Implement a do-while loop

1
2
3
4
5
6
count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

Output:

1
2
3
4
5
0
1
2
3
4

Break and Continue Statements

The break statement is used to exit a loop prematurely, while the continue statement is used to skip over the current iteration in the loop and move on to the next one. With continue, the current loop (for loop or while loop etc) is stopped where the condition is met and goes to the next value in the loop. The syntax of the break and continue statements is:

1
2
break
continue

Example 5: Use break and continue statements

1
2
3
4
5
6
for number in range(1, 10):
    if number == 5:
        break
    if number % 2 == 0:	
        continue
    print(number)

Output:

1
2
1
3

In this example, the loop is terminated prematurely when the number variable equals 5, and any even numbers are skipped over with the continue statement.

Another example using continue command:

1
2
3
4
5
for x in range(5,10):
    if (x==7):
        continue
    print (x)
    print ("Today is sunday.")

Output:

1
2
3
4
5
6
7
8
5
Today is sunday.
6
Today is sunday.
8
Today is sunday.
9
Today is sunday.

Same example using break command:

1
2
3
4
5
for x in range(5,10):
    if (x==7):
        break
    print (x)
    print ("Today is sunday.")

Output:

1
2
3
4
5
Today is sunday.
6
Today is sunday.

When break command is used, when the if statement is true, it immediately breaks the if loop and stops the execution. It will not even process any other commands in the for loop. The print command “Today is sunday” is also not executed when using break command.

When continue command it used, it only stops the execution for the matching value and moves to the next value in for loop. In the example, 7 is the matching value. So 5, 6, are displayed in output, 7 is ignored, next 8 and 9 are displayed on the output along with “Today is sunday” print command.

Using the Enumerate Function

The enumerate() function is a built-in Python function that can be used to add a counter to an iterable object, such as a list or tuple. The syntax of the enumerate() function is:

1
enumerate(iterable, start=0)

Here, iterable is the object to be enumerated, and start is an optional parameter that specifies the starting value of the counter. The enumerate() function returns an iterator that yields pairs of the form (index, element).

Example 6: Use the enumerate() function

1
2
3
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

1
2
3
0 apple
1 banana
2 cherry

In this example, the enumerate() function is used to add an index to each element of the fruits list, and the resulting pairs are printed out in the loop.

Range function

Range starts from 0 by default. If you want to change it, specify the start value and end value like range(1,5). List of numbers generated in range() are one value less than the end value as range starts from 0.

Range function can receive one, two or three parameters.

  • range(n): 0, 1, 2, … n-1. If it receives one value, it will create a sequence one by one from zero until one less than the value received. Ex: If you’d like to iterate a for loop for x number of times, directly specify the value in range function like range(5). Here, it will start from 0 to 4. You are not looking for a start value here. You just need to loop it for x number of times.

  • range(x,y): x, x+1, x+2, … y-1. If it receives two values, it will create a sequence one by one from the first value until one less than the second value. Ex: If you’d like to iterate a for loop for x number of times but from a starting value you specify, you have to use range(1,5). Here, it will start from 1 to 4.

  • range(p,q,r): p, p+r, p+2r, p+3r, … q-1 (if it’s a valid increment). Finally, if it receives three values, it will create a sequence starting from the first number and moving towards the second number. But this time, the jumps between the numbers will be the size of the third number, and again, it will stop before the second number. Ex: If you’d like to iterate a for loop for x number of times but specific intervals you specify, you should use the range function as range(1,100,10). Here, for loop will iterate at interval of 10.

Tip

Use for loop when there is a sequence of items that you want to iterate. For loops are mostly used when there’s a pre-defined sequence or range of numbers to iterate.

Use while loop when you want to repeat an action until a condition changes.

Suggested Article

If you’d like to continue reading, checkout our other python commands article here or browse all other topics here.

Conclusion

Loops are an essential programming construct that allows us to execute a block of code repeatedly until a certain condition is met. Python provides several loop constructs, including for loops, while loops, and do-while loops (which can be emulated using a while loop and a break statement). Additionally, we can use the break and continue statements to control the flow of the loop, and the enumerate() function to add a counter to an iterable object. By mastering these loop constructs and statements, you will be able to write more powerful and efficient Python programs.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.