Sunday, October 25, 2020

for 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 for loop in  python. syntax of for loop in python programming

for data in sequence:
    Loop Statements
for loop starts with while keyword and data in sequence followed by a colon representing a new block of for. Statements in the loop are executed repetitively until the data is available in sequence.

paste the below code into a file for_loop.py and execute the code. Code referred will be same as while chapter, difference will be using for loop in place of while loop.

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()
    for word in wordList :
        print(word)
        

if (__name__ == '__main__'):
    if(len(sys.argv) < 2):
        print('Provide string as an argument')
        exit(0)
    inpStr = sys.argv[1]
    printWords(inpStr)


Output produced by while and for loop are same. Refer to usage of while loop in python.

Code snippet of for loop from GitHub

No comments:

Post a Comment

Operations on Python Dictionaries