0% found this document useful (0 votes)
4 views

Function

The document discusses common errors in function definitions, the importance of scope in Python, and the differences between local and global variables. It also covers assertions related to function parameters and the use of default and keyword arguments. Additionally, it explains the utility of functions, their types, and the concept of returning multiple values.

Uploaded by

mahmoodkhurram8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Function

The document discusses common errors in function definitions, the importance of scope in Python, and the differences between local and global variables. It also covers assertions related to function parameters and the use of default and keyword arguments. Additionally, it explains the utility of functions, their types, and the concept of returning multiple values.

Uploaded by

mahmoodkhurram8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1

Find the errors in following function definitions :


1. def main()
2. print ("hello")
3. def func2():
4. print(2 + 3)
5. def compute():
6. print (x * x)
7. square (a)
8. return a * a
Answer
1. Colon is missing at the end of function header.
2. There is no error.
3. The variable x is not defined.
4. def keyword at the beginning and colon at the end of function header are missing.
The corrected function definitions are:
1. def main():
2. print("hello")
3. def func2():
4. print(2 + 3)
5. def compute(x):
6. print (x * x)
7. def square(a):
8. return a * a

The positional parameters must occur to the left of default parameters because in a function
header, any parameter cannot have a default value unless all parameters appearing on its
right have their default values.

Which of the following is not correct in context of scope of


variables ?
1. Global keyword is used to change value of a global variable in a local scope.
2. Local keyword is used to change value of a local variable in a global scope.
3. Global variables can be accessed without using the global keyword in a local scope.
4. Local variables cannot be used outside its scope.
Answer
Local keyword is used to change value of a local variable in a global scope.
Reason — If you need to modify a local variable in global scope, you do so by passing it as
an argument to a function and/or returning a modified value from the function.

For a function header as follows :


def Calc(X,Y = 20):
Which of the following function calls will give an error ?
1. Calc(15, 25)
2

2. Calc(X = 15, Y = 25)


3. Calc(Y = 25)
4. Calc(X = 25)
Answer
Calc(Y = 25)
Reason — The function call statement must match the number and order of arguments as defined
in the function definition. Here, the X positional argument is missing.

A global variable is a variable declared in top level segment (__main__) of a program and
usable inside the whole program and all blocks contained within the program.
A local variable is a variable declared in a function-body and it can be used only within
this function and the other blocks contained under it.
A default argument is an argument with a default value in the function header, making it
optional in the function call. The function call may or may not have a value for it.
3

Assertions and Reasons


Question 1
Assertion. A function is a subprogram.
Reason. A function exists within a program and works within it when called.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
A function is a subprogram that acts on data and often returns a value. It is a self-
contained unit of code that performs a specific task within a larger program. Functions are
defined within a program and can be called upon to execute a specific set of instructions
when needed.
Question 2
Assertion. Non-default arguments cannot follow default arguments in a function call.
Reason. A function call can have different types of arguments.
Answer
(b)
Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
Explanation
In a function call, any parameter cannot have a default value unless all parameters appearing
on its right have their default values. Hence, non-default arguments cannot follow default
arguments in a function call. Python supports three types of formal arguments :
1. Positional arguments
2. Default arguments
3. keyword arguments
Question 3
Assertion. A parameter having a default in function header becomes optional in function
call.
Reason. A function call may or may not have values for default arguments.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
When a parameter in a function header has a default value, it means that if no value is
provided for that parameter during the function call, the default value will be used. This
effectively makes the parameter optional in the function call. When calling a function with
default arguments, we have the option to either provide values for those arguments or omit
them, in which case the default values will be used.
Question 4
Assertion. A variable declared inside a function cannot be used outside it.
Reason. A variable created inside a function has a function scope.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
Variables declared inside a function are typically local to that function, meaning they
4
exist only within the scope of the function and they can only be accessed and used within
the function in which they are declared.
Question 5
Assertion. A variable not declared inside a function can still be used inside the function
if it is declared at a higher scope level.
Reason. Python resolves a name using LEGB rule where it checks in Local (L), Enclosing (E),
Global (G) and Built-in scopes (B), in the given order.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
In Python, if a variable is not declared inside a function but is declared at a higher scope
level (e.g., in the global scope or an enclosing scope), the function can still access and
use that variable. Since Python follows the LEGB rule, variables declared at higher scope
levels can be accessed within functions.
Question 6
Assertion. A parameter having a default value in the function header is known as a default
parameter.
Reason. The default values for parameters are considered only if no value is provided for
that parameter in the function call statement.
Answer
(b)
Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
Explanation
A default parameter is a parameter in a function definition that has a predefined value.
When we call a function with default parameters, if we don't provide a value for a parameter,
the default value specified in the function header will be used instead.
Question 7
Assertion. A function declaring a variable having the same name as a global variable, cannot
use that global variable.
Reason. A local variable having the same name as a global variable hides the global variable
in its function.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
Inside a function, you assign a value to a name which is already there in 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 a global variable hides the global variable in its
function.
Question 8
Assertion. 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.
Reason. During a function call, the argument list first contains default argument(s)
followed positional argument(s).
5
Answer
(c)
Assertion is true but Reason is false.
Explanation
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. During
a function call, the argument list first contains positional argument followed by default
arguments because any parameter cannot have a default value unless all parameters appearing
on its right have their default values.
6

Type A: Short Answer Questions/Conceptual 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. It makes program handling easier as only a small part of the program is dealt with
at a time, thereby avoiding ambiguity.
2. It reduces program size.
3. Functions make a program more readable and understandable to a programmer thereby
making program management much easier.
Question 2
What all information does a function header give you about the
function ?
Answer
Function header is the first line of function definition that begins with keyword def and
ends with a colon (:), specifies the name of the function and its parameters.
Question 3
What do you understand by flow of execution ?
Answer
Flow of execution refers to the order in which statements are executed during a program
run.
Question 4
What are arguments ? What are parameters ? How are these two terms
different yet related ? Give example.
Answer
Arguments — The values being passed through a function-call statement are called
arguments.
Parameters — The values received in the function definition/header are called parameters.
Arguments appear in function call statement whereas parameters appear in function header.
The two terms are related because the values passed through arguments while calling a
function are received by parameters in the function definition.
For example :
def multiply(a, b):
print(a * b)
multiply(3, 4)
Here, a and b are parameters while 3, 4 are arguments.
Question 5
What is the utility of : (i) default arguments, (ii) keyword arguments
?
Answer
7
(i) 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.
(ii) 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
Explain with a code example the usage of default arguments and keyword
arguments.
Answer
Default arguments — Default arguments are used to provide a default value to a function
parameter if no argument is provided during the function call.
For example :
def greet(name, message="Hello"):
print(message, name)

greet("Alice")
greet("Bob", "Hi there")
Output
Hello Alice
Hi there Bob
In this example, the message parameter has a default value of "Hello". If no message
argument is provided during the function call, the default value is used.
Keyword arguments — Keyword arguments allow us to specify arguments by their parameter
names during a function call, irrespective of their position.
def person(name, age, city):
print(name, "is", age, "years old and lives in", city)

person(age=25, name="Alice", city="New York")


person(city="London", name="Bob", age=30)
Output
Alice is 25 years old and lives in New York
Bob is 30 years old and lives in London
In this example, the arguments are provided in a different order compared to the function
definition. Keyword arguments specify which parameter each argument corresponds to, making
the code more readable and self-explanatory.
Both default arguments and keyword arguments provide flexibility and improve the
readability of code, especially in functions with multiple parameters or when calling
functions with optional arguments.
Question 7
Describe the different styles of functions in Python using
appropriate examples.
Answer
The different styles of functions in Python are as follows :
8
1. Built-in functions — These are pre-defined functions and are always available for
use. For example:
2. name = input("Enter your name: ")
3. name_length = len(name)
print("Length of your name:", name_length)
In the above example, print(), len(), input() etc. are built-in functions.
4. User defined functions — These are defined by programmer. For example:
5. def calculate_area(length, width):
6. area = length * width
7. return area
8. length = 5
9. width = 3
10.result = calculate_area(length, width)
print("Area of the rectangle:", result)
In the above example, calculate_area is a user defined function.
11.Functions defined in modules — These functions are pre-defined in particular modules
and can only be used when corresponding module is imported. For example:
12.import math
13.num = 16
14.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 8
Differentiate between fruitful functions and non-fruitful
functions.
Answer
Fruitful functions Non-fruitful functions

Functions returning some value Functions that does not return


are called as fruitful any value are called as non-
functions. fruitful functions.

They are also called as non- They are also called as void
void functions. functions.

They may or may not have a


They have return statements in return statement, but if they
the syntax : return<value>. do, it typically appears as per
syntax : return.

Fruitful functions return some Non-fruitful functions return


computed result in terms of a legal empty value of Python,
value. which is None, to their caller.
Question 9
Can a function return multiple values ? How ?
Answer
9
Yes, a function can return multiple values. To return multiple values from a function, we
have to ensure following things :
1. The return statement inside a function body should be of the form :
return <value1/variable1/expression1>,<value2/variable2/expression2>,....
2. The function call statement should receive or use the returned values in one of the
following ways :
(a) Either receive the returned values in form a tuple variable.
(b) Or we can directly unpack the received values of tuple by specifying the same number
of variables on the left-hand side of the assignment in function call.
Question 10
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 11
What is the difference between local and global variable ?
Answer
Local variable Global variable

A local variable is a variable defined A global variable is a variable


within a function. defined in the 'main' program.

They are accessible from anywhere


They are only accessible within the
within the program, including inside
block in which they are defined.
functions.

These variables have local scope. These variables have global scope.

The lifetime of a local variable is Global variables persist throughout


limited to the block of code in which it the entire execution of the program.
is defined. Once the execution exits They are created when the program
that block, the local variable is starts and are only destroyed when the
destroyed, and its memory is released. program terminates.
Question 12
When is global statement used ? Why is its use not recommended ?
Answer
If we want to assign some value to the global variable without creating any local variable
then global statement is used. It is not recommended because once a variable is declared
global in a function, we cannot undo the statement. That is, after a global statement, the
function will always refer to the global variable and local variable cannot be created of
the same name. Also, by using global statement, programmers tend to lose control over
variables and their scopes.
Question 13
Write the term suitable for following descriptions :
10
(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 value
(e) Keyword argument
(f) Global variable
(g) Local variable
Question 14
What do you understand by local and global scope of variables ? How
can you access a global variable inside the function, if function
has a variable with same name.
Answer
Local scope — Variables defined within a specific block of code, such as a function or a
loop, have local scope. They are only accessible within the block in which they are
defined.
Global scope — Variables defined outside of any specific block of code, typically at the
top level of a program or module, have global scope. They are accessible from anywhere
within the program, including inside functions.
To access a global variable inside a function, even if the function has a variable with
the same name, we can use the global keyword to declare that we want to use the global
variable instead of creating a new local variable. The syntax is :
global<variable name>
For example:
def state1():
global tigers
tigers = 15
print(tigers)
tigers = 95
print(tigers)
state1()
print(tigers)
In the above example, tigers is a global variable. To use it inside the function state1 we
have used global keyword to declare that we want to use the global variable instead of
creating a new local variable.
11

Type B: Application Based Questions


Question 1(a)
What are the errors in following codes ? Correct the code and predict output :
total = 0;
def sum(arg1, arg2):
total = arg1 + arg2;
print("Total :", total)
return total;
sum(10, 20);
print("Total :", total)
Answer
total = 0
def sum(arg1, arg2):
total = arg1 + arg2
print("Total :", total)
return total
sum(10, 20)
print("Total :", total)
Output
Total : 30
Total : 0

Question 1(b)
What are the errors in following codes ? Correct the code and predict output :
def Tot(Number) #Method to find Total
Sum = 0
for C in Range (1, Number + 1):
Sum += C
RETURN Sum
print (Tot[3]) #Function Calls
print (Tot[6])
Answer
def Tot(Number): #Method to find Total
Sum = 0
for C in range(1, Number + 1):
Sum += C
return Sum
print(Tot(3)) #Function Calls
print(Tot(6))
Output
6
21

Find and write the output of the following python code :


def Call(P = 40, Q = 20):
P = P + Q
12
Q = P - Q
print(P, '@', Q)
return P
R = 200
S = 100
R = Call(R, S)
print(R, '@', S)
S = Call(S)
print(R, '@', S)
Answer
Output
300 @ 200
300 @ 100
120 @ 100
300 @ 120

Draw the entire environment, including all user-defined variables at the time line 10 is
being executed.
1. def sum(a, b, c, d):
2. result = 0
3. result = result + a + b + c + d
4. return result
5.
6. def length():
7. return 4
8.
9. def mean(a, b, c, d):
10. return float(sum(a, b, c, d))/length()
11.
12. print(sum(a, b, c, d), length(), mean(a, b, c, d))
Answer
13
Find and write the output of the following python code :
a = 10
def call():
global a
a = 15
b = 20
print(a)
call()
Answer
Output
15
In the following code, which variables are in the same scope ?
def func1():
a = 1
b = 2

def func2():
c = 3
d = 4
e = 5
Answer
In the code, variables a and b are in the same scope because they are defined within the
same function func1(). Similarly, variables c and d are in the same scope because they are
defined within the same function func2(). e being a global variable is not in the same
scope.
Write a program with a function that takes an integer and prints the number that follows
after it. Call the function with these arguments :
4, 6, 8, 2 + 1, 4 - 3 * 2, -3 -2
Answer
1. def print_number(number):
2. next_number = number + 1
3. print("The number following", number, "is", next_number)
4. print_number(4)
5. print_number(6)
6. print_number(8)
7. print_number(2 + 1)
8. print_number(4 - 3 * 2)
9. print_number(- 3 - 2)
Output
The print_number following 4 is 5
The print_number following 6 is 7
The print_number following 8 is 9
The print_number following 3 is 4
The print_number following -2 is -1
The print_number following -5 is -4
Write a program with non-void version of above function and then write flow of execution
for both the programs.
14
Answer
The non-void version of above code is as shown below :
1. def print_number(number):
2. next_number = number + 1
3. return next_number
4. print(print_number(4))
5. print(print_number(6))
6. print(print_number(8))
7. print(print_number(2 + 1))
8. print(print_number(4 - 3 * 2))
9. print(print_number(-3 - 2))
Output
5
7
9
4
-1
-4
What will be the output of the following Python code ?
V = 25
def Fun(Ch):
V = 50
print(V, end = Ch)
V *= 2
print(V, end = Ch)
print(V, end = "*")
Fun("!")
print(V)
1. 25*50!100!25
2. 50*100!100!100
3. 25*50!100!100
4. Error
Answer
25*50!100!25
15

Type C: Programming Practice/Knowledge based Questions


Question 1
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 2
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 ;
16

(b) width of box ;


(c) height of box.
Test it by writing 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 3
Write a program to have following functions :
(i) a function that takes a number as argument and calculates
cube for it. The function does not return a value. If there
is no value passed to the function in function call, the
function should calculate cube of 2.
(ii) a function that takes two char arguments and returns
True if both the arguments are equal otherwise False.
Test both these functions by giving appropriate function call
statements.
Solution
# Function to calculate cube of a number
def calculate_cube(number = 2):
cube = number ** 3
print("Cube of", number, "is", cube)

# Function to check if two characters are equal


def check_equal_chars(char1, char2):
17
return char1 == char2

calculate_cube(3)
calculate_cube()

char1 = 'a'
char2 = 'b'
print("Characters are equal:", check_equal_chars(char1, char1))
print("Characters are equal:", check_equal_chars(char1, char2))
Output
Cube of 3 is 27
Cube of 2 is 8
Characters are equal: True
Characters are equal: False
Question 4
Write a function that receives two numbers and generates a
random number from that range. Using this function, the main
program should be able to print three numbers randomly.
Solution
import random

def generate_random_number(num1, num2):


low = min(num1, num2)
high = max(num1, num2)
return random.randint(low, high)

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

for i in range(3):
random_num = generate_random_number(num1, num2)
print("Random number between", num1, "and", num2, ":", random_num)
Output
Enter the first number: 2
Enter the second number: 78
Random number between 2 and 78 : 77
Random number between 2 and 78 : 43
Random number between 2 and 78 : 52

Enter the first number: 100


Enter the second number: 599
Random number between 100 and 599 : 187
Random number between 100 and 599 : 404
Random number between 100 and 599 : 451
Question 5
18

Write a function that receives two string arguments and checks


whether they are same-length strings (returns True in this
case otherwise False).
Solution
def same_length_strings(str1, str2):
return len(str1) == len(str2)

s1 = "hello"
s2 = "world"
s3 = "python"

print(same_length_strings(s1, s2))
print(same_length_strings(s1, s3))
Output
True
False
Question 6
Write a function namely nthRoot( ) that receives two
parameters x and n and returns nth root of x i.e., x^(1/n).
The default value of n is 2.
Solution
def nthRoot(x, n = 2):
return x ** (1/n)

x = int(input("Enter the value of x:"))


n = int(input("Enter the value of n:"))

result = nthRoot(x, n)
print("The", n, "th root of", x, "is:", result)

default_result = nthRoot(x)
print("The square root of", x, "is:", default_result)
Output
Enter the value of x:36
Enter the value of n:6
The 6 th root of 36 is: 1.8171205928321397
The square root of 36 is: 6.0

Question 7
Write a function that takes a number n and then returns a
randomly generated number having exactly n digits (not
starting with zero) e.g., if n is 2 then function can randomly
19

return a number 10-99 but 07, 02 etc. are not valid two digit
numbers.
Solution
import random
def generate_number(n):
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)

n = int(input("Enter the value of n:"))


random_number = generate_number(n)
print("Random number:", random_number)
Output
Enter the value of n:2
Random number: 10

Enter the value of n:2


Random number: 50

Enter the value of n:3


Random number: 899

Enter the value of n:4


Random number: 1204
Question 8
Write a function that takes two numbers and returns the number
that has minimum one's digit.
[For example, if numbers passed are 491 and 278, then the
function will return 491 because it has got minimum one's
digit out of two given numbers (491's 1 is < 278's 8)].
Solution
def min_ones_digit(num1, num2):
ones_digit_num1 = num1 % 10
ones_digit_num2 = num2 % 10
if ones_digit_num1 < ones_digit_num2:
return num1
else:
return num2

num1 = int(input("Enter first number:"))


num2 = int(input("Enter second number:"))
result = min_ones_digit(num1, num2)
print("Number with minimum one's digit:", result)
Output
20
Enter first number:491
Enter second number:278
Number with minimum one's digit: 491

Enter first number:543


Enter second number:765
Number with minimum one's digit: 543
Question 9
Write a program that generates a series using a function which
takes first and last values of the series and then generates
four terms that are equidistant e.g., if two numbers passed
are 1 and 7 then function returns 1 3 5 7.
Solution
def generate_series(first, last):
step = (last - first) // 3
series = [first, first + step, first + 2 * step, last]
return series

first_value = int(input("Enter first value:"))


last_value = int(input("Enter last value:"))
result_series = generate_series(first_value, last_value)
print("Generated Series:", result_series)
Output
Enter first value:1
Enter last value:7
Generated Series: [1, 3, 5, 7]

Enter first value:10


Enter last value:25
Generated Series: [10, 15, 20, 25]

You might also like