Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Thursday, 1 December 2016

Python 'for-else' loop with 'break' & 'continue' statements

Python for-else loop - We are going to cover for and for-else loop in this discussion. In the last article, we have learned about Python conditional statements in which we had covered if, if-else and if-elif-else statements. Moving a step forward, we now try to understand Python loop statements which are for and while statements. In this article, we will be discussing about for and for-else loop along with their syntax and examples.

python-for-else-loop-with-break-continue-statements

Generally, a for loop in any programming language is used to execute a block of statements for a specific number of times. We can also use break statement in order to exit from the loop based on some condition or even jump to the next iteration using continue statement. Without these two statements, a for loop will execute a fixed number of times. Normally, in order to create a for loop, you will need to include three things - Initialization (where you initialize the variable), Condition (where condition is checked, if False we come out of the loop) and Increment or Decrement (where the variable is incremented or decremented). All these things in a for statement will create a loop for you. Have a look at the syntax below:

for ( initialization, check_condition, increment/decrement)
{
    # Block of statements starts
    ----
    ----
    ----
    # Block of statements ends
}

In the first step Initialization, we declare a variable (often known as 'loop control variable'). In the next step Condition check, a condition is checked whether it evaluates to True or False. If it evaluates to True, block of code is executed, else not. After completion of each iteration, the variable is incremented or decremented and condition is re-checked. Depending upon the situation, the block of statements is executed or loop is exited. Thus, as long as the condition evaluates to True, the block of statements will keep on executing. So, we have the increment/decrement option in order to ensure that the loop will exit at some point of time. If it was not there, we would have been caught inside an infinite loop that never exits.

Python for Loop

In Python, we do not have Initialization, Condition check and Increment/Decrement. Instead, we have a Python object that can be iterated over, like a String, a List, a Tuple. We also have a variable that takes values from the Python iterable object, one-by-one, and runs the block of statements, till the last item in the iterable is reached. Once the last item from the Python object is processed, the for loop is exited. Take a look at the for loop syntax in Python.

Syntax :

for variable_name in python_iterable_object :
    # Block of code starts
    ----
    ----
    ----
    # Block of code ends

In the first iteration, the iterable variable variable_name will take the value equal to first item in python_iterable_object, execute the block of commands and control goes back to the for statement to start the second iteration. In second iteration, the iterable variable variable_name will take the value equal to second item in python_iterable_object, execute the block of commands and control is shifted back to the for statement. This process continues till last item in the iterable object is reached, after which loop is ended.

Please take a look at below example, wherein we have used Python built-in range() function, which returns a list type and a Python iterable object. Please read our article Introduction to Python Lists for more information about range() function.

Example 1 : Iteration using range() function

# range(6) returns [0, 1, 2, 3, 4, 5]
>>> for myVar in range(6):
...     print 'This is the iteration number : ' + str(myVar + 1)
...
This is the iteration number : 1
This is the iteration number : 2
This is the iteration number : 3
This is the iteration number : 4
This is the iteration number : 5
This is the iteration number : 6

Example 2 : Calculation of squares of first 10 integers

>>> for myVar in range(10):
...     myVar += 1
...     print 'Square of ' + str(myVar) + ' = ' + str(myVar ** 2)
...
Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
Square of 4 = 16
Square of 5 = 25
Square of 6 = 36
Square of 7 = 49
Square of 8 = 64
Square of 9 = 81
Square of 10 = 100

Example 3 : Iterating through a String

>>> myStr = 'CodeNinjadotin'
>>> for myVar in myStr:
...     print 'This letter is ' + myVar.upper()
...
This letter is C
This letter is O
This letter is D
This letter is E
This letter is N
This letter is I
This letter is N
This letter is J
This letter is A
This letter is D
This letter is O
This letter is T
This letter is I
This letter is N

Example 4 : Iterating through a List

>>> myList = [5, 10, 15, 20]
>>> for myVar in myList:
...     print 'Cube of ' + str(myVar) + ' = ' + str(myVar ** 3)
...
Cube of 5 = 125
Cube of 10 = 1000
Cube of 15 = 3375
Cube of 20 = 8000

Example 5 : Iterating through a Tuple

>>> myTuple = ('Barcelona', 'Real Madrid', 'Liverpool', 'Bayern Munich')
>>> for myClub in myTuple:
...     print 'I Love ' + myClub + ' !'
...
I Love Barcelona !
I Love Real Madrid !
I Love Liverpool !
I Love Bayern Munich !

Example 6 : Iterating through Key-Values in a Dictionary

>>> myDict = {'Italy': 'Juventus', 'Germany': 'Bayern Munich', 'England': 'Leicester City', 'Spain': 'Barcelona'}
>>> for (country, club) in myDict.items():
...     print club + ' -> ' + country
...
Bayern Munich -> Germany
Juventus -> Italy
Leicester City -> England
Barcelona -> Spain

The break and continue Statements

Any discussion on loop statements without mentioning break and continue statements is incomplete. The break statement are typically used inside an if statement in order to prematurely exit from the for loop based on certain condition. Whereas, continue statement will jump to the next iteration without executing subsequent block of code, based on a condition.

Syntax :

for variable_name in python_iterable_object :
    ----
    ----
    ----
    if (condition) :
        ----
        ----
        break
    ----
    ----
    if (condition) :
        ----
        ----
        continue

Example 1 : 'break' statement to stop counting at 5

>>> for myVar in range(1, 11):
...     if myVar > 5 :
...             break
...     print 'This number = ' + str(myVar)
...
This number = 1
This number = 2
This number = 3
This number = 4
This number = 5

In above example, myVar is always kept in check whether it is greater than 5. Until it is less or equal to 5, if condition evaluates to False and print statement is executed. Once it reaches 6, condition evaluates to True which then executes break statement, thus exiting from the loop. In the end, we have all the numbers less or equal to 5.

Example 2 : 'continue' statement to print only Even numbers

>>> for myVar in range(1, 11):
...     if myVar % 2 != 0 :
...             continue
...     print 'This number = ' + str(myVar)
...
This number = 2
This number = 4
This number = 6
This number = 8
This number = 10

In this example, we keep a check on myVar whether it is Even or Odd with the expression myVar % 2 == 0. Whenever the condition evaluates to False, print statement is executed. When it evaluates to True, continue statement is executed, that jumps to next iteration skipping the execution of further statements, due to which print does not execute. As a result, we have all the even numbers printed on the terminal.

for-else Loop

Well, this might seem to be very unusual, but we do have an optional else block in for statement in Python. This else block gets executed only when break statement is not executed. If there is no break statement in the code, else block will always execute.

>>> myNum = 9
>>> for myVar in range(15):
...     if myVar == myNum:
...             print 'Found !'
...             break
...     else:
...             continue
... else:
...     print 'Not found !'
...
Found !

>>> myNum = 21
>>> for myVar in range(15):
...     if myVar == myNum:
...             print 'Found !'
...             break
...     else:
...             continue
... else:
...     print 'Not found !'
...
Not found !

In above example, we iterate through a list of 15 integers and compare if the number is myNum. If the number matches, we print Found! and execute break statement. If the number is not found, break statement is never executed, because of which else block gets executed, which eventually prints Not found !.

With this, we end our discussion on Python for and for-else loops. In this article, we learned how both these loops can be constructed and used. We have also learned about loop control statements - break and continue, along with their examples. In the next article, we will learn about another Python loop statement - while loop. Note that, break and continue statements will have the same role in case of while loops also. Please share your opinions and feedback in the comment section below and stay tuned for more articles. Thank you.

This article is originally published at www.codeninja.in - Python for-else loop with break and continue statements

0 comments:

Post a Comment