Courses
Courses for Kids
Free study material
Offline Centres
More
Store Icon
Store

NCERT Solutions For Class 11 Computer Science Chapter 7 Functions - 2025-26

ffImage
banner

How to Write Perfect Stepwise Answers for Functions Chapter 7?

Struggling to master functions? Our NCERT Solutions for Class 11 Computer Science Chapter 7 Functions help you tackle every question, step by step, as per the CBSE 2025–26 exam pattern. Get clear, student-friendly answers you can rely on!


Each solution matches exercise-wise questions so you never miss a mark. Discover stepwise answers, exam-ready definitions, and free PDF downloads designed to boost your confidence before tests and improve understanding of functions concepts.


With our Computer Science Chapter 7 Functions solutions, you’ll find back exercise help, CBSE marking scheme tips, and quick revision essentials—so you’re always ready to score high!


How to Write Perfect Stepwise Answers for Functions Chapter 7?

Exercise

Question 1: Observe the following programs carefully, and identify the error:

a) def create (text, freq):
for i in range (1, freq):
print text
create(5) #function call

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

c) mynum = 9
def add9():
mynum = mynum + 9
print mynum
add9() #function call

d) def findValue( vall = 1.1, val2, val3):
final = (val2 + val3)/ vall
print(final)
findvalue() #function call

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

Answer:

  • (a) Indentation + call signature error: the loop body must be indented; also create(5) is missing the text argument. Python 3 needs print().

    def create(text, freq):
        for i in range(1, freq):
            print(text)

    create("Hello", 5)

  • (b) Missing import for cos + Python 3 print: you imported sqrt, ceil but used cos. Import it or use math.cos.

    from math import sqrt, ceil, cos

    def calc():
        print(cos(0))

    calc()

  • (c) UnboundLocalError: assignment to mynum inside the function makes it local; either declare global or use a parameter/return value.

    # Option 1 (use return):
    def add9(n):
        n = n + 9
        print(n)
        return n
    mynum = 9
    mynum = add9(mynum)

  • (d) Default parameter order + case-sensitive call: parameters with defaults must come after non-defaults; function is called as findvalue() (wrong case).

    def findValue(val2, val3, vall=1.1):
        final = (val2 + val3) / vall
        print(final)

    findValue(10, 22)


  • (e) Cannot assign to a function call: you should assign the return value to a variable.

    def greet():
        return "Good morning"

    message = greet()
    print(message)


Question 2: How is math.ceil(89.7) different from math.floor (89.7)?

Answer: math.ceil(89.7) returns the smallest integer 89.7 → 90. math.floor(89.7) returns the largest integer 89.7 → 89.


Question 3: Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.

Answer: Use randint(1, 5) because it returns an integer in the inclusive range [1, 5]. random() returns a float in [0.0, 1.0). While you could scale/shift it, randint (or randrange(1,6)) is precise and simpler.


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

Answer: pow() is a built-in that supports the optional modulus (pow(a, b, m)) and preserves integers for exact integer powers; it also works with complex numbers. math.pow() converts arguments to floats and returns a float, no modulus.

pow(2, 3, 5)      # 3  (works)
# math.pow(2, 3, 5) -> TypeError (no 3-arg version)

pow(9, 2)         # 81 (int)
math.pow(9, 2)    # 81.0 (float)


Question 5: Using an example show how a function in Python can return multiple values.

def stats(a, b, c):
    s = a + b + c
    avg = s / 3
    mn = min(a, b, c)
    mx = max(a, b, c)
    return s, avg, mn, mx

total, mean, lo, hi = stats(5, 8, 2)


Question 6: Differentiate between following with the help of an example:

               a) Argument and Parameter

                b) Global and Local variable

Answer:

  1. Argument vs Parameter: Parameters are placeholders in the function definition; arguments are actual values passed in the call.

    def greet(name):   # 'name' is a parameter
        print("Hi", name)

    greet("Asha")      # "Asha" is an argument

  2. Global vs Local: A global variable is defined at module level; a local exists within a function scope.

    count = 0  # global

    def inc():
        global count
        count += 1   # modifies global
        x = 10       # local to inc()

    inc()
    # print(x) -> NameError: x is local inside inc()


Question 7: Does a function always return a value? Explain with an example.

Answer: If a function has no return (or returns without a value), it implicitly returns None.

def demo():
    print("Hello")   # no explicit return

res = demo()         # prints "Hello"
print(res)           # None

Activity-based Questions

Note: Writing a program implies:

• Adding comments as part of documentation

• Writing function definition

• Executing the function through a function call


Question 1: To secure your account, whether it be an email, online bank account or any other account, it is important that we use authentication. Use your programming expertise to create 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”.

Answer:

def login(uid_expected="ADMIN", pwd_expected="St0rE@1"):
    """
    Prompts user up to 3 attempts. Blocks on 3 wrong tries.
    """
    attempts = 0
    while attempts < 3:
        uid = input("User ID: ").strip()
        pwd = input("Password: ").strip()
        if uid == uid_expected and pwd == pwd_expected:
            print("login successful")
            return True
        else:
            attempts += 1
            print(f"Invalid credentials. Attempts left: {3 - attempts}")
    print("account blocked")
    return False

# Example call:
# login()


Question 2: XYZ store plans to give festival discount to its customers. The store management has decided to give discount on the following criteria:

Shopping Amount Discount Offered

Shopping Amount

Discount Offered

>=500 and <1000

5%

>=1000 and <2000

8%

>=2000

10%



An additional discount of 5% is given to customers who are the members of the store. Create a program using user defined function that accepts the shopping amount as a parameter and calculates discount and net amount payable on the basis of the following conditions:

Net Payable Amount = Total Shopping Amount – Discount.

Answer:

def net_payable(amount, is_member=False):
    """
    Returns (discount, net_amount) based on slabs + member extra 5%.
    """
    if amount < 0:
        raise ValueError("Amount must be non-negative")

    if amount >= 2000:
        base = 0.10
    elif amount >= 1000:
        base = 0.08
    elif amount >= 500:
        base = 0.05
    else:
        base = 0.0

    extra = 0.05 if is_member else 0.0
    rate = base + extra
    discount = amount * rate
    net = amount - discount
    return round(discount, 2), round(net, 2)

# Example:
# d, n = net_payable(1200, True)


Question 3: ‘ Play and learn’ strategy helps toddlers understand concepts in a fun way. Being a senior student you have taken responsibility to 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. Make sure that you perform a careful analysis of the type of questions that can be included as per the age and curriculum.

Answer: (Sample interactive drills for 2/3-letter words and single-digit addition.)

import random

TWO_LETTER = ["am","an","as","at","be","do","go","he","in","it","me","no","on","up","we"]
THREE_LETTER = ["cat","dog","sun","map","pen","bag","cap","jam","pot","red","bed","cup"]

def word_drill(n=5, length=2):
    words = TWO_LETTER if length == 2 else THREE_LETTER
    score = 0
    for _ in range(n):
        w = random.choice(words)
        ans = input(f"Spell this word: {w}  (type it) ")
        if ans.strip().lower() == w:
            print("Great!")
            score += 1
        else:
            print(f"Try again. Correct: {w}")
    print(f"Word drill score: {score}/{n}")

def add_drill(n=5):
    score = 0
    for _ in range(n):
        a, b = random.randint(0,9), random.randint(0,9)
        ans = input(f"{a} + {b} = ")
        if ans.strip().isdigit() and int(ans) == a+b:
            print("Nice!")
            score += 1
        else:
            print(f"Oops. It's {a+b}.")
    print(f"Addition score: {score}/{n}")

# Example:
# word_drill(5, length=2); word_drill(5, length=3); add_drill(5)


Question 4: Take a look at the series below:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55...

To form the pattern, start by writing 1 and 1. Add them together to get 2. Add the last two numbers: 1+2 = 3.Continue adding the previous two numbers to find the next number in the series. These numbers make up the famed Fibonacci sequence: previous two numbers are added to get the immediate new number.

Answer:

def fibonacci(n):
    """Return list of first n Fibonacci numbers starting 1, 1, 2, ..."""
    if n <= 0: return []
    if n == 1: return [1]
    seq = [1, 1]
    while len(seq) < n:
        seq.append(seq[-1] + seq[-2])
    return seq

# Example: print(fibonacci(10)) -> [1,1,2,3,5,8,13,21,34,55]


Question 5: Create a menu driven program using user defined functions to implement a calculator that performs the following:

a) Basic arithmetic operations(+,-,*,/)

b) log10(x),sin(x),cos(x)

Answer:

import math

def add(a,b): return a+b
def sub(a,b): return a-b
def mul(a,b): return a*b
def div(a,b): return a/b

def sci_log10(x): return math.log10(x)
def sci_sin(x): return math.sin(x)
def sci_cos(x): return math.cos(x)

def calculator():
    menu = """
1) Add
2) Subtract
3) Multiply
4) Divide
5) log10(x)
6) sin(x)
7) cos(x)
0) Exit
Choose: """
    while True:
        ch = input(menu).strip()
        if ch == "0": break
        try:
            if ch in {"1","2","3","4"}:
                a = float(input("a = "))
                b = float(input("b = "))
                res = {"1":add,"2":sub,"3":mul,"4":div}[ch](a,b)
            elif ch == "5":
                x = float(input("x = "))
                res = sci_log10(x)
            elif ch == "6":
                x = float(input("x (radians) = "))
                res = sci_sin(x)
            elif ch == "7":
                x = float(input("x (radians) = "))
                res = sci_cos(x)
            else:
                print("Invalid choice"); continue
            print("Result:", res)
        except Exception as e:
            print("Error:", e)

# Example: calculator()

Suggested Lab. Exercises

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

Answer:

def is_divisible_by_7(n):
    return n % 7 == 0

# Example:
# print(is_divisible_by_7(21))  # True
# print(is_divisible_by_7(20))  # False


Question 2: Write 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.

Answer:

def prefix_name(name, gender):
    gender = gender.strip().upper()
    if gender == "M":
        return f"Mr {name}"
    elif gender == "F":
        return f"Ms {name}"
    else:
        return name  # or raise ValueError

# Example: print(prefix_name("Asha", "F")) -> Ms Asha


Question 3: Write 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-4ac. Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result.

Answer:

def discriminant(a, b, c):
    D = b*b - 4*a*c
    if D > 0:
        nature = "Two distinct real roots"
    elif D == 0:
        nature = "One real root (repeated)"
    else:
        nature = "Complex conjugate roots"
    return D, nature

# Example:
# print(discriminant(1, -3, 2)) -> (1, 'Two distinct real roots')


Question 4: ABC 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. The winner would receive a special prize. Write a program using Python that helps to automate the task.(Hint: use random module)

Answer:

import random

def pick_winner(start=1, end=600):
    return random.randint(start, end)

# Example: print("Winner token:", pick_winner())


Question 5: Write 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)nt)

Answer:

def compound_interest(P, r, t, n):
    """
    P = principal, r = annual rate in decimal (e.g., 0.08 for 8%),
    t = time in years, n = compounding per year.
    Returns (Amount, CompoundInterest)
    """
    A = P * (1 + r/n) ** (n*t)
    CI = A - P
    return round(A, 2), round(CI, 2)

# Example:
# print(compound_interest(1000, 0.08, 2, 4))


Question 6: Write 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 number1 and number 1 is reformed in place of number 2, otherwise the same order is returned.

Answer:

def swap_if_needed(a, b):
    return (b, a) if a < b else (a, b)

# Example:
# print(swap_if_needed(3, 9))  -> (9, 3)
# print(swap_if_needed(9, 3))  -> (9, 3)


Question 7: Write 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.

Answer:

# shapes.py (module)
import math

def square_area(a): return a*a
def square_perimeter(a): return 4*a

def rectangle_area(l,w): return l*w
def rectangle_perimeter(l,w): return 2*(l+w)

def triangle_area(b,h): return 0.5*b*h

def circle_area(r): return math.pi*r*r
def circle_circumference(r): return 2*math.pi*r

def cylinder_surface_area(r,h):
    return 2*math.pi*r*h + 2*math.pi*r*r

# main.py
# from shapes import *
# print(circle_area(3))


Question 8: Write 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 as follows:

Marks

Remarks

5

Outstanding

4

Excellent

3

Good

2

Read more to score more

1

Needs to take interest

0

General knowledge will always help you. Take it seriously.



Answer:

import random

QUESTIONS = [
    ("Capital of India?", "new delhi"),
    ("Planet known as Red Planet?", "mars"),
    ("Largest ocean?", "pacific"),
    ("National animal of India?", "tiger"),
    ("Language with most native speakers?", "mandarin"),
]

def score():
    qs = random.sample(QUESTIONS, k=5)
    s = 0
    for q, ans in qs:
        user = input(q + " ").strip().lower()
        if user == ans:
            print("Correct!")
            s += 1
        else:
            print("Incorrect. Answer:", ans.title())
    return s

def remark(scorevalue):
    mapping = {
        5: "Outstanding",
        4: "Excellent",
        3: "Good",
        2: "Read more to score more",
        1: "Needs to take interest",
        0: "General knowledge will always help you. Take it seriously."
    }
    return mapping.get(scorevalue, "Invalid score")

# Example:
# s = score(); print("Score:", s, "-", remark(s))

Case Study-based Question

Question 1: For the SMIS system extended in Chapter 6 let us do the following:

1. 7.1 Convert all the functionality in Chapter 5 and 6 using user defined functions.

Answer: Refactor each feature (e.g., add_student, edit_student, delete_student, record_marks, compute_grade, print_report, search_student) into separate functions that accept clear parameters and return values without using input()/print() inside the core logic. Keep I/O (menus, prompts) in a thin wrapper. Example:

# core.py
def add_student(db, roll, name, cls):
    if roll in db: return False
    db[roll] = {"name": name, "class": cls, "marks": {}}
    return True

def record_marks(db, roll, subject, marks):
    if roll not in db: return False
    db[roll]["marks"][subject] = marks
    return True

def compute_percentage(marks_dict):
    if not marks_dict: return 0.0
    total = sum(marks_dict.values())
    return total / (len(marks_dict) * 100) * 100

# ui.py would import core functions and provide menus.


Question 2: 7.2 Add another user defined function to the above 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 his or her attendance using the formula: Count of days the student was present or the total number of working days. In case the attendance calculated is less than 78%, the function should return 1 indicating short attendance otherwise the function should return 0 indicating attendance is not short. Let’s peer review the case studies of others based on the parameters given under “DOCUMENTATION TIPS” at the end of Chapter 5 and provide a feedback to them.

Answer:

def attendance_flag(days_present, working_days):
    """
    Returns 1 if attendance < 78%, else 0.
    """
    if working_days <= 0:
        raise ValueError("working_days must be positive")
    pct = (days_present / working_days) * 100
    return 1 if pct < 78 else 0

# Example:
# For 18/25 = 72% -> returns 1 (short attendance)

Mastering Functions in Python: Key Points and Exam Tips

Chapter 7 of NCERT Computer Science (2025-26) focuses on Python functions, a cornerstone of writing clean, modular code. Understanding these concepts helps students improve both code reusability and exam readiness.


Practicing with NCERT Solutions Computer Science Chapter 7 Functions will help you quickly identify the important function concepts, argument types, and the distinctions between local and global variables for improved understanding.


Regular review of exercise-based solutions ensures you are confident with Python’s standard library modules and practical programming skills—key for scoring top marks in your Computer Science exam!


CBSE Class 11 Computer Science Chapter-wise NCERT Solutions



CBSE Class 11 Computer Science Study Materials

FAQs on NCERT Solutions For Class 11 Computer Science Chapter 7 Functions - 2025-26

1. What is included in the NCERT Solutions for Class 11 Computer Science Chapter 7 Functions?

The NCERT Solutions for Class 11 Computer Science Chapter 7 Functions offer stepwise, detailed answers to all textbook exercises, following the CBSE 2025–26 marking scheme. These solutions include:

  • Solutions for intext and back exercise questions
  • Definitions and formulae relevant to functions and Python programming
  • Sample diagrams, code examples, and answer structuring tips
  • Practice questions and exam-oriented strategies

2. How can I write stepwise answers to score full marks in Computer Science Chapter 7 Functions?

To score full marks, present answers in clear, stepwise format as expected in CBSE board exams:

  • Start with correct definitions or statements
  • Break solutions into logical steps or code blocks
  • Highlight key terms such as function definition, parameters, return values
  • Draw neat diagrams or code snippets where required
  • Use points or numbering for clarity

3. Which questions from NCERT Chapter 7 Functions are likely to appear in school exams?

Important questions from Class 11 Computer Science Chapter 7 Functions often include:

  • Define different types of functions (built-in, user-defined)
  • Explain function arguments and return values with examples
  • Differences between local and global variables
  • Write Python code using functions
  • Short notes on the scope of variables, recursion, and library functions

4. Are diagrams or definitions mandatory in answers for Computer Science Chapter 7?

Including definitions and diagrams (or code snippets) can help you score better in CBSE exams:

  • Definitions for key terms are often mandatory
  • Neat diagrams or sample code are recommended for programming concepts
  • Label all diagrams clearly as per NCERT and CBSE guidelines

5. How should I structure long answers in Class 11 Computer Science Chapter 7 to get maximum marks?

For long answers in NCERT Computer Science Chapter 7 Functions, follow these steps:

  • Start with a brief introduction using the main keyword
  • Present the body in points or logical paragraphs, covering all sub-parts
  • Include examples, diagrams, or code if required
  • Summarize with a clear conclusion or takeaway point

6. Where can I download the NCERT Solutions Computer Science Chapter 7 Functions PDF for offline use?

You can download the free PDF of Class 11 Computer Science Chapter 7 Functions Solutions from educational platforms like Vedantu, which provide stepwise, CBSE-aligned content for offline study and revision.

7. What are the key definitions and formulae to remember from Chapter 7 Functions?

Key definitions and formulae to remember in NCERT Chapter 7 Functions include:

  • Function: A reusable block of code that performs a specific task
  • Parameter and Argument: Input values for functions
  • Return Statement: Used to send results back from a function
  • Formulas for passing arguments, recursion, and library usage in Python

8. How do examiners mark answers in Class 11 Computer Science Chapter 7 Functions?

Examiners mark answers stepwise in CBSE exams. You can get full or partial marks by:

  • Following the latest CBSE marking scheme
  • Including definitions, diagrams, and key steps
  • Writing answers in clear, exam-ready language

9. Do examiners award partial marks for correct steps even if the final answer is wrong?

Yes, in CBSE exams, partial marks are given for correct intermediate steps even if the final answer is incorrect, especially in stepwise Computer Science solutions. Clearly showing your process helps maximize your score.

10. Is referencing textbook page numbers useful when revising NCERT Computer Science Chapter 7 Functions?

Referencing NCERT textbook page numbers can help during revision by:

  • Locating key concepts and sample code quickly
  • Improving accuracy in answers
  • Ensuring full coverage according to the syllabus