Python Loops – For, While, Nested Loops With Examples

This video tutorial explains the role of Loops in Python, their types: For, While, Nested Loops with syntax and practical programming examples:

We learned about the four different Conditional statements in Python in our previous tutorial.

Loops are powerful programming concepts supported by almost all modern programming languages. It allows a program to implement iterations, which basically means executing the same block of code two or more times.

Though they are supported by all modern programming languages and provide similar basic functionality, their implementations and syntax may differ.

The Full Training Series on Python will give you a brief idea of what Python is all about.

Loops in Python

Python Loops Video Tutorial

What Are Python Loops

In Python, statements are executed in a sequential manner i.e. if our code is made up of several lines of code, then execution will start at the first line, followed by the second, and so on.

However, there will be cases where we may want a block of code to execute several times until a condition is met. Thanks to loop statements, we can do just that.

Given below is a flowchart that illustrates how a loop statement works.

Flowchart of a Loop Statement
Flowchart of a Loop Statement

Based on the above diagram, a Python program will start at Start[circle], and the execution will proceed to the condition statement[Diamond], if the condition is TRUE, then the program will execute the code block.

Execution will proceed again to the condition statement and the same process continues each time when the condition is TRUE. It only breaks out of the loop or stops executing the code block if the condition is FALSE, and in this case, the program will continue execution sequentially.

Python has two types of Loops.

#Loop typeDescription
1for loopIs an iterator based loop, which steps through the items of iterable objects like lists, tuples, string and executes a piece of code repeatedly for a number of times, based on the number of items in that iterable object.
2while loopExecutes a block of statements repeatedly as long as the condition is TRUE.

These two types of loops can be used inside each other to generate nested loops(more on this later).

General Use Of  Python Loops

In Python, loops can be used to solve awesome and complex problems. You will likely encounter problems that would require you to repeat an action until a condition is met(while loop works best here) or a problem that requires you to perform an action on a bunch of items(for loop works best here).

For Loop In Python

The for loop works well with iterable objects like lists, tuples, strings, etc. This way, we can step through these object’s items and manipulate their values based on our linking.

The for loop is zero-indexed and has the following syntax.

for in n:

The condition in the for loop stays TRUE only if it hasn’t iterated through all the items in the iterable object(n). To better understand the for loop, we will address several examples and finally, we shall work on a practical example.

Example 1: Print Numbers ranging from Start to End

To achieve this, we will use the Python range function.

This is how the flowchart will look like:

Flowchart of for loop
Flowchart of for loop
def range_from_start_to_end(start, end):

    for i in range(start, end+1):
        print(i)

if __name__ == "__main__":
    start = int(input("Enter a start number: "))
    end = int(input("Enter an end number: "))
    # Call our function to print the ranges
    range_from_1_to_20(start, end)

Output

for_loop

In the above example, we used Python range, which is a function that returns a sequence of numbers, starting from a start number(0 by default), increments by a step(1 by default), and stops before an end number.

For this example, we have the following:

Parameters and Values for the Python range function

ParametersValue
start1
end20
step1 (default value)

So, our for loop will iterate through a sequence of numbers from 1 to 20, and for each iteration, it will print the number. The iteration stops when all the numbers in the sequence have been visited.

Example 2: Determine if a number is a prime number.

In this example, we will see why the for loop is so powerful and useful. Here, we will iterate through a sequence of numbers, and for each number, we will perform some computation to determine if a condition is TRUE or FALSE.

It may help to know the conditions for a number to be prime.

  • The number is always positive, greater than 1.
  • Has no positive divisors other than 1 and itself.
def isPrime(number):
    # rule 1: number should be positive, and greater than 1.
    if number > 1:
        # iterate over a range from 2 to half the number.
        for i in range(2, number//2):
            # rule 2: shouldn't have any positive divisor 
            # order than 1 and itself.
            if(number % i) ==0:
                return False
        
        return True
    else:
        return False

if __name__ == '__main__':
    number = int(input("Enter number to check if it's prime: "))

    if isPrime(number):
        print("{} is a prime number".format(number))
    else:
        print("{} is not a prime number".format(number))

Output when input is 13

check if it is a prime number

Output when input is 10

check if it is not a prime number

Note: The if-else used in the above example is a conditional statement and not a loop. But just like the while loop(which we will cover soon), it uses the comparison operators for its condition.

Example – Find Word Count In A Text Using The for Loop

This example is all about counting how many times each word occurs in a text. There are so many ways in which this can be achieved but for this example, we shall use the for loop.

We shall be counting the words from the text below.

Hello, welcome to Software Testing Help. In this article:”Loops in Python”, you’ll learn about loops with practical examples. Great right? Make sure to follow along as we learn together.

Happy coding!

The first thing we shall do is to remove punctuations, whitespace, and all lowercase letters. We shall remove punctuation in the traditional way by identifying which punctuations exist in our text, and then use the for loop to replace them with an empty string.

As the text is not much, we see that the punctuations are commas(,), period(.), question mark(?) , colon(:), double quotation mark(“) and apostrophe(‘).

Given below is the code to replace them with an empty string. Note that we will not replace apostrophe.

# replace punctuation(except apostrophe) and white spaces
    for punc in '.,\n?!"':
        text = text.replace(punc, '')
    # lowercase all letters.
    text = text.lower()

Output

Count the word

Next, we shall split the text into a list of words separated by whitespace.

# Split text into list of words separated by whitespaces(tab, newline)
text = text.split()

Output

split the text

Finally, we will count and see how many times each word occurs in the splitted text.

# initialize a dictionary to hold words:count
wordsCount = {} 
# if a word is already a key in our dictionary, increment it's value. 
# If not, initialize it's value to 1.
for word in text:
    wordsCount[word] = wordsCount.get(word, 0) + 1

Output

practical_WordCount_count

We can clearly see some words to appear twice, and some only once. Let’s sort this dictionary by its value in descending order so that we can clearly differentiate. Here, we have used the Python sorted function, lambda expression, and dictionary comprehension.

# Sort dictionary by value, in descending order
wordsCount = {w: c for w, c in sorted(wordsCount.items(), key=lambda item: item[1], reverse=True)}

Finally, we have used the for loop to clean, count, and sort the words in our text.

Given below is the complete code.

def word_count(text):
    # initialize a dictionary to hold words:count
    wordsCount = {} 
    # replace punctuation(except apostrophe) and white spaces
    for punc in '.,\n?!"':
        text = text.replace(punc, '')
    # lowercase all letters.
    text = text.lower()
    # Split text into list of words separated by whitespaces(tab, newline) and apostrophe(')
    text = text.split()

    # if a word is already a key in our dictionary, increment it's value. 
    # If not, initialize it's value to 1.
    for word in text:
            wordsCount[word] = wordsCount.get(word, 0) + 1

    # Sort dictionary by value, in descending order
    wordsCount = {w: c for w, c in sorted(wordsCount.items(), key=lambda item: item[1], reverse=True)}

    print(wordsCount)


if __name__ == '__main__':
    text = "Hello, welcome to Software Testing Help. In this article: \"Loops in Python\", \
you'll learn about loops with practical examples. \
Great right? Make sure to follow along as we  learn together. \n \
Happy coding!"

    word_count(text)

Final Output

Practical Word Count - Final Output

The While Loop

The Python while loop executes a block of statements repeatedly as long as the condition is TRUE. We notice that it is a bit similar to the if statement. However, unlike the while loop, the if statement executes only once if its condition is TRUE.

The while loop has the following syntax:

While condition:
	expression(block of code)

Unlike the for loop, the while loop doesn’t iterate over a sequence. It uses the comparison operators and booleans for its condition.

Let’s look at some examples to better understand how it is used.

Example 1: Print “Hello World!” a count number of times

The while loop checks the condition(count < n), each time when it’s TRUE, it prints our “Hello world!” and increments the count.

This is how the flowchart will look like:

Flowchart of while loop

def print_count_times(n):
    # set count to 0
    count = 0

    while count < n:
        print("Hello World!")
        # increment count
        count += 1

if __name__ == '__main__':
    # number of times we want to print 
    n = 10
    # call our function to print n times.
    print_count_times(n)

Output:

Print “Hello World!” a count number of times

Example 2: Find factorial of a number

The factorial of a number is represented as n! and it has the formula

1*2*...*(n-1)

The program checks if the number is 0 and returns 1(factorial of 0 is 1). Then the while loop checks the condition (n >=1) to see if our n is equal to 1 or greater than 1. Each time when this condition is TRUE, our program computes the formula in the loop block

Let’s use the while loop to solve the factorial problem

def factorial(n):
    if n == 0:
        # The factorial of 0 is 1.
        return 1
    else:
        fac = 1
        while n >= 1: # while this condition is TRUE
            # 1*2*3*...*(n-1)
            fac *= n # same as 'fac = fac * n'
            n -= 1   # same as 'n = n - 1'
        return fac

if __name__ =='__main__':
    n = int(input("Find factorial of: "))

    fac = factorial(n)
    print("Factorial of {} is {} ".format(n,fac))

Output

factorial problem

Example – Find A Fibonacci Sequence Upto nth Term Using The While Loop

A Fibonacci sequence has the formula.

0,1,1,...((n-1)th + (n-2)th)

The first two numbers are 0 and 1, then the next numbers are the sum of the two previous numbers (n-1)th and (n-2)th.

The Fibonacci sequence of 8 will be 0,1,1,2,3,5,8,13

def fibonacci(n_term):
    n1 = 0 # (n-1)th
    if n_term == 1:
        # if n_term term is 1, print 0
        print(n1)
    else:
        count = 0
        n2 = 1 # (n-2)th
        # Loop while 'count<n_term' is TRUE
        while count < n_term:
            print(n1)
            # save second term in a temporary variable
            temp = n2
            # compute sum of the 2 previous numbers and assign to (n-2)th
            n2 = n1 + n2
            # assign the temporary variable to (n-1)th
            n1 = temp
            # increment count
            count += 1

if __name__ == "__main__":
    n_term = int(input("Find Fibonacci of how many terms: "))
    fibonacci(n_term)

Output

Fibonacci Sequence

Our program first defines the first nth value (n1=0), then it checks if the n_term passed as an argument is equal to 1. If TRUE, it returns 0.

Else, it defines two variables:

  • count=0: This will be used in the while loop to check the condition if the count is lesser than n_term(count < n_term)
  • n2=1: This is our second nth value.

So far, we have 0,1 in our sequence(n1, n2). While the condition is TRUE:

  • The value of n2 gets assigned to a temporary variable(temp = n2).
  • The sum of the two previous numbers are calculated and assigned to n2(n2 = n1 + n2).
  • Our temporary value(n2 old value) is assigned to n1(n1 = temp).
  • Our count is incremented(count +=1), and the condition is checked again.

At the end of the first iteration, we have 0,1,1 where:

  • n1 = 1 ( the first 1)
  • n2= 1 ( the second 1)

This operation will repeat until the condition count<n_term becomes FALSE.

Nested Loop

The cool thing about Python loops is that they can be nested i.e. we can use one or more loops inside another loop. This enables us to solve even more complex problems.

#1) Nesting for Loops

for loops can be nested within themselves. The syntax below shows a 1-level nested for loop.

for in n:
	# piece of code goes here
	for in n:
		#  piece of code goes here 

Example 1: Use nested for loop to print numbers in patterns

Let’s use the nested for loop to print the following pattern:

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

Each number is printed a number of times corresponding to its number itself.

This is how the flowchart will look like:

Flowchart of a nested for loop
Flowchart of a nested for loop
def print_numbers():
    for i in range(1, 6):
        # outer loop
        for j in range(i):
            # 1st level inner loop
            print(i, end=" ")
        print('\n')

if __name__ == '__main__':
    print_numbers()

Output

Nested for Loop

Our program works as follows:

  • The outer loop iterates through the range from 1 to 6 and for each item in that sequence.
  • It enters the inner loop where it iterates over a range of that item.
  • For each iteration of that item, it prints the item.
  • It only leaves the inner loop when it has completely iterated through a range of that item.
  • When it leaves the inner loop, it goes back to the outer loop and the process continues until it has completely iterated over its sequence.

Example 2: Manipulate items of a nested list using a nested for loop

A situation we will likely come across in Python is to access the items of a nested list.

For example, take the nested list below.

>>> [[3,4.0,2,8.4,6],[0,2,0.2,4,6],[9,3.5,0.32,5,4]]

For this example, let’s write a program that will count the number of integers and floats in this nested list.

def float_and_int_count(nested_list):
    float_count = 0 # set our float count to zero
    int_count = 0   # set our integer count to zero

    for l in nested_list:
        # outer loop accesses each list in the nested list
        for item in l:
            # inter loop accesses each item in the list
            if isinstance(item, int): # if item is an instance of int
                int_count += 1 # increment integer count
            elif isinstance(item, float): # if item is an instance of float
                float_count += 1 # increment float count

    # return a tuple 
    return float_count, int_count


if __name__ == '__main__':

    nested_list = [[3,4.0,2,8.4,6],[0,2,0.2,4,6],[9,3.5,0.32,5,4]]

    float_n, int_n = float_and_int_count(nested_list)  

    print("Float count: {} \nInteger count: {}".format(float_n, int_n))

Output

Manipulate items of a nested list

Our program works this way:

  • The outer loop accesses the first inner lists [3,4.0,2,8.4,6] in our nested list.
  • The inner loop accesses each item in this first inner list. For each item, it checks if it is a float or integer. If it is an integer, it increments the integer count (int_count). Else if it is a float, it increments the float count (float_count).
  • Once it has finished iterating through this first inner list, it then moves back to the outer loop and accesses the second list [0,2,0.2,4,6] and the same process continues until it has accessed all the inner lists.

#2) Nesting While Loops

While loops can be nested within themselves.

The syntax below shows a 1-level nested while loop.

while condition:
	# piece of code goes here
	while condition:
		#  piece of code goes here 

Example 3: Use nested while loop to print stars(*) in patterns

Let’s use nested while loop to construct the following pattern:

* 
* * 
* * * 
* * * * 
* * * * *
def print_pattern(n):
    i = 0 # initialize to zero for outer loop
    j = 0 # initialize to zero for inner loop

    while i <= n:
        # outer loop runs n times
        while j < i:
            # inner loop runs i times
            print("*", end=" ")
            j += 1  # increment before checking inner loop condition
        j = 0       # re-initialize after leaving inner loop
        i += 1      # increment before checking outer loop condition
        print('')


if __name__ == '__main__':
    n = 5 
    print_pattern(5)

Output

Nested while loop to print stars

Our program works as follows:

  • Variables are initialized (i=0, j=0, n=5)
  • Our outer loop checks the condition (0 <= 5) which is obviously TRUE.
  • Our inner loop checks the condition (0 < 0) which is obviously FALSE, so our program breaks out of the inner loop.
  • i is incremented and the outer loop checks again its condition (1 <= 5) which is TRUE.
  • Our inner loop checks the condition (0 < 1) which is TRUE. So a star(*) is printed and j is incremented and the inner loop condition is checked with (1 < 1) which is FALSE, thus breaks out of the inner loop.

The process above continues until the outer loop condition becomes FALSE.

Example – Numbers Spelling Game

To round up with a nested loop, we will build an exciting game to help in evaluating the kid’s ability to recognize and spell numbers.

The program displays random numbers on the screen and requests for the spelling of that number. It checks if the input is correct, then it displays another number. If the input is wrong, then it will send an error message and request another answer.

import random # random contain 'shuffle' used to shuffle our list
def word_spelling():
    print("HELLO, WELCOME TO THE WORD SPELLING GAME.\n")
    print("SPELL AS MUCH NUMBERS AS YOU CAN TO GET MARKS\n")
    print("-----------------------------------------------\n")

    correct_score = 0  # keep record of correct spellings
    wrong_score = 0    # keep record of wrong spellings exceeding number of trials
    max_trials = 3     # maximum number of trials

    # A dictionary of numbers as keys and spellings as values. This can be expanded to increase its level of difficulty.

    number_spell = {0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",
                        7:"seven",8:"eight",9:"nine",10:"ten"}

    # get the list of keys from the dict and shuffle them so that random numbers are displayed on the screen.
    number_spell_keys = list(number_spell.keys())
    random.shuffle(number_spell_keys)

    # Our game starts here
    for number in number_spell_keys:
        # outer loop is a for loop which iterate through the keys

        trial_count = 0 # keeps track of number of trials
        while trial_count < max_trials:
            # inner loop is a while loop that checks if number of trials by the user exceeded the max
            # get user input
            spelling = input("Spell {}: ".format(number))
            if spelling.lower() == number_spell[number]:
                # if user got it right, increment it's score and break out of the outer loop
                correct_score += 1
                break
            else:
                # if not, increment number of trials and ask the user to try again
                trial_count += 1
                print("Incorrect spelling. {} trials left\n".format(max_trials-trial_count))
        
        else:
            # if while loop condition fails, increment wrong score and quit the inner loop
            print("Sorry! Number of trials Exceeded")
            wrong_score += 1

    print("-------------------\nEND OF GAME\n")
    print("CORRECT SPELLING SCORE: {}\n".format(correct_score))
    print("WRONG SPELLING SCORE: {}".format(wrong_score))



if __name__ == '__main__':
    word_spelling()

Output

Spelling game

The main functionalities of our for-loop and while-loop are:

  • The for loop iterates through a list of numbers that are presented to the user to spell.
  • The while loop checks if the number of trials has been exceeded. In this way, a user is given a maximum number of trials to get it right.

We have seen two new concepts while-else, break(more on this later). The while loop and for loop originally have an else statement which only executes once when the condition is FALSE.

Python Infinite Loops

If we are not careful with how we implement our loops, then it can lead to an infinite loop i.e. the program will execute a block of code forever until our computer runs out of resources like CPU memory.

Example 1: Infinite while loop

def infinit_loop_1():
    numb = 0
    while numb < 5:
        print(numb)

if __name__ == '__main__':
    infinit_loop_1()

Output

Infinite while loop

Note: To stop this program from running, use Ctrl+z or Ctrl+c on the terminal you used to run the code.

Our code above implements an infinite while loop. However, this is by mistake because our while loop checks the condition numb < 5, but there is nowhere in the code that actually increments the numb’s value. Hence the value of numb is always zero and the condition keeps returning TRUE.

So, the way to fix this is to provide a means to increment numb’s value.

def infinit_loop_1():
    numb = 0
    while numb < 5:
        print(numb)
        numb += 1 # fix by incrementing numb's value

if __name__ == '__main__':
    infinit_loop_1()

Output

Fix infinite loop

A question may arise as are infinite loops really necessary? Spoiler alert: Yes they are. A server may be programmed to run continuously while serving the needs of clients. In gaming, an event may run until the user selects an action to quit or break the loop.

Believe it or not, we actually used an infinite loop in the last practical example above. So, how do we deal with infinite loops?

Python Break And Continue Statements

As we explained above, there are cases where we will need to write intentional infinite loops. In these cases, we will see that the break and continue keywords are the backbone of infinite loops.

The break and continue keywords are commonly used within a Python if statement where the if statement checks a condition and if it’s TRUE, we either break out of the loop in which our if statement was called or continue by skipping all code below it and return to the beginning of the loop.

Example – Accumulate Numbers Until A Threshold Is Met

Let’s consider a program that gets numbers from a randomly generated source and accumulate the numbers until a threshold is reached.

The reason why this example requires an infinite loop is that we don’t know exactly how many iterations our program will need to perform for the accumulated numbers to reach the threshold.

Our only savior is the Python if statement together with the break statement. Our if statement checks if the threshold is reached, then it breaks out of the loop if TRUE.

Our program also requires that some restricted numbers shouldn’t be accumulated. So, if our program encounters these numbers, it should skip all the codes and return to the beginning of the loop. This is achievable with the continue statement.

import random
def acc_numbers():
    acc_numb = 0    # initialize our accumulator
    threshold = 45  # define our threshold value
    Rejected_numbers = [4,0,1] # define our rejected numbers

    while True: # This is an uncontrolled condition.
        # our infinite while loop

        # return random integer number within 0 and 10.
        numb = random.randint(0, 10)

        # check if the number is in the list of rejected numbers
        if numb in Rejected_numbers:
            print("Not accepting ", numb)
            continue # skip all code blow it and return to the beginning of the while loop

        # add random number to our store
        acc_numb += numb

        # check if the accumulated number has reached threshold
        if acc_numb >= threshold:
            print("Threshold attended")
            break # break out of the loop.
        

if __name__ == '__main__':
    acc_numbers()

Output

Threshold is met

Frequently Asked Questions

Q #1) How do you control a Loop in Python?

Answer: In Python, you can control a loop with the following control statements:

  • The break keyword breaks out of a loop.
  • The continue keyword skips all the codes below it and returns to the beginning of the loop.

These keywords are mostly used in an if statement that first checks if a condition is TRUE or FALSE.

Q #2) What is the difference between for loop and while loop?

Answer: A for loop is an iterator based loop, which steps through the items of iterable objects like lists, tuples, etc. While a while loop is a condition-based loop, that executes a block of statements repeatedly as long as its condition is TRUE.

Q #3) Does Python do support until loop?

Answer: Unfortunately, Python doesn’t support the do-while loop.

Q #4) What are the two types of loops in Python?

Answer: Python generally supports two types of loops: for loop and while loop. However, a third loop[nested loop] can be generated by nesting two or more of these loops.

More About Python Loops

Looping statements in python are used to execute a block of statements or code repeatedly for several times as specified by the user.

Python provides us with 2 types of loops as stated below:

  • While loop
  • For loop

#1) While loop:

While loop in python is used to execute multiple statements or codes repeatedly until the given condition is true.

We use a while loop when we don’t know the number of times to iterate.

Syntax:

while (expression): block of statements Increment or decrement operator

In the while loop, we check the expression, if the expression becomes true, only then the block of statements present inside the while loop will be executed. For every iteration, it will check the condition and execute the block of statements until the condition becomes false.

Example:


number = 5
sum = 0
i = 0

while (i<number):
        sum = sum + i
        i = i+1

print(sum)

Output:

10

while_loop

Output:

while_loop_output

#2) For loop:

For loop in python is used to execute a block of statements or code several times until the given condition becomes false.

We use the for loop when we know the number of times to iterate.

Syntax:

for var in sequence: Block of code

Here var will take the value from the sequence and execute it until all the values in the sequence are done.

Example:


language = [‘Python’, ‘Java’, ‘Ruby’]

for lang in language:
      print(“Current language is: “, lang)

Output:

Current language is: Python

Current language is: Java

Current language is: Ruby

for_loop

Output:

for_loop_output

For loop using range () function:

The Range () function is used to generate a sequence of numbers.

For Example, range (5) will generate numbers from 0 to 4 (5 numbers).

Example:


language = [‘Python’, ‘Java’, ‘Ruby’]

for lang in range(len(language)):
      print(“Current language is: “, language[lang])

Output:

Current language is: Python

Current language is: Java

Current language is: Ruby

for_loop_using_range

Output:

for_loop_using_range_output

Conclusion

In this tutorial, we saw the definition of loops, the types of Python loops, usage of for loop, and while loop with some examples.

We also learned how nested loops are generated and finite loops as well and we came to know how to use the break and continue keywords.

=> Check ALL Python Tutorials Here

PREV Tutorial | NEXT Tutorial