Learn Python Loops Including FOR, WHILE, Nested and more

By:   |   Updated: 2022-03-25   |   Comments   |   Related: > Python


Problem

Using the Python programming language for data analytics is helpful and, in some cases, more efficient that using other tools. In this tutorial series we will examine Python functionality. As a scripting language, here too you may need to repeat certain blocks of code. This process allows you to automate the control flow of your program as needed.

Solution

To iterate a block of code, Python offers a specific instruction for repetition which is referred to as the "loop" construct. Looping is a handy and powerful way to execute the same or different instructions several times instead of hard coding a finite number of repetitions. Loops are critical constructs that are extremely helpful in building complex algorithms and programs. Beware - every loop has the inherent propensity to slip into a state of infinite execution. This and other points on Python loops will be covered in this Python tutorial. Let's begin by examining the different types of loops.

While Loops

The while loop has a main line containing a conditional expression, a body with a unit of code and an optional else statement is used if there was no break that terminated the loop prior.

while conditional_expression:
   statement # body
else: # optional
   statement # runs only the loop has not been terminated with a break

As you can see in the above example, the while-loop is typically used when you want to iterate a block of code while a certain condition is true (in fact, notice the similarity between the natural language and Python with while). As soon as the conditional expression returns a false outcome, the while loop terminates, and the program continues the execution of the code after the loop. A suitable example to illustrate the while construct is a program calculating the factorial of a number. In math, the factorial of a number n is the product of all positive integers less than or equal to n. Here is how to do it with a Python while loop, while also encapsulating the logic in a function:

def calculate_factorial(n):
    result = 1
    if n == 0 or n == 1:
        return result
    while n > 1:
        result = result * n
        n = n - 1
    return result

The case of 1 is obvious while the case of 0 is defined to be 1. For our program these are both special cases that require a conditional expression. The rest of the logic follows that. The while loop continuously checks the value of the input argument, while we keep decrementing that value with 1 every step of the loop. This is how we multiply the result variable by the next value of the input argument. Here is the program in action:

calculate factorial with a while loop

To illustrate how the else clause acts coupled with a while loop, consider the following example:

limit = 5
while limit > 0:
    print(limit)
    limit -= 1
else:
    print('limit depleted')

We have the simple task of checking if a variable is within a limit and display the current value of that variable. Here is the result:

while loop with else clause

Notably, once we exit the while loop based on the defined condition (variable > 0), control jumps to the else clause.

Definite Loops or Python For Loop

Also known as "for loops", they provide the same result but in combination with a finite set of items. The general structure of the for loop statement is:

for member in [a finite list of members]:
     statement # for loop body

The list must be finite otherwise you will create an infinite loop which is rarely what you need. The other component -the "member" variable - is the iteration local variable that keeps count of how many times you need to loop. For example:

tips = ['Python', 'SQL', 'PowerBi']
for tip in tips:
    print(tip)
basic for loop

The for loop is often used to access the indices of the member variable from the list of variables that defines the bounds of the loop:

for index in range(len(tips)):
    print(f'{index} - {tips[index]}')

In the result you can see how we iterate over each element displaying its index and value at the same time:

for loop with range to display item indices

Notice the range() function which is an iterator. It is helpful also in cases where you want to iterate over something but in reverse order:

num = int(input())
for i in range(num, 0, -1):
    print(i)
for loop looping backwards

Some more details on the range function you can find in this prior tip on complex data types.

Here is another example of a for loop illustrating how you can also work with variable assignment and conditional expressions in the body of the loop. Let us imagine we need to find the largest number in a list of numbers:

def get_largest(list_of_numbers):
    largest_num = 0
    for current_num in list_of_numbers:
        if current_num > largest_num:
            largest_num = current_num
    return largest_num

Running this code, you get:

for looping for getting the largest number in a sequence

Nested Loops

Nested loops consist of one outer loop whose body contains one or many inner (nested) loops. Here is how they work:

  • Every nested loop always starts by executing the outermost loop. The loop variable is initialized, and the inner code unit is executed.
  • Next, the inner loop is executed in the same way: by first initializing its loop variable and incrementing (or decrementing) according to its definition.
  • Then, after the inner loop terminates, program control goes a step back to the body of the parent loop (which may or may not be the outermost loop). The loop variable is evaluated again, and execution continues accordingly.
  • This whole sequence repeats until the outermost loop finishes its execution.

Inner loops may behave similarly to a cross join command. They can be useful in obtaining a Cartesian product of two collections. Let us imagine we needed to generate quickly tip titles based on technology and difficulty level:

tips = ['Python', 'SQL', 'PowerBi']
levels = [100,200,400]
for tip in tips:
    for level in levels:
        print(tip, level)
nested for loop

Iterating over all levels for each tip will produce a combination of all the elements of the two collections

Break, Continue and Pass Syntax in Python

These operators provide further flexibility when working with loops.

Break Statement

The Break Statement terminates the immediate encompassing loop. Allows the programmer to exit the loop at a random place or make the "break" part of a logical construct, whose true or false (boolean) outcome will terminate the loop. For example, let us investigate another way to calculate a factorial:

def calculate_factorial(n):
    result = 1
    while True:
        if not n > 1:
            break
        result = result * n
        n -= 1
    return result
calculate factorial with a while loop and the break operator

As compared to the previous approach this one is different: we explicitly create an infinite loop as True is always true. In the meantime, we make sure that upon a certain outcome (negative n or n = 0) the loop will terminate. Then we return the result from the calculation.

Continue Statement

With continue you can finish the execution of the current iteration and jump to the next iteration without terminating the loop itself. In other words, continue is the opposite of break in the looping context because it instructs control to go to the immediate encompassing loop. Let us imagine we wanted to count the occurrences of the letter S in MSSQLTips:

word = 'MSSQLTips'
count_s = 0
for letter in word:
    if letter != 'S':
        continue
    else:
        count_s += 1
for loop with the continue operator

With the help of continue we ensure the variable count_s is incremented only when S occurs, i.e., when letter == S.

Pass Statement

The pass operator is applicable to loops but unlike break and continue, it can be applied to other constructs as well. It does nothing in practice and is just a type of placeholder. Use it when you will implement your logic in the unit of code later:

word = 'MSSQLTips'
for letter in word:
    pass
pass operator as a placeholder in a for loop
Conclusion

In this tutorial, we covered the basics of iteration in Python: while loops, for loops, nested loops and their inherent operators break and continue. With this knowledge we can proceed to building more complex scripts and solutions.

Next Steps

Learn more about Python:



sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Hristo Hristov Hristo Hristov is a Data Scientist and Power Platform engineer with more than 12 years of experience. Between 2009 and 2016 he was a web engineering consultant working on projects for local and international clients. Since 2017, he has been working for Atlas Copco Airpower in Flanders, Belgium where he has tackled successfully multiple end-to-end digital transformation challenges. His focus is delivering advanced solutions in the analytics domain with predominantly Azure cloud technologies and Python. Hristo's real passion is predictive analytics and statistical analysis. He holds a masters degree in Data Science and multiple Microsoft certifications covering SQL Server, Power BI, Azure Data Factory and related technologies.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2022-03-25

Comments For This Article

















get free sql tips
agree to terms