Python Function Concepts Guide
Python Function Concepts Guide
PRACTICE QUESTIONS
THEORY QUESTIONS
      def Disp(x=0,y):
          print(x,y)
10.   User can change the functionality of a built in functions.
11.   The variable declared outside a function is called a global variable.
12.   The following code is a valid code (T/F)       ?
      def Disp(sub1,sub2):
          print(sub1,sub2)
      Disp(sub=100,sub2=89) #Calling
13.   The default valued parameter specified in the function header
      becomes optional in the function calling statement.
14.   The following Python code is a example of Positional argument
      (T/F)
      def Swap(x,y):
         x,y=y,x
      p=90
      q=78
      Swap(p,q)#Calling
15.   Default parameters can be skipped in function call?
16.   Variable defined inside functions cannot have global scope?
17.   A python function may return multiple values?
18.   Positional arguments can follow keyword arguments?
19.   If function returns multiple values, then it will return as List.
                        ASSERTION & REASONING
1.   A: The function header ‘def read (a=2, b=5, c):’ is not
         correct.
     R: Non default arguments can’t follow default arguments.
2.   A function code is given as follows:
     def study (num = 5):
          print(num + 5)
     A: We can call the above function either by statement
         'study(7)' or 'study( )'.
     R: As the function contains default arguments, it depends
         on the caller that the above function can be called with
         or without the value.
3.   A: len( ), type( ), int( ), input( ) are the functions that are
         always available for use.
     R: Built in functions are predefined functions that are
         always available for use. For using them we don’t need
         to import any module.
4.   A:
     def Disp(x,y,z):
         print(x+y+z)
     z=10
     Disp(x=67,y=78,z)
      print(max_of_three(3, 6, -5))
25.   By default if you return multiple value separated by comma, then it
      is returned as
      (a) List     (b) Tuples (c) String    (d) None of the above.
26.   Find the output of following code :
      x=100
      def study(x):
               global x
      x=50
      print(“Value of x is :”, x)
      a. 100      b. 50        c. Error   d. None of the above
27.   What will be the output of the following Python code?
      def change(i = 1, j = 2):
          i=i+j
          j=j+1
          print(i, j)
      change(j = 1, i = 2)
      Findoutput()
29.   If a function doesn’t have a return statement, which of the
      following does the function return?
      (a) int    (b) null (c) None
      (d) An exception is thrown without the return statement
30.   The values being passed through a function call statements are
      called
      (a) Actual parameter         (b) Formal parameter
      (c) default parameter        (d) None of these
31.   How many types of arguments are there in function?
      (a) 1     (b) 2     (c) 3  (d) 4
32.   Predict the output of the following code:
      def fun(x):
           yield x+1
      g=fun(8)
      print(next(g))
      (a) 8    (b) 9 (c) 7 (d) Error
33.   Predict the output of the following code:
      def New(x):
            yield x+1
            print("Hi")
            yield x+2
      G=New(9)
      (a) Error (b) Hi (c) Hi        (d) No output
                             10
                             12
34.   Consider square numbers defined as follows:
      compute(1) = 1
      compute(N) = compute(N-1) + 2N-1
      According to this definition, what is compute (3)?
      (a)compute(3) = compute(2) +compute(1)
      (b)compute(3) = compute(2) -2*3+1
      (c)compute(3) = compute(2) + 2*3-1
      (d)compute(3) = compute(3) +2*3-1
35.   Predict the output of the following code:
      def fun1():
            x=20                         (a) 10
           def fun2():                   (b) 20
                nonlocal x               (c) Error
    3.   Write down the python to swap the values of x and y for the
         blank space in the line marked as Statement-3.
    4.   Mention the output for the line marked as Statement-4.
    5.   The missing code for the blank space in the line marked as
         Statement-5.
4.   Give Output of :
     def Change (P, Q=30) :
         P=P+Q
         Q=P-Q
         print (P,"@",Q)
         return P
     R =150
     S= 100
     R=Change(R, S)
     print(R,"@",S)
     S=Change (S)
5.   Predict the output of the following code:
     def Fun():
          G=(i for in range(5,15,3))
          print(G)
     Fun()
6.   Give output of the following code:
     def func(a, b=5, c=10):
         print('a is', a, 'and b is', b, 'and c is', c)
     func(3, 7)
     func(25, c = 24)
     func(c = 50, a = 100)
7.   Predict the output of the following code?
     def my_func(a=10,b=30):
         a+=20
         b-=10
         return a+b,a-b print(my_func(a=60)
     [0],my_func(b=40)[1])
8.   Write a function DIVI_LIST() where NUM_LST is a list of numbers
     passed as argument to the function. The function returns two list
     D_2 and D_5 which stores the numbers that are divisible by 2 and
     5     respectively       from        the      NUM_LST.  Example:
     NUM_LST=[2,4,6,10,15,12,20]
     D_2=[2,4,6,10,12,20]          D_5=[10,15,20]
9.    Predict the output of the following code:
      def Get(x,y,z):
        x+=y
        y-=1
        z*=(x-y)
        print(x,'$',y,'#',z)
      def Put(z,y,x):
        x*=y
        y+=1
        z*=(x+y)
        print(x,'$',z,'%',y)
      a=10
      b=20
      c=5
      Put(a,c,b)
      Get(a,b,c)
      Put(b,a,c)
10.   Predict the output of the Python code given below:
      value = 50
      def display(N):
          global value
          value = 25
          if N%7==0:
             value = value + N
          else:
              value = value - N
          print(value, end="#")
      display(20)
      print(value)
11.   Write a function countNow(PLACES) in Python, that takes the
      dictionary, PLACES as an argument and displays the names (in
      uppercase)of the places whose names are longer than 5 characters.
      For example, Consider the following dictionary
      PLACES={1:"Delhi",2:"London",3:"Paris",4:"New
      York",5:"Doha"}
      The output should be: LONDON NEW YORK
12.   Consider the program given below and justify the output.
      c = 10
      def add():
          global c
          c=c+2
          print("Inside add():", c)
      add()
      c=15
      print("In main:", c)
      Output:
      Inside add() : 12
      In main: 15
      What is the output if “global c" is not written in the function
      add()?
13.   Predict the output of the following code:
      L=5
      B=3
      def getValue():
             global L, B
             L = 10
             B=6
       def findArea():
             Area = L * B
             print("Area = ", Area)
      getValue()
      findArea()
14.   Predict the output of the following code:
      def process_strings():
          words = ['Python', 'Java', 'C++', 'JavaScript']
          result = ['', '', '',
          ''] index = 0
          for word in words:
              if word[-1] in ['n', 't']:
                 result[index] = word.upper()
                 index += 1
              else:
                 result[index] = word.lower()
                 index -= 1
          print(result) process_strings()#calling function
15.   Write a function, lenWords(STRING), that takes a string as an
      argument and returns a tuple containing length of each word of a
      string. For example, if the string is "Come let us have some fun",
      the tuple will have (4, 3, 2, 4, 4, 3)
16.   Predict the output of the following code:
      def OUTER(Y, ch):
         global X, NUM
         Y=Y+X
         X=X+Y
         print(X, "@", Y)
         if ch == 1:
             X = inner_1(X, Y)
             print(X, "@", Y)
         elif ch == 2:
             NUM = inner_2(X, Y)
      def inner_1(a, b):
         X=a+b
         b=b+a
         print(a, "@", b)
         return a
      def inner_2(a, b):
         X = 100
         X=a+b
         a=a+b
         b=a-b
         print(a,    "@",
         b) return b
      X, NUM = 100, 1
      OUTER(NUM, 1)
      OUTER(NUM, 2)
      print(NUM, "@", X)
17.   Rewrite the correct program:
      Def fun():
           x = input("Enter a number")
           for i in range[x):
               if (int(s.fabs(x)) % 2== 0) :
                  print ("Hi")
               Else:
                     print("Number is odd")
18.   Rewrite the code after correcting it and underline the
      corrections.
      def sum(arg1,arg2):
           total=arg1+arg2;
           print(”Total:”,total)
           return
      sum(10,20)
      print("Total:",total)
19.   Predict the output of the following code:
      def hello():
         a=['MDU','MS','CGL','TBM']
         k=-1
         for i in ['MDU','MS','CGL','TBM'][:-2]:
             if i in ['A','E','I','O','U']:
                 a[k]=['MDU','MS','CGL','TBM'][k]
                 k+=1
             else:
                 a[k]=['MDU','MS','CGL','TBM'][k]
                 k-=1
         print(a)
      hello()
20.   Write a function in python named SwapHalfList(Array), which
      accepts a list Array of numbers and swaps the elements of 1st
      Half of the listwith the 2nd Half of the list, ONLY if the sum of
      1st Half is greaterthan 2nd Half of the list.
      Sample Input Data of the list
      Array= [ 100, 200, 300, 40, 50, 60],
      Output Array = [40, 50, 60, 100, 200, 300]
21.   Predict the output of the following code:
      L = [5,10,15,1]
      G=4
      def Change(X):
          global G
          N=len(X)
          for i in range(N):
              X[i] += G
      Change(L)
      for i in L:
       print(i,end='$')
22.   Predict the output of the following:
      def Facto(x):
            a=None
            b=None
            for i in range(2,x//2):
                  if x%i==0:
                      if a is None:
                             a=i
                      else:
                            b=i
                            break
            return a,b
      S=Facto(4)
      print(S)
23.   Write a            Python     Program    containing   a    function
      FindWord(STRING,SEARCH), that accepts two arguments :
      STRING and SEARCH, and prints the count of occurrence of
      SEARCH in STRING. Write appropriate statements to call the
      function.
      For example, if STRING = "Learning history helps to know
      about        history      with    interest    in    history"     and
      SEARCH = 'history', the function should display:
      The word history occurs 3 times.
24.    Rewrite the code after correcting it and underline the
       corrections.
       Def swap(d):
          n={}
           values = d.values()
           keys = list(d.keys[])
           k=0
           for i in values
              n(i) = keys[k]
              k=+1
          return n
      result = swap({‘a’:1,’b’:2,’c’:3})
      print(result)
25.   Predict the output of the following:
      def fun(s):
         k=len(s)
         m=""
         for i in range(0,k):
            if(s[i].isupper()):
              m=m+s[i].lower()
            elif s[i].isalpha():
                 m=m+s[i].upper()
            else:
                m=m+'bb'
         print(m)
      fun('school2@com')
26.   Predict the output of the following code:
      def runme(x=1, y=2):
           x = x+y
           y+=1
           print(x, '$', y)
           return x,y
      a,b = runme()
      print(a, '#', b)
      runme(a,b)
      print(a+b)
27.   Write a function Interchange (num) in Python, which accepts a
      list num of integers, and interchange the adjacent elements of the
      list and print the modified list as shown below: (Number of
      elements in the list is assumed as even) Original List:
      num = [5,7,9,11,13,15]
      After Rearrangement num = [7,5,11,9,15,13]
28.   Rewrite the corrected code and underline each correction.
      def Tot (Number):
           Sum=0
           for C in RANGE (1, Number + 1):
               Sum + = C
      return Sum
      print(Tot [3])
29.   Predict the output of the following:
      def ChangeVal(M,N):
           for i in range(N):
               if M[i]%5 == 0:
                   M[i] //= 5
                if M[i]%3 == 0:
                   M[i] //= 3
      L=[25,8,75,12]
      ChangeVal(L,4)
      for i in L :
           print(i, end='#')
30.   Predict the output of the following:
      R=0
      def change( A , B ) :
         global R
         A += B
         R +=3
         print(R , end='%')
      change(10 , 2)
      change(B=3 , A=2)
31.   Write a function sumcube(L) to test if an element from list L is
      equal to the sum of the cubes of its digits i.e. it is an "Armstrong
      number". Print such numbers in the list.
      If L contains [67,153,311,96,370,405,371,955,407]
      The function should print 153,370,371,407
32.   Predict the output of the following code:
      def result(s):
                n = len(s)
                m=''
                for i in range(0, n):
                    if (s[i] >= 'a' and s[i] <= 'm'):
                           m = m + s[i].upper()
                   elif (s[i] >= 'n' and s[i] <= 'z'):
                           m = m + s[i-1]
                   elif (s[i].isupper()):
                          m = m + s[i].lower()
                   else:
                          m = m + '#'
               print(m)
      result('Cricket') #Calling
33.   Predict the output of the following:
      def Bigger(N1,N2):
          if N1>N2:
             return N1
          else:
              return N2
      L=[32,10,21,54,43]
      for c in range (4,0,-1):
           a=L[c]
           b=L[c-1]
           print(Bigger(a,b),'@', end=' ')
34.   What will be the output of following Python Code:
      def change(num):
             for x in range(0,len(num),2):
                 num[x], num[x+1]=num[x+1], num[x]
      data=[10,20,30,40,50,60]
      change(data)
      print(data)
35.   Write a function listchange(Arr,n)in Python, which accepts a list
      Arr of numbers and n is an numeric value depicting length of the
      list. Modify the list so that all even numbers doubled and odd
      number multiply by 3 Sample Input Data of the list: Arr= [
      10,20,30,40,12,11], n=6 Output: Arr = [20,40,60,80,24,33]
36.   Predict the output of the following:
      def Compy(N1,N2=10):
            return N1 > N2
      NUM= [10,23,14,54,32]
      for VAR in range (4,0,-1):
           A=NUM[VAR]
           B=NUM[VAR-1]
           if VAR >len(NUM)//2:
               print(Compy(A,B),'#', end=' ')
          else:
             print(Compy(B),'%',end=' ')
37.   Predict the output of the following:
      p=8
      def sum(q,r=5):
         global p
         p=(r+q)**2
         print(p, end= '#')
      a=2;
      b=5;
      sum(b,a)
      sum(r=3,q=2)
38.   Mr.Raja wants to print the city he is going to visit and the
      distance to reach that place from his native. But his coding is not
      showing the correct: output debug the code to get the correct
      output and state what type of argument he tried to implement in
      his coding.
      def Travel(c,d)
           print("Destination     city   is     ",city)
           print("Distance from native is ",distance)
      Travel(distance="18 KM",city="Tiruchi")
39.   Predict the output of the following:
      value = 50
      def display(N):
          global value
          value = 25
          if N%7==0:
             value = value + N
          else:
              value = value - N
          print(value, end="#")
      display(20)#Calling
      print(value)
40.   Predict the output of the following code:
      def f():
            global s
            s += ' Is Great'
            print(s)
            s = "Python is funny"
      s = "Python"
      f()
      print(s)
41.   Write a function in python named SwapHalfList(Array), which
      accepts a list Array of numbers and swaps the elements of 1st
      Half of the listwith the 2nd Half of the list, ONLY if the sum of 1st
      Half is greaterthan 2nd Half of the list. Sample Input Data of the
      list Array= [ 100, 200, 300, 40, 50, 60],
      Output Array = [40, 50, 60, 100, 200, 300]
42.   Predict the output of the following:
      def func(b):
          global x
          print('Global x=', x)
          y=x + b
          x=7
          z=x-b
          print('Local x =',x)
          print('y=',y)
      print('z=',z)
      x=3
      func(5)
43.   Write a function LShift(Arr,n) in Python, which accepts a list Arr
      of numbers and n is a numeric value by which all elements of the
      list are shifted to left. Sample Input
      Data of the list
      Arr= [ 10,20,30,40,12,11], n=2
      Output Arr = [30,40,12,11,10,20]
44.   Predict the output of the following:
      def change(A):
           S=0
           for i in range(len(A)//2):
               S+=(A[i]*2)
           return S
      B = [10,11,12,30,32,34,35,38,40,2]
      C = change(B)
      print('Output is',C)
45.   Write the output for the following python code:
      def Change_text(Text):
         T=" "
         for K in range(len(Text)):
            if Text[K].isupper():
                T=T+Text[K].lower();
            elif K%2==0:
                T=T+Text[K].upper()
            else:
                T=T+T[K-1]
         print(T)
      Text="Good go Head"
      Change_text(Text)
46.   Write a function called letter_freq(my_list) that takes one
      parameter, a list of strings(mylist) and returns a dictionary where
      the keys are the letters from mylist and the values are the
      number of times that letter appears in the mylist, e.g.,if the
      passed list is as: wlist=list("aaaaabbbbcccdde")
      then it should return a dictionary as{‘a’:5,’b’:4,’c’:3,’d’:2,’e’:1}
47.   Write the output for the following python code:
      def Quo_Mod (L1):
         L1.extend([33,52])
         for i in range(len(L1)):
            if L1[i]%2==0:
                L1[i]=L1[i] /5
            else:
               L1[i]=L1[i]%10
      L=[100,212,310]
      print(L)
      Quo_Mod(L)
      print(L)
48.   Predict the output for the following code:
      def test(i, a =[]):
           a.append(i)
           return a
      test(25)
      test(32)
      s = test(17)
      print(s)
49.   Write a function in Shift(Lst), Which accept a List ‘Lst’ as argument
      and swaps the elements of every even location with its odd location
      and store in different list eg. if the array initially contains 2, 4, 1,
      6, 5, 7, 9, 2, 3, 10
      then it should contain 4, 2, 6, 1, 7, 5, 2, 9, 10, 3
50.   Write the output given by following Python code.
      x=1
      def fun1():
           x=3
           x=x+1
           print(x)
       def fun2():
           global x
           x=x+2
           print(x)
      fun1()
      fun2()
51.   Predict the output of the following:
      def changer(p, q=10):
          p=p/q
          q=p%q
          print(p,'#',q)
          return p
      a=200
      b=20
      a=changer(a,b)
      print(a,'$',b)
      a=changer(a)
      print(a,'$',b)
52.   Write a Python function SwitchOver(Val) to swap the even and odd
      positions of the values in the list Val. Note : Assuming that the list
      has even number of values in it.
      For example : If the list Numbers contain [25,17,19,13,12,15] After
      swapping the list content should be displayed                       as
      [17,25,13,19,15,12]
53.   Define a function ZeroEnding(SCORES) to add all those values in
      the list of SCORES, which are ending with zero (0) and display the
      sum. For example : If the SCORES contain [200, 456, 300, 100,
      234, 678] The sum should be displayed as 600
54.   Determine the output of the following code fragments:
      def determine(s):
           d={"UPPER":0,"LOWER":0}
           for c in s:
               if c.isupper( ):
                  d["UPPER"]+=1
               elif c.islower( ):
                    d["LOWER"]+=1
               else:
                       pass
       print("Original String:",s)
       print("Upper case count:", d["UPPER"])
      print("Lower case count:", d["LOWER"])
      determine("These are HAPPY Times")
55.   Write a function in Display which accepts a list of integers and its
      size as arguments and replaces elements having even values with
      its half and elements having odd values with twice its value . eg: if
      the list contains 5, 6, 7, 16, 9 then the function should rearranged
      list as 10, 3,14,8, 18
56.   Predict the output of the Python code given below:
      def Alpha(N1,N2):
        if N1>N2:
           print(N1%N2)
        else:
            print(N2//N1,'#',end=' ')
      NUM=[10,23,14,54,32]
      for C in range (4,0,-1):
         A=NUM[C]
         B=NUM[C-1]
         Alpha(A,B)
57.   Write a function INDEX_LIST(L), where L is the list of elements
      passed as argumentto the function. The function returns another
      list named ‘indexList’ that stores theindices of all Non-Zero
      Elements of L. For example: If L contains [12,4,0,11,0,56] The index
      List will have - [0,1,3,5]
58.   Predict the output of the code given below:
      def Convert(Old):
         l=len(Old)
         New=" "
         for i in range(0,1):
             if Old[i].isupper():
                 New=New+Old[i].lower()
             elif Old[i].islower():
                  New=New+Old[i].upper()
             elif Old[i].isdigit():
                  New=New+"*"
             else:
                New=New+"%"
         return New
      Older="InDIa@2022";
      Newer=Convert(Older)
      print("New String is: ", Newer)
59.  Give output of the following program:
     Predict the output of the following code:
     def div5(n):
        if n%5==0:
           return n*5
        else:
            return n+5
     def output(m=5):
        for i in range(0,m):
             print(div5(i),'@',end=" ")
             print('\n')
     output(7)
     output()
     output(3)
60. Write a function INDEX_LIST(S), where S is a string. The function
     returnsa list named indexList‘ that stores the indices of all vowels
     of S. For example: If S is "Computer", then indexList should be
     [1,4,6]
61. Write a function INDEX_LIST(L), where L is the list of elements
     passed as argument to thefunction. The function returns another
     list named ‘indexList’ that stores the indices of allElements of L
     which has a even unit place digit.
     For example: If L contains [12,4,15,11,9,56]
     The indexList will have - [0,1,5]
 *********************************************************