Output:  16  {1: 1, 2: 4, 3: 9, 5: 25}  (5, 25)  {1: 1, 2: 4, 3: 9}  {}    Dictionary Methods    Method                                Description    clear()                    Removes all items from the dictionary.    copy()                     Returns a shallow copy of the dictionary.                                Returns a new dictionary with keys from seq and value equal to v  fromkeys(seq[, v])                                (defaults to None).    get(key[,d])               Returns the value of the key. If the key does not exist, returns d                             (defaults to None).    items()                    Return a new object of the dictionary's items in (key, value)                             format.    keys()                     Returns a new object of the dictionary's keys.                               Removes the item with the key and returns its value or d if key is    pop(key[,d])               not found. If d is not provided and the key is not found, it raises                               KeyError.    popitem()                  Removes and returns an arbitrary item (key, value). Raises                             KeyError if the dictionary is empty.                               Returns the corresponding value if the key is in the dictionary. If    setdefault(key[,d]) not, inserts the key with a value of d and returns d (defaults to                               None).    update([other])            Updates the dictionary with the key/value pairs from other,                             overwriting existing keys.    values()                   Returns a new object of the dictionary's values                               Table 2.5 Dictionary Method in Python                                                                                                    51                               CU IDOL SELF LEARNING MATERIAL (SLM)
Exercise:  Write a Python program to combine two dictionary adding values for common keys.      from collections import Counter    d1 = {'a': 100, 'b': 200, 'c':300}    d2 = {'a': 300, 'b': 200, 'd':400}    d = Counter(d1) + Counter(d2)    print(d)      Output    Counter{'d': 400, 'b': 400, 'a': 400, 'c': 300}    Exercise: Write a Python script to print a dictionary where the keys are numbers between 1  and 15 (both included) and the values are square of keys.      d=dict()    for x in range(1,16):         d[x]=x**2    print(d)      Output    {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12:    144, 13: 169, 14: 196, 15: 225}    DICTIONARY COMPREHENSION  Dictionary comprehension is an elegant and concise way to create dictionaries.  Syntax      dictionary = {key: value for vars in iterable}    Example                                          52    CU IDOL SELF LEARNING MATERIAL (SLM)
square_dict = {num: num*num for num in range(1, 11)}    print(square_dict)      Output    {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}    Conditionals in Dictionary Comprehension  We can further customize dictionary comprehension by adding conditions to it      original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}    even_dict = {k: v for (k, v) in original_dict.items() if v % 2 == 0}    print(even_dict)      Output    {'jack': 38, 'michael': 48}    2.5 SUMMARY     • Python is used to store collections of data enclosed with [ ]. List is mutable.   • List is a versatile data type available in Python. It is a sequence in which elements are         written as a list of comma-separated values (items) between square brackets   • A tuple is a collection of objects which ordered and immutable which are enclosed in ()   • A tuple is a sequence of immutable objects   • Tuples can be used as key for a dictionary   • A set is an unordered collection of unique items enclosed within {}   • Every set element is unique (no duplicates) and must be immutable (cannot be changed)   • Dictionary is a data structure in which we store values as a pair of key and value. Each         key is separated from its value by a colon (:), and consecutive items are separated by       commas.   • Dictionaries are used to store data values in key: value pairs enclosed with {}.    2.6 KEY WORDS        • List-versatile type stores data inside []      • Dictionary-key value pair stored in {}                                                                                  53    CU IDOL SELF LEARNING MATERIAL (SLM)
• Set –unordered collection stored in {}      • Tuples-mutable types represented as ()      • Comprehension-Short way to create Dictionary    2.7 LEARNING ACTIVITY    1. Write a Python program to get a list, sorted in increasing order by the last element in each      tuple from a given list of non-empty tuples.      Sample List: [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]      Expected Result: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]    2. Write a Python script to print a dictionary where the keys are numbers between 1 and 15      (both included) and the values are square of keys.      Sample Dictionary      {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169,      14: 196, 15: 225}    3. Write a Python program to create and display all combinations of letters, selecting each      letter from a different key in a dictionary.      Sample data: {'1':['a','b'], '2':['c','d']}    2.8 UNIT END QUESTIONS                                                                      54    A. Descriptive Questions  Short Questions        1. Differentiate tuple and list      2. Compare list and dictionary      3. What is set in python?                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
4. Can the values of tuple be changed? Justify                                          55      5. What are the properties of dictionary keys?  Long Questions      1. Discuss about the dictionary data type with relevant example.      2. Compare List and Dictionaries      3. Describe about various list operations and list methods with example      4. Write a program to perform binary search      5. How are sets used in python? Give example  B. Multiple Choice Questions   1. Which of the following two Python codes will produce the same output?                tupl1 = (5, 3, 1, 9, 0)           i) print(tup1[:-1])           ii) print(tup1[0:5])           iii) print(tupl1[0:4])           iv) print(tupl1[-4:])        a. i, ii      b. ii, iv      c. i, iv      d. i, iii     2. What will be the output of the following code snippet?       a=[1,2,3,4,5,6,7,8,9]       print(a[::2])        a. [1,2]      b. [8,9]      c. [1,3,5,7,9]      d. [1,2,3]     3. What will be the output of the following code snippet?       arr = [[1, 2, 3, 4],                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
[4, 5, 6, 7],                                                                    56           [8, 9, 10, 11],           [12, 13, 14, 15]]      for i in range(0, 4):         print(arr[i].pop())       a. 1 2 3 4     b. 1 4 8 12     c. 7 11 15     d. 12,13,14,15    4. What will be the output of the following code snippet?      arr = [1, 2, 3, 4, 5, 6]      for i in range(1, 6):         arr[i - 1] = arr[i]      for i in range(0, 6):         print(arr[i], end = \" \")           a.1 2 3 4 5 6           b.3 3 4 5 6 1           c.1 1 2 3 4 5           d.2 3 4 5 6 6    5. What will be the output of the following code snippet?  fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']  fruit_list2 = fruit_list1  fruit_list3 = fruit_list1[:]  fruit_list2[0] = 'Guava'  fruit_list3[1] = 'Kiwi'  sum = 0  for ls in (fruit_list1, fruit_list2, fruit_list3):       if ls[0] == 'Guava':        sum += 1                                                        CU IDOL SELF LEARNING MATERIAL (SLM)
if ls[1] == 'Kiwi':                                                                    57        sum += 20    print (sum)       a. 22     b. 21     c. 0     d. 43    6. What will be the output of the following code snippet?      arr = {}      arr[1] = 1      arr['1'] = 2      arr[1] += 1      sum = 0      for k in arr:         sum += arr[k]      print (sum)     a. 1     b. 2     c. 3     d. 4    7. What will be the output of the following code snippet?      my_dict = {}      my_dict[1] = 1      my_dict['1'] = 2      my_dict[1.0] = 4      sum = 0      for k in my_dict:         sum += my_dict[k]      print (sum)                                                        CU IDOL SELF LEARNING MATERIAL (SLM)
a. 7                                                                                   58     b. Syntax error     c. 3     d. 6    8. What will be the output of the following code snippet?      my_dict = {}      my_dict[(1,2,4)] = 8      my_dict[(4,2,1)] = 10      my_dict[(1,2)] = 12      sum = 0      for k in my_dict:         sum += my_dict[k]      print (sum)      print(my_dict)     a. Syntax error     b. 30             {(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}     c. 47             {(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}     d. 30             {[1, 2]: 12, [4, 2, 1]: 10, [1, 2, 4]: 8}    9. What will be the output of the following code snippet?      box = {}      jars = {}      crates = {}      box['biscuit'] = 1      box['cake'] = 3      jars['jam'] = 4      crates['box'] = box      crates['jars'] = jars                                                        CU IDOL SELF LEARNING MATERIAL (SLM)
print (len(crates[box]))      a. 1      b. 3      c. 4      d. Type Error     10. What will be the output of the following code snippet?         rec = {\"Name\" : \"Python\", \"Age\":\"20\", \"Addr\" : \"NJ\", \"Country\" : \"USA\"}       id1 = id(rec)       del rec       rec = {\"Name\" : \"Python\", \"Age\":\"20\", \"Addr\" : \"NJ\", \"Country\" : \"USA\"}       id2 = id(rec)       print(id1 == id2)      a. True      b. False      c. 1      d. Exception    Answers  1-d, 2-c, 3- c, 4- d, 5- a, 6– d, 7- d, 8– b, 9-d, 10-a.    2.9 REFERENCES    Text Books:      • Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd           edition, Updated for Python 3, Shroff/O ‘Reilly Publishers, 2016      • Michael Urban, Joel Murach, Mike Murach: Murach's Python Programming; Dec,           2016    Reference Books:      • Guido van Rossum and Fred L. Drake Jr, An Introduction to Python – Revised and           updated for Python 3.2,      • Jake VanderPlas, “Python Data Science Handbook”, O ‘Reilly Publishers, 2016.                                          59    CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT - 3: FLOW CONTROL CONSTRUCTS    Structure   3.0. Learning Objectives   3.1. Introduction to control Flow   3.2. The IF Statement   3.3. While Loop   3.4. For Loop   3.5. Jumping Statements   3.6. Summary   3.7. Keywords   3.8. Learning Activity   3.9. Unit End Questions      3.10. References    3.0 LEARNING OBJECTIVES    After studying this unit, you will be able to:       ● Outline the concept of control flow in python       ● Summarise the operators available in python       ● Illustrate the working of branching and looping statements       ● Apply the break and continue statements    3.1 INTRODUCTION-CONTROL FLOW    The control flow of a program is the sequence in which the program's code runs. Conditional  statements, loops, and function calls rule the control flow of a Python program. Unless  control-flow statements are used to branch elsewhere in code, statements execute  sequentially, one after the other. (e.g., if, while, for, raise, calls, etc.).    A nested block is characterized by consistently indenting all of its statements by the same  length, with any number of spaces or tabs used. A nested block will exist on the same line as  the statement header. (following the header’s: character), if it consists of simple (non-  compound) statements only.                                          60    CU IDOL SELF LEARNING MATERIAL (SLM)
Python Indentation    Braces are used to describe a block of code in most programming languages, including C,  C++, and Java. Python, on the other hand, employs indentation. A code block (the body of a  method, loop, or whatever) begins with indentation and ends with the first unintended  segment. It is up to you how much indentation you use, but it must be consistent in the block.  Generally, four whitespaces are used for indentation and are preferred over tabs. Here is an  example      Fori in range(1,11):             print(i)             ifi == 5:                      break    Python enforces indentation, which helps the code appear tidy and clean. As a consequence,  Python code appear identical and stable.    Python Comments  When writing the code, comments are incredibly necessary. They explain what is going on  inside a code so that someone looking at the source code will figure it out. In a month's time,  we might forget the main details of the software we just wrote. Taking the time to illustrate  these principles in the form of comments, on the other hand, is often helpful.  To begin writing a comment in Python, we use the hash (#) symbol. It goes all the way up to  the newline character. Comments are meant to help programmers better understand a code.  The Python interpreter disregards comments.      Example:    #This is a comment    #print welcome message    print('This is my first program')    We may have statements that stretch many lines. In that case, either the hash (#) symbol or  triple quotes may be used before and after the statements.                                          61    CU IDOL SELF LEARNING MATERIAL (SLM)
Example:    ‘‘‘This is a    perfect example of    multi-line comments‘‘‘    3.2 THE IF STATEMENT    The most important aspect of nearly all programming languages is decision making. Decision  making, as the name suggests, helps one to run a certain block of code for a specific decision.  Decisions on the validity of specific criteria are taken here. The foundation of decision  making is condition checking.  The if statement is used to evaluate a condition, and if the condition is correct, it executes an  if-block of code. The if statement's condition can be any valid logical statement that can be  tested as true or false.      Syntax    if test expression/condition:               statement(s)    Flow Chart                                          62    CU IDOL SELF LEARNING MATERIAL (SLM)
Fig 2.1 Working of if statement    Python program to check whether a person is eligible for vote.    n=int(input())    if(n>=18):             print(“Eligible for vote”)    Output:    25    Eligible for vote    Python program to check whether the given number is even or odd.    n=int(input())    if(n%2==0):             print(‘Number is an even number’)      Output:    20    Number is an even number    if...else Statement:    The if-else statement combines an else block with the if statement, which is executed when  the condition is false. If the condition is met, the if-block is run. If not, the else-block is  executed.      Syntax of if...else    if (test expression/condition) :               Body of if    else:               Body of else    Flow Chart:                                          63    CU IDOL SELF LEARNING MATERIAL (SLM)
Fig 2.2 Working of if else statement                      64    Program to checks if the number is positive or negative    num = input(“Enter a number”)    if num>= 0:             print(\"Positive or Zero\")    else:             print(\"Negative number\")      Output:    Enter a number:10    Positive or zero    Python program to check whether the year is leap year or not    n=int(input((“Enter a number”))    if(n%4==0):             print(“Leap year”)    else:             print(“Not Leap year”)    Output:    2000    Leap year                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
elif Statement:  The elif statement helps one to verify several conditions and execute a particular block of  statements based on the true status of those conditions. Based on our needs, we will have as  many elif statements as we like in our code. However, using elif is optional. The elif  statement works like an if-else-if ladder statement in C. It must be succeeded by an if  statement.      Syntax:             if (test expression/condition):                      Body of if             elif (test expression/condition):                      Body of elif             else:                      Body of else    Flow Chart:    Fig 2.3 Working if elif else statement    65        CU IDOL SELF LEARNING MATERIAL (SLM)
Python program to check if the number is positive or negative or zero                       66    num = 3.4    if num> 0:             print(\"Positive number\")    elif num = = 0:             print(\"Zero\")    else:             print(\"Negative number\")      Output:    Positive number    Python program to determine the name of the shape from its number of sides.    n=int(inut())    if(n==7):             print(‘heptagon’)    elif(n==8):             print(“octogon”)    elif(n==9):             print(“nanogon”)    elif(n==10):             print(“decagon”)    else:             print(“input should be from 7 to 10”)      Output:    9    nanogon    Nested if statements:                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
Having an if...elif...else statement inside another if...elif...else statement is referred as nested  if statements. Any number of if statements can be nested inside another if statement, and the  only way to evaluate the degree of nesting is by indentation.  Example  Python program to check if the number is positive or negative or zero using nested if.      num = float(input(\"Enter a number: \"))    if num>= 0:               if num == 0:                      print(\"Zero\")               else:                      print(\"Positive number\")      else:             print(\"Negative number\")    Output 1:  Enter a number: 5  Positive number    Output 2  Enter a number: -1  Negative number    Output 3  Enter a number: 0  Zero    3.3 WHILE LOOP    By default, the flow of writing programs in any programming language is sequential.  We can need to change the program's flow from time to time. The execution of a particular  code can need to be replicated many times. Programming languages have different types of  loops for this purpose, and are capable of repeating a particular code a number of times.  The Python while loop executes a segment of code until the specified condition returns false.                                                              67                        CU IDOL SELF LEARNING MATERIAL (SLM)
It is often referred to as a pre-tested loop. When we don't know how many iterations the  sentences can go to, the while loop is the most efficient way to go.      Syntax             while expression:                      statements    Here, the statements can be a single statement or a group of statements. The expression can  be any legitimate Python expression that returns true or false. True is every non-zero value,  while false is 0.  Flow Chart of while loop:                                         Fig 2.4 Working of while loop    Example:  Python program using while Loop to add natural numbers up to n                                                                        68    CU IDOL SELF LEARNING MATERIAL (SLM)
n = int(input(\"Enter n:\"))    sum = 0    i=1    while i<= n:               sum= sum + i             i = i+1    print(\"The sum is\", sum)      Output:    Enter n: 10    The sum is 55    In the above program, the test expression will be True as long as our counter variable i is less  than or equal to n.  Program to add n Natural numbers      n = int(input(\"Enter n: \"))    sum = 0    i=1    while i<= n:               sum = sum + i             i = i+1    print(\"The sum is\", sum)      Output:    Enter n: 10    The sum is 55    While loop with else:    Python allows us to use the else statement with the while loop also. The else block is  executed when the condition given in the while statement becomes false. Like for loop, if the  while loop is broken using break statement, then the else block will not be executed, and the  statement present after else block will be executed. The else statement is optional to use with  the while loop.                                          69    CU IDOL SELF LEARNING MATERIAL (SLM)
Example:  Python program to illustrate the use of else statement with the while loop      counter = 0    while counter < 3:                        print(\"Inside loop\")                      counter = counter + 1    else:                      print(\"Inside else\")      Output:    Inside loop    Inside loop    Inside loop    Inside else    A counter variable used to print the string inside loop three times. On the fourth iteration,  the condition in while becomes False. Hence, the else part is executed.    Exercise: Write a python program to compute Highest Common Factor (HCF) of the given  two numbers.      # HCF using Euclidean Algorithm    x=int(input(“Enter a number”))    y= int(input(“Enter a number”))    while(y):           x, y = y, x % y    print(\"The HCF is\", x)      Output:    Enter a number:10    Enter a number:20    The HCF is 10                                          70    CU IDOL SELF LEARNING MATERIAL (SLM)
3.4 FOR LOOP    The for loop is used whenever we need to run a segment of code before the specified  condition is met. A pre-tested loop is another name for the for loop. If the number of  iterations is determined ahead of time, the for loop is preferable. In Python, the for loop is  used to iterate over a sequence (list, tuple, string) or other iterable properties. Iterating over a  sequence is called traversal.      Syntax of for Loop             forval in sequence:                      Body of for                            Fig 2.5 Working of for loop    The range () function:                                                                  71                            CU IDOL SELF LEARNING MATERIAL (SLM)
The range () function is used to generate the sequence of the numbers. If we pass the range  (10), it will generate the numbers from 0 to 9. The syntax of the range () function is given  below.  Syntax:             range(start,stop,step size)        • The start represents the beginning of the iteration.      • The stop represents that the loop will iterate till stop-1. The range(1,5) will generate             numbers 1 to 4 iterations. It is optional.      • The step size is used to skip the specific numbers from the iteration. It is optional to             use. By default, the step size is 1. It is optional.    Example:  Program to print the sum of first n natural numbers      n=input(“Enter range”)    sum = 0    forval in range(1, n):               sum = sum + val             print(“The sum is”,sum)      Output:    Enter range: 5    The sum is 15    Python program to find the factorial of a given number.                                          72    CU IDOL SELF LEARNING MATERIAL (SLM)
num = int(input(\"Enter a number: \"))  factorial = 1  ifnum< 0:             print(\"Sorry, factorial does not exist for negative numbers\")  elifnum == 0:             print(\"The factorial of 0 is 1\")  else:             fori in range(1,num + 1):                    factorial = factorial*i    print(\"The factorial of\", num, \"is\", factorial)    Output:  Enter a number:7  The factorial of 7 is 5040    Program to find the sum of all numbers stored in a list      # List of numbers    numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]    # variable to store the sum    sum = 0    # iterate over the list    forval in numbers:               sum = sum+val    print(\"The sum is\", sum)    Output:  The sum is 48    For loop with else block:    In Python we can have an optional ‘else’ block associated with the loop. The ‘else’ block  executes only when the loop has completed all the iterations.  Example:  Program to check if a number is prime or not                                                                            73                               CU IDOL SELF LEARNING MATERIAL (SLM)
num = int(input(\"Enter a number: \"))    fori in range(2,num):               if (num % i) == 0:                      print(num, \"is not a prime number\")                      break      else:             print(num, \"is a prime number\")      Output:             Enter a number: 13             13 is a prime number    3.5 JUMPING STATEMENTS    In Python, break and continue statements can alter the flow of a normal loop. Loops iterate  over a block of code until the test expression is false, but sometimes we wish to terminate the  current iteration or even the whole loop without checking test expression.    Break Statement:    The break statement terminates the loop containing it. The control of the program flows to the  statement immediately after the loop body.                                          74    CU IDOL SELF LEARNING MATERIAL (SLM)
Fig 2.6 Working of break statement  If the break statement is put inside the nested loops (loop inside another loop), the break  statement will end the inner loop. Working of break statement inside for loop and while loop  is shown below.                                          75    CU IDOL SELF LEARNING MATERIAL (SLM)
Example:    forval in \"string\":               ifval == \"i\":                      break               else:                      print(val)      print(\"The end\")    Output:    s    t    r    The end    Continue Statement:    The continue statement is used to skip the rest of the code inside a loop for the current  iteration only. Loop does not terminate but continues on with the next iteration.  Flow Chart:                                          76    CU IDOL SELF LEARNING MATERIAL (SLM)
Fig 2.7 Working of continue statement  The working of continue statement in for and while loop is shown below.                                                                             77    CU IDOL SELF LEARNING MATERIAL (SLM)
Python Program to show the use of continue statement inside loops      n=int(input())    fori in range(0,n):               a=int(input())             if(a<0):                        continue             print(a)    Output:    n=2    a=-1    a=1    1    Pass Statement:  It is used when a statement is required syntactically but you do not want any command or  code to execute. The pass statement is a null operation; nothing happens when it executes.  The pass is also useful in places where your code will eventually go, but has not been written  yet.                                          78    CU IDOL SELF LEARNING MATERIAL (SLM)
Example:                                                                                  79    for letter in 'Python':               if letter == 'h':                      pass                      print 'This is pass block'               print 'Current Letter :', letter    print \"Good bye!\"      Output:    Current Letter : P    Current Letter : y    Current Letter : t    This is pass block    Current Letter : h    Current Letter : o    Current Letter : n    Good bye!    Exercise:Write a program to display all prime numbers within the given range.    start = int(input(“Enter the starting limit”))    end = int(input(“Enter the ending limit”))    print(\"Prime numbers between\", start, \"and\", end, \"are:\")    for num in range(start, end + 1):       if num > 1:          for i in range(2, num):             # check for factors             if (num % i) == 0:                # not a prime number so break inner loop and                # look for next number                break          else:             print(num)                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
Output:  Enter the starting limit: 4  Enter the ending limit 30  Prime numbers between 4 and 30 are  5  7  11  13  17  19  23  29    3.6 SUMMARY     • A nested block is delimited by indenting all of its statements by the same amount, with       any number of spaces or tabs used consistently     • Comments are for programmers to better understand a program. # is used for single line       comment and ‘’’ are used for multiline comments.     • The if statement is used to test a particular condition and if the condition is true, it       executes a block of code known as if-block.     • Python has two looping statements: for and while loop. Else statement can be used with       loops and will be executed completion of all iteration of loop.     • The break statement terminates the loop containing it. Control flows to the statement       immediately after the body of the loop.     • The continue statement is used to skip the rest of the code inside a loop for the current       iteration only    3.7 KEY WORDS        • Control Statements-control the order of execution      • Looping Statements-used for iterating over a sequence      • Jumping Statements-alter the flow of a loop                                          80    CU IDOL SELF LEARNING MATERIAL (SLM)
• Break-terminate the loop      • Continue-terminate the current iteration and resumes with next iteration    3.8 LEARNING ACTIVITY    1. Write a Python program to display the current date and time.      Sample Output:      Current date and time:      2014-07-05 14:34:14    2. Write a Python program to find those numbers which are divisible by 7 and multiple of 5,      between 1500 and 2700 (both included)    3. Write a Python program to construct the following pattern, using a nested for loop.  *                                                                                          *  *                                                                                       *  *                                                                                       *  **                                                                                      *  ***                                                                                     *  ****                                                                                    *  ***  **  *  *    4. Write a Python program which iterates the integers from 1 to 50. For multiples of three  print \"Fizz\" instead of the number and for the multiples of five print \"Buzz\". For numbers  which are multiples of both three and five print \"FizzBuzz\"                                                                                            81    CU IDOL SELF LEARNING MATERIAL (SLM)
3.9 UNIT END QUESTIONS    A. Descriptive Questions  Short Questions        1. Specify the syntax of range function.      2. Differentiate break and continue statement      3. Discuss about continue and pass statements      4. What are the properties of dictionary keys?      5. Is it possible to use else block with while loop?  Long Questions      1. Explain the various forms of if statements used on python.      2. Explain the looping statements with suitable example.      3. Explain the branching statements with suitable example.      4. Write a Program to Prompt for a Score between 0.0 and 1.0. If the Score is out of             range, print an error. If the score is between 0.0 and 1.0, print a grade using the           following table.        5. Write a python program to all the prime numbers between the given range.             82  B. Multiple Choice Questions  1. Which of the following looping statement is not available in Python?        a. for loop      b. while loop      c. do while      d. None of these    2. Which of the following is True regarding loops in Python?      a. Loops should be ended with keyword \"end\".                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
b. No loop can be used to iterate through the elements of strings.  c. Keyword \"break\" can be used to bring control out of the current loop.  d. Keyword \"continue\" is used to continue with the remaining statements inside the        loop.    3. How many times will the loop run?          i=2        while(i>0):        i=i-12    a. 2    b. 3    c. 1    d. 0    4. Which one of the following is a valid Python if statement      a. if a>=2:      b. if (a >= 2)      c. if (a => 22)      d. if a >= 22    5. In a Python program, a control structure:      a. Defines program-specific data structures      b. Directs the order of execution of the statements in the program      c. Dictates what happens before the program starts and after it terminates      d. None of these    Answers  1-c, 2-c, 3-a, 4-a, 5-b    3.10 REFERENCES                                                                                    83                       CU IDOL SELF LEARNING MATERIAL (SLM)
Text Books:      • Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd           edition, Updated for Python 3, Shroff/O ‘Reilly Publishers, 2016        • Michael Urban, Joel Murach, Mike Murach: Murach's Python Programming; Dec,           2016    Reference Books:      • Guido van Rossum and Fred L. Drake Jr, An Introduction to Python – Revised and           updated for Python 3.2,      • Jake Vander Plas, “Python Data Science Handbook”, O ‘Reilly Publishers, 2016.                                          84    CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT - 4: FUNCTIONS    Structure   4.0. Learning Objectives   4.1. Introduction   4.2. User Defined Functions   4.3. recursive Function   4.4. Arbitrary Number of Arguments   4.5. Keyword and Optional Parameters   4.6. Functions in Modules   4.7. Lambda Functions   4.8. Using map () Function   4.9. filter () function   4.10. reduce () function   4.11. Summary   4.12. Keywords   4.13. Learning Activity   4.14. Unit End Questions   4.15. References    4.0 LEARNING OBJECTIVES    After studying this unit, you will be able to:      • Discuss the concept of functions in python      • Illustrate the working of keyword and optional parameters of functions      • Create programs for real time scenarios using functions with variable arguments      • Apply the lambda functions for solving the given problem    4.1 INTRODUCTION    In Python, a function is a group of related statements that performs a specific task. Functions  help break our program into smaller and modular chunks. As our program grows larger and  larger, functions make it more organized and manageable. A function can be called multiple  times to provide reusability and modularity to the Python program.                                          85    CU IDOL SELF LEARNING MATERIAL (SLM)
Furthermore, it avoids repetition and makes the code reusable.  Types of Functions  Basically, we can divide functions into the following two types:        1. Built-in functions - The built-in functions are those functions that are pre-defined in           Python and are available as libraries.        2. User-defined functions - The user-defined functions are those define by the user to           perform the specific task.    4.2 USER DEFINED FUNCTIONS    You can define functions to provide the required functionality. Here are simple rules to  define a function in Python.        • The keyword def is used to start a function block, followed by the function name and           parentheses (()).        • All input parameters or statements should be enclosed by parentheses.      • Inside these brackets, you can also specify parameters.      • The first statement of a function may be an optional statement - the function's             documentation string, or docstring.      • Any function's code block begins with a colon (:) and is indented.      • The optional declaration return [expression] exits a function by transferring an             expression back to the caller.      • A return declaration with no parameter is synonymous with return None.  Syntax      def functionname( parameters ):             \"function_docstring\"             function_suite             return [expression]    By default, parameters have a positional behaviour, and you need to inform them in the same  order that they were defined                                          86    CU IDOL SELF LEARNING MATERIAL (SLM)
Example:    def factorial(n):               fact=1;             fori in range(1,n+1):                        fact*=i             return fact    In above program one parameter is passed to the functions. The function finds the factorial of  the given number and returns the result    Function Call    A function is defined by giving it a name, specifying the parameters that will be used in the  function, and structuring the code blocks.  If the basic form of a function has been defined, you can invoke it from another function or  directly from the Python prompt.  To call a function we simply type the function name with appropriate parameters.      f=factorial(5)    print(f)      Output:    120    Fig 4.1 Working of functions    Scope and Lifetime of variables    Scope of a variable is the portion of a program where the variable is recognized. Parameters  and variables defined inside a function are not visible from outside the function. As a result,                                          87    CU IDOL SELF LEARNING MATERIAL (SLM)
they have a limited scope. The period of a variable's existence in memory is defined as its  lifetime. Variables within a function have a lifespan equal to the function's execution time.  They are lost when we exit the function. As a result, a function does not recall the value of a  variable from previous call.      Example:    def my_func():               x = 10             print(\"Value inside function:\",x)    x = 20    my_func()    print(\"Value outside function:\",x)      Output:    Value inside function: 10    Value outside function: 20    Here, we can see that the value of x is 20 initially. Even though the function my_func()  changed the value of x to 10, it did not affect the value outside the function.  This is due to the fact that the vector x inside the function differs (is local to the function)  from the one outside. Despite their similar names, they are two distinct variables with distinct  scopes. Variables outside of the function, on the other hand, are noticeable from inside. They  have a global scope.  We can read these values from inside the function but cannot change (write) them. In order to  modify the value of variables outside the function, they must be declared as global variables  using the keyword global.                                          88    CU IDOL SELF LEARNING MATERIAL (SLM)
Program to find GCD of two numbers using functions    def gcd(a,b):               m=min(a,b)             gcd1=1             fori in range(1,m+1):                        ifa%i==0 and b%i==0:                               gcd1=i               return gcd1    x=int(input(\"Enter first number\"))    y=int(input(\"Enter second number\"))    g=gcd(x,y)    print(\"GCDof\",x,\"and \",y,\"is \",g)      Output:    Enter first number: 16    Enter second number:32    GCD of 16 and 32 is 16    Formal parameter -- The parameter defined as part of the function definition, e.g., a, b in  above function definition sum    Actual Parameter -- The actual data sent to a function. It's found in the function call    Fig 4.2: Actual and Formal parameters in function                                                       89    CU IDOL SELF LEARNING MATERIAL (SLM)
Program to find sum of two numbers using functions               def add(a,b):                      c=a+b                      return c               x=int(input(“Enter first number”))             y=int(input(“Enter second number”))             z=sum(x,y)             print(“The sum is”,z)               Output:             Enter the first number 25             Enter the second number 35             The sum is 60    In the above program, the parameters a and b in function definition are formal parameters and  the parameters x and y in the function call are actual parameters    4.3 RECURSIVE FUNCTION    A function is recursive if the function invokes itself. We know in Python that a method can  call other methods. It's also likely that the function would invoke itself. These kinds of  structures are known as recursive functions.  The following figure shows the working of a recursive function called recurse.    Fig 4.3 Working of recursive function      90         CU IDOL SELF LEARNING MATERIAL (SLM)
Program to find factorial using recursion    def factorial(x):               \"\"\"This is a recursive function to find the factorial of an integer\"\"\"             if x == 1:                        return 1             else:                        return (x * factorial(x-1))    num = input(“Enter a number:”)    print(\"The factorial of\", num, \"is\", factorial(num))      Output:    Enter a number:5    The factorial of 5 is 120    When we call this function with a positive integer, it will recursively call itself by decreasing  the number. Each function multiplies the number with the factorial of the number below it  until it is equal to one.  Our recursion ends when the number reduces to 1. This is called the base condition. Every  recursive function must have a base condition that stops the recursion or else the function  calls itself infinitely. The Python interpreter limits the depths of recursion to help avoid  infinite recursions, resulting in stack overflows. By default, the maximum depth of recursion  is 1000                                          91    CU IDOL SELF LEARNING MATERIAL (SLM)
Fig 4.4 Working of recursive factorial function    Program to find exponentiation of two numbers (ab) using recursion  def exp(base,power):             if power==1:                    return base             else:                    return base*exp(base, power-1)    b=int(input(\"Enter the base\"))  p=int(input(\"Enter the power\"))  e=exp(b,p)  print(\"The value of ”,b, \" ^ \",p \"is\",e)                                                                           92    CU IDOL SELF LEARNING MATERIAL (SLM)
Output:  Enter the base:2  Enter the power:3  The value of 2 ^ 3 is 8    4.4 ARBITRARY NUMBER OF ARGUMENTS    Sometimes when we write a function, it's not possible to know ahead of time how many  arguments we will be providing to the function. Suppose we wish to write a function which  will examine an arbitrary number of strings, and return the length of the longest string. By  passing a function argument with a name that starts with an asterisk, Python can collect any  anonymous arguments passed to the function in a tuple that can be reached by the argument's  name. We may use this feature to write a function that returns the length of the longest of a  variable number of arguments by adding an argument whose name starts with an asterisk. (in  this case, we'll use the name *strings), which will become a tuple containing all the  arguments passed to the function:    Example:  def longlen(*strings):             max = 0           for s in strings:                      if len(s) > max:                             max = len(s)             return max    Notice that inside the function, strings are just an ordinary tuple; the asterisk before its name  is only needed when the function is defined. If we call the function with a collection of  strings as arguments, it will check them all, and return the maximum length of any of them:    >>>longlen('apple','banana','cantaloupe','cherry')    10                                                                   93                             CU IDOL SELF LEARNING MATERIAL (SLM)
A similar strategy can be used to write methods that can handle an infinite number of  keyword/argument pairs. If a function argument is followed by two asterisks, Python can  collect all keyword/argument pairs that were not expressly declared as arguments into a  dictionary within the function. When using such an argument, it must be the last argument in  the function's description. In this manner, you can write a function that accepts any specified  parameter, even though its name is unknown when the function is written.      Example:    def printargs(a,b,**dict):               print ('a=', a)             print ('b=’,b_             for k in dict.keys():                        print '%s=%s' % (k,dict[k])    printargs(x='seven',a='six',b='five',next='four',last='three')      Output    a=six    b=five    next=four    x=seven    last=three    Notice that arguments a and b were not placed in the dictionary, since they were explicitly  specified as part of the function definition.                                          94    CU IDOL SELF LEARNING MATERIAL (SLM)
def                     i                       add(*b):     result=0                in b:     for        result=result+i                              result     return    print (add(1,2,3,4,5))  print (add(10,20))    Output:  15  30    4.5 KEYWORD AND OPTIONAL PARAMETERS    Keyword arguments are related to the function calls. When you use keyword arguments in a  function call, the caller identifies the arguments by the parameter name.    This allows you to skip arguments or place them out of order because the Python interpreter  is able to use the keywords provided to match the values with parameters.      Example:    def printinfo( name, age):               \"This prints a passed info into this function\"             print \"Name: \", name             print \"Age \", age             return;    # Now you can call printinfo function    printinfo( age=50, name=\"miki\" )    Output:  Name: miki  Age 50                                                                     95                               CU IDOL SELF LEARNING MATERIAL (SLM)
**kwargs    The special syntax **kwargs in function definitions in python is used to pass a keyworded,  variable-length argument list. We use the name kwargs with the double star. The reason is  because the double star allows us to pass through keyword arguments (and any number of  them).        • A keyword argument is where you provide a name to the variable as you pass it into           the function.        • One can think of the kwargs as being a dictionary that maps each keyword to the           value that we pass alongside it. That is why when we iterate over the kwargs there           doesn’t seem to be any order in which they were printed out.      # Python program to illustrate    # *kwargs for variable number of keyword arguments    def myFun(**kwargs):         for key, value in kwargs.items():          print (\"%s == %s\" %(key, value))      # Driver code    myFun(first ='Geeks', mid ='for', last='Geeks')      Output:    last == Geeks    mid == for    first == Geeks    In short, the unpacking operators are operators that unpack the values from iterable objects in  Python. The single asterisk operator * can be used on any iterable that Python provides, while  the double asterisk operator ** can only be used on dictionaries.    Optional Parameters    If a parameter specified in a Python function definition has the form <name>=<value>, then  <value> becomes a default value for that parameter. Parameters defined this way are referred                                          96    CU IDOL SELF LEARNING MATERIAL (SLM)
to as default or optional parameters. A default argument is an argument that assumes a default  value if a value is not provided in the function call for that argument.      Example:    def printinfo( name, age = 35 ):               \"This prints a passed info into this function\"             print \"Name: \", name             print \"Age \", age             return.    # Now you can call printinfo function    printinfo( age=50, name=\"miki\" )    printinfo( name=\"miki\" )      Output:    Name: miki    Age 50    Name: miki    Age 35    In the above example when age is not passed in the function call it uses the default value as  50.      def student(firstname, lastname ='Mark', standard ='Fifth'):             print(\"First Name: \",firstname)             print(\"Last Name: \", lastname)             print(\"'Studying Class: \", standard)      student(\"John\",\"Sharma\",\"Eigth\")    student(\"Virat\", \"Kohli\")                                          97    CU IDOL SELF LEARNING MATERIAL (SLM)
Output:  First Name:John  Last Name:Sharma  Studying Standard:Eigth  First Name:Virat  Last Name:Kohli  Studying Standard:Fifth    4.6 FUNCTIONS IN MODULES    A module is just another Python file. It can include methods, classes, references to other  modules, and even executing code. When you bring the module into your program, the  methods, classes and modules are made available in your current namespace. Whether or not  Python can find modules and packages depends on their relative location to your current file.    Let us create a module. Type the following and save it as example.py.      example.py    # Python Module example    def add(a, b):               \"\"\"This program adds two numbers and return the result\"\"\"             result = a + b             return result    Here, we have defined a function add() inside a module named example. The function takes  in two numbers and returns their sum.  Importing Modules    We can import the definitions inside a module to another module or the interactive interpreter  in Python. We use the import keyword to do this. To import our previously defined module  example, we type the following in the Python prompt.  >>> import example    This does not import the names of the functions defined in example directly in the current  symbol table. It only imports the module name example there.    Using the module name we can access the function using the dot. operator. For example:                                                                   98                             CU IDOL SELF LEARNING MATERIAL (SLM)
>>>example.add(4,5.5)  9.5    4.7 LAMBDA FUNCTION    A lambda function in Python is an anonymous function that is specified without a name. In  Python, regular functions are defined with the def keyword, while anonymous functions are  defined with the lambda keyword. As a result, anonymous functions are also known as  lambda functions. Python allows one to avoid declaring the method in the traditional way, i.e.  with the def keyword. Rather, the lambda keyword is used to announce anonymous functions.  Lambda functions, on the other hand, can take any number of arguments but can only return  one value in the form of an expression. The anonymous function contains a small piece of  code. It simulates inline functions of C and C++, but it is not exactly an inline function.  Syntax:             lambda arguments: expression  Lambda functions can have any number of arguments but only one expression. The  expression is evaluated and returned. Lambda functions can be used wherever function  objects are required.      # Program to show the use of lambda functions    double = lambda x: x * 2    print(double(5))      Output:    10    If we need a nameless function for a short period of time, we use lambda functions. In  Python, it is commonly used as an argument to a higher-order method. (a function that takes  in other functions as arguments).  Multiply argument a with argument b and return the result:                                          99    CU IDOL SELF LEARNING MATERIAL (SLM)
x = lambda a, b : a * b  print(x(5, 6))    Output:  30    4.8 USING map() FUNCTION    The map() function applies the specified function to every item of the passed iterable, yields  the results, and returns an iterator.  Syntax:  map(function, iterables) --> map object  Parameters:        • function: The function to be called for each element of the specified iterable.      • iterables: One or more iterables separated by a comma (such as string, list, tuple,             dictionary).  Return Value:  Returns an iterator object of the map class.  Example:  def square(x):  return x*x  Now, we can call the map function with the list of numbers to get the list of results, as shown  below.  >>>numbers=[1, 2, 3, 4, 5]  >>> sqrs_of_numbers=map(square, numbers)  >>>next(sqrs_of_numbers)  1  >>>next(sqrs_of_numbers)  4  >>>next(sqrs_of_numbers)  9  >>>next(sqrs_of_numbers)  16  >>>next(sqrs_of_numbers)                                                                   100                             CU IDOL SELF LEARNING MATERIAL (SLM)
                                
                                
                                Search
                            
                            Read the Text Version
- 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 - 11
 - 12
 - 13
 - 14
 - 15
 - 16
 - 17
 - 18
 - 19
 - 20
 - 21
 - 22
 - 23
 - 24
 - 25
 - 26
 - 27
 - 28
 - 29
 - 30
 - 31
 - 32
 - 33
 - 34
 - 35
 - 36
 - 37
 - 38
 - 39
 - 40
 - 41
 - 42
 - 43
 - 44
 - 45
 - 46
 - 47
 - 48
 - 49
 - 50
 - 51
 - 52
 - 53
 - 54
 - 55
 - 56
 - 57
 - 58
 - 59
 - 60
 - 61
 - 62
 - 63
 - 64
 - 65
 - 66
 - 67
 - 68
 - 69
 - 70
 - 71
 - 72
 - 73
 - 74
 - 75
 - 76
 - 77
 - 78
 - 79
 - 80
 - 81
 - 82
 - 83
 - 84
 - 85
 - 86
 - 87
 - 88
 - 89
 - 90
 - 91
 - 92
 - 93
 - 94
 - 95
 - 96
 - 97
 - 98
 - 99
 - 100
 - 101
 - 102
 - 103
 - 104
 - 105
 - 106
 - 107
 - 108
 - 109
 - 110
 - 111
 - 112
 - 113
 - 114
 - 115
 - 116
 - 117
 - 118
 - 119
 - 120
 - 121
 - 122
 - 123
 - 124
 - 125
 - 126
 - 127
 - 128
 - 129
 - 130
 - 131
 - 132
 - 133
 - 134
 - 135
 - 136
 - 137
 - 138
 - 139
 - 140
 - 141
 - 142
 - 143
 - 144
 - 145
 - 146
 - 147
 - 148
 - 149
 - 150
 - 151
 - 152
 - 153
 - 154
 - 155
 - 156
 - 157
 - 158
 - 159
 - 160
 - 161
 - 162
 - 163
 - 164
 - 165
 - 166
 - 167
 - 168
 - 169
 - 170
 - 171
 - 172
 - 173
 - 174
 - 175
 - 176
 - 177
 - 178
 - 179
 - 180
 - 181
 - 182
 - 183
 - 184
 - 185
 - 186
 - 187
 - 188
 - 189
 - 190
 - 191
 - 192
 - 193
 - 194
 - 195
 - 196
 - 197
 - 198
 - 199
 - 200
 - 201
 - 202
 - 203
 - 204
 - 205
 - 206
 - 207
 - 208
 - 209
 - 210
 - 211
 - 212
 - 213
 - 214
 - 215
 - 216
 - 217
 - 218
 - 219
 - 220
 - 221
 - 222
 - 223
 - 224
 - 225
 - 226
 - 227
 - 228
 - 229
 - 230
 - 231
 - 232
 - 233
 - 234
 - 235
 - 236
 - 237
 - 238
 - 239
 - 240
 - 241
 - 242
 - 243
 - 244
 - 245
 - 246
 - 247
 - 248
 - 249
 - 250
 - 251
 - 252
 - 253
 - 254
 - 255
 - 256
 - 257
 - 258
 - 259
 - 260
 - 261
 - 262
 - 263
 - 264
 - 265
 - 266
 - 267
 - 268
 - 269
 - 270
 - 271
 - 272
 - 273
 - 274
 - 275
 - 276
 - 277
 - 278
 - 279
 - 280
 - 281
 - 282
 - 283
 - 284
 - 285
 - 286
 - 287
 - 288
 - 289
 - 290
 - 291
 - 292
 - 293
 - 294
 - 295
 - 296
 - 297
 - 298
 - 299
 - 300
 - 301
 - 302
 - 303
 - 304
 - 305
 - 306
 - 307
 - 308
 - 309
 - 310
 - 311
 - 312
 - 313
 - 314
 - 315
 - 316
 - 317
 - 318