In the previous post, we covered conditional statements in Python. In this post, we will be covering various looping constructs in Python. Like conditional statements, statements within loops are also distinguished by Python based on indentation.

for loop

A for loop is used to iterate over a fixed number of items (i.e., you (or at least the program) know(s) the number of items before entering into the loop). The for loop in Python can be used to iterate over any of the sequence data types which have an iterable method including strings (though they don’t have an iterable method). Following snippet is an example of simple for loop in Python:

for x in "spam":
    print (x)

The above for loop would print each letter of the word “spam” on a new line.

The range() function

As we are learning the for loop, it is equally important to know about the built-in range() function. The range() function takes up to 3 arguments (at least 1 is required), the first one being the start value of the range (default value is 0), the second is the end value of the range (required) and the third one being the step value of the range (i.e., difference between two adjacent members of the range) (default value is 1).

Let’s consider some examples:

  1. range(3) -> Range of numbers from 0 to 2.
  2. range(1,10) -> Range of numbers from 1 to 9.
  3. range(5,26,5) -> All multiples of 5 up to and including 25.

(Note: The end value is not inclusive)

The range() function can be used in place of a sequence data type while using the for loop. (See Examples below for reference)

while loop

The while loop is a bit different than the for loop. Unlike the latter which iterates over a fixed number of items or a range of numbers, the while loop runs for unfixed number of iterations not known at the beginning and stops when a condition is satisfied.

Following is the syntax of the while loop:

while conditional_expression:
    statements_within_while

The conditional expression evaluates to True at the beginning and the while loop exits when the expression evaluates to False. while loop is usually used in cases like waiting for user input, reading files, waiting for an operation to complete etc. Consider going through the example given a little below in this post to get an idea of a situation in which the while loop could be used.

Infinite while loop

Consider the following while loop snippet:

while True:
    print ("Spam")

The above loop would never terminate at all and keep going on forever as the condition never evaluates to False. This is called as the infinite loop and such loops never terminate. (However, you can stop the program by pressing Ctrl + C on your keyboard if you executed the above code)

Control statements

Python provides 4 useful control statements which can be used to control the execution of both the the for loop and the while loop.

break statement

The break statement is used to terminate a loop’s execution before it has finished the total iterations (in case of for) or the conditional expression evaluates to False (in case of while).

A good situation to use the while loop along with the break statement would be the following snippet which prints the square of the number entered by the user and stops only when the user enter a character.

while True:
    a = float(input ("Enter a number or enter 0 to stop: "))
    if a==0:
        break
    print(f"Square of {a} is {float(a)**2}")

You can see the output below:

Output of program

continue statement

The continue statement is used to skip the execution of any statements below itself in the loop. It is particularly useful when combined with an if statement.

For example, the following snippet would print all numbers from 1 to 10 except 5:

for x in range(1,11):
    if x == 5:
        continue
    print(x)

You can see the output below:

Output of for loop

pass statement

The pass statement is simply does nothing. It is used where code is required syntactically but requires no computation or action. So, our infinite while loop snippet could be simplified as under:

while True:
    pass

else statement

Python allows using else statements with loops (Yes, you heard it right!). The else statement, unlike when used with if, is executed only after the loop completes iterations (in case of for loop) or the condition evaluates to False (in case of while loop).

Important Note: The else statement is not triggered when the loop terminates due to break statement.

Examples

Let’s go through some example snippets below based on conditionals and looping statements.

  1. Write code to print all the even numbers from 1 to n on the same line. n is input by the user.

    The Snippet:

    n = int(input("Enter a number: "))
    if n>1:
        for x in range(2,n+1,2):
            print (x)
    else:
        print ("Number should be greater than 1.")
    

    The output can be seen as under: Snippet 1 output

  2. Write code to print the following patterns:

    a)

    *

    **

    ***

    ****

    *****

    b)

    *****

    ****

    ***

    **

    *

    The Snippet:

    for x in range(1,6):
        print (x*"*")
    print()
    for x in range (5,0,-1): # Yes, we can use ranges in reverse order.
        print (x*"*")
    

    The output can be seen as under: Output of snippet 2

  3. Write code to check whether a number is prime or not. (A number is prime if it does not have any other factor other than 1 and the number itself. 1 is neither prime nor composite)

    The Snippet:

    n = int(input("Enter a number: "))
    
    if n == 1:
        print (f"{n} is neither prime nor composite.")
    
    else:
        for x in range(2,n):
            if n%x == 0:
                print (f"{n} is not prime.")
                break
        else: # Note the use of the else statement with the for loop.
            print (f"{n} is a prime number.")
    

    The output can be seen as under: Prime Number Output

  4. Write code to print the first n numbers of the Fibonacci series where n is input by user. The Fibonacci starts from 0 and 1 and every next number is the sum of previous 2 numbers. So the first 5 numbers of the series would be 0,1,1,2,3,5.

    The Snippet:

    n = int(input("Enter the number of terms of the Fibonacci series to be printed: "))
    p=0
    q=1
    
    for x in range(1,n):
        if x == 1:
            print(p)
        print (q)
        (p,q) = (q,p+q) # This is a method by which you can swap the values between 2 variables in Python.
    

    The output can be seen as under: Fibonacci Output

Summary

In this post, we have learnt looping statements in Python and how to use each one of them along with some example programs. Thank you for reading through and hope you learnt something valuable from this post. Follow us for more posts on tech and software.