Functions

ICSE Class 9 Robotics & AI · Solutions for Class 9 KIPS ICSE Robotics & Artificial Intelligence · 43 solved questions

Exercise
1State True or False

In Python, it is necessary to provide at least one argument in a function.

Show SolutionHide Solution↓

False

Reason — A function can take any number of arguments or none. If a function does not accept any arguments, the parentheses are left empty while defining the function. Therefore, it is not necessary to provide at least one argument in a Python function.

2State True or False

Within a function, the parameters act as placeholders for the passed argument.

Show SolutionHide Solution↓

True

Reason — Within the function, the parameters act as placeholders for the arguments. The actual values are passed during the function call, and the parameters receive and represent those values inside the function body.

3State True or False

All other arguments to the right side of default argument must also have default values.

Show SolutionHide Solution↓

True

Reason — Non-default arguments should not follow default arguments. This means that once a default argument is specified in a function definition, all arguments to its right must also have default values.

4State True or False

The return statement in Python function cannot return multiple values.

Show SolutionHide Solution↓

False

Reason — In Python, a function is allowed to return more than one value using a single return statement by separating the values with commas.

5State True or False

Python allows you to combine different types of arguments in a function call.

Show SolutionHide Solution↓

True

Reason — Python provides different types of arguments such as fixed length arguments, variable length arguments (*args and **kwargs), and default arguments. Python allows the use of different types of arguments together in a function call.

6State True or False

Non-fruitful functions use the return statement to return values.

Show SolutionHide Solution↓

False

Reason — Non-fruitful functions (void functions) do not return any value. They may or may not contain a return statement, but if present, it returns no value and hence returns None. Therefore, non-fruitful functions do not use the return statement to return values.

7State True or False

Invoking a function is similar as calling a function in a program.

Show SolutionHide Solution↓

True

Reason — The process of using a function in a program after defining it is called calling a function or invoking a function. Both terms are used interchangeably and refer to the same action of executing a function.

8State True or False

'*args' keyword allows to pass a variable number of arguments and arguments are stored in a tuple.

Show SolutionHide Solution↓

True

Reason — The *args keyword is used to pass a variable number of arguments to a function. The arguments passed using *args are automatically stored in a tuple, which can be accessed inside the function.

9State True or False

'**kwargs' keyword allows to pass variable number of arguments in a function and store the provided arguments in tuple.

Show SolutionHide Solution↓

False

Reason — The **kwargs keyword is used to pass a variable number of arguments to a function, but the provided arguments are stored in a dictionary, not in a tuple.

10State True or False

In Python, functions can be defined to accept variable length of arguments.

Show SolutionHide Solution↓

True

Reason — Python allows functions to accept a variable length of arguments using *args and **kwargs.

1Select the correct option

Functions in programming:

Show SolutionHide Solution↓

All of these

Reason — Functions help in achieving modularity by breaking a large program into smaller manageable parts. They promote code reusability by allowing the same block of code to be used multiple times, and they improve program readability by organising code into logical blocks.

2Select the correct option

The structure of function header in Python is:

Show SolutionHide Solution↓

"def" keyword followed by the function name and parameters

Reason — A Python function header consists of the def keyword, followed by the function name, a list of parameters enclosed in parentheses, and ends with a colon.

3Select the correct option

A function in Python is called by:

Show SolutionHide Solution↓

using the function name followed by parenthesis and arguments

Reason — A function in Python is called or invoked by writing the function name followed by parentheses, with the required input values passed as arguments inside the parentheses.

4Select the correct option

What is the purpose of return statement in Python functions?

Show SolutionHide Solution↓

It is used to terminate the execution of a function

Reason — The return statement ends the execution of a function and transfers the control back to the place where the function was called. Once the return statement is executed, no further statements in the function body are executed.

5Select the correct option

What would be output of the following code snippet?

def multiply(x, y=2): 
    return x * y 
result = multiply(5) 
print(result)
Show SolutionHide Solution↓

10

Reason — Default arguments are used when a value is not provided during the function call. In the given function multiply(x, y=2), the parameter y has a default value of 2. When the function is called as multiply(5), the value 5 is assigned to x and the default value 2 is assigned to y. Therefore, the function returns 5 × 2 = 10, which is printed as the output.

6Select the correct option

In the following code snippet, what does 5 in the argument list represent?

def add(x, y=5):
    return x + y
Show SolutionHide Solution↓

default value

Reason — Default arguments allow a function parameter to have a predefined value. In the given function definition def add(x, y=5):, the value 5 is assigned to parameter y as its default value, which is used when no value is provided for y during the function call.

7Select the correct option

Which keyword is used to define function with variable length arguments?

Show SolutionHide Solution↓

Both a and b

Reason — Python allows functions to accept a variable number of arguments using *args and **kwargs.

8Select the correct option

Which of the following is not a built-in function in Python?

Show SolutionHide Solution↓

add()

Reason — Built-in functions are functions that are already defined in Python, such as input(), print(), and len(). The function add() is not listed as a built-in function.

9Select the correct option

What would be the return type of the following function in Python?

def mul(x, y): 
    return x * y 
result= multiply(5, 2) 
print(result)
Show SolutionHide Solution↓

int

Reason — The return type of a function depends on the type of value returned by the return statement. In the given function, the statement return x * y returns the product of two integer values. Since the multiplication of integers results in an integer value, the return type of the function is int.

10Select the correct option

What would be the return type of the following function in Python?

def is_positive(number): 
    if number > 0: 
        return True 
    else: 
        return False
Show SolutionHide Solution↓

bool

Reason — The return type of a function depends on the value returned by the return statement. In the given function, the return statements return either True or False, which are Boolean values. Therefore, the return type of the function is bool.

11Select the correct option

Which of the following keywords is used to create a user-defined function?

Show SolutionHide Solution↓

def

Reason — The def keyword is used to define or create a user-defined function in Python.

12Select the correct option

The structure of a Python function contains a function header and ............... .

Show SolutionHide Solution↓

Function Body

Reason — The structure of a Python function consists of two parts: the function header and the function body. The function body contains the statements that define what the function does.

13Select the correct option

Which of the following is not a part of function header?

Show SolutionHide Solution↓

Keyword return

Reason — A function header includes the def keyword, the function name, and the list of parameters enclosed in parentheses, followed by a colon. The return keyword is used inside the function body, not in the function header.

14Select the correct option

The multiple values returned by the return statement are packed into the ............... data type.

Show SolutionHide Solution↓

Tuple

Reason — When a function returns multiple values using a single return statement, those values are automatically grouped together into a tuple. Therefore, the multiple values returned by a function are packed into the tuple data type.

15Select the correct option

Which of the following statements is true for functions in Python?

Show SolutionHide Solution↓

Function is a reusable code segment of program.

Reason — Functions allow reusability of code by enabling a block of code to be defined once and used multiple times in a program.

1Fill blanks

Fill in the blanks:

  1. Function can accept inputs called ................ .
  2. The ................ arguments allow to specify a default value for a function parameter.
  3. The ................ statement is used to return a value from a function.
  4. A function can have ................ parameters, which have default values assigned to them.
  5. In a ................, a large program is broken down into individual blocks of code that work together to complete a task.
  6. ................ functions refer to those functions that are already defined in Python and user can use them directly without referring to any module or library.
  7. The ................ keyword is used to define a user-defined function.
  8. The two parts of a function are ................ and ................ .
  9. ................ are the names given to variables that are given in the parentheses in the function definition.
  10. Multiple values are returned by a function in the form of the ................ data type.
  11. The function is called ................ if it does not return any value or has an empty return statement.
  12. The functions that return some value using the return statement after execution are called ................ functions.
Show SolutionHide Solution↓
  1. Function can accept inputs called arguments or parameters.
  2. The default arguments allow to specify a default value for a function parameter.
  3. The return statement is used to return a value from a function.
  4. A function can have default parameters, which have default values assigned to them.
  5. In a function, a large program is broken down into individual blocks of code that work together to complete a task.
  6. Built-in functions refer to those functions that are already defined in Python and user can use them directly without referring to any module or library.
  7. The def keyword is used to define a user-defined function.
  8. The two parts of a function are function header and function body.
  9. parameters are the names given to variables that are given in the parentheses in the function definition.
  10. Multiple values are returned by a function in the form of the tuple data type.
  11. The function is called void or non-fruitful function if it does not return any value or has an empty return statement.
  12. The functions that return some value using the return statement after execution are called Non-void or fruitful functions.
1Short answer type questions

Write a Python program to calculate the area of a square and a rectangle by defining a function.

Show SolutionHide Solution↓
def area(length, breadth=-1):
    if breadth == -1:
        return length * length
    else:
        return length * breadth

s = int(input("Enter side of square: "))
result_square = area(s)
print("Area of square:", result_square)

l = int(input("Enter length of rectangle: "))
b = int(input("Enter breadth of rectangle: "))
result_rectangle = area(l, b)
print("Area of rectangle:", result_rectangle)
Enter side of square: 4
Area of square: 16
Enter length of rectangle: 5
Enter breadth of rectangle: 6
Area of rectangle: 30
2Short answer type questions

Write a Python program to print the table of a given number by using a function.

Show SolutionHide Solution↓
def print_table(n):
    for i in range(1, 11):
        print(n, "x", i, "=", n * i)

num = int(input("Enter a number: "))
print_table(num)
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
3Short answer type questions

Write a Python program to demonstrate the concept of default arguments in a function.

Show SolutionHide Solution↓
def add_numbers(a, b=5):
    print(a + b)

add_numbers(3)
add_numbers(9, 4)
8
13
4Short answer type questions

Is the return statement mandatory for every function?

Show SolutionHide Solution↓

No, the return statement is not mandatory for every function. If a function does not contain a return statement, it does not return any value and is called a void (or non-fruitful) function. In such cases, the function returns None automatically.

5Short answer type questions

Write a function that returns the greater of two numbers passed as arguments.

Show SolutionHide Solution↓
def greater(a, b):
    if a > b:
        return a
    else:
        return b

x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

result = greater(x, y)
print("Greater number is:", result)
Enter first number: 80
Enter second number: 82
Greater number is: 82
6Short answer type questions

Write a function called ice_water that takes a number as input. Perform the following operations:

  • If the number is divisible by 3, then it should return "ice".
  • If it is divisible by 5, then it should return "water".
  • If it is divisible by both 3 and 5, then it should return "icewater".
  • Otherwise, it should return the same number.
Show SolutionHide Solution↓
def ice_water(n):
    if n % 3 == 0 and n % 5 == 0:
        return "icewater"
    elif n % 3 == 0:
        return "ice"
    elif n % 5 == 0:
        return "water"
    else:
        return n

num = int(input("Enter a number: "))
result = ice_water(num)
print(result)
Enter a number: 15
icewater

Enter a number: 9
ice

Enter a number: 20
water
7Short answer type questions

Write a function for checking the speed of drivers. This function should have one parameter: speed.

  • If speed is less than 70, it should print "OK".
  • Otherwise, for every 5 km above the speed limit (70), it should give the driver one demerit point. Calculate and print the total number of demerit points at the end. For example, if the speed is 80, it should print: "Demerit Points: 2".
  • If the driver gets more than 12 demerit points, the function should print: "License suspended".
Show SolutionHide Solution↓
def check_speed(speed):
    if speed < 70:
        print("OK")
    else:
        points = (speed - 70) // 5
        print("Demerit Points:", points)
        if points > 12:
            print("License suspended")

speed = int(input("Enter speed: "))
check_speed(speed)
Enter speed: 85
Demerit Points: 3

Enter speed: 60
OK

Enter speed: 140
Demerit Points: 14
License suspended
8Short answer type questions

Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if the limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.

Show SolutionHide Solution↓
def sum_multiples(limit):
    s = 0
    for i in range(0, limit + 1):
        if i % 3 == 0 or i % 5 == 0:
            s = s + i
    return s

limit = int(input("Enter limit: "))
result = sum_multiples(limit)
print(result)
Enter limit: 20
98
1Long answer type questions

What are the various parameter passing techniques?

Show SolutionHide Solution↓

Python supports the following parameter passing techniques:

  1. Fixed Length Arguments: These are the arguments defined in the function header. While calling the function, the values must be passed in the same order and number as specified in the function definition.
  2. Variable Length Arguments: Python allows a function to accept a variable number of arguments. There are two types:
    • *args: Stores the passed arguments in a tuple.
    • **kwargs: Stores the passed arguments in a dictionary.
  3. Default Arguments: These arguments have a default value assigned in the function definition. If no value is provided during the function call, the default value is used. Default arguments must appear after non-default arguments.
2Long answer type questions

Describe user-defined functions in Python with the help of an example.

Show SolutionHide Solution↓

A user-defined function is a function that is defined by the user to perform a specific task. It enables the user to write their own code and reuse it whenever required. User-defined functions help in reducing repetition of code and make programs easier to understand and maintain.

In Python, a user-defined function is created using the def keyword, followed by the function name, parameters enclosed in parentheses, and a colon. The statements that define the task of the function form the function body.

Example:

def add(a, b):
    return a + b
result = add(5, 6)
print(result)

In the above example, the function add() is a user-defined function that takes two parameters and returns their sum using the return statement. This function can be called any number of times with different arguments.

3Long answer type questions

Distinguish between void functions and non-void functions with the help of an example.

Show SolutionHide Solution↓

Void functions are those functions that do not return any value. They may or may not contain a return statement, but even if the return statement is present, it returns no value. When such a function is called, it automatically returns None. Void functions are also called non-fruitful functions.

Example of a void function:

def msg():
    print("Welcome")
msg()

In this example, the function msg() only prints a message and does not return any value. Hence, it is a void (non-fruitful) function.

A non-void function is a function that returns a value using the return statement after execution. The value returned is passed back to the calling statement. Non-void functions are also known as fruitful functions.

Example of a non-void function:

def add(a, b):
    return a + b
result = add(4, 6)
print(result)

In this example, the function add() returns the sum of two numbers using the return statement. Hence, it is a non-void (fruitful) function.

4Long answer type questions

Discuss the structure of a Python function with the help of an example.

Show SolutionHide Solution↓

The structure of a Python function consists of two main parts: Function Header and Function Body.

The function header includes the def keyword, followed by the function name, a list of parameters enclosed within parentheses, and ends with a colon. It defines the name of the function and the parameters that the function can accept.

The function body consists of an indented block of statements that specify what the function does. It may include one or more statements and can optionally contain a return statement to return a value to the calling statement.

Example:

def square(n):
    return n * n
result = square(6)
print(result)

In this example, def square(n): is the function header, where square is the function name and n is the parameter. The indented statement return n * n forms the function body, which calculates and returns the square of the given number when the function is called.

1Higher Order Thinking Skills (HOTS)

Write a function which returns if a number passed as as argument is a perfect number or an Armstrong number.

Show SolutionHide Solution↓
def check_number(n):
    s = 0
    temp = n
    digits = len(str(n))

    while temp > 0:
        d = temp % 10
        s = s + d ** digits
        temp = temp // 10

    p = 0
    for i in range(1, n):
        if n % i == 0:
            p = p + i

    if p == n:
        return "Perfect Number"
    elif s == n:
        return "Armstrong Number"
    else:
        return "Neither Perfect nor Armstrong"

num = int(input("Enter a number: "))
result = check_number(num)
print(result)
Enter a number: 9474
Armstrong Number

Enter a number: 28
Perfect Number
2Higher Order Thinking Skills (HOTS)

Write a function which returns if a number passed as an argument is a prime or composite number.

Show SolutionHide Solution↓
def prime_composite(n):
    if n <= 1:
        return "Neither Prime nor Composite"

    count = 0
    for i in range(1, n + 1):
        if n % i == 0:
            count = count + 1

    if count == 2:
        return "Prime Number"
    else:
        return "Composite Number"

num = int(input("Enter a number: "))
result = prime_composite(num)
print(result)
Enter a number: 7
Prime Number

Enter a number: 12
Composite Number
3Higher Order Thinking Skills (HOTS)

Write a function which counts and displays the number of vowels, consonants, uppercase, and lowercase characters in a string entered as input.

Show SolutionHide Solution↓
def count_characters(s):
    vowels = 0
    consonants = 0
    uppercase = 0
    lowercase = 0

    for ch in s:
        if 'A' <= ch <= 'Z':
            uppercase += 1
            if ch in 'AEIOU':
                vowels += 1
            else:
                consonants += 1
        elif 'a' <= ch <= 'z':
            lowercase += 1
            if ch in 'aeiou':
                vowels += 1
            else:
                consonants += 1

    print("Vowels:", vowels)
    print("Consonants:", consonants)
    print("Uppercase letters:", uppercase)
    print("Lowercase letters:", lowercase)

text = input("Enter a string: ")
count_characters(text)
Enter a string: HelloWorld
Vowels: 3
Consonants: 7
Uppercase letters: 2
Lowercase letters: 8
4Higher Order Thinking Skills (HOTS)

Write a function which deletes all the negative values from a list passed as an argument.

Show SolutionHide Solution↓
def remove_negative(lst):
    new_list = []
    for x in lst:
        if x >= 0:
            new_list.append(x)
    return new_list

numbers = eval(input("Enter list: "))
result = remove_negative(numbers)
print(result)
Enter list: [2, -5, 6, -3, 0, 8]
[2, 6, 0, 8]
5Higher Order Thinking Skills (HOTS)

Write a function which takes a number and a list as arguments and counts the occurrence of that number in the given list.

Show SolutionHide Solution↓
def count_occurrence(num, lst):
    count = 0
    for x in lst:
        if x == num:
            count = count + 1
    return count

numbers = eval(input("Enter list: "))
num = int(input("Enter the number to count: "))

result = count_occurrence(num, numbers)
print("Occurrence:", result)
Enter list: [2, 4, 5, 2, 7, 2, 9]
Enter the number to count: 2
Occurrence: 3

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