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



Monday, 5 December 2016

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

Python while-else loop - In the last article, we have covered the first loop statement in Python, for-else statement. In this article, we are going to learn about another loop statement - while-else loop. There are some differences as far as syntax and their working patterns are concerned, which we will be studying in this tutorial. Lets begin!


Python while Loop

The key difference between for and while loops is that, where for requires a Python iterable object to form a loop, while loop, we do not have any such prerequisites. It just needs a condition to be provided, which is tested at every iteration. As long as the condition is True, the block of statement is executed repeatedly. Once the condition becomes False, while loop is exited. Have a look at the while loop syntax below.

while (condition) :
    # Block of statements starts
    ----
    ----
    ----
    ----
    # Block of statements ends

In this, when we enter the while loop for the first time, condition is checked, if it evaluates to False, it does not enter into the loop. If the condition evaluates to True, the block of statement is executed to finish the first iteration. After this, control goes back to the while (condition) : statement to re-check the condition and the process repeats. The block of statements will keep executing repeatedly as long as the condition evaluates to True, thus forming a loop. An immense care should be taken in order not to get caught into an infinite loop, while using while loop. Lets check out some examples of while loop.

Example 1 : Printing numbers and their squares

>>> myNum = 11
>>> myVar = 0
>>> while myVar < myNum :
...     print 'Square of ' + str(myVar) + ' is ' + str(myVar ** 2)
...     myVar += 1
...
Square of 0 is 0
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
Square of 6 is 36
Square of 7 is 49
Square of 8 is 64
Square of 9 is 81
Square of 10 is 100

In above example, we have a variable myVar which begins counting from 0 until its value is less than another variable myNum = 11. In the first iteration, myVar = 0 which is less than myNum and evaluates the condition to True and executes the print statement. After printing, the value of myVar is incremented by 1 to finish the first iteration. Now, control goes back to while statement where condition myVar < myNum is checked. Here, myVar = 1 and myNum = 11 evaluates the condition to True and block of statement is executed. This process will repeat till myVar reaches 10. At this point, myVar = 10 and myNum = 11 evaluates the condition to True, prints the statement and increments myVar by 1 to take a value 11. Now, when the control goes back to while statement, it evaluates the condition to False which terminates the loop.

Example 2 : Factorial of a number

# Calculating 7!
>>> myNum = 7
>>> fact = 1
>>> while myNum :
...     fact *= myNum
...     myNum -= 1
...
>>> print fact
5040

# Calculating 5!
>>> myNum = 5
>>> fact = 1
>>> while myNum :
...     fact *= myNum
...     myNum -= 1
...
>>> print fact
120

In above example, we use while loop such that the variable myNum takes the values ranging from it's initial value to 1 (Please observe the myNum -= 1 statement). We use these values to continuously keep multiplying another variable fact, that stores the result. Eventually, fact will contain 1 * 2 * 3 * ... * myNum which is printed on the last line. Please note that, when the variable myNum reaches the value 0, condition evaluates to False to come out of while loop.

break and continue Statements Revisited

As we've already seen in the last article on Python for loops, break statements are used for terminating a loop prematurely, based on certain condition. The break statement can also be used in the same way in case of while loops. We also have continue statement, that is used to skip executing further code, by jumping straight to the next iteration, based on certain condition.

Example 1 : Breaking the iteration

>>> myNum = 11
>>> myVar = 1
>>> while myVar < myNum :
...     print 'This is iteration #' + str(myVar)
...     if myVar == 6 :
...             print 'This is the last iteration and we stop here.'
...             break
...     myVar += 1
...
This is iteration #1
This is iteration #2
This is iteration #3
This is iteration #4
This is iteration #5
This is iteration #6
This is the last iteration and we stop here.

In above example, we created a loop which starts with myVar = 1 and is expected to run till myVar reaches myNum. But, with the if condition mentioned, the loop is terminated prematurely when the value of myVar reaches 6.

Example 2 : Printing only Even numbers using 'continue' statement

>>> myNum = 15
>>> myVar = 1
>>> while myVar < myNum :
...     if myVar % 2 != 0 :
...             myVar += 1
...             continue
...     print 'This number = ' + str(myVar)
...     myVar += 1
...
This number = 2
This number = 4
This number = 6
This number = 8
This number = 10
This number = 12
This number = 14

In above example, we create a loop which is expected to print values from 1 to 14. But, with if statement, we check whether myVar is an Even number, if it is, we print the statement. If myVar is Odd, continue statement is executed, which jumps to the next iteration by skipping the execution of subsequent lines of code. As a result, we get only even numbers printed on the screen.

Python while-else Loop

As in case of for loop, we have an optional else block in case of while loops. It does work in exactly the same way it works in case of for loop. The else block gets executed only when the break statement is not executed. This also means that, absence of break statement will execute the else block once. Please take a look at below examples.

Example :

# 'break' is executed, hence 'else' will not be executed
>>> myNum = 6
>>> myVar = 1
>>> while myVar <= 10 :
...     if myVar == myNum :
...             print 'Breaking out of the loop'
...             break
...     print 'This number = ' + str(myVar)
...     myVar += 1
... else:
...     print 'Break statement is executed, printing "else" block'
...
This number = 1
This number = 2
This number = 3
This number = 4
This number = 5
Breaking out of the loop

# 'break' is not executed, hence 'else' will be executed
>>> myNum = 12
>>> myVar = 1
>>> while myVar <= 10 :
...     if myVar == myNum :
...             print 'Breaking out of the loop'
...             break
...     print 'This number = ' + str(myVar)
...     myVar += 1
... else:
...     print 'Break statement is executed, printing "else" block'
...
This number = 1
This number = 2
This number = 3
This number = 4
This number = 5
This number = 6
This number = 7
This number = 8
This number = 9
This number = 10
Break statement is executed, printing "else" block

In above examples, we try to print numbers from 1 to 10. In first example, we introduce a break statement when myVar reaches 6. Due to this, the program will print numbers from 1 to 5 and as soon as myVar takes value equal to 6, program executes break, due to which else block is skipped from being executed. In the second example, the loop will be broken when myVar reaches 12, which it will never reach and break statement will never get executed. As break is not executed, else block is executed.

With this, we have come to an end of this discussion on Python while loops. In this article, we've learned how while are constructed and how the control flow works. We have also revised how break and continue statements work in while loops. After that we studied the while-else loop along with its examples. Having covered for and while loops, we have finished the loop statements in Python. In the next article, we will be discussing on Python functions. Please share your views and feedback on this article in the comments section below and stay tuned. Thank you!

This article is originally published at www.codeninja.in - Python while-else Loop with break and continue Statement

0 comments:

Post a Comment