Which of the following statements is the most appropriate for Python function?
- A block of code that only runs when it is called
- A variable used to store data
- A way to print output to the console
- An error message
Answer
A block of code that only runs when it is called
Reason — A Python function is a block of reusable code designed to perform a specific task. It is executed only when it is called (invoked) from the main program or from another function.
In Python, the keyword used for defining a function is ..............
- func
- function
- def
- import
Answer
def
Reason — In Python, the keyword def is used to define a function. It is followed by the function name and parentheses containing the parameters, ending with a colon. The other options like func and function are not valid Python keywords, while import is used to include modules.
Which of the following are the two main parts of every function in Python?
- Function header and function body
- Function block and main block
- Function head and function tail
- None of the above
Answer
Function header and function body
Reason — Every function in Python consists of two main parts — the function header which contains the def keyword, the function name, and the list of parameters, and the function body which contains the set of statements to be executed. Together, they form the function block.
Which of the following statements is not true for a function in Python?
- It is a program module.
- It is reusable piece of a program.
- It is not a program module.
- All of the above
Answer
It is not a program module.
Reason — A function is a program module (a part of the program) used simultaneously at different instances to perform a specific task. It is also a reusable piece of code. Therefore, the statement "It is not a program module" is not true for a Python function.
What is the default return value when a function does not return any value explicitly?
- null
- void
- empty
- None
Answer
None
Reason — A Python function will always have a return value. If we do not explicitly use a return value, the function implicitly returns a default value that is None.
When the arguments and parameters are with same variable names, they are known as:
- default arguments
- keyword arguments
- positional arguments
- None of them
Answer
keyword arguments
Reason — Keyword arguments allow us to pass values to a function by specifying argument names matching the parameter names. This gives us the flexibility to write the arguments in any order during the function call, provided the arguments names and the parameters' names are the same.
State whether the following statements are True or False:
- A function cannot be defined without parameters.
- The return statement without parameter indicates a non-returnable function.
- A function can return only one value to its caller program.
- The parameters used in the function definition are called actual parameters.
- A function may or may not return a value to the main program.
- A function always contains the header and the footer.
Answer
- False
Corrected Statement: A function can be defined without parameters. An empty parameter list simply indicates that the function doesn't receive any value during its call. - True
- False
Corrected Statement: Unlike other programming languages, Python can return more than one value or multiple values from a function to its caller. - False
Corrected Statement: The parameters used in the function definition are called formal parameters, not actual parameters. The values passed to the function during its call are called actual parameters (or arguments). - True
- False
Corrected Statement: A function always contains the header and the body, not the footer. A function consists of a function header and a function body.
Predict the output of the following snippet:
m=32
n=float(m)
print(n)Answer
32.0
The float() function converts the integer value 32 stored in m into a floating-point number. Hence, the value of n becomes 32.0 which is displayed by the print() statement.
Predict the output of the following snippet:
a=42.85
b=int(a)
print(b)Answer
42
The int() function takes a floating-point value and truncates the decimal part to return an integer. Hence, 42.85 becomes 42 and is stored in b, which is then displayed.
Predict the output of the following snippet:
wd="Robotics"
print(len(wd))Answer
8
The len() function returns the number of characters in the string. The string "Robotics" contains 8 characters (R, o, b, o, t, i, c, s), so the output is 8.
Predict the output of the following snippet:
List1=["Happy", "New", "Year", 2026]
print(len(List1))Answer
4
The len() function returns the number of items (elements) in a list. List1 contains four elements — "Happy", "New", "Year", and 2026. Hence, the output is 4.
Python has a built-in type() function to ascertain the data type of a specific value. Predict the data type of the given Python statement:
m=32
n=float(m)
print(type(n))Answer
<class 'float'>
The float() function converts the integer 32 into a floating-point number 32.0. Therefore, the data type of n is float.
Predict the data type of the given Python statement:
a=42.85
b=int(a)
print(type(b))Answer
<class 'int'>
The int() function converts the floating-point value 42.85 into an integer 42 by truncating the decimal part. Therefore, the data type of b is int.
Predict the data type of the given Python statement:
m=12E4
print(type(m))Answer
<class 'float'>
The value 12E4 represents 12 × 10⁴ = 120000 in scientific (exponential) notation. Numbers written in exponential notation are always treated as floating-point numbers in Python. Hence, the data type of m is float.
Predict the data type of the given Python statement:
p='10'
print(type(int(p)))Answer
<class 'int'>
The int() function converts the string '10' into an integer 10. Therefore, the data type returned by type(int(p)) is int.
Predict the data type of the given Python statement:
n=0.0025
print(type(n))Answer
<class 'float'>
The value 0.0025 is a number with a decimal point, which is treated as a floating-point number in Python. Hence, the data type of n is float.
Predict the output of the following code:
def Add(num1, num2):
sum = num1 + num2
sum = Add(20, 30)
print(sum)Answer
None
The function Add() is called with the values 20 and 30. Inside the function, the statement sum = num1 + num2 calculates the addition and stores the result in the local variable sum. However, the function does not contain a return statement to send the value back to the main program. Therefore, Python automatically returns None. In the main program, the same variable name sum is used as sum = Add(20, 30), so the value None gets stored in it. Hence, the print(sum) statement displays None.
Predict the output of the following code:
def Sum(a, b):
return a+5, b*5
# main program
result = Sum(4, 5)
print(result)Answer
(9, 25)
The function Sum() is called with the values 4 and 5. Inside the function, the expression a+5 becomes 4+5 = 9 and the expression b*5 becomes 5*5 = 25. The return statement sends both values back to the main program. In Python, when multiple values are returned together, they are stored as a tuple. Therefore, the variable result stores the tuple (9, 25), which is displayed by the print(result) statement.
Predict the output of the following code:
def Disp_Max(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
Disp_Max(22, 14)Answer
22 is maximum
The function Disp_Max() is called with the values 22 and 14. Inside the function, the condition a > b is checked first. Since 22 > 14 is True, the statement print(a, 'is maximum') gets executed and displays 22 is maximum. The elif and else blocks are skipped because the first condition is already satisfied.
Assertion (A): When the user defines a function of his/her own and use it in the program to perform a specific task, it is known as user defined function.
Reason (R): The types of functions viz. built-in functions and modules are also known as user defined functions because they are not defined by the system developers. Thus, it is not necessary that the system developers are only authorised for creating a function.
Based on the above discussion, choose an appropriate statement from the options given below:
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true and R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false.
Answer
A is true but R is false.
Reason — The assertion is correct because when a user defines a function of his/her own to perform a specific task, it is called a user-defined function. However, the reason is false because built-in functions and modules are defined by the system developers (language creators), not by the users. They are not user-defined functions.
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The following program is designed to generate next five terms of the Fibonacci series, excluding 0 and 1 (i.e., first two terms of the series). The incomplete user-defined program is given as under:
def Fibo_Series():
a = 0
b = 1
count = ........... # Line 1
while(count <= ............): # Line 2
c = a + b
print(.............) # Line 3
a = ............. # Line 4
b = c
count = count + 1
# main program
Fibo_Series()Now, complete the above program to generate next five numbers of the series as 1, 2, 3, 5, 8.
Answer
def Fibo_Series():
a = 0
b = 1
count = 1 # Line 1
while(count <= 5): # Line 2
c = a + b
print(c) # Line 3
a = b # Line 4
b = c
count = count + 1
# main program
Fibo_Series()Explanation:
- Line 1:
count = 1— initializes the counter to start from 1. - Line 2:
count <= 5— loop runs five times to generate five terms of the series. - Line 3:
print(c)— displays the next Fibonacci number which is the sum of the two preceding terms. - Line 4:
a = b— updatesawith the previous value ofbso that the next sum is calculated correctly.
Trace of values:
| Iteration | a | b | c = a+b | Output |
|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 1 |
| 2 | 1 | 1 | 2 | 2 |
| 3 | 1 | 2 | 3 | 3 |
| 4 | 2 | 3 | 5 | 5 |
| 5 | 3 | 5 | 8 | 8 |
Write a user-defined function def Circle() to input radius of a circle from the user. The program calculates area and circumference inside the function. Finally, it returns the values to main program to display the result.
def Circle(r):
ar = 3.14 * r * r
cir = 2 * 3.14 * r
return(ar, cir)
radius = float(input("Enter radius of circle:"))
area, circumference = Circle(radius)
print("Area of circle:", area)
print("Circumference of circle:", circumference)Enter radius of circle:7
Area of circle: 153.86
Circumference of circle: 43.96
Write a user-defined function def Perfect() to input a number from the user. The program checks whether it is a perfect number or not. Finally, it returns the values to main program to display the result.
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself.
For example, 6 = 1 + 2 + 3
It is a perfect number.
def Perfect(n):
s = 0
for i in range(1, n):
if(n % i == 0):
s = s + i
return(s)
# main program
num = int(input("Enter a number:"))
sum1 = Perfect(num)
if(sum1 == num):
print("It is a Perfect number")
else:
print("It is not a perfect number")Enter a number:6
It is a Perfect number
Write a user-defined function def Sum_Digits() to input a number from the user. The program calculates sum of the digits of the number inside the function without returning any data to the main program.
Sample Input: 345
Output: 3 + 4 + 5 = 12
def Sum_Digits(n):
s = 0
temp = n
while(n != 0):
d = n % 10
s = s + d
n = n // 10
print("Sum of digits =", s)
# main program
num = int(input("Enter a number:"))
Sum_Digits(num)Enter a number:345
Sum of digits = 12
Write a user-defined function def Rev_Digits() to input a number from the user. The program reverses the digits to produce a new number inside the function. However, it displays the new number inside the function without returning any data to the main program.
Sample Input: 257
Output: 752
def Rev_Digits(n):
rev = 0
while(n != 0):
d = n % 10
rev = rev * 10 + d
n = n // 10
print("Reversed number =", rev)
# main program
num = int(input("Enter a number:"))
Rev_Digits(num)Enter a number:257
Reversed number = 752
Write a user-defined function def HCF() to input two numbers from the user. The program calculates greatest common divisor of the two numbers inside the function. Finally, it returns the value to main program to display the result.
Sample Input: First Number: 25
Second Number: 60
HCF = 5
def HCF(a, b):
if(a < b):
small = a
else:
small = b
for i in range(1, small + 1):
if(a % i == 0 and b % i == 0):
hcf = i
return(hcf)
# main program
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
result = HCF(num1, num2)
print("HCF =", result)Enter first number:25
Enter second number:60
HCF = 5
Write a user-defined function def Fact() to input 1 to 5 from the user. The program calculates the factorial of each number inside the function. Finally, it returns the values to main program to display the result.
Hint:
def Fact(n):
f = 1
for a in range(1, n+1):
f = f * a
return f
# main program
for i in range(1, 6):
print("Factorial of", i, "=", Fact(i))def Fact(n):
f = 1
for a in range(1, n + 1):
f = f * a
return f
# main program
for i in range(1, 6):
print("Factorial of", i, "=", Fact(i))Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
Define function.
Answer
A function is a program module (a part of the program) used simultaneously at different instances in a program to perform a specific task. In other words, a Python function is a block of reusable code designed to perform a specific task which allows to encapsulate code, making it more modular, readable and easier to debug.
What are the components of a function?
Answer
The various components involved in defining a function in Python are as follows:
- Function Header — It is the first line of the function which contains the keyword
def, function name and a list of parameters followed by a colon (:). It is also termed as function prototype. - Function Body — A set of statements used within a function header under same indentation. The function header along with the function body is referred to as a Function Block.
- Function Name — A specific name given to the function that should preferably relate to the operation being carried out.
- Function Signature — The function name along with the number of arguments used while invoking a function.
- Parameter List — A list of variables which receives the values passed during a function call.
- Return Statement — The statement which sends back the value (result/outcome) from a function to its caller program. It is also called Function Terminator.
- Arguments and Parameters — The values passed to the function during its call are called arguments (actual parameters) and the variables defined in the function header that receive these values are called parameters (formal parameters).
How will you define a function?
Answer
The rules to be followed for defining a function in Python are as mentioned below:
(a) The first line of the function called header must begin with the keyword def followed by the function name and parentheses ( ).
(b) Any input parameters should be defined within the parentheses.
(c) The function header must end with a colon (:). The function block (i.e., a set of statements) should be indented under function header.
(d) A docstring (resembles as a comment statement) can be used to state about the action taken in the function block. The docstring is written within triple quotes (''' or """ """). It is written just below the function header.
(e) The return statement signifies an exit of control from the function. It may or may not pass the value back to the caller function.
Syntax:
def <function name>(<parameters>):
<"function documentation (docstring)">
<function statements>
<return [expression]>
# Main Program
.....................................
Statements
.....................................What is the significance of non-returnable function?
Answer
A non-returnable function is a function that does not return any value to its caller program. It is significant in situations where the function is only intended to perform a specific task — such as displaying output, modifying data, or printing results — without needing to send any result back to the main program. In such functions, the return statement is either omitted or used without any value, and Python implicitly returns the default value None. Non-returnable functions help in organising code into reusable modules even when no value needs to be passed back.
Is it possible to return more than one statement to the main function? Justify.
Answer
Yes, it is possible to return more than one value from a function to the main program in Python. Unlike other programming languages, Python allows a function to return multiple values using a single return statement, where the values are separated by commas. These multiple values are automatically packed into a tuple and returned to the caller.
For example,
def Sum(a, b):
return a+5, b*5
# main program
result = Sum(4, 5)
print(result)Output: (9, 25)
Here, the function Sum() returns two values which are received as a tuple in the main program.
Distinguish between Actual Parameters and Formal Parameters.
Answer
| Actual Parameters | Formal Parameters |
|---|---|
| The values which are passed to the function from the main program at the time of its call are known as Actual Parameters. | The variables declared in the function header which receive the values from its caller program are known as Formal Parameters. |
| They are also known as Arguments. | They are also known as Parameters. |
| They appear in the function call statement in the main program. | They appear in the function header (function definition). |
Example: In Calculate(12, 8), the values 12 and 8 are actual parameters. | Example: In def Calculate(l, b):, the variables l and b are formal parameters. |
What is the implication of the return statement in a function?
Answer
The return statement is the statement which sends back the value (result/outcome) from a function to its caller program. It is usually the last statement of the function body and is also referred to as the Function Terminator. The implications of the return statement are as follows:
- It signifies an exit of control from the function back to the caller program.
- It may or may not pass a value back to the caller function. If used without any value, it simply terminates the function and Python implicitly returns
None. - A function can return more than one value using a single return statement (values are returned as a tuple).
- Once the control exits from a function through the return statement, it can't get back into the function block for any further execution.
Syntax: return <value>
Define the following built-in functions:
(a) abs()
(b) pow()
(c) len()
(d) type()
Answer
(a) abs() — This function is used to return an absolute value (magnitude of the number). It returns the value as an int or a float type, depending upon the given argument.
For example,
a = abs(-99)
print(a)Output: 99
(b) pow() — This function is used to find the power 'b' raised to a specified base 'a' (i.e., aᵇ). It will return the data of type int or float, depending upon the output.
For example,
a = pow(10, 3)
print(a)Output: 1000
(c) len() — This function returns the length or the number of items of an object such as a string, list, tuple or dictionary.
For example,
wd = "Artificial Intelligence"
print(len(wd))Output: 23
(d) type() — This function returns the data type of elements stored in any data type depending on the arguments passed to the function.
For example,
a = 10
print(type(a))Output: <class 'int'>