Functions

ICSE Class 9 Robotics & AI · Solutions for Class 9 ICSE Exploring Robotics & Artificial Intelligence · 35 solved questions

Exercise
Marks
11 Mark · Multiple Choice Questions

Which of the following statements is the most appropriate for Python function?

Show SolutionHide Solution↓

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.

21 Mark · Multiple Choice Questions

In Python, the keyword used for defining a function is ..............

Show SolutionHide Solution↓

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.

31 Mark · Multiple Choice Questions

Which of the following are the two main parts of every function in Python?

Show SolutionHide Solution↓

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.

41 Mark · Multiple Choice Questions

Which of the following statements is not true for a function in Python?

Show SolutionHide Solution↓

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.

51 Mark · Multiple Choice Questions

What is the default return value when a function does not return any value explicitly?

Show SolutionHide Solution↓

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.

61 Mark · Multiple Choice Questions

When the arguments and parameters are with same variable names, they are known as:

Show SolutionHide Solution↓

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.

1State True or False

State whether the following statements are True or False:

Show SolutionHide Solution↓
  1. 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.
  2. True
  3. False
    Corrected Statement: Unlike other programming languages, Python can return more than one value or multiple values from a function to its caller.
  4. 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).
  5. True
  6. 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.
1Predict Output — Snippets

Predict the output of the following snippet:

m=32
n=float(m)
print(n)
Show SolutionHide Solution↓
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.

2Predict Output — Snippets

Predict the output of the following snippet:

a=42.85
b=int(a)
print(b)
Show SolutionHide Solution↓
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.

3Predict Output — Snippets

Predict the output of the following snippet:

wd="Robotics"
print(len(wd))
Show SolutionHide Solution↓
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.

4Predict Output — Snippets

Predict the output of the following snippet:

List1=["Happy", "New", "Year", 2026]
print(len(List1))
Show SolutionHide Solution↓
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.

1Predict Data Type

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))
Show SolutionHide Solution↓
<class 'float'>

The float() function converts the integer 32 into a floating-point number 32.0. Therefore, the data type of n is float.

2Predict Data Type

Predict the data type of the given Python statement:

a=42.85
b=int(a)
print(type(b))
Show SolutionHide Solution↓
<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.

3Predict Data Type

Predict the data type of the given Python statement:

m=12E4
print(type(m))
Show SolutionHide Solution↓
<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.

4Predict Data Type

Predict the data type of the given Python statement:

p='10'
print(type(int(p)))
Show SolutionHide Solution↓
<class 'int'>

The int() function converts the string '10' into an integer 10. Therefore, the data type returned by type(int(p)) is int.

5Predict Data Type

Predict the data type of the given Python statement:

n=0.0025
print(type(n))
Show SolutionHide Solution↓
<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.

1Predict Output — Code

Predict the output of the following code:

def Add(num1, num2):
    sum = num1 + num2
sum = Add(20, 30)
print(sum)
Show SolutionHide Solution↓
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.

2Predict Output — Code

Predict the output of the following code:

def Sum(a, b):
    return a+5, b*5
# main program
result = Sum(4, 5)
print(result)
Show SolutionHide Solution↓
(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.

3Predict Output — Code

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)
Show SolutionHide Solution↓
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.

1Assertion and Reason based question

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:

Show SolutionHide Solution↓

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.

1Application based question

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.

Show SolutionHide Solution↓
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 — updates a with the previous value of b so that the next sum is calculated correctly.

Trace of values:

Iterationabc = a+bOutput
10111
21122
31233
42355
53588
1Python Programs

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.

Show SolutionHide Solution↓
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
2Python Programs

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.

Show SolutionHide Solution↓
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
3Python Programs

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

Show SolutionHide Solution↓
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
4Python Programs

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

Show SolutionHide Solution↓
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
5Python Programs

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

Show SolutionHide Solution↓
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
6Python Programs

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))
Show SolutionHide Solution↓
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
1Answer the following questions

Define function.

Show SolutionHide Solution↓

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.

2Answer the following questions

What are the components of a function?

Show SolutionHide Solution↓

The various components involved in defining a function in Python are as follows:

  1. 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.
  2. 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.
  3. Function Name — A specific name given to the function that should preferably relate to the operation being carried out.
  4. Function Signature — The function name along with the number of arguments used while invoking a function.
  5. Parameter List — A list of variables which receives the values passed during a function call.
  6. Return Statement — The statement which sends back the value (result/outcome) from a function to its caller program. It is also called Function Terminator.
  7. 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).
3Answer the following questions

How will you define a function?

Show SolutionHide Solution↓

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
.....................................
4Answer the following questions

What is the significance of non-returnable function?

Show SolutionHide Solution↓

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.

5Answer the following questions

Is it possible to return more than one statement to the main function? Justify.

Show SolutionHide Solution↓

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.

6Answer the following questions

Distinguish between Actual Parameters and Formal Parameters.

Show SolutionHide Solution↓
Actual ParametersFormal 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.
7Answer the following questions

What is the implication of the return statement in a function?

Show SolutionHide Solution↓

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:

  1. It signifies an exit of control from the function back to the caller program.
  2. 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.
  3. A function can return more than one value using a single return statement (values are returned as a tuple).
  4. 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>

8Answer the following questions

Define the following built-in functions:

(a) abs()

(b) pow()

(c) len()

(d) type()

Show SolutionHide Solution↓

(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'>

Press ↓ to reveal a solution and move to the next question. Back to Solutions for Class 9 ICSE Exploring Robotics & Artificial Intelligence.