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.
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.
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 callShow solution
Errors identified:
print text— In Python 3,printis a function and must be called with parentheses. It should beprint(text).
create(5)— The functioncreateis defined with two parameters (textandfreq), but the function call passes only one argument. It should be something likecreate("Hello", 5).
range(1, freq)— This will printtextonlyfreq - 1times (from 1 to freq-1). If the intent is to printfreqtimes, it should berange(1, freq+1)orrange(freq).
Corrected Code:
def create(text, freq):
for i in range(1, freq + 1):
print(text)
create("Hello", 5) # function call1bObserve the following program carefully, and identify the error:
from math import sqrt,ceil
def calc():
print cos(0)
calc() #function callShow 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 callNote: 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 callShow solution
Errors identified:
UnboundLocalError— Insideadd9(),mynumis 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 anUnboundLocalError. To modify the global variablemynuminside the function, theglobalkeyword must be used.
print mynum— In Python 3,printrequires parentheses:print(mynum).
Corrected Code:
mynum = 9
def add9():
global mynum
mynum = mynum + 9
print(mynum)
add9() # function call1dObserve the following program carefully, and identify the error:
def findValue( vall = 1.1, val2, val3):
final = (val2 + val3) / vall
print(final)
findvalue() #function callShow solution
Errors identified:
SyntaxError: non-default argument follows default argument— In Python, default parameters must come after non-default parameters. Hereval1 = 1.1(default) is placed beforeval2andval3(non-default), which is not allowed.
findvalue()— Python is case-sensitive. The function is defined asfindValue(capital V) but called asfindvalue(lowercase v). This will cause aNameError.
findvalue()— Even after fixing the name, the call provides no arguments for the required parametersval2andval3.
Corrected Code:
def findValue(val2, val3, val1=1.1):
final = (val2 + val3) / val1
print(final)
findValue(2.2, 3.3) # function call1eObserve the following program carefully, and identify the error:
def greet():
return("Good morning")
greet() = message #function callShow 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 morning2How 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.
| Function | Description | Result 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: 89Conclusion:
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 . 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 such that . 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 .
4How is built-in function pow() function different from function math.pow()? Explain with an example.Show solution
Differences between pow() and math.pow():
| Feature | Built-in pow() | math.pow() |
|---|---|---|
| Module | No import needed (built-in) | Requires import math |
| Return type | Returns int if both arguments are integers | Always returns a float |
| Third argument | Accepts an optional third argument for modulus: pow(x, y, z) computes | Does not accept a third argument |
| Negative exponents | Works with integer types | Works 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 argumentConclusion: 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.0Explanation: 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:
| Basis | Parameter | Argument |
|---|---|---|
| Definition | A variable listed in the function definition/header that receives a value | The actual value passed to the function during a function call |
| Where used | In the function definition | In the function call |
| Also called | Formal parameter | Actual 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 ARGUMENTSExplanation:
nameandagein the function headerdef greet(name, age):are parameters — they are placeholders that receive values."Riya"and16in the function callgreet("Riya", 16)are arguments — they are the actual values supplied to the function.
Output:
Hello Riya
Your age is 166bDifferentiate between Global and Local variable with the help of an example.Show solution
Global vs Local Variable:
| Basis | Global Variable | Local Variable |
|---|---|---|
| Definition | Defined outside any function or block | Defined inside a function or block |
| Scope | Accessible anywhere in the program | Accessible only within the function/block where defined |
| Lifetime | Exists for the entire duration of the program | Exists only while the function is executing |
| Keyword | Use global keyword to modify inside a function | No 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 hereOutput:
Hello
10
10Explanation:
counteris a global variable — it is accessible both inside and outsidedisplay().messageis a local variable — it is created whendisplay()is called and destroyed when the function ends. Accessing it outside the function causes aNameError.
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
returnstatement with a value returns that value to the caller. - A function that has no
returnstatement, or has areturnstatement without any value, implicitly returnsNone. - 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: 25Example 2 — Function that does NOT return a value:
def display(n):
print("Number is:", n) # no return statement
result = display(5)
print(result) # Output: NoneOutput:
Number is: 5
NoneConclusion: 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 blockedSample Output (successful login):
Enter User ID: ADMIN
Enter Password: St0rE@1
Login successful2XYZ 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.00Free with a Super Tutor account
Free with a Super Tutor account
Free with a Super Tutor account
Suggested Lab Exercises
Free with a Super Tutor account
Free with a Super Tutor account
Free with a Super Tutor account
Free with a Super Tutor account
Free with a Super Tutor account
Free with a Super Tutor account
Free with a Super Tutor account
Free with a Super Tutor account
Case Study-based Questions
Free with a Super Tutor account
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?
Are these NCERT Solutions for Functions free?
How should I revise Functions for Class 11 exams?
Sources & Official References
- NCERT Official — ncert.nic.in
- CBSE Academic — cbseacademic.nic.in
- CBSE Official — cbse.gov.in
- National Education Policy 2020 — education.gov.in
Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.
More resources for Functions
Practice Quiz
Test yourself with a quick quiz
Important Questions
Exam-style questions with answers
Revision Notes
Key points for last-minute revision
Formula Sheet
The chapter's formulas in one place
Chapter Summary
Understand the chapter at a glance
Concept Maps
See how topics connect
Study Plan
Step-by-step plan for this chapter
Flashcards
Quick-fire cards for active recall
Syllabus
What topics to cover
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.