KnowledgeBoat Logo
OPEN IN APP

Chapter 2

Functions

Class 12 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

A set of instructions/operations which is a part of a program and can be executed independently to do specific task is called a function.

Question 2

Python passes parameters by value.

Question 3

The variable declared outside all the functions is called a global variable.

Question 4

The order in which statements are executed during a program run is called the flow of execution.

Question 5

A module is a file containing Python definitions and statements intended for use in other Python programs.

Question 6

Functions that do not explicitly return a value return the special object None.

Question 7

The first line of a function definition is called function header.

Question 8

The function which is written by the programmer as per his/her requirements is known as user-defined function.

Question 9

A function is said to be recursive if it calls itself.

Question 10

Arguments/Parameters act as a means of communication between the called and calling function.

Question 11

The scope of a variable is the area of the program where it may be referenced.

Question 12

The terminating condition used for solving a problem using recursion is termed as the base case for that problem.

Question 13

def keyword is used to define a function.

Question 14

Function name must be followed by () (Parenthesis) and : (colon).

State True or False

Question 1

More than one value(s) can be returned by a function in Python.

Answer

True

Reason — A Python function may return multiple values i.e., more than one value from a function.

Question 2

The variable declared inside a function is called a global variable.

Answer

False

Reason — Variables declared inside a function in Python are called local variables. These variables are local to that function and can only be accessed within that function's scope.

Question 3

Once a function is defined, it may be called only once from many different places in a program.

Answer

False

Reason — Once a function is defined in Python, it can be called multiple times from different places in a program. Functions are reusable blocks of code, and their purpose is to be called and executed whenever needed.

Question 4

Value returning functions should be generally called from inside of an expression.

Answer

True

Reason — Value returning functions in Python compute a value and return it to the caller. These functions are called from within an expression where their returned value is used for further computation, assignment, or comparison.

Question 5

A local variable having the same name as that of a global variable hides the global variable in its function.

Answer

True

Reason — Inside a function, you assign a value to a name which is already there in a global scope, Python won't use the global scope variable because it is an assignment statement and assignment statement creates a variable by default in current environment. That means a local variable having the same name as that of a global variable, hides the global variable in its function.

Question 6

In Python, function arguments are required and we cannot define a function without them.

Answer

False

Reason — Python allows defining functions without specifying any arguments. These functions are known as functions with no parameters or parameterless functions.

Question 7

Parameters specified within a pair of parentheses in the function definition are the actual parameters or non-formal parameters.

Answer

False

Reason — Parameters specified within a pair of parentheses in a function definition are called formal parameters. These serve as placeholders for the values that will be passed to the function when it is called. Formal parameters are specified in the function definition and act as variables within the function's scope.

Question 8

A function in Python is used by invoking it via a function call.

Answer

True

Reason — In Python, a function is used by invoking it through a function call. This involves using the function's name followed by parentheses (), which may contain arguments if the function requires any. The function call executes the code inside the function's body and then returns to the point in the code where the function was called from.

Question 9

Built-in functions are created by users and are not a part of the Python library.

Answer

False

Reason — Built-in functions in Python are pre-defined functions that are part of the Python programming language itself. These functions are included in the Python standard library and are available for use without users needing to create them. Users can also create their own functions, which are called user-defined functions.

Question 10

The first line of a function header begins with def keyword and eventually ends with a colon (:).

Answer

True

Reason — The function header starts with def keyword, followed by the function name and any parameters enclosed in parentheses. It ends with a colon (:) to indicate the beginning of the function's code block. The syntax for defining a function in Python is as follows: def function_name(parameters):.

Question 11

Recursive functions are faster than their iterative counterparts.

Answer

False

Reason — When a loop is executed repeatedly, it uses the same memory locations for variables and repeats the same unit of code. On the other hand, recursion allocates fresh memory space for each recursive call, avoiding the repetition of code and the reuse of memory locations for variables. Due to stack manipulation and the allocation of additional memory space, recursive functions often run slower and consume more memory than their iterative counterparts.

Question 12

Recursion is defined as defining anything in terms of itself.

Answer

True

Reason — Recursion is defined as defining anything in terms of itself. In other words, it is a method in which a function calls itself one or more times in its body.

Question 13

Function can alter only mutable data types.

Answer

True

Reason — Functions can alter only mutable data types because mutable data types in Python can be modified in-place, meaning their internal state can be changed by functions. This includes data types like lists, dictionaries, and sets. On the other hand, immutable data types, such as strings, tuples, and numbers, cannot be altered in-place.

Multiple Choice Questions

Question 1

A function in Python begins with which keyword?

  1. void
  2. return
  3. int
  4. def

Answer

def

Reason — Functions in Python are defined as per the following format :

def function_name(parameters):
    statements

According to this format, function definition begins with keyword def.

Question 2

Name the statement that sends back a value from a function.

  1. print
  2. input
  3. return
  4. None

Answer

return

Reason — The return statement in a function specifies the value to be sent back to the calling function and also signifies the end of the function's execution.

Question 3

Functions that do not return any value are known as:

  1. fruitful functions
  2. void functions
  3. library functions
  4. user-defined functions

Answer

void functions

Reason — Functions that do not return any value are known as void functions because they do not produce any output or result that can be used in the calling code.

Question 4

A variable created or defined within a function body is classified as:

  1. local
  2. global
  3. built-in
  4. instance

Answer

local

Reason — A variable created or defined within a function body is classified as a local variable because it is only accessible and usable within that specific function and the other blocks contained under it.

Question 5

Which of the following arguments works with implicit values that are used if no value is provided?

  1. keyword
  2. required
  3. variable-length
  4. default

Answer

default

Reason — Default arguments are used with implicit values that are used if no value is provided when calling the function. This is because default arguments are predefined values assigned to parameters in a function.

Question 6

Which values are used by the functions to communicate information back to the caller?

  1. local
  2. global
  3. return
  4. random

Answer

return

Reason — The return statement is used by functions to communicate information back to the caller. It allows functions to send a specific value or result back to the code that called the function, which can then be used for further processing or operations.

Question 7

What is the output of the program given below?

x = 50
def func(x):
    x = 2
func(x)
print('x is now', x)
  1. x is now 50
  2. x is now 2
  3. x is now 100
  4. Error

Answer

x is now 50

Reason — The output of the program will be x is now 50. This is because the variable x inside the func function is a local variable, so any changes made to it inside the function do not affect the global variable x defined outside the function. Therefore, after calling the func function, the value of x remains unchanged and is still 50 when printed.

Question 8

Which is the most appropriate definition for recursion?

  1. A function that calls itself
  2. A function execution instance that calls another execution instance of the same function
  3. A class method that calls another class method
  4. An inbuilt method that is automatically called

Answer

A function execution instance that calls another execution instance of the same function

Reason — Recursion is defined as a function execution instance that calls another execution instance of the same function. In recursive functions, the function calls itself, creating a chain of function calls where each instance of the function invokes another instance until a termination condition is met.

Question 9

Fill in the line of code for calculating the factorial of a number:

def fact(num):
    if num == 0:
        return 1
    else:
        return...............
  1. num*fact (num-1)
  2. (num-1) * (num-2)
  3. num* (num-1)
  4. fact (num) *fact (num-1)

Answer

num*fact (num-1)

Reason — The fact function is designed to calculate the factorial of a given number through recursion. It checks if the input num is zero; if so, it returns 1 as the factorial of 0 is defined as 1. Otherwise, it recursively calls itself with the argument num-1, reducing num with each call until reaching 0, which serves as the base case to stop recursion. During each recursive call, the function multiplies the current num by the factorial of num-1, effectively computing the factorial of the original input number through successive multiplications until the base case is reached.

Question 10

Which of the following statements is false about recursion?

  1. Every recursive function must have a base case.
  2. Infinite recursion can occur if the base case isn't properly mentioned.
  3. A recursive function makes the code easier to understand.
  4. Every recursive function must have a return value.

Answer

Every recursive function must have a return value.

Reason — The statement "Every recursive function must have a return value" is false because recursive functions in Python don't necessarily have to return a value.

Question 11

What is the output of the following snippet?

def fun(n):
    if (n > 100):
        return n - 5
    return fun (fun (n+11) )
print(fun(45))
  1. 50
  2. 100
  3. 74
  4. Infinite loop

Answer

100

Reason — Initially, the function fun is called with the argument 45. Since 45 is less than 100, the else block is executed, and fun is called recursively with the argument fun(n+11). This leads to another recursive call fun(56), as 45 + 11 = 56. Again, since 56 is less than 100, the else block is executed, and another recursive call fun(n+11) is made with n = 67. This process continues until n exceeds 100, at which point the base case is triggered.

Question 12

What happens if the base condition isn't defined in recursive programs?

  1. Program gets into an infinite loop
  2. Program runs once
  3. Program runs n number of times, where n is the argument given to the function
  4. An exception is thrown

Answer

Program gets into an infinite loop

Reason — When the base condition in a recursive program is not properly defined, the recursive calls continue indefinitely without a stopping criterion. This leads to an infinite loop where the program keeps executing recursive calls without making progress towards a termination point.

Assertions and Reasons

Question 1

Assertion (A): Function can take input values as parameters, execute them and return output (if required) to the calling function with a return statement.

Reasoning (R): A function in Python can return multiple values.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
Functions in Python can take input values as parameters, perform operations on them, and return output if needed using the return statement. A function in Python can return multiple values using a single return statement by separating the values with commas.

Question 2

Assertion (A): If the arguments in a function call statement match the number and order of arguments as defined in the function definition, such arguments are called positional arguments.

Reasoning (R): During a function call, the argument list first contains default argument(s) followed by positional argument(s).

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
Positional arguments are those arguments in a function call that match the number and order of arguments as defined in the function definition. During a function call, the argument list can contain positional arguments first, followed by default arguments if there are any.

Question 3

Assertion (A): Local Variables are accessible only within a function or block in which they are declared.

Reasoning (R): Global variables are accessible in the whole program.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true but R is not the correct explanation of A.

Explanation
Local variables have a limited scope and are accessible only within the function or block where they are defined. On the other hand, global variables have a broader scope and can be accessed from any part of the program, including functions and blocks.

Question 4

Assertion (A): The local and global variables declared with the same name in the function are treated in the same manner by the Python interpreter.

Reasoning (R): The variable declared within the function block is treated as local, whereas the variable declared outside the function block will be referred to as a global variable.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is false but R is true.

Explanation
When a variable shares the same name both locally within a function and globally outside it, the Python interpreter treats them differently based on the scope where they are accessed. Local variables, declared within a function, are accessible only within that function and don't affect the global variable of the same name. The interpreter prioritizes the local variable over the global one within the function's scope. However, globally declared variables are accessible throughout the program, and their value can be modified or accessed from any function or block.

Question 5

Assertion (A): The functions developed and defined by language programmers and provided within the framework of the language are termed as built-in functions.

Reasoning (R): Each and every built-in function contains a set of statements to perform a specific task. They are independent entities and, hence, not included within any module or object.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
Built-in functions are developed and defined by language programmers and provided within the framework of the programming language itself. They are designed to perform specific tasks and are not tied to any particular module or object. In Python, built-in functions are part of the built-in namespace and are accessible throughout the program without the need to import specific modules.

Question 6

Assertion (A): To use positional arguments, the arguments need to be passed in the same order as their respective parameters in the function definition.

Reasoning (R): If three positional arguments are to be passed to the function, the first argument will be assigned to the first parameter, second argument to the second parameter and the third argument to the third parameter.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
Positional arguments in Python must be passed in the same order as their respective parameters in the function definition. This means that the first argument passed will be assigned to the first parameter, the second argument to the second parameter, and so on. As positional arguments are those arguments in a function call that match the number and order of arguments as defined in the function definition.

Solutions to Unsolved Questions

Question 1

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

Answer

A program having multiple functions is considered better designed than a program without any functions because:

  1. Program handling becomes easier: Only a small part of the program is dealt with at a time.
  2. Code reusability: A Python function can be defined once and used many times. So, it results in code reuse, we don't need to write the same code more than once.
  3. Compact code: While working with functions, a common set of code is written only once and can be called from any part of the program which reduces lines of code and programming overheads.
  4. Easy updation: If we need to update a formula or expression, changes must be made everywhere it's used, risking errors. Using functions simplifies this by making changes in only one place (which is function itself).

Question 2

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

Solution
def calculate_area(base, height):
    area = (1/2) * base * height
    return area

base_value = int(input("Enter the base value: "))
height_value = int(input("Enter the height value: "))
triangle_area = calculate_area(base_value, height_value)
print("Area of the triangle:", triangle_area)
Output
Enter the base value: 10
Enter the height value: 5
Area of the triangle: 25.0

Question 3

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

Solution
def calculate_area(base, height, shape_type):
    if shape_type == "triangle":
        area = (1/2) * base * height
    elif shape_type == "rectangle":
        area = base * height
    else:
        area = None
        print("Invalid shape type. Please specify either 'triangle' or 'rectangle'.")
    return area

shape_type = input("Enter the shape type, triangle or rectangle: ")
base_value = int(input("Enter the base value: "))
height_value = int(input("Enter the height value: "))
area = calculate_area(base_value, height_value, shape_type)
print("Area of the", shape_type, "is ", area)
Output
Enter the shape type, triangle or rectangle: triangle
Enter the base value: 10
Enter the height value: 5
Area of the triangle is  25.0


Enter the shape type, triangle or rectangle: rectangle
Enter the base value: 8
Enter the height value: 9
Area of the rectangle is  72

Question 4

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:

*
**
***
****
Solution
def print_pattern(num):
    for i in range(1, num + 1):
        print("*" * i)
        
num = int(input("Enter a number: "))        
print("Pattern for input", num, ":")
print_pattern(num)
Output
Enter a number: 4
Pattern for input 4 :
*
**
***
****

Enter a number: 5
Pattern for input 5 :
*
**
***
****
*****

Question 5

What is the utility of:

  1. Default arguments
  2. Keyword arguments

Answer

  1. Default arguments — Default arguments are useful in case a matching argument is not passed in the function call statement. They give flexibility to specify the default value for a parameter so that it can be skipped in the function call, if needed. However, still we cannot change the order of the arguments in the function call.

  2. Keyword arguments — Keyword arguments are useful when you want to specify arguments by their parameter names during a function call. This allows us to pass arguments in any order, as long as we specify the parameter names when calling the function. It also makes the function call more readable and self-explanatory.

Question 6

Describe the different types of functions in Python using appropriate examples.

Answer

The different types of functions in Python are as follows :

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

name = input("Enter your name: ")
name_length = len(name)
print("Length of your name:", name_length)

In the above example, print(), len(), input() etc. are built-in functions.

2. User defined functions — These are defined by programmer. For example:

def calculate_area(length, width):
    area = length * width
    return area

length = 5
width = 3
result = calculate_area(length, width)
print("Area of the rectangle:", result)

In the above example, calculate_area is a user defined function.

3. Functions defined in modules — These functions are pre-defined in particular modules and can only be used when corresponding module is imported. For example:

import math
num = 16
square_root = math.sqrt(num)
print("Square root of", num, ":", square_root)

In the above example, sqrt is a function defined in math module.

Question 7

What is scope? What is the scope-resolving rule of Python?

Answer

Scope refers to part(s) of program within which a name is legal and accessible. When we access a variable from within a program or function, Python follows name resolution rule, also known as LEGB rule. When Python encounters a name (variable or function), it first searches the local scope (L), then the enclosing scope (E), then the global scope (G), and finally the built-in scope (B).

Question 8

What is the difference between local and global variables?

Answer

Local variableGlobal variable
A local variable is a variable defined within a function.A global variable is a variable defined in the 'main' program.
They are only accessible within the block in which they are defined.They are accessible from anywhere within the program, including inside functions.
These variables have local scope.These variables have global scope.
The lifetime of a local variable is limited to the block of code in which it is defined. Once the execution exits that block, the local variable is destroyed, and its memory is released.Global variables persist throughout the entire execution of the program. They are created when the program starts and are only destroyed when the program terminates.

Question 9

Write the term suitable for the following descriptions:

(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 call.

(e) A name defined outside all function definitions.

(f) A variable created inside a function body.

Answer

(a) Parameter

(b) Keyword argument

(c) Argument

(d) Keyword argument

(e) Global variable

(f) Local variable

Question 10

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

1. def power(b, p):
2. y = b ** p
3. return y
4. 
5. def calcSquare(x):
6. a = power(x, 2)
7. return a
8. 
9. n = 5
10. result = calcSquare(n)
11. print(result)

Answer

The flow of execution for the above program is as follows :

1 → 5 → 9 → 10 → 5 → 6 → 1 → 2 → 3 → 6 → 7 → 10 → 11

Explanation

Line 1 is executed and determined that it is a function header, so entire function-body (i.e., lines 2 and 3) is ignored. Line 5 is executed and determined that it is a function header, so entire function-body (i.e., lines 6 and 7) is ignored. Lines 9 and 10 are executed, line 10 has a function call, so control jumps to function header (line 5) and then to first line of function-body, i.e., line 6, it has a function call , so control jumps to function header (line 1) and then to first line of function-body, i.e, line 2. Function returns after line 3 to line 6 and then returns after line 7 to line containing function call statement i.e, line 10 and then to line 11.

Question 11

What will the following function return?

def addEm(x, y, z): 
   print(x + y + z) 
x = y = z = 10

Answer

The function addEm will return None. The provided function addEm takes three parameters: x, y, and z. It calculates their sum, which is 30, and then prints it. However, it doesn't explicitly return any value. In Python, when a function doesn't have a return statement, it implicitly returns None.

Question 12

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

def addEM(x, y, z): 
    return x + y + z 
x=y=z=20

Answer

When the addEM() function is called or executed, there will be no output displayed because there is no print statement.

Explanation

When the function addEM(x, y, z) is called with the values 20 for each of its parameters (x, y, and z), it calculates their sum (20 + 20 + 20), which equals 60. Since the function uses the return keyword to return this calculated sum, calling addEM(20, 20, 20) will return 60.

Question 13(i)

What will be the output of the following program?

num = 1
def myfunc() :
    return num
print (num) 
print (myfunc())
print (num)

Answer

Output
1
1
1
Working

The code initializes a global variable num with 1. myfunc just returns this global variable. Hence, all the three print statements print 1.

Question 13(ii)

What will be the output of the following program?

num = 1
def myfunc() :
    num = 10 
    return num
print (num) 
print (myfunc())
print (num)

Answer

Output
1
10
1
Working
  1. num = 1 — This line assigns the value 1 to the global variable num.
  2. def myfunc() — This line defines a function named myfunc.
  3. print(num) — This line prints the value of the global variable num, which is 1.
  4. print(myfunc()) — This line calls the myfunc function. Inside myfunc function, num = 10 defines a local variable num and assigns it the value of 10 which is then returned by the function. It is important to note that the value of global variable num is still 1 as num of myfunc is local to it and different from global variable num.
  5. print(num) — This line prints the value of the global variable num, which is still 1.

Question 13(iii)

What will be the output of the following program?

num = 1
def myfunc():
    global num
    num = 10 
print (num) 
print (myfunc())
print (num)

Answer

Output
1
None
10
Working
  1. num = 1 — This line assigns the value 1 to the global variable num.
  2. def myfunc(): — This line defines a function named myfunc.
  3. global num — Inside the myfunc function, this line declares that the variable num is a global variable, meaning it refers to the num variable defined outside the function.
  4. num = 10 — Inside the myfunc function, this line changes the value of the global variable num to 10.
  5. print(num) — This line prints the value of the global variable num, which is still 1 at this point as myfunc hasn't been called yet.
  6. print(myfunc()) — This line calls the myfunc function. However, since the function doesn't have a return statement, it implicitly returns None, which is then printed.
  7. print(num) — Finally, this line prints the value of the global variable num after the myfunc function has been called, which is now 10 due to the assignment inside the function.

Question 13(iv)

What will be the output of the following program?

def display():
    print ("Hello",) 
display()
print("bye!")

Answer

Output
Hello
bye!
Working
  1. def display(): — This line defines a function named display with no parameters.
  2. print("Hello",) — Inside the display function, it prints the string "Hello".
  3. display() — This line calls the display function, which then prints "Hello" due to the print statement inside the function.
  4. print("bye!") — This line prints "bye!" on a new line.

Question 14

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

In the above function definition, the line print("the answer is", x + y + z) is placed after the return statement. In python, once a return statement is encountered, the function exits immediately, and any subsequent code in the function is not executed. Therefore, the print statement will never be executed.

Question 15

Predict the output of the following code:

a = 10
y = 5
def myfunc (a) :
    y = a
    a = 2
    print ("y=",y, "a=", a) 
    print ("a+y", a + y) 
    return a + y
print ("y=",y, "a=", a) 
print (myfunc (a))
print ("y=", y, "a=", a)

Answer

Output
y= 5 a= 10
y= 10 a= 2
a+y 12
12
y= 5 a= 10
Working
  1. a = 10 — This line assigns the value 10 to the global variable a.
  2. y = 5 — This line assigns the value 5 to the global variable y.
  3. def myfunc(a): — This line defines a function named myfunc that takes a parameter a.
  4. y = a — This line assigns the value of the parameter a (which is 10) to the local variable y within the function.
  5. a = 2 — This line assigns the value 2 to the local variable a within the function, effectively shadowing the global variable a.
  6. print("y=", y, "a=", a) — This line prints the values of the local variables y and a within the function.
  7. print("a+y", a + y) — This line prints the sum of the local variables a and y within the function.
  8. return a + y — This line returns the sum of the local variables a and y within the function.
  9. print("y=", y, "a=", a) — This line prints the values of the global variables y and a outside the function.
  10. print(myfunc(a)) — This line calls the myfunc function with the value of the global variable a (which is 10) as an argument and prints the returned value.
  11. print("y=", y, "a=", a) — This line prints the values of the global variables y and a again.

Question 16(a)

Find the errors in the code given below:

def minus (total, decrement)
    output = total - decrement
    print (output) 
    return (output)

Answer

The errors in the code are:

def minus(total, decrement) # Error 1  
    output = total - decrement                              
    print(output)
    return (output)

1. There should be a colon at the end of the function definition line.

The corrected code is given below:

def minus(total, decrement): 
    output = total - decrement
    print(output)
    return (output)

Question 16(b)

Find the errors in the code given below:

define check() 
   N = input ( 'Enter N:'_
   I = 3
   Answer = 1 + i ** 4/N
   Return answer

Answer

The errors in the code are:

define check() #Error 1
    N = input ('Enter N: '  #Error 2
    I = 3                                             
    Answer = 1 + i ** 4 / N  #Error 3                        
    Return answer #Error 4
  1. The function definition lacks a colon at the end.
  2. The 'input' function returns a string. To perform arithmetic operations with N, it needs to be converted to a numeric type, such as an integer or a float. Parenthesis should be closed after input() function.
  3. In Python, variable names are case-sensitive. So if we define a variable as 'I', we should use it consistently as 'I' throughout code.
  4. The return statement should be in lowercase. If a variable is named 'Answer' (with an uppercase first letter), it should be used consistently with that casing throughout the program.

The corrected code is given below:

def check():
    N = int(input('Enter N:'))
    I = 3
    Answer = 1 + I ** 4 / N
    return Answer

Question 17

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

Answer

Flow of execution refers to the order in which statements are executed during a program run.

Execution always begins at the first statement of the program. Statements are executed one at a time, starting from the top to the bottom. Function definition does not alter the flow of execution of a program, as the statement inside the function is not executed until the function is called. On a function call, instead of going to the next statement of the program, the control jumps to the body of the function, executes all statements of the function, starting from the top to the bottom and then comes back to the point where it left off.

Question 18

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.

Solution
def convert_dollars_to_rupees(amount_in_dollars, conversion_rate):
    amount_in_rupees = amount_in_dollars * conversion_rate
    return amount_in_rupees

def convert_dollars_to_rupees_void(amount_in_dollars, conversion_rate):
    amount_in_rupees = amount_in_dollars * conversion_rate
    print("Amount in rupees:", amount_in_rupees)

amount = float(input("Enter amount in dollars "))
conversion_rate = float(input("Enter conversion rate "))

# Non-void function call
converted_amount = convert_dollars_to_rupees(amount, conversion_rate)
print("Converted amount (non-void function):", converted_amount)

# Void function call
convert_dollars_to_rupees_void(amount, conversion_rate)
Output
Enter amount in dollars 50
Enter conversion rate 74.5
Converted amount (non-void function): 3725.0
Amount in rupees: 3725.0


Enter amount in dollars 100
Enter conversion rate 75
Converted amount (non-void function): 7500.0
Amount in rupees: 7500.0

Question 19

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

  1. Length of box
  2. Width of box
  3. Height of box

Test it by writing a complete program to invoke it.

Solution
def calculate_volume(length = 5, width = 3, height = 2):
    return length * width * height

default_volume = calculate_volume()
print("Volume of the box with default values:", default_volume)

v = calculate_volume(10, 7, 15)
print("Volume of the box with default values:", v)

a = calculate_volume(length = 23, height = 6)
print("Volume of the box with default values:", a)

b = calculate_volume(width = 19)
print("Volume of the box with default values:", b)
Output
Volume of the box with default values: 30
Volume of the box with default values: 1050
Volume of the box with default values: 414
Volume of the box with default values: 190

Question 20

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

Solution
def display_multiples(n, count = 1):
    if count > 4:
        return
    print(n * count)
    display_multiples(n, count + 1)

n = int(input("Enter the number: "))
display_multiples(n)
Output
Enter the number: 11
11
22
33
44

Question 21

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

Answer

Recursion refers to a programming technique in which a function calls itself either directly or indirectly.

The advantages of using recursion are as follows :

  1. Recursion can simplify the solution to complex problems by breaking them down into smaller, more manageable sub-problems.
  2. Recursive solutions often result in simple and concise code compared to iterative approaches, especially for problems that involve repeated patterns or structures.
  3. Recursion can make code easier to understand.
  4. Recursive functions can handle problems of variable size without requiring changes to the function itself, as long as the base case and recursive cases are properly defined.

The disadvantages of using recursion are as follows :

  1. It consumes more storage space because the recursive calls along with local variables are stored on the stack.
  2. The computer may run out of memory if the recursive calls are not checked.
  3. It is less efficient in terms of speed and execution time.

Question 22

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

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

Solution
def add_series_terms(n):
    if n == 1:
        return 1
    elif n % 2 == 0:
        return add_series_terms(n - 1) + 1 / n
    else:
        return add_series_terms(n - 1) - 1 / n

n = int(input("Enter the term: "))
print(add_series_terms(n))
Output
Enter the term: 2
1.5

Enter the term: 5
1.2166666666666668

Question 23

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

Solution
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
gcd_value = gcd(num1, num2)
print("The greatest common divisor of", num1, "and", num2, "is", gcd_value)
Output
Enter the first number: 24
Enter the second number: 6
The greatest common divisor of 24 and 6 is 6

Question 24

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

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

Solution
def multiply_list(numbers):
    product = 1
    for num in numbers:
        product *= num
    return product

numbers = eval(input("Enter the list: "))
product = multiply_list(numbers)
print("The product of the numbers in the list is", product)
Output
Enter the list: [8, 2, 3, -1, 7] 
The product of the numbers in the list is -336


Enter the list: [1, 6, 3, 5]  
The product of the numbers in the list is 90

Question 25

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.

Solution
def factorial(n):
    product = 1
    for i in range(1, n + 1):
        product *= i
    return product

n = int(input("Enter a number: "))
fact = factorial(n)
print("The factorial of", n, "is", fact)
Output
Enter a number: 5
The factorial of 5 is 120.


Enter a number: 0
The factorial of 0 is 1.

Question 26

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

Solution
def is_prime(n):
    if n <= 1:
        return False
    factors = 0
    for i in range(1, n + 1):
        if n % i == 0:
            factors += 1
        if factors > 2:
            return False
    return True

num = int(input("Enter a number: "))
is_prime_num = is_prime(num)
print("Is", num, "prime?", is_prime_num)
Output
Enter a number: 4
Is 4 prime? False

Enter a number: 29
Is 29 prime? True

Question 27

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.

Solution
def is_palindrome(s):
    s = s.lower()
    return s == s[::-1]

input_string = input("Enter a string: ")
if is_palindrome(input_string):
    print(input_string, "is a palindrome.")
else:
    print(input_string, "is not a palindrome.")
Output
Enter a string: madam
madam is a palindrome.


Enter a string: nursesrun
nursesrun is a palindrome.


Enter a string: watermelon
watermelon is not a palindrome.

Question 28

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

Solution
def sort_words(s):
    words = s.split('-')
    words.sort()
    return '-'.join(words)

input_str = input('Enter a hyphen-separated sequence of words: ')
print(sort_words(input_str))
Output
Enter a hyphen-separated sequence of words: green-red-yellow-black-white   
black-green-red-white-yellow

Enter a hyphen-separated sequence of words: delhi-bangalore-mumbai-chennai-lucknow-patna
bangalore-chennai-delhi-lucknow-mumbai-patna

Question 29

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

Answer

A recursive function is a function that calls itself directly or indirectly in order to solve a problem.

One advantage of using recursive functions is their ability to solve problems in a simple and concise manner.

Question 30

What are the two cases required in a recursive function?

Answer

The base case and recursive case are the two cases required in a recursive function.

Question 31

What is base case?

Answer

Base case is the termination condition that defines when the recursion should stop. It prevents the function from infinitely calling itself and ensures that the recursion reaches a stopping point.

Question 32

What is recursive case?

Answer

Recursive case is the case where the function calls itself with a modified input, moving towards the base case. It allows the function to break down the problem into smaller instances of the same problem until reaching the base case.

Question 33

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

Answer

Yes, it is necessary to have a base case in a recursive function. Without a base case, the recursive function would continue calling itself indefinitely, leading to infinite recursion. This can cause the program to run out of memory and crash, resulting in an error. The base case provides a condition that stops the recursion, allowing the function to return a result and terminate.

Question 34

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

def function1(n): 
    if n == 0:
       return 5
    elif n == 1: 
       return 8
    elif n > 8 :
       return function1(n-1) + function1(n-2)
    else:
       return -1

Answer

The base case(s) in the given recursive function function1 are:

  1. if n == 0: - This is the first base case, which returns a specific value (5) when n is equal to 0.

  2. elif n == 1: - This is the second base case, which returns another specific value (8) when n is equal to 1.

These base cases provide termination conditions for the recursive function, ensuring that it stops calling itself when n reaches 0 or 1.

Question 35

Why are recursive functions considered slower than their iterative counterparts?

Answer

When a loop is executed repeatedly, it uses the same memory locations for variables and repeats the same unit of code. On the other hand, recursion allocates fresh memory space for each recursive call, avoiding the repetition of code and the reuse of memory locations for variables. Due to stack manipulation and the allocation of additional memory space, recursive functions often run slower and consume more memory than their iterative counterparts.

Question 36

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

Answer

  1. Memory Space: — Iterative solutions require less memory space because they reuse the same variables and memory locations for each iteration of the loop. Memory allocation is minimal, leading to efficient memory usage. On the other hand, recursive solutions require more memory space compared to iteration. This is because recursion involves creating a new stack for each recursive call, storing local variables and function calls. As a result, recursion can lead to higher memory consumption.
  2. Speed: — Iterative solutions are faster in terms of execution speed compared to recursion. Since iteration involves a simple loop structure that directly manipulates variables, it results in faster execution times. On the other hand, recursive solutions are slower than their iterative counterparts due to the overhead of function calls and stack manipulation.

Question 37(a)

Predict the output of the following code.

def code(n):
    if n == 0:
       print ( 'Finally' ) 
    else:
       print (n)
code (3)
code (15)

Answer

Output
3
15
Explanation

The code defines a function code(n) that takes a single argument n. Inside the function, if the input n is equal to 0, it prints "Finally", otherwise, it prints the value of n. When called with code(3), it passes the argument 3 to the function. Since 3 is not equal to 0, the function prints 3. Similarly, calling code(15) prints 15 as it also doesn't meet the condition for 0.

Question 37(b)

Predict the output of the following code.

def code (n) :
    if n==0:
       print('Finally') 
    else:
       print(n)
code (2-2)
code (15)

Answer

Output
Finally
15
Explanation

The code defines a function code(n) that takes a single argument n. Inside the function, if the input n is equal to 0, it prints "Finally", otherwise, it prints the value of n. In the first function call code(2-2), the expression 2-2 evaluates to 0, so the function prints "Finally". Conversely, in the second function call code(15), the value 15 is not equal to 0, so the function prints 15.

Question 37(c)

Predict the output of the following code.

def code(n):
    if n == 0:
       print(' Finally') 
    else:
       print (n)
code (10)

Answer

Output
10
Explanation

This code defines a function called code(n) that takes a single argument n. Inside the function, there's a conditional statement that checks if n is equal to 0. If n is indeed 0, it prints the string " Finally". Otherwise, it prints the value of n. When the function code(10) is called, it passes the argument 10 to the function. Since 10 is not equal to 0, the function prints 10.

Question 37(d)

Predict the output of the following code.

def code (n) :
    if n==0:
       print ( 'Finally' ) 
    else:
       print (n)
       print (n-3)
code (10)

Answer

Output
10
7
Explanation

This code defines a function code(n) that takes a single argument n. Inside the function, there's a conditional statement that checks if n is equal to 0. If n is indeed 0, it prints the string "Finally". Otherwise, it prints the value of n and then calculates and prints n-3. When the function code(10) is called, it passes the argument 10 to the function. Since 10 is not equal to 0, the function first prints 10 and then calculates and prints 10-3, which is 7.

Question 38

Predict the output of the 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

The code will not print anything because it doesn't include a print statement. Instead, it returns a value without displaying it.

Explanation

The code defines a recursive function express(x, n) that takes two arguments x, n. Inside the function, it checks for three conditions: if n is 0, it returns 1; if n is even (checked using the modulo operator), it recursively calls itself with x*x and n/2; and if n is odd, it recursively calls itself with x and n-1, then multiplies the result by x. When express(2, 5) is called, it eventually evaluates to 32 but does not print or display anything.

Question 39

Consider the 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

True is returned by check(8).

Explanation

The provided code defines a recursive function check(n) that takes single argument. Inside the function, it checks if a given number n is less than or equal to 1, in which case it returns True. If n is even (i.e., divisible by 2 without a remainder), the function recursively calls itself with n/2. If n is odd, it recursively calls itself with n/1 (which effectively does not change n). However, the condition n/1 doesn't modify n and leads to an infinite recursion for odd numbers greater than 1, causing the function to keep calling itself indefinitely without reaching a base case.

Question 40

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

def check (n) :
    if n <=1:
        return True
    elif n % 2 == 0:
        return check (n/2) 
    else:
        return check (n/1)

Answer

Yes, there is a error in the provided code. If we evaluate check(3), it will result in an infinite recursion and eventually lead to an error.

This happens because when check(3) is called, the function first checks if n is less than or equal to 1, which is not the case. Since n is odd (i.e., n % 2 == 1), it enters the else block and calls check(n/1) which leads to the same value of n being passed recursively to the function without any change. As a result, the function keeps calling itself with the same value of n, leading to an infinite loop of recursion.

Question 41

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 the following function calls?

  1. Fn (12)
  2. Fn (10)
  3. Fn (7)

Answer

1.

Output
12 6 3 1 1 2 4 2 1 

2.

Output
10 5 2 1 3 1 1 

3.

Output
7 3 1 1 2 
Explanation

The provided code defines a recursive function Fn(n) that prints the value of n and then checks if n is less than 3. If n is less than 3, the function returns n. Otherwise, it recursively calls itself with n//2 (integer division by 2) and subtracts the result of another recursive call with n//3 (integer division by 3).

Question 42

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

def recur(p): 
   if p == 0:
       print ("##")
   else:
       recur(p) 
       p = p - 1

Answer

The error in the provided code is that inside the else block the value of p is modified after the recursive call. This leads to an infinite recursion because p remains the same in each recursive call, never reaching the base case (p == 0) and causing the program to enter an infinite loop.

Explanation

The corrected code is:

def recur(p):
    if p == 0:
        print("##")
    else:
        recur(p - 1)

In this corrected version, p is decremented by 1 in each recursive call, ensuring that the recursive process eventually reaches the base case where p == 0 and terminates the recursion.

Question 43

Write a method in Python to find and display the prime numbers from 2 to N. The value of N should be passed as an argument to the method.

Solution
def find_primes(N):
    primes = [] 
    for num in range(2, N + 1):  
        factors = 0  
        for i in range(1, num + 1):  
            if num % i == 0:  
                factors += 1 
        if factors == 2:  
            primes.append(num)  
    return primes

N = int(input("Enter the value of N: "))
prime_numbers = find_primes(N)
print("Prime numbers from 2 to", N, "are:", prime_numbers)
Output
Enter the value of N: 10
Prime numbers from 2 to 10 are: [2, 3, 5, 7]


Enter the value of N: 30
Prime numbers from 2 to 30 are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Question 44

Write a method EvenSum(NUMBERS) to add those values in the tuple of NUMBERS which are even.

Solution
def EvenSum(NUMBERS):
    even_sum = 0
    for number in NUMBERS:
        if number % 2 == 0:
            even_sum += number
    return even_sum


n = eval(input("Enter the tuple: "))
result = EvenSum(n)
print("The sum of even numbers in the tuple is:", result)
Output
Enter the tuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
The sum of even numbers in the tuple is: 30

Question 45

Write a method COUNTNOW(PLACES) to find and display those place names in which there are more than 5 characters after storing the name of places in a dictionary. For example, if the dictionary PLACES contains:

{'1': "DELHI", '2': "LONDON", '3': "PARIS", '4': "NEW YORK", '5': "DUBAI"}

The following output should be displayed:
LONDON
NEW YORK

Solution
PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5: "Doha"}
def countNow(PLACES):
    for place in PLACES.values():
        if len(place) > 5:
            print(place.upper())
countNow(PLACES)
Output
LONDON
NEW YORK

Question 46

Write a program using user-defined function to calculate and display average of all the elements in a user-defined tuple containing numbers.

Solution
def calculate_average(num):
    total = 0
    for element in num:
        total += element
    average = total / len(num)
    return average

n = eval(input("Enter the tuple: "))
average = calculate_average(n)
print("The average of the elements in the tuple is:", average)
Output
Enter the tuple: (2, 4, 6, 8, 10)
The average of the elements in the tuple is: 6.0

Question 47

Name the built-in mathematical function/method:

(a) Used to return an absolute value of a number.

(b) Used to return the value of xy, where x and y are numeric expressions.

(c) Used to return a positive value of the expression in float.

Answer

(a) abs()

(b) pow(x, y)

(c) math.fabs()

Question 48

Name the built-in String function:

(a) Used to remove the space(s) from the left of the string.

(b) Used to check if the string is uppercase or not.

(c) Used to check if the string contains only whitespace characters or not.

Answer

(a) lstrip()

(b) isupper()

(c) isspace()

Question 49

Write a function LeftShift(lst, x) in Python which accepts numbers in a list (lst) and all the elements of the list should be shifted to left according to the value of x.

Sample Input Data of the list lst = [20, 40, 60, 30, 10, 50, 90, 80, 45, 29] where x = 3

Output lst = [30, 10, 50, 90, 80, 45, 29, 20, 40, 60]

Solution
def LeftShift(lst, x):
    if x >= len(lst):
        x %= len(lst)
    shifted_lst = lst[x:] + lst[:x]
    return shifted_lst

lst = eval(input("Enter the list: "))
x = int(input("Enter the value of x: "))
result = LeftShift(lst, x)
print(result)
Output
Enter the list: [20, 40, 60, 30, 10, 50, 90, 80, 45, 29]
Enter the value of x: 3
[30, 10, 50, 90, 80, 45, 29, 20, 40, 60]



Enter the list: [55, 66, 77, 88, 99, 44, 33, 22, 11]
Enter the value of x: 4
[99, 44, 33, 22, 11, 55, 66, 77, 88]
PrevNext