Skip to main content

Class 12 Python Preeti Arora Solutions Chapter: Functions

Class 12 Python Preeti Arora Solutions Chapter: Functions

Class 12 Python Preeti Arora Solutions.


Class 12 Python Preeti Arora Solutions



Q1. A program having multiple function is considered better designed than a program without any function. Why?

AnswerBecause:-

 

(i) The program is easier to understand: -

 

Main block of program becomes compact as the code of functions is not part of it, thus is easier to read and understand.

 

(ii) Redundant code is at one place, so making changes is easier:-

 

Instead of writing code again when we need to use it more than once, we can write the code in the form of a function and call it more than once. If we later need to change the code, we change it in one place only. Thus it saves our time also.

 

(iii) Reusable functions can be put in a library in modules:-

 

We can store the reusable functions in the form of modules. These modules can be imported and used when needed in other programs.


Q2. Write a function called calculate_area() that takes base and height as input arguments and returns area of a triangle as an output. The formula used is:

Triangle Area = 1/2*base*height

Answer:

def calculate_area(x , y) :

return 1 / 2 * x * y

base = float(input("Enter the Base of triangle : -"))

height = float (input ("Enter the Height of triangle : - "))

print ("Area of Triangle is : - ", calculate_area(base , height))


Q3. Modify the above function to take a third parameter called shape type. Shape type should be either triangle or rectangle. Based on the shape, it should calculate the area.

Formula used: Rectangle Area = length*width

Answer:

def calculate_area(x , y , z) :

    if z == "rectangle" :

        print ("Area of Rectangle : - ", x * y)

    elif z == "triangle" :

        print ("Area of Triangle is : - ", 1 / 2 * x * y)

    else :

        print ("Error :( ")

shape = input("Enter the Shape (rectangle OR triangle) :- ")

base_or_length = float(input("Enter the Base of triangle : -"))

height_or_width = float (input ("Enter the Height of triangle : - "))

calculate_area(base_or_length , height_or_width , shape)




Q4. Write a function called print_pattern that takes integer number as argument and prints the following pattern.

If the input number is 3.

*

* *

* * *

If input is 4, then it should print:

*

* *

* * *

* * * *

Answer:

def print_pattern (x) :
    for i in range (1, x + 1) :
        print (i * "*")
num = int (input ("Enter the number : - "))
print_pattern (num)


Q5. What is the utility of: -

(I) default arguments

(II) Keyword arguments?

Answer:

(i) 

A parameter having a default value in function header becomes optional in function call. Functions call may or may not have value for it.

 

(ii)

Keyword arguments are the named arguments with assigned values being passed in the function call statement.


Q6. What are operators? Give examples of some unary and binary operators.

Answer:

The operation between two operands is called operator.

 

Example of unary operator: -

+ unary plus , -  unary minus etc.

 

Example of binary operator:

+ addition ,- subtraction etc.


Q7. Describe the different styles of functions in Python using appropriate examples.

Answer:

1. Built-in functions: - These are pre-defined functions and are always available for use.

 

For example: -

len(), type(), int(), input() etc.

 

2. Functions defined in modules: - These functions are pre-defined in particular modules and can only be used when the corresponding module is imported.

For example, if you to use pre-defined functions inside a module, say sin(), you need to first import the module math (that contains definition of sin() ) in your program.

 

3. User defined functions: - These are defined by the programmer. As programmers you can create your own functions.


Q8. What is scope? What is the scope resolving rule of Python?

Answer:

Parts of program within which a name is legal and accessible, is called scope of the name.

 

• The scope resolving rule of Python is LEGB rule.


Q9. What is the difference between local and global variables?

Answer:

Local variable:-

• It is a variable which is declared within a function or within a block.

• It is accessible only within a function/block in which it is declared.

 

Global variable: -

• It is variable which is declared outside all the functions.

• It is accessible throughout the program.


Q10. Write the term suitable for following description:

(a) A name inside the parentheses of a function header that can receive a value.

(b) An argument passed to a specific parameter using the parameter name.

(c) A value passed to a function parameter.

(d) A value assigned to a parameter name in the function header.

(e) A value assigned to a parameter name in the function call.

(f) A name defined outside all function definitions.

(g) A variable created inside a function body.

Answer:

(a) Parameter.

(b) Keyword argument.

(c) Argument.

(d) Default argument.

(e) Keyword argument.

(f) Global variable.

(g) Local variable.


Q11. Consider the following code and write the flow of execution for this. Line numbers have been given for our reference.

def power (b, p):        1

    y = b ** p        2

    return y        3

            4

def calcSquare(x):        5

    a = power (x, 2)        6

    return a        7

            8

n = 5            9

result = calcSquare(n)    10

print (result)        11

Answer:

1->5->9->10->5->6->7->10->11


Q12. What will the following function return?

def addEm(x, y, z):

    print (x + y + z)

Answer:

When arguments are passed in addEm(x, y, z) then it add all the arguments and print the result.


Q13. What will be the output displayed when addEM() is called/executed?

def addEm(x, y, z):

    return x + y + z

    print (x+ y + z)

Answer:

When function called then it will add all the argument and it will show nothing.


Q14. What will be the output of the following programs?

(i)

num = 1

def myfunc ():

    return num

print(num)

print(myFunc())

print(num)

(ii)

num = 1

def myfunc():

    num = 10

    return num

print (num)

print(myfunc())

print(num)

(iii)

num = 1

def myfunc ():

    global num

    num = 10

    return num

print (num)

print(myfunc())

print(num)

(iv)

def display():

    print("Hello", end = ' ')

display()

print("there!")

Answer:

(i)

Output:-

 

1

Error: - NameError: name 'myFunc' is not defined

 

(ii)

Output:-

1

10

1

 

(iii)

Output:-

1

10

10

 

(iv)

Output:-

Hello there!


Q15. Predict the output of the following code:

a = 10

y = 5

def myfunc():

    y = a

    a = 2

    print("y =", y, "a =", a)

    print("a+y =", a + y)

    return a + y

print("y =", y, "a =", a)

print(myfunc())

print("y =", y, "a =", a)

Answer:

Output:-

y = 5 a = 10

Error


Q16. What is wrong with the following function definition?

def addEm(x, y, z):

    return x + y + z

    print("the answer is", x + y + z)

Answer:

(a)

def minus (total, decrement):

    output = total - decrement

    print(output)

    return (output)

 

(b)

def check():

    N = input ("Enter N: ")

    i = 3

    answer = 1 + i ** 4 / N

    return answer

 

(c)

Calling of function is in wrong way. If that is corrected then it will show no error.


Q17. Find the errors in the code given below:

(a)

def minus (total, decrement)

    output = total - decrement

    print(output)

    return (output)

(b)

define check()

    N = input ("Enter N: ")

    i = 3

    answer = 1 + i ** 4 / N

    Return answer

(c)

def alpha (n, string ='xyz', k = 10) :

    return beta(string)

    return n

def beta (string)

    return string == str(n)

print(alpha("Valentine's Day") :)

print(beta (string = 'true' ))

print(alpha(n = 5, "Good-bye") :)

Answer:

(a)

def minus (total, decrement):

    output = total - decrement

    print(output)

    return (output)

 

(b)

def check():

    N = input ("Enter N: ")

    i = 3

    answer = 1 + i ** 4 / N

    return answer

 

(c)

Calling of function is in wrong way. If that is corrected then it will show no error.


Q18. Define flow of execution. What does it do with functions?

Answer:

The flow of execution refers to the order in which statement are executed during a program run.

It do nothing with functions.


Q19. Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns the amount converted to rupees. Create the function in both void and non-void forms.

Answer:

def rup(doll) :     #void
    print(" (void ) rupees in ",doll ,"dollar = ",doll * 72)

def rupee(doll) :  # non Void
    return doll * 72

doll = float(input("Enter dollar : "))

rup(doll)    #void

print(" ( non void ) rupees in ",doll ,"dollar = ", rupee(doll) )  # non Void


Q20. Write a function to calculate volume of a box with appropriate default values for its parameters. Your function should have the following input parameters:

(a) Length of box;

(b) Width of box;

(c) Height of box.

Test it by writing complete program to invoke it.

Answer:

def vol( l = 1, w=1 , h=1 ) :
    return l * w * h

length = int(input("Enter the length : "))
width = int(input("Enter the width : "))
height = int(input("Enter the height : "))

print("volume of box = ", vol( length , width , height ))


Q21. Write a program to display first four multiples of a number using recursion.

Answer:

def multi(n,x):
    if x == 4 :
        print(n*x)
    else :
        print(n*x,end =",")
        multi(n,x+1)
num = int(input("Enter a number :-"))
multi(num,1)


Q22. What do you understand by recursion? State the advantages and disadvantages of using recursion.

Answer:

Process of calling a function from within itself is known as recursion.

 

Advantage:-

Recursion makes the code short and simple.

 

Disadvantage: -

It is slow in executing the program due to over of multiple function calls.


Q23. Write a recursive function to add the first 'n' terms of the series:

1+1/2-1/3+1/4-1/5……

Answer:

def add(n):
    if n==term+1:
        return 0
    elif n%2 == 0 :
        return add(n+1) + 1/n
    elif n%2 != 0 :
        return add(n+1) - 1/n
    
term = int(input("Enter the terms :- "))
print(add(2)+1)


Q24. Write a program to find the greatest common divisor between two numbers.

Answer:

def great(a , b) :
    if b == 0 :
        return a
    else :
        return great (b, a % b)

num1 = int (input("Enter the first number :- "))
num2 = int (input ("Enter the second number :- "))
print ("Greatest common divisor of ", num1 ,'&', num2, 'is' ,great(num1 , num2))


Q25. Write a Python function to multiply all the numbers in a list.

Sample List: (8, 2, 3, -1, 7)

Expected Output: -336

Answer:

def multi (x) :
    mul = 1
    for i in x :
        mul *= i
    print ("Answer after multiply:- ", mul)

lst = eval(input("Enter a List :- "))
multi(lst)


Q26. Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number whose factorial is to be calculated as the argument.

Answer:

def fact (n) :
    if n== term +1 :
        return 1
    else :
        return n*fact(n+1)
term = int(input("Enter the term :-"))
print("Factorial =",fact(1))

Q27. Write a Python function that takes a number as a parameter and checks whether the number is prime or not.

Answer;

def prime(a):
    for i in range (2,a) :
        if a % i == 0 :
            return "This is not prime number"
    return "Prime number"

a = int(input("Enter a number : "))
print(prime(a))


Q28. Write a Python function that checks whether a passed string is a palindrome or not.

Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.

Answer:

def check(x) :
    if x[  -1 : - len(x) - 1  : -  1] == x:
        print ("String is a palindrome.")
    else :
        print ("String is not a palindrome ")

string = input ("Enter a String :- ")
check(string)

Output: -

 

If input is ‘madam’:-

 

Enter a String :- madam

String is a palindrome.

>>>

 

If input is ‘nurses’:-

Enter a String :- nurses

String is not a palindrome

>>> 


Q29. Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.

Sample Items: green-red-yellow-black-white

Expected Result: black-green-red-white-yellow

Answer:

def word (x) :
    for i in range (len(x) + 1) :
        for j in range (len(x) - 1) :
            if x[ j ][ 0 ] > x[ j + 1][ 0 ] :
                x[ j ], x[ j + 1 ] = x[ j + 1 ], x[ j ]
                
    string = ("-").join(x)
    print("Sequence After sorting :- ", string)

str = input ("Enter hyphen-separated sequence of words :- ")
a = str.split("-")
word(a)


Q30. What is a recursive function? Write one advantage of recursive functions.

Answer:

A function calling itself is known as recursive function.

 

Advantage: -

• Recursion makes the code short and simple.


Q31. What are the two cases required in a recursive function?

Answer:

1 Recursive case

2 Base case


Q32. What is base case?

Answer:

It is the case that causes the recursion to end.


Q33. What is recursive case?

Answer:

It is the case that solves the problem by using recursive call function to same function.


Q34. Is it necessary to have a base case in a recursive function? Why/Why not?




Answer:

Here base case are:

(i)

    if n == 0 :

        return 5

   

(ii)

    elif n == 1 :

        return 8

 

(iii)

    else:

        return -1


Q35. Identify the base case(s) in the following recursive function:

def function(n) :

    if n == 0 :

        return 5

    elif n == 1 :

        return 8

    elif n > 0 :

        return function1(n-1) + function1(n-2)

    else:

        return -1

Answer:

Here base case are:

(i)

    if n == 0 :

        return 5

   

(ii)

    elif n == 1 :

        return 8

 

(iii)

    else:

        return -1


Q36. Why are recursive functions considered slower than their iterative counterparts?

Answer:

Because of overhead of multiple function calls. And maintaining a stack for it.


Q37. Compare and contrast the use of iteration and recursion in terms of memory space and speed.

Answer:

In iteration, the code is executed repeatedly using the same memory space. That is, the memory space allocated once, is used for each pass of the loop.

On the other hand in recursion, since it involves function call at each step, fresh memory is allocated for each recursive call. For this reason i.e., because of function call overheads, the recursive function runs slower than its iterative counterpart.


Q38. Predict the output of following codes.

(a)

def codo (n):

    if n== 0:

        print('Finally ')

    else:

              print(n)

              codo(n - 3)

codo(15)

(b)

def codo (n):

    if n== 0:

        print('Finally ')

    else:

              print(n)

              codo(n - 2)

codo(15)

(c)

def codo (n):

    if n== 0:

        print('Finally')

    else:

              print(n)

              codo(n - 2)

codo(10)

(d)

def codo (n):

    if n== 0:

        print('Finally')

    else:

              print(n)

              codo(n - 3)

codo(10)

Answer:

(a)

Output:

15

12

9

6

3

Finally

 

(b) It will give an error, error type (“RecursionError: maximum recursion depth exceeded while pickling an object”). Because there is no “base case”.

 

(c)

Output:

10

8

6

4

2

Finally

 

(d) It will also give an error, error type (“RecursionError: maximum recursion depth exceeded while pickling an object”). Because there is no “base case”.


Q39. Predict the output of following code.

def express(x, n):

    if n== 0:

        return 1

    elif n%2 == 0:

        return express(x*x, n/2))

    else:

        return x * express (x, n-1)

express (2,5)

Answer:

Its output is:

32


Q40. Consider following Python function that uses recursion:

def check(n):

    if n <= 1:

        return True

    elif n % 2 == 0 :

        return check(n/2)

    else:

        return check(n/1)

What is the value returned by check(8)?

Answer:

Value returned by check(8) is ‘True’.


Q41. Can you find an error or problem with the above code? Think about what happens if we evaluate check(3). What output would be produced by Python? Explain the reason(s) behind the output.

Answer:

Error is ‘maximum recursion depth exceeded in comparison’

It will give error when we evaluate check(3) error is ‘maximum recursion depth exceeded in comparison’ because in program in else clause there is no base case. If there is base case in else clause then it will give no error.


Q42. Consider the following Python function Fn(), that follows:

def Fn(n):

    print(n, end=" ")

    if n< 3:

        return n

    else:

        return Fn(n // 2) - Fn(n//3)

What will be the result produced by following function calls?

(a) Fn(12)

(b) Fn(10)

(c) Fn(7)

Answer:

(a) Result produced by Fn(12) is:

 

12 6 3 1 1 2 4 2 1 -3

 

(b) Result produced by Fn(10) is:

 

10 5 2 1 3 1 1 1

 

(c) Result produced by Fn(7) is:

 

7 3 1 1 2 -2



Q43. Figure out the problem with following code that may occur when it is run?

def recur(p) :

    if p == 0:

        print("##")

    else:

        recur(p)

        p=p-1

recur(5)

x

Answer:

def recur(p) :

    if p == 0:

        print ("##")

    else:

        return recur(p-1)

recur(5)


Keywords:

class 12 preeti arora python solutions

class 11 python preeti arora solutions

computer science with python class 12 preeti arora solutions

computer science with python class 11 preeti arora solutions

ip with python class 11 preeti arora solutions

preeti arora python class 12 solutions pdf

preeti arora python class 12 solutions

class 12 python sumita arora solutions

class 12 python solutions


Class 12 Python Preeti Arora Solutions Chapter: Functions

Comments

Popular posts from this blog

Class 12 Python Project With MySQL PDF Download

Class 12 Python Project With MySQL PDF Download Class 12 Python Project, Class 12 Python Project With MySQL, Class 12 CBSE Python Project Using MySQL, Python Project Class 12, Class 12 Python Project PDF Download. How To Use Given Class 12 Python Project PDF : STEP 1: Download these PDF STEP 2: Open Downloaded PDF In MS Word 2007 or Google Docs (Web Free) STEP 3: Edit the You're Name, Teacher Name, School Name & More STEP 4: MAKE SURE TO READ THE WHOLE PROJECT BEFRORE SUBMMITING 1)  AIRLINE RESERVATION PROJECT          :  DOWNLOAD .py FILE OF PROJECT 2)  BANKING MANAGEMENT                        :  DOWNLOAD .py FILE OF PROJECT 3)  BILL MANAGEMENT                                 :  DOWNLOAD .py FILE OF PROJECT 5)  COURSE DETAILS             ...

Class 12 Business Studies Project On Marketing Management

Class 12 Business Studies Project On Marketing Management Class 12 Business Studies Project, Class 12  Business Studies Project On Marketing Management,  Business Studies Project Class 12, Class 12 BST Project On Marketing Management. Click Here To Download PDF Keywords: class 12 business studies project on marketing management on mobile class 12 business studies project on marketing management on chocolate class 12 business studies project on marketing management on shampoo class 12 business studies project on marketing management topics class 12 business studies project on marketing management on hair oil class 12 business studies project on marketing management on biscuits class 12 business studies project on marketing management pdf class 12 business studies project on marketing management on coffee class 12 business studies project on marketing management on fruit juice business studies class 12 project on marketing management acknowledgement business studies class 12 pr...