Functions
Mizoram Board · Class 11 · Computer Science
NCERT Solutions for Functions — Mizoram Board Class 11 Computer Science.
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.
1,000+ Class 11 students started this chapter today
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
1. `print text` — In Python 3, `print` is a function and must be called with parentheses. It should be `print(text)`.
2. `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)`.
3. `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:
```python
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 callShow solution
`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:
```python
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 callShow solution
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.
2. `print mynum` — In Python 3, `print` requires parentheses: `print(mynum)`.
Corrected Code:
```python
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 callShow solution
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.
2. `findvalue()` — Python is case-sensitive. The function is defined as `findValue` (capital V) but called as `findvalue` (lowercase v). This will cause a `NameError`.
3. `findvalue()` — Even after fixing the name, the call provides no arguments for the required parameters `val2` and `val3`.
Corrected Code:
```python
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 callShow solution
`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:
```python
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
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:
```python
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
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:
```python
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
| 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:
```python
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
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:
```python
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
| 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:
```python
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
| 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:
```python
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
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:
```python
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:
```python
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.Show solution
# Play and Learn program for toddlers
import random
def two_letter_words():
"""
Function to quiz children on two-letter words.
"""
words = ["at", "in", "on", "up", "go", "do", "be", "me", "he", "we"]
word = random.choice(words)
# Display word with one letter missing
pos = random.randint(0, 1)
hint = list(word)
hint[pos] = "_"
print(f"\nComplete the two-letter word: {''.join(hint)}")
answer = input("Your answer: ").strip().lower()
if answer == word:
print("Correct! Well done!")
else:
print(f"Oops! The correct word is: {word}")
def three_letter_words():
"""
Function to quiz children on three-letter words.
"""
words = ["cat", "bat", "hat", "dog", "pig", "hen", "sun", "run", "fun", "cup"]
word = random.choice(words)
pos = random.randint(0, 2)
hint = list(word)
hint[pos] = "_"
print(f"\nComplete the three-letter word: {''.join(hint)}")
answer = input("Your answer: ").strip().lower()
if answer == word:
print("Correct! Well done!")
else:
print(f"Oops! The correct word is: {word}")
def addition_quiz():
"""
Function to quiz children on addition of single digit numbers.
"""
a = random.randint(1, 9)
b = random.randint(1, 9)
print(f"\nWhat is {a} + {b} ?")
try:
answer = int(input("Your answer: "))
if answer == a + b:
print("Correct! Great job!")
else:
print(f"Oops! The correct answer is: {a + b}")
except ValueError:
print("Please enter a valid number.")
# Main program
print("=== Welcome to Play and Learn ===")
while True:
print("\n1. Two-letter words")
print("2. Three-letter words")
print("3. Addition of numbers")
print("4. Exit")
choice = input("Choose an activity (1-4): ")
if choice == '1':
two_letter_words()
elif choice == '2':
three_letter_words()
elif choice == '3':
addition_quiz()
elif choice == '4':
print("Goodbye! Keep learning!")
break
else:
print("Invalid choice. Please try again.")
```
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.Show solution
# Program to generate Fibonacci sequence using user defined function
def fibonacci(n):
"""
Function to generate and display Fibonacci sequence up to n terms.
Parameter: n - number of terms to generate
"""
if n <= 0:
print("Please enter a positive integer.")
return
elif n == 1:
print("Fibonacci sequence:")
print(1)
return
# Initialize first two terms
first = 1
second = 1
print("Fibonacci sequence:")
print(first, end=" ")
print(second, end=" ")
# Generate remaining terms
for i in range(3, n + 1):
next_term = first + second
print(next_term, end=" ")
first = second
second = next_term
print() # newline at end
# Main program
terms = int(input("Enter the number of terms: "))
fibonacci(terms)
```
Sample Output:
```
Enter the number of terms: 10
Fibonacci sequence:
1 1 2 3 5 8 13 21 34 55
```
Explanation:
- The function starts with `first = 1` and `second = 1`.
- Each subsequent term is computed as `next_term = first + second`.
- The variables are then shifted: `first = second`, `second = next_term`.
- This continues for `n` total terms.
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)Show solution
# Menu-driven calculator using user defined functions
import math
def add(a, b):
"""Returns sum of a and b"""
return a + b
def subtract(a, b):
"""Returns difference of a and b"""
return a - b
def multiply(a, b):
"""Returns product of a and b"""
return a * b
def divide(a, b):
"""Returns quotient of a divided by b"""
if b == 0:
return "Error: Division by zero!"
return a / b
def log10_val(x):
"""Returns log base 10 of x"""
if x <= 0:
return "Error: log undefined for non-positive values!"
return math.log10(x)
def sin_val(x):
"""Returns sine of x (x in degrees)"""
return math.sin(math.radians(x))
def cos_val(x):
"""Returns cosine of x (x in degrees)"""
return math.cos(math.radians(x))
# Main program
print("========== CALCULATOR ==========")
while True:
print("\n--- MENU ---")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. log10(x)")
print("6. sin(x)")
print("7. cos(x)")
print("8. Exit")
choice = input("\nEnter your choice (1-8): ")
if choice in ['1', '2', '3', '4']:
a = float(input("Enter first number : "))
b = float(input("Enter second number: "))
if choice == '1':
print(f"Result: {a} + {b} = {add(a, b)}")
elif choice == '2':
print(f"Result: {a} - {b} = {subtract(a, b)}")
elif choice == '3':
print(f"Result: {a} * {b} = {multiply(a, b)}")
elif choice == '4':
print(f"Result: {a} / {b} = {divide(a, b)}")
elif choice in ['5', '6', '7']:
x = float(input("Enter the value of x: "))
if choice == '5':
print(f"Result: log10({x}) = {log10_val(x)}")
elif choice == '6':
print(f"Result: sin({x}°) = {sin_val(x):.4f}")
elif choice == '7':
print(f"Result: cos({x}°) = {cos_val(x):.4f}")
elif choice == '8':
print("Exiting calculator. Goodbye!")
break
else:
print("Invalid choice! Please enter a number between 1 and 8.")
```
Sample Output:
```
--- MENU ---
1. Addition (+)
...
Enter your choice (1-8): 6
Enter the value of x: 90
Result: sin(90°) = 1.0000
```
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.Show solution
# Program to check divisibility of a number by 7
def check_divisibility(num):
"""
Function to check if num is divisible by 7.
Parameter: num - the number to check
"""
if num % 7 == 0:
print(f"{num} is divisible by 7.")
else:
print(f"{num} is NOT divisible by 7.")
# Main program
number = int(input("Enter a number: "))
check_divisibility(number)
```
Sample Output 1:
```
Enter a number: 49
49 is divisible by 7.
```
Sample Output 2:
```
Enter a number: 20
20 is NOT divisible by 7.
```
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.Show solution
# Program to prefix Mr/Ms based on gender
def display_name(name, gender):
"""
Function to display name with appropriate prefix.
Parameters: name - person's name
gender - 'M' for Male, 'F' for Female
"""
gender = gender.upper()
if gender == 'M':
print(f"Hello, Mr. {name}")
elif gender == 'F':
print(f"Hello, Ms. {name}")
else:
print("Invalid gender entered. Please enter M or F.")
# Main program
person_name = input("Enter name : ")
person_gender = input("Enter gender (M/F): ")
display_name(person_name, person_gender)
```
Sample Output 1:
```
Enter name : Arjun
Enter gender (M/F): M
Hello, Mr. Arjun
```
Sample Output 2:
```
Enter name : Priya
Enter gender (M/F): F
Hello, Ms. Priya
```
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 . Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result.Show solution
- D > 0: Two distinct real roots
- : Two equal real roots
- D < 0: No real roots (complex roots)
```python
# Program to find discriminant of a quadratic equation
import math
def quadratic_discriminant(a, b, c):
"""
Function to calculate discriminant and determine nature of roots.
Parameters: a, b, c - coefficients of quadratic equation ax^2 + bx + c = 0
"""
if a == 0:
print("Coefficient 'a' cannot be 0 for a quadratic equation.")
return
discriminant = b**2 - 4*a*c
print(f"\nQuadratic Equation: {a}x² + {b}x + {c} = 0")
print(f"Discriminant D = b² - 4ac = {b}² - 4×{a}×{c} = {discriminant}")
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
print("D > 0: Two distinct real roots exist.")
print(f"Root 1 = {root1:.2f}")
print(f"Root 2 = {root2:.2f}")
elif discriminant == 0:
root = -b / (2*a)
print("D = 0: Two equal real roots exist.")
print(f"Root = {root:.2f}")
else:
print("D < 0: No real roots. Roots are complex/imaginary.")
# Main program
print("Enter coefficients of quadratic equation ax² + bx + c = 0")
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
quadratic_discriminant(a, b, c)
```
Sample Output:
```
Enter a: 1
Enter b: -5
Enter c: 6
Quadratic Equation: 1.0x² + -5.0x + 6.0 = 0
Discriminant D = b² - 4ac = -5.0² - 4×1.0×6.0 = 1.0
D > 0: Two distinct real roots exist.
Root 1 = 3.00
Root 2 = 2.00
```
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)Show solution
# Program to automate lucky draw for ABC School Annual Day
import random
def lucky_draw():
"""
Function to randomly select a winner from token IDs 1 to 600.
Returns: winning token ID
"""
winner = random.randint(1, 600)
return winner
def display_result(winner_id):
"""
Function to display the lucky draw result.
Parameter: winner_id - the winning token number
"""
print("\n========================================")
print(" ABC SCHOOL ANNUAL DAY LUCKY DRAW")
print("========================================")
print(f" 🎉 Congratulations! 🎉")
print(f" The Lucky Winner is Token ID: {winner_id}")
print("========================================")
# Main program
print("Welcome to ABC School Annual Day Lucky Draw!")
print("Token IDs range from 1 to 600.")
input("\nPress ENTER to draw the lucky winner...")
winning_token = lucky_draw()
display_result(winning_token)
```
Sample Output:
```
Welcome to ABC School Annual Day Lucky Draw!
Token IDs range from 1 to 600.
Press ENTER to draw the lucky winner...
========================================
ABC SCHOOL ANNUAL DAY LUCKY DRAW
========================================
🎉 Congratulations! 🎉
The Lucky Winner is Token ID: 347
========================================
```
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: )Show solution
Where:
- = Principal Amount
- = Annual Rate of Interest (in decimal, e.g., 5% = 0.05)
- = Time in years
- = Number of times interest is compounded per year
```python
# Program to calculate Compound Interest
def compound_interest(P, r, t, n):
"""
Function to calculate compound interest.
Parameters:
P - Principal Amount
r - Annual Rate of Interest (in %)
t - Time in years
n - Number of times interest compounded per year
"""
r = r / 100 # Convert percentage to decimal
A = P * (1 + r/n) ** (n * t) # Amount after interest
CI = A - P # Compound Interest
print(f"\nPrincipal Amount (P) : Rs. {P:.2f}")
print(f"Annual Rate of Interest (r) : {r*100:.2f}%")
print(f"Time (t) : {t} years")
print(f"Compounded (n) : {n} times/year")
print(f"Amount (A) : Rs. {A:.2f}")
print(f"Compound Interest (CI) : Rs. {CI:.2f}")
# Main program
P = float(input("Enter Principal Amount : Rs. "))
r = float(input("Enter Annual Rate of Interest: % "))
t = float(input("Enter Time (in years) : "))
n = int(input("Enter number of times compounded per year: "))
compound_interest(P, r, t, n)
```
Sample Output:
```
Enter Principal Amount : Rs. 10000
Enter Annual Rate of Interest: % 5
Enter Time (in years) : 2
Enter number of times compounded per year: 12
Principal Amount (P) : Rs. 10000.00
Annual Rate of Interest (r) : 5.00%
Time (t) : 2.0 years
Compounded (n) : 12 times/year
Amount (A) : Rs. 11049.41
Compound Interest (CI) : Rs. 1049.41
```
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.Show solution
# Program to swap two numbers if first is less than second
def swap_if_less(num1, num2):
"""
Function to swap num1 and num2 if num1 < num2.
Parameters: num1, num2 - two numbers
Returns: (num2, num1) if num1 < num2, else (num1, num2)
"""
if num1 < num2:
# Swap: return num2 in place of num1 and num1 in place of num2
return num2, num1
else:
# No swap needed
return num1, num2
# Main program
a = float(input("Enter number 1: "))
b = float(input("Enter number 2: "))
result1, result2 = swap_if_less(a, b)
print(f"\nOriginal : Number 1 = {a}, Number 2 = {b}")
if a < b:
print("Since Number 1 < Number 2, numbers are swapped.")
else:
print("Since Number 1 >= Number 2, no swap needed.")
print(f"Returned : Number 1 = {result1}, Number 2 = {result2}")
```
Sample Output 1 (swap occurs):
```
Enter number 1: 5
Enter number 2: 10
Original : Number 1 = 5.0, Number 2 = 10.0
Since Number 1 < Number 2, numbers are swapped.
Returned : Number 1 = 10.0, Number 2 = 5.0
```
Sample Output 2 (no swap):
```
Enter number 1: 15
Enter number 2: 8
Original : Number 1 = 15.0, Number 2 = 8.0
Since Number 1 >= Number 2, no swap needed.
Returned : Number 1 = 15.0, Number 2 = 8.0
```
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.Show solution
```python
# shapes.py — Module containing functions for various shapes
import math
def square_area(side):
"""Returns area of a square. Formula: side²"""
return side ** 2
def square_perimeter(side):
"""Returns perimeter of a square. Formula: 4 × side"""
return 4 * side
def rectangle_area(length, breadth):
"""Returns area of a rectangle. Formula: l × b"""
return length * breadth
def rectangle_perimeter(length, breadth):
"""Returns perimeter of a rectangle. Formula: 2(l + b)"""
return 2 * (length + breadth)
def triangle_area(base, height):
"""Returns area of a triangle. Formula: 0.5 × base × height"""
return 0.5 * base * height
def triangle_perimeter(a, b, c):
"""Returns perimeter of a triangle. Formula: a + b + c"""
return a + b + c
def circle_area(radius):
"""Returns area of a circle. Formula: π × r²"""
return math.pi * radius ** 2
def circle_perimeter(radius):
"""Returns circumference of a circle. Formula: 2πr"""
return 2 * math.pi * radius
def cylinder_surface_area(radius, height):
"""Returns total surface area of a cylinder. Formula: 2πr(r + h)"""
return 2 * math.pi * radius * (radius + height)
```
Step 2: Create the main program file
```python
# main.py — Main program that imports and uses shapes module
import shapes
print("===== SHAPE CALCULATOR =====")
print("1. Square")
print("2. Rectangle")
print("3. Triangle")
print("4. Circle")
print("5. Cylinder")
choice = int(input("\nEnter your choice (1-5): "))
if choice == 1:
s = float(input("Enter side of square: "))
print(f"Area = {shapes.square_area(s):.2f}")
print(f"Perimeter = {shapes.square_perimeter(s):.2f}")
elif choice == 2:
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
print(f"Area = {shapes.rectangle_area(l, b):.2f}")
print(f"Perimeter = {shapes.rectangle_perimeter(l, b):.2f}")
elif choice == 3:
base = float(input("Enter base: "))
height = float(input("Enter height: "))
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c: "))
print(f"Area = {shapes.triangle_area(base, height):.2f}")
print(f"Perimeter = {shapes.triangle_perimeter(a, b, c):.2f}")
elif choice == 4:
r = float(input("Enter radius: "))
print(f"Area = {shapes.circle_area(r):.2f}")
print(f"Circumference = {shapes.circle_perimeter(r):.2f}")
elif choice == 5:
r = float(input("Enter radius: "))
h = float(input("Enter height: "))
print(f"Total Surface Area = {shapes.cylinder_surface_area(r, h):.2f}")
else:
print("Invalid choice!")
```
Sample Output:
```
Enter your choice (1-5): 4
Enter radius: 7
Area = 153.94
Circumference = 43.98
```
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.Show solution
# GK Quiz Program with random questions, score and remarks
import random
# GK Questions: list of [question, option_a, option_b, option_c, option_d, correct_answer]
questions = [
["What is the capital of India?",
"A. Mumbai", "B. New Delhi", "C. Kolkata", "D. Chennai", "B"],
["Which planet is known as the Red Planet?",
"A. Venus", "B. Jupiter", "C. Mars", "D. Saturn", "C"],
["Who wrote the national anthem of India?",
"A. Bankim Chandra", "B. Rabindranath Tagore", "C. Sarojini Naidu", "D. Mahatma Gandhi", "B"],
["What is the chemical symbol for Gold?",
"A. Go", "B. Gd", "C. Au", "D. Ag", "C"],
["How many continents are there on Earth?",
"A. 5", "B. 6", "C. 8", "D. 7", "D"]
]
def score(user_answers, correct_answers):
"""
Function to calculate the quiz score.
Parameters: user_answers - list of answers given by user
correct_answers - list of correct answers
Returns: total score
"""
total = 0
for i in range(len(correct_answers)):
if user_answers[i].upper() == correct_answers[i]:
total += 1
return total
def remark(scorevalue):
"""
Function to display remark based on score.
Parameter: scorevalue - the final score
"""
print(f"\nYour Score: {scorevalue} / 5")
if scorevalue == 5:
print("Remark: Outstanding")
elif scorevalue == 4:
print("Remark: Excellent")
elif scorevalue == 3:
print("Remark: Good")
elif scorevalue == 2:
print("Remark: Read more to score more")
elif scorevalue == 1:
print("Remark: Needs to take interest")
else:
print("Remark: General knowledge will always help you. Take it seriously.")
# Main program
print("========== GK QUIZ ==========")
print("Answer each question with A, B, C, or D.\n")
# Shuffle questions for random display
random.shuffle(questions)
user_answers = []
correct_answers = []
for idx, q in enumerate(questions):
print(f"Q{idx+1}. {q[0]}")
print(f" {q[1]}")
print(f" {q[2]}")
print(f" {q[3]}")
print(f" {q[4]}")
ans = input(" Your answer: ").strip().upper()
user_answers.append(ans)
correct_answers.append(q[5])
print()
# Calculate and display score and remark
final_score = score(user_answers, correct_answers)
remark(final_score)
```
Sample Output:
```
========== GK QUIZ ==========
Q1. Which planet is known as the Red Planet?
A. Venus
B. Jupiter
C. Mars
D. Saturn
Your answer: C
...
Your Score: 4 / 5
Remark: Excellent
```
CASE STUDY-BASED QUESTIONS
7.1Convert all the functionality in Chapter 5 and 6 (SMIS system) using user defined functions.Show solution
Concept: Each menu option or logical task should be wrapped in its own user defined function. The main program then calls these functions based on user choice.
General Structure:
```python
# SMIS - Student Management Information System
# Using User Defined Functions
def input_student_details():
"""
Function to accept and store student details.
"""
name = input("Enter student name : ")
roll_no = int(input("Enter roll number : "))
marks = float(input("Enter marks obtained : "))
return name, roll_no, marks
def display_student_details(name, roll_no, marks):
"""
Function to display student details.
"""
print("\n--- Student Details ---")
print(f"Name : {name}")
print(f"Roll Number : {roll_no}")
print(f"Marks : {marks}")
def calculate_grade(marks):
"""
Function to calculate grade based on marks.
Parameter: marks - marks obtained by student
Returns: grade as a string
"""
if marks >= 90:
return 'A+'
elif marks >= 80:
return 'A'
elif marks >= 70:
return 'B'
elif marks >= 60:
return 'C'
elif marks >= 33:
return 'D'
else:
return 'F'
def display_result(name, marks):
"""
Function to display result with grade.
"""
grade = calculate_grade(marks)
print(f"\nResult for {name}:")
print(f"Marks : {marks}")
print(f"Grade : {grade}")
if grade != 'F':
print("Status: PASS")
else:
print("Status: FAIL")
# Main Menu
def main():
while True:
print("\n===== SMIS MENU =====")
print("1. Enter Student Details")
print("2. Display Student Details")
print("3. Display Result")
print("4. Exit")
choice = input("Enter choice: ")
if choice == '1':
name, roll_no, marks = input_student_details()
elif choice == '2':
display_student_details(name, roll_no, marks)
elif choice == '3':
display_result(name, marks)
elif choice == '4':
print("Exiting SMIS. Goodbye!")
break
else:
print("Invalid choice!")
main()
```
Key Principle: Each distinct operation (input, display, grade calculation, result) is encapsulated in its own function, promoting modularity and reusability.
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.Show solution
- If Attendance % < 78\% → return 1 (short attendance / defaulter)
- If Attendance % → return 0 (attendance is not short)
```python
# Function to check short attendance
def check_attendance(total_working_days):
"""
Function to check if a student has short attendance.
Parameter: total_working_days - total number of working days in a month
Returns: 1 if attendance < 78% (short attendance / defaulter)
0 if attendance >= 78% (attendance is fine)
"""
days_present = int(input(f"Enter number of days present (out of {total_working_days}): "))
# Validate input
if days_present < 0 or days_present > total_working_days:
print("Invalid input: days present cannot be negative or exceed working days.")
return -1
# Calculate attendance percentage
attendance_percent = (days_present / total_working_days) * 100
print(f"\nDays Present : {days_present}")
print(f"Working Days : {total_working_days}")
print(f"Attendance : {attendance_percent:.2f}%")
if attendance_percent < 78:
print("Status: SHORT ATTENDANCE (Defaulter)")
return 1
else:
print("Status: Attendance is satisfactory.")
return 0
# Integration into SMIS main menu
total_days = int(input("Enter total working days in the month: "))
result = check_attendance(total_days)
if result == 1:
print("\nAlert: Student is marked as DEFAULTER due to short attendance.")
elif result == 0:
print("\nStudent attendance is within acceptable limits.")
```
Sample Output 1 (Short Attendance):
```
Enter total working days in the month: 25
Enter number of days present (out of 25): 18
Days Present : 18
Working Days : 25
Attendance : 72.00%
Status: SHORT ATTENDANCE (Defaulter)
Alert: Student is marked as DEFAULTER due to short attendance.
```
Sample Output 2 (Attendance OK):
```
Enter total working days in the month: 25
Enter number of days present (out of 25): 22
Days Present : 22
Working Days : 25
Attendance : 88.00%
Status: Attendance is satisfactory.
Student attendance is within acceptable limits.
```
Stuck on a step?
Ask Super Tutor AI to explain any solution on this page in a simpler way — free, 24x7.
Ask a Doubt FreeFrequently Asked Questions
What are the important topics in Functions for Mizoram Board Class 11 Computer Science?
How to score full marks in Functions — Mizoram Board Class 11 Computer Science?
Where can I get free NCERT Solutions for Functions Class 11 Computer Science?
Sources & Official References
Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.
More resources for Functions
Important Questions
Practice with board exam-style questions
Syllabus
What topics to cover
Revision Notes
Key points for last-minute revision
Study Plan
Step-by-step plan to ace this chapter
Flashcards
Quick-fire cards for active recall
Formula Sheet
All formulas in one place
Chapter Summary
Understand the chapter at a glance
Practice Quiz
Test yourself with a quick quiz
Concept Maps
See how topics connect visually
For serious students
Get the full Functions chapter — for free.
Quizzes, flashcards, AI doubt-solver and a step-by-step study plan for Mizoram Board Class 11 Computer Science.