Sunday, October 25, 2020

While Loop in Python

Loops are used in programming language to perform a particular task repetitively until a condition is met. In this chapter we will cover while loop in  python. syntax of while loop in python programming

while expression:
    Loop Statements
While loop starts with while keyword and expression (condition for while) followed by a colon representing a new block of while. Statements in the loop are executed repetitively until the expression is evaluated to false.

paste the below code into a file while_loop.py and execute the code

import sys

'''
    Program to demonstrate while loop 
    Reads a string and prints each word.    
'''
def printWords(string):
    '''
        print Words function reads the strings, splits on space
        loops through the words and prints the words
        
        Args:
            Takes a string as a input
        Returns:
            no return
    '''
    wordList = string.split()
    wordCount = len(wordList)
    k = 0
    while(k < wordCount):
        print(wordList[k])
        k += 1
        
        

if (__name__ == '__main__'):
    if(len(sys.argv) < 2):
        print('Provide string as an argument')
        exit(0)
    inpStr = sys.argv[1]
    printWords(inpStr)
 
Alternatively code can be downloaded from GitHub

Here we are passing a command line argument to the program while_loop.py . The program parses the argument string splits and prints words to the console using while loop.

Let us see one more simple program using while loop with continue and break.
continue: skips the current iteration and continues with the next one.

i=0
while (i<=10):
    i += 1
    if (i%2 == 0):
        continue
    print(i)


break: stops the loop at the current iteration and exits the loop.

i=0
while (i<10):
    i += 1
    if (i == 5):
        break
    print(i)


loop starts evaluating the statements inside the loop, Immediately after break statement the control comes out of the loop and loop stops executing.

No comments:

Post a Comment

Operations on Python Dictionaries