NCERT Solutions — CBSE Class 11 Computer Science: Functions
Complete solved exercises for NCERT Chapter 7 — Functions. Each question includes a clear explanation and working Python code that you can run and verify.
How to Use These Solutions
1. Attempt the question on your own first. Write the code in your notebook or IDE before looking at the answer. 2. Compare your approach with the solution provided. There can be more than one correct way to solve a problem. 3. Run the code in Python to see the output. Understanding the output is as important as writing the code. 4. Focus on the concept, not just the answer. Examiners test your understanding of the underlying ideas.
Key Concepts — Quick Review
- Define a function with
def function_name(parameters): - Call a function by writing
function_name(arguments) - Return a value with
return; without it, the function returnsNone - Parameters are in the definition; arguments are in the call
- Default arguments have preset values; they must come after non-default parameters
- Keyword arguments are passed by name, not position
- Local variables exist only inside the function; global variables exist everywhere
- Use
globalkeyword to modify a global variable inside a function - Recursion requires a base case and a recursive case
- Modules are imported with
import,from...import, orimport...as
Exercise Solutions
Q1. Write a function to find the factorial of a number.
def factorial(n):
"""Return the factorial of n."""
if n < 0:
return "Factorial not defined for negative numbers."
result = 1
for i in range(1, n + 1):
result *= i
return result
# Test
num = int(input("Enter a number: "))
print(f"Factorial of {num} = {factorial(num)}")
Sample output:
Q2. Write a function to check whether a number is prime.
def is_prime(n):
"""Return True if n is prime, False otherwise."""
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Test
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Sample output:
Q3. Write a function to calculate simple interest using default arguments.
def simple_interest(principal, rate=5, time=1):
"""Calculate simple interest. Rate defaults to 5%, time to 1 year."""
return (principal * rate * time) / 100
# Test with different argument combinations
print(simple_interest(10000)) # 50.0
print(simple_interest(10000, 8)) # 80.0
print(simple_interest(10000, 8, 3)) # 240.0
print(simple_interest(10000, time=2)) # 100.0 (rate defaults to 5)
Output:
Q4. Write a function that demonstrates local and global variable scope.
# Global variable
message = "Hello from global scope"
def demonstrate_scope():
# Local variable
message = "Hello from local scope"
print("Inside function:", message)
demonstrate_scope()
print("Outside function:", message)
Output:
Q5. Write a function that modifies a global variable using the global keyword.
counter = 0 # global variable
def increment():
"""Increment the global counter by 1."""
global counter
counter += 1
def reset():
"""Reset the global counter to 0."""
global counter
counter = 0
print("Initial counter:", counter) # 0
increment()
increment()
increment()
print("After 3 increments:", counter) # 3
reset()
print("After reset:", counter) # 0
Output:
Q6. Write a function that uses keyword arguments to create a student profile.
def student_profile(name, age, city="Not specified", stream="Science"):
"""Display student profile using keyword arguments."""
print(f"Name : {name}")
print(f"Age : {age}")
print(f"City : {city}")
print(f"Stream: {stream}")
# Calling with keyword arguments — order does not matter
student_profile(age=16, name="Arjun", stream="Commerce")
Output:
Q7. Write a recursive function to calculate the Fibonacci number.
def fibonacci(n):
"""Return the nth Fibonacci number using recursion."""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
# Print the first 10 Fibonacci numbers
print("Fibonacci series:")
for i in range(10):
print(fibonacci(i), end=" ")
print()
Output:
Q8. Create a module calc with basic arithmetic functions and import it.
Step 1 — Save this as calc.py:
# calc.py — a simple calculator module
def add(a, b):
"""Return the sum of a and b."""
return a + b
def subtract(a, b):
"""Return the difference of a and b."""
return a - b
def multiply(a, b):
"""Return the product of a and b."""
return a * b
def divide(a, b):
"""Return a divided by b. Returns None if b is 0."""
if b == 0:
print("Error: Division by zero!")
return None
return a / b
Step 2 — Import and use in another file:
import calc
print("Add :", calc.add(10, 3)) # 13
print("Subtract:", calc.subtract(10, 3)) # 7
print("Multiply:", calc.multiply(10, 3)) # 30
print("Divide :", calc.divide(10, 3)) # 3.3333...
Output:
Q9. Write a function that accepts variable-length arguments using *args.
def find_average(*numbers):
"""Calculate the average of any number of values."""
if len(numbers) == 0:
return 0
return sum(numbers) / len(numbers)
# Test with different numbers of arguments
print(find_average(10, 20, 30)) # 20.0
print(find_average(5, 15, 25, 35, 45)) # 25.0
print(find_average(100)) # 100.0
print(find_average()) # 0
Output:
Q10. Write a function to calculate the area of different shapes using keyword arguments.
def area(shape, **dimensions):
"""Calculate area of a shape based on keyword arguments."""
if shape == "circle":
return 3.14159 * dimensions["radius"] ** 2
elif shape == "rectangle":
return dimensions["length"] * dimensions["breadth"]
elif shape == "triangle":
return 0.5 * dimensions["base"] * dimensions["height"]
else:
return "Unknown shape"
# Test
print(area("circle", radius=7)) # 153.93791
print(area("rectangle", length=10, breadth=5)) # 50
print(area("triangle", base=8, height=5)) # 20.0
Output:
Q11. Write a function that returns multiple values.
def calculate(a, b):
"""Return sum, difference, product, and quotient of two numbers."""
s = a + b
d = a - b
p = a * b
q = a / b if b != 0 else None
return s, d, p, q
# Test
result = calculate(20, 5)
print(f"Sum = {result[0]}")
print(f"Difference = {result[1]}")
print(f"Product = {result[2]}")
print(f"Quotient = {result[3]}")
Output:
Q12. Use the math module to solve mathematical problems.
import math
def circle_properties(radius):
"""Calculate circumference and area of a circle."""
circumference = 2 * math.pi * radius
area = math.pi * radius ** 2
return circumference, area
# Test
r = 7
c, a = circle_properties(r)
print(f"Radius : {r}")
print(f"Circumference: {c:.2f}")
print(f"Area : {a:.2f}")
# Using other math functions
print(f"Square root of 144: {math.sqrt(144)}")
print(f"Ceiling of 4.3: {math.ceil(4.3)}")
print(f"Floor of 4.7: {math.floor(4.7)}")
print(f"GCD of 24 and 36: {math.gcd(24, 36)}")
Output:
Related Chapters
- [CBSE Class 11 Computer Science Chapter 7 — Functions (Chapter Guide)](/class/11/computer-science/cbse-functions)
- [CBSE Class 11 Computer Science Chapter 8 — Strings (Chapter Guide)](/class/11/computer-science/cbse-strings)
- [Strings — NCERT Class 11 Computer Science (Exercise Solutions)](/class/11/computer-science/solutions/cbse-strings-exercise-solutions)
