Skip to main content
Chapter 7 of 11
NCERT Solutions

Functions — NCERT Solutions

CBSE · Class 11 · Computer Science

NCERT Solutions for Functions, CBSE Class 11 Computer Science: 27 textbook questions solved step by step. Covers Exercise, Activity-based Questions.

42 questions80 flashcards6 formulas & key relations5 concepts

Interactive on Super Tutor

Studying Functions? Get the full interactive chapter.

Quizzes, flashcards, AI doubt-solver and a step-by-step study plan — built for NCERT solutions and more.

Free trial, no card needed.

27 Questions Solved · 4 Sections

The first 14 solutions are open to read. The other 13 are free with a Super Tutor account.

Exercise

1aObserve the following program carefully, and identify the error:
def create (text, freq):
for i in range (1, freq):
print text
create(5) #function call
Show solution

Errors identified:

  1. print text — In Python 3, print is a function and must be called with parentheses. It should be print(text).
  1. create(5) — The function create is defined with two parameters (text and freq), but the function call passes only one argument. It should be something like create("Hello", 5).
  1. range(1, freq) — This will print text only freq - 1 times (from 1 to freq-1). If the intent is to print freq times, it should be range(1, freq+1) or range(freq).

Corrected Code:

def create(text, freq):
    for i in range(1, freq + 1):
        print(text)
create("Hello", 5)  # function call
1bObserve the following program carefully, and identify the error:
from math import sqrt,ceil
def calc():
print cos(0)
calc() #function call
Show solution

Error identified:

cos function is used inside calc(), but it has not been imported from the math module. Only sqrt and ceil were imported.

To use cos(0), it must be imported explicitly.

Corrected Code:

from math import sqrt, ceil, cos
def calc():
    print(cos(0))
calc()  # function call

Note: print cos(0) is also a Python 2 style statement. In Python 3, it must be print(cos(0)).

1cObserve the following program carefully, and identify the error:
mynum = 9
def add9():
mynum = mynum + 9
print mynum
add9() #function call
Show solution

Errors identified:

  1. UnboundLocalError — Inside add9(), mynum is being assigned a value (mynum = mynum + 9). Python treats it as a local variable. However, it is used on the right-hand side before being assigned locally, causing an UnboundLocalError. To modify the global variable mynum inside the function, the global keyword must be used.
  1. print mynum — In Python 3, print requires parentheses: print(mynum).

Corrected Code:

mynum = 9
def add9():
    global mynum
    mynum = mynum + 9
    print(mynum)
add9()  # function call
1dObserve the following program carefully, and identify the error:
def findValue( vall = 1.1, val2, val3):
final = (val2 + val3) / vall
print(final)
findvalue() #function call
Show solution

Errors identified:

  1. SyntaxError: non-default argument follows default argument — In Python, default parameters must come after non-default parameters. Here val1 = 1.1 (default) is placed before val2 and val3 (non-default), which is not allowed.
  1. findvalue() — Python is case-sensitive. The function is defined as findValue (capital V) but called as findvalue (lowercase v). This will cause a NameError.
  1. findvalue() — Even after fixing the name, the call provides no arguments for the required parameters val2 and val3.

Corrected Code:

def findValue(val2, val3, val1=1.1):
    final = (val2 + val3) / val1
    print(final)
findValue(2.2, 3.3)  # function call
1eObserve the following program carefully, and identify the error:
def greet():
return("Good morning")
greet() = message #function call
Show solution

Error identified:

SyntaxError — greet() = message is invalid syntax. A function call cannot appear on the left-hand side of an assignment statement. To store the returned value in a variable, the variable must be on the left and the function call on the right.

Corrected Code:

def greet():
    return("Good morning")
message = greet()  # function call
print(message)

Output:

Good morning
2How is math.ceil(89.7) different from math.floor(89.7)?Show solution

Concept:

Both math.ceil() and math.floor() are functions from the math module used for rounding numbers, but they round in opposite directions.

FunctionDescriptionResult for 89.7
math.ceil(x)Returns the smallest integer greater than or equal to x (rounds up)90
math.floor(x)Returns the largest integer less than or equal to x (rounds down)89

Example:

import math
print(math.ceil(89.7))   # Output: 90
print(math.floor(89.7))  # Output: 89

Conclusion:

  • math.ceil(89.7) returns 90 (rounds up to the nearest integer).
  • math.floor(89.7) returns 89 (rounds down to the nearest integer).
3Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.Show solution

Answer: We should use randint() to generate random numbers between 1 and 5.

Justification:

  • random() — This function returns a random floating-point number in the range [0.0,1.0)[0.0, 1.0). It does not accept any range parameters, so it cannot directly generate integers between 1 and 5.
  • randint(a, b) — This function returns a random integer NN such that a≤N≤ba \leq N \leq b. Both endpoints are inclusive. Therefore, randint(1, 5) will return one of the integers: 1, 2, 3, 4, or 5.

Example:

import random
print(random.randint(1, 5))  # Output: any integer from 1 to 5
print(random.random())       # Output: float like 0.573... (not suitable)

Conclusion: randint(1, 5) is the appropriate choice as it directly generates a random integer in the closed interval [1,5][1, 5].

4How is built-in function pow() function different from function math.pow()? Explain with an example.Show solution

Differences between pow() and math.pow():

FeatureBuilt-in pow()math.pow()
ModuleNo import needed (built-in)Requires import math
Return typeReturns int if both arguments are integersAlways returns a float
Third argumentAccepts an optional third argument for modulus: pow(x, y, z) computes (xy)mod  z(x^y) \mod zDoes not accept a third argument
Negative exponentsWorks with integer typesWorks with floats

Example:

import math

# Built-in pow()
print(pow(2, 3))       # Output: 8  (integer)
print(pow(2, 3, 3))    # Output: 2  (8 mod 3 = 2)

# math.pow()
print(math.pow(2, 3))  # Output: 8.0 (always float)
# math.pow(2, 3, 3)    # TypeError: takes no third argument

Conclusion: The key differences are that built-in pow() returns an integer when given integer inputs and supports a third modulus argument, whereas math.pow() always returns a float and does not support the modulus argument.

5Using an example show how a function in Python can return multiple values.Show solution

Concept:

In Python, a function can return multiple values using a tuple. The values are separated by commas in the return statement, and Python automatically packs them into a tuple.

Example:

def calculate(a, b):
    """Function to return sum, difference, product and quotient"""
    add  = a + b
    sub  = a - b
    mul  = a * b
    div  = a / b
    return add, sub, mul, div   # returns a tuple

# Function call
result = calculate(10, 2)
print("Returned tuple:", result)

# Unpacking the returned values
s, d, m, q = calculate(10, 2)
print("Sum      =", s)
print("Difference =", d)
print("Product  =", m)
print("Quotient =", q)

Output:

Returned tuple: (12, 8, 20, 5.0)
Sum       = 12
Difference = 8
Product   = 20
Quotient  = 5.0

Explanation: The return add, sub, mul, div statement packs all four values into a tuple (12, 8, 20, 5.0) and returns it. The caller can either receive the whole tuple or unpack it into individual variables.

6aDifferentiate between Argument and Parameter with the help of an example.Show solution

Argument vs Parameter:

BasisParameterArgument
DefinitionA variable listed in the function definition/header that receives a valueThe actual value passed to the function during a function call
Where usedIn the function definitionIn the function call
Also calledFormal parameterActual parameter

Example:

def greet(name, age):   # 'name' and 'age' are PARAMETERS
    print("Hello", name)
    print("Your age is", age)

greet("Riya", 16)       # "Riya" and 16 are ARGUMENTS

Explanation:

  • name and age in the function header def greet(name, age): are parameters — they are placeholders that receive values.
  • "Riya" and 16 in the function call greet("Riya", 16) are arguments — they are the actual values supplied to the function.

Output:

Hello Riya
Your age is 16
6bDifferentiate between Global and Local variable with the help of an example.Show solution

Global vs Local Variable:

BasisGlobal VariableLocal Variable
DefinitionDefined outside any function or blockDefined inside a function or block
ScopeAccessible anywhere in the programAccessible only within the function/block where defined
LifetimeExists for the entire duration of the programExists only while the function is executing
KeywordUse global keyword to modify inside a functionNo special keyword needed

Example:

counter = 10          # Global variable

def display():
    message = "Hello" # Local variable
    print(message)    # Accessible here
    print(counter)    # Global variable accessible here too

display()
print(counter)        # Accessible outside function
# print(message)      # ERROR: message is not accessible here

Output:

Hello
10
10

Explanation:

  • counter is a global variable — it is accessible both inside and outside display().
  • message is a local variable — it is created when display() is called and destroyed when the function ends. Accessing it outside the function causes a NameError.
7Does a function always return a value? Explain with an example.Show solution

Answer: No, a function does not always return a value.

Explanation:

  • A function that has a return statement with a value returns that value to the caller.
  • A function that has no return statement, or has a return statement without any value, implicitly returns None.
  • Such functions are sometimes called void functions — they perform an action (like printing) but do not send back a meaningful value.

Example 1 — Function that returns a value:

def square(n):
    return n * n        # returns a value

result = square(5)
print(result)           # Output: 25

Example 2 — Function that does NOT return a value:

def display(n):
    print("Number is:", n)   # no return statement

result = display(5)
print(result)                # Output: None

Output:

Number is: 5
None

Conclusion: A function always returns something — if no explicit return is given, Python returns None by default. So while every function technically returns a value, it is not always a meaningful/user-defined value.

Activity-based Questions

1Create a program using user defined function named login that accepts userid and password as parameters (login(uid,pwd)) that displays a message 'account blocked' in case of three wrong attempts. The login is successful if the user enters user ID as 'ADMIN' and password as 'St0rE@1'. On successful login, display a message 'login successful'.Show solution
# Program to simulate login authentication with 3 attempts

def login(uid, pwd):
    """
    Function to validate user credentials.
    Parameters: uid - user ID, pwd - password
    Returns: True if login successful, False otherwise
    """
    if uid == "ADMIN" and pwd == "St0rE@1":
        print("Login successful")
        return True
    else:
        print("Invalid credentials. Please try again.")
        return False

# Main program
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    user_id  = input("Enter User ID: ")
    password = input("Enter Password: ")
    attempts += 1

    if login(user_id, password):
        break
    else:
        remaining = max_attempts - attempts
        if remaining > 0:
            print(f"You have {remaining} attempt(s) remaining.")
        else:
            print("Account blocked")

Sample Output (wrong attempts):

Enter User ID: admin
Enter Password: abc
Invalid credentials. Please try again.
You have 2 attempt(s) remaining.
Enter User ID: ADMIN
Enter Password: wrong
Invalid credentials. Please try again.
You have 1 attempt(s) remaining.
Enter User ID: ADMIN
Enter Password: hello
Invalid credentials. Please try again.
Account blocked

Sample Output (successful login):

Enter User ID: ADMIN
Enter Password: St0rE@1
Login successful
2XYZ store plans to give festival discount to its customers based on shopping amount (>=500 and <1000: 5%, >=1000 and <2000: 8%, >=2000: 10%). An additional discount of 5% is given to members. Create a program using user defined function that accepts the shopping amount as a parameter and calculates discount and net amount payable.Show solution
# Program to calculate discount and net payable amount for XYZ store

def calculate_discount(amount):
    """
    Function to calculate discount and net payable amount.
    Parameter: amount - total shopping amount
    """
    discount_percent = 0

    # Determine discount percentage based on shopping amount
    if amount >= 2000:
        discount_percent = 10
    elif amount >= 1000 and amount < 2000:
        discount_percent = 8
    elif amount >= 500 and amount < 1000:
        discount_percent = 5
    else:
        discount_percent = 0

    # Check for store membership
    member = input("Are you a store member? (yes/no): ").strip().lower()
    if member == "yes":
        discount_percent += 5   # Additional 5% for members

    # Calculate discount amount and net payable
    discount_amount = (discount_percent / 100) * amount
    net_payable     = amount - discount_amount

    print(f"\nShopping Amount   : Rs. {amount:.2f}")
    print(f"Discount Percent  : {discount_percent}%")
    print(f"Discount Amount   : Rs. {discount_amount:.2f}")
    print(f"Net Payable Amount: Rs. {net_payable:.2f}")

# Main program
total_amount = float(input("Enter total shopping amount: Rs. "))
calculate_discount(total_amount)

Sample Output:

Enter total shopping amount: Rs. 1500
Are you a store member? (yes/no): yes

Shopping Amount   : Rs. 1500.00
Discount Percent  : 13%
Discount Amount   : Rs. 195.00
Net Payable Amount: Rs. 1305.00
3'Play and learn' strategy — develop a program using user defined functions to help children master two and three-letter words using English alphabets and addition of single digit numbers.

Free with a Super Tutor account

4Create a program using user defined functions to generate and display the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55... where each number is the sum of the previous two numbers.

Free with a Super Tutor account

5Create a menu driven program using user defined functions to implement a calculator that performs: a) Basic arithmetic operations (+, -, *, /) b) log10(x), sin(x), cos(x)

Free with a Super Tutor account

Suggested Lab Exercises

1Write a program to check the divisibility of a number by 7 that is passed as a parameter to the user defined function.

Free with a Super Tutor account

2Write a program that uses a user defined function that accepts name and gender (as M for Male, F for Female) and prefixes Mr/Ms on the basis of the gender.

Free with a Super Tutor account

3Write a program that has a user defined function to accept the coefficients of a quadratic equation in variables and calculates its determinant. For example: if the coefficients are stored in the variables a, b, c then calculate determinant as b2−4acb^2 - 4ac. Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result.

Free with a Super Tutor account

4ABC School has allotted unique token IDs from (1 to 600) to all the parents for facilitating a lucky draw on the day of their Annual day function. Write a program using Python that helps to automate the task. (Hint: use random module)

Free with a Super Tutor account

5Write a program that implements a user defined function that accepts Principal Amount, Rate, Time, Number of Times the interest is compounded to calculate and displays compound interest. (Hint: CI=P∗(1+r/n)ntCI = P*(1 + r/n)^{nt})

Free with a Super Tutor account

6Write a program that has a user defined function to accept 2 numbers as parameters, if number 1 is less than number 2 then numbers are swapped and returned, i.e., number 2 is returned in place of number 1 and number 1 is returned in place of number 2, otherwise the same order is returned.

Free with a Super Tutor account

7Write a program that contains user defined functions to calculate area, perimeter or surface area whichever is applicable for various shapes like square, rectangle, triangle, circle and cylinder. The user defined functions should accept the values for calculation as parameters and the calculated value should be returned. Import the module and use the appropriate functions.

Free with a Super Tutor account

8Write a program that creates a GK quiz consisting of any five questions of your choice. The questions should be displayed randomly. Create a user defined function score() to calculate the score of the quiz and another user defined function remark(scorevalue) that accepts the final score to display remarks.

Free with a Super Tutor account

Case Study-based Questions

7.1Convert all the functionality in Chapter 5 and 6 (SMIS system) using user defined functions.

Free with a Super Tutor account

7.2Add another user defined function to the SMIS menu to check if the student has short attendance or not. The function should accept total number of working days in a month and check if the student is a defaulter by calculating attendance using: Count of days present / total working days. If attendance is less than 78%, return 1 (short attendance), otherwise return 0.

Free with a Super Tutor account

13 more solved questions in Functions

They are free with a Super Tutor account, along with practice quizzes and flashcards for this chapter. Free to start, no card needed.

Frequently Asked Questions

What are the important topics in Functions for CBSE Class 11 Computer Science?
Key topics in Functions include Core Ideas of Functions, User Defined Functions, Arguments, and Parameters, Return Values and Multiple Values, Flow of Execution and Function Call Order. Study these first, then practise questions on each for Class 11 exams.
Are these NCERT Solutions for Functions free?
The first 14 of the 27 solutions on this page are open to read. The other 13 are free with a Super Tutor account — signing up is free and needs no card.
How should I revise Functions for Class 11 exams?
Learn the core ideas first, then work through the 42 practice questions on Functions. Revise definitions regularly and use flashcards for quick recall before the exam.

Sources & Official References

Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.

For serious students

Get the full Functions chapter — start free.

Quizzes, flashcards, an AI doubt solver and a study plan for CBSE Class 11 Computer Science. Free to start, no card needed.