This page contains the NCERT Computer Science class 11 chapter 7 Functions. You can find the solutions for the chapter 7 of NCERT class 11 Computer Science Exercise. So is the case if you are looking for NCERT class 11 Computer Science related topic Functions questions and answers for the Exercise
Exercise
1. Observe the following programs carefully, and identify the error:
a)
def create (text, freq):for i in range (1, freq):print textcreate(5) #function callb)
from math import sqrt,ceildef calc():print cos(0)calc() #function callc)
mynum = 9def add9():mynum = mynum + 9print mynumadd9() #function calld)
def findValue( vall = 1.1, val2, val3):final = (val2 + val3)/ vallprint(final)findvalue() #function calle)
def greet():return("Good morning")greet() = message #function call(a):
# Example with errors: missing argument and Python 2 print style
def create (text, freq):
for i in range (1, freq):
print text
create(5) #function call
Sample Output (Error)
File "functions_question_1_a.py, line 4
print text
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(text)?
Errors (what’s wrong):
•
Indentation is incorrect.
•
`print text` is Python 2 style; in Python 3 it must be `print(text)`.
•
Function call is wrong: `create()` needs two arguments (`text` and `freq`), but only one is given.
Correct program:
# Corrected version: print a string multiple times
def create(text, freq):
# Loop from 1 to freq (inclusive) and print each time
for i in range(1, freq + 1):
print(text)
create("Hello", 5) # function call
Sample Output
Hello
Hello
Hello
Hello
Hello
(b):
# Example with errors: missing import and Python 2 print
from math import sqrt,ceil
def calc():
print cos(0)
calc() #function call
Sample Output (Error)
File "functions_question_1_b.py, line 4
print cos(0)
^
SyntaxError: invalid syntax
Errors:
•
`cos()` is not imported.
•
`print cos(0)` is Python 2 style; use `print(cos(0))`.
Correct program (using from statement):
# Corrected version: import cos before using it
from math import cos
def calc():
# cos(0) returns 1.0
print(cos(0))
calc()
Sample Output
1.0
(c)
# Example with errors: local variable shadowing
mynum = 9
def add9():
mynum = mynum + 9
print mynum
add9() #function call
Sample Output (Error)
File "functions_question_1_c.py, line 5
print mynum
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(mynum)?
Errors:
•
Inside the function, `mynum` becomes a local variable, so Python thinks you’re using it before assigning it (scope issue).
•
`print mynum` should be `print(mynum)` in Python 3.
Correct program (using `global`):
# Corrected version using the global keyword
mynum = 9
def add9():
global mynum
# Now we can update the global variable safely
mynum = mynum + 9
print(mynum)
add9()
Sample Output
18
(d)
# Example with errors: default argument position and name mismatch
def findValue( vall = 1.1, val2, val3):
final = (val2 + val3)/ vall
print(final)
findvalue() #function call
Sample Output (Error)
File "functions_question_1_d.py, line 2
def findValue( vall = 1.1, val2, val3):
^
SyntaxError: non-default argument follows default argument
Errors:
•
Default parameter must be a trailing parameter (default should come at the end).
•
Function call name mismatch: `findvalue()` vs `findValue()`.
•
Missing required arguments in function call.
Correct program:
# Corrected version: default argument at the end
def findValue(val2, val3, vall=1.1):
# Default vall is used if not provided by the caller
final = (val2 + val3) / vall
print(final)
findValue(10, 20) # function call
Sample Output
27.272727272727273
(e)
# Example with error: assigning to a function call
def greet():
return("Good morning")
greet() = message #function call
Sample Output (Error)
functions_question_1_d.py, line 4
greet() = message #function call
^
SyntaxError: cannot assign to function call
Errors:
•
Assignment is reversed. You must store the returned value like: `message = greet()`.
Correct program:
# Corrected version: store return value from function call
def greet():
return "Good morning"
# Capture the returned greeting and display it
message = greet()
print(message)
Sample Output
Good morning
2. How is math.ceil(89.7) different from math.floor(89.7)?
•
`math.ceil(89.7)` gives the smallest integer greater than or equal to 89.7 → 90
•
`math.floor(89.7)` gives the largest integer less than or equal to 89.7 → 89
Example:
# Demonstrate ceiling vs floor rounding
import math
print(math.ceil(89.7)) # 90
print(math.floor(89.7)) # 89
3. Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.
Use `randint(1, 5)` because it gives a random integer including both 1 and 5.
•
`random()` gives a float between 0.0 and 1.0, so it’s not directly 1 to 5.
Example:
# randint(a, b) returns an integer in the inclusive range [a, b]
import random
print(random.randint(1, 5))
4. How is built-in function pow() different from function math.pow()? Explain with an example.
In Python, pow() is a built-in function, while math.pow() is a function of the math module. The main differences are:
1
Modulo (3rd argument)
•
pow(x, y, z) can take an optional third argument z and returns:
{(x^y) \% z}
•
math.pow(x, y) does not support this modulo feature.
2
Return type
•
math.pow(x, y) converts inputs to float and always returns a float.
•
pow(x, y) returns an int if the result is a whole number (and inputs are integers); otherwise it can return float.
Example Program:
# Compare built-in pow with math.pow
import math
print("math.pow(5, 2) =", math.pow(5, 2)) # always float
print("pow(5, 2) =", pow(5, 2)) # can be int
# Modulo use (only with built-in pow)
print("pow(2, 5, 3) =", pow(2, 5, 3)) # (2^5) % 3
Sample Output
math.pow(5, 2) = 25.0
pow(5, 2) = 25
pow(2, 5, 3) = 2
5. Using an example show how a function in Python can return multiple values.
Python returns multiple values using a tuple.
Example:
# Return area and perimeter as a tuple
def area_perimeter(l, b):
area = l * b
peri = 2 * (l + b)
return area, peri # returns a tuple
# Unpack the returned tuple into two variables
a, p = area_perimeter(10, 5)
print("Area =", a)
print("Perimeter =", p)
Sample Output
Area = 50
Perimeter = 30
ℹ️ You’ll learn more about tuples in later chapters.
6. Differentiate between following with the help of an example:
a)
Argument and Parameter
b)
Global and Local variable
(a) Argument and Parameter
Basis
Argument
Parameter
Meaning
The actual value passed to the function while calling it
A variable written in the function definition to receive a value
Where used
In the function call
In the function header
Example
add(10, 5) → 10, 5 are arguments
def add(a, b): → a, b are parameters
Example Program:
def add(a, b): # a and b are PARAMETERS
return a + b
result = add(10, 5) # 10 and 5 are ARGUMENTS
print("Sum =", result)
Sample Output
Sum = 15
(b) Global and Local variable
Basis
Global Variable
Local Variable
Where it is declared
Outside all functions
Inside a function
Scope (where it can be used)
Can be used throughout the program
Can be used only inside that function
Lifetime
Exists till the program runs
Exists only while the function is running
Modification inside function
To change it inside a function, use global
Can be changed normally inside the function
Example Program:
x = 10 # GLOBAL variable
def show_values():
x = 5 # LOCAL variable
print("Inside show_values(), local x =", x)
def change_global():
global x
x = x + 20
print("Inside change_global(), global x =", x)
print("Before function call, global x =", x)
show_values()
print("After show_values(), global x =", x)
change_global()
print("After change_global(), global x =", x)
Sample Output
Before function call, global x = 10
Inside show_values(), local x = 5
After show_values(), global x = 10
Inside change_global(), global x = 30
After change_global(), global x = 30
Conclusion:
•
The variable created inside a function is local and does not affect the global variable of the same name.
•
Using global allows us to modify the global variable inside a function.
7. Does a function always return a value? Explain with an example.
A function may or may not return a value explicitly.
•
If a function uses return, it sends a value back to the caller.
•
If a function does not use return, Python returns None by default.
Example Program:
# Function that does NOT return any value
def func1():
a = 5
b = 6
# no return statement
# Function that returns a value
def func2():
a = 5
return a
# Calling the functions and storing their return values
message1 = func1()
message2 = func2()
print("Return value of func1() =", message1)
print("Return value of func2() =", message2)
Sample Output
Return value of func1() = None
Return value of func2() = 5
Activity-based Questions
Note: Writing a program implies:
•
Adding comments as part of documentation
•
Writing function definition
•
Executing the function through a function call
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”.
Below is a complete, well-documented Python program that matches our requirement:
•
Uses a user-defined function login(uid, pwd)
•
Takes userid and password as parameters
•
Allows maximum 3 attempts
•
Prints “login successful” if uid == “ADMIN” and pwd == “St0rE@1”
•
Prints “account blocked” after 3 wrong attempts
•
Includes extensive comments
•
Includes a sample console execution with output
# ------------------------------------------------------------
# Program: Login Authentication with 3 Attempts
# Requirement:
# - Create a user-defined function login(uid, pwd)
# - Login is successful only when:
# User ID = "ADMIN"
# Password = "St0rE@1"
# - The user gets at most 3 attempts
# - If all 3 attempts are wrong, display: "account blocked"
# - If correct, display: "login successful"
# ------------------------------------------------------------
def login(uid, pwd):
"""
User-defined function to validate login credentials.
Parameters:
uid (str): The user ID entered by the user.
pwd (str): The password entered by the user.
Returns:
bool: True if credentials match the required values,
False otherwise.
"""
# Check whether both user id and password match exactly.
# The function returns True only if BOTH conditions are satisfied.
return (uid == "ADMIN" and pwd == "St0rE@1")
# ------------------- Main Program Starts Here -------------------
# attempts will count how many wrong tries have happened
# this helps us stop after exactly 3 failed logins
attempts = 0
# We allow a maximum of 3 attempts.
# The loop continues until attempts becomes 3.
while attempts < 3:
# Read user id and password from the console (keyboard input)
uid = input("Enter User ID: ")
pwd = input("Enter Password: ")
# Call the user-defined function login(uid, pwd)
# If it returns True, login is successful.
if login(uid, pwd):
print("login successful")
break # Exit the loop because login is successful
else:
# If login fails, increase attempt count and show a message
attempts += 1
print("Wrong credentials!")
# After the loop, if attempts reached 3, it means all 3 were wrong
# and no successful login happened inside the loop
if attempts == 3:
print("account blocked")
Sample Execution 1 (3 Wrong Attempts → Account Blocked)
Console Input/Output:
Enter User ID: admin
Enter Password: 1234
Wrong credentials!
Enter User ID: ADMIN
Enter Password: store@1
Wrong credentials!
Enter User ID: USER
Enter Password: pass
Wrong credentials!
account blocked
Sample Execution 2 (Successful Login on 2nd Attempt)
Console Input/Output:
Enter User ID: ADMIN
Enter Password: wrongpass
Wrong credentials!
Enter User ID: ADMIN
Enter Password: St0rE@1
login successful
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
>=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.
Below is a complete Python program (with a user-defined function, extensive comments/documentation, and a sample console execution with output) that follows the exact discount rules you provided.
# ---------------------------------------------------------------
# Program: XYZ Store Festival Discount Calculator
#
# Problem Statement:
# XYZ store offers festival discounts based on shopping amount:
# - Amount >= 500 and < 1000 -> 5% discount
# - Amount >= 1000 and < 2000 -> 8% discount
# - Amount >= 2000 -> 10% discount
#
# Additional Rule:
# - If the customer is a store member, give an EXTRA 5% discount
# (on the original total shopping amount).
#
# Net Payable Amount = Total Shopping Amount - Discount
#
# This program:
# 1) Defines a user-defined function calc_discount(amount, is_member)
# 2) Takes user input for amount and membership status
# 3) Calls the function and prints discount and net payable amount
# ---------------------------------------------------------------
def calc_discount(amount, is_member):
"""
Calculate the total discount and net payable amount.
Parameters:
amount (float): Total shopping amount entered by the user
is_member (bool): True if the customer is a member, otherwise False
Returns:
(discount, net) as a tuple:
discount (float): total discount amount in currency
net (float): net payable amount after discount
"""
# Start discount at 0. This variable will store the total discount money value.
discount = 0.0
# -----------------------------------------------------------
# Step 1: Apply festival discount based on shopping amount
# -----------------------------------------------------------
# Check which slab/range the amount falls into and compute discount accordingly.
if amount >= 500 and amount < 1000:
# 5% discount slab
discount = 0.05 * amount
elif amount >= 1000 and amount < 2000:
# 8% discount slab
discount = 0.08 * amount
elif amount >= 2000:
# 10% discount slab
discount = 0.10 * amount
else:
# If amount is less than 500, no festival discount is applied.
discount = 0.0
# -----------------------------------------------------------
# Step 2: Apply additional member discount (extra 5%)
# -----------------------------------------------------------
# If the person is a member, add extra 5% discount on the total amount.
if is_member:
discount += 0.05 * amount
# -----------------------------------------------------------
# Step 3: Calculate net payable amount
# -----------------------------------------------------------
# Net amount is what the customer pays after subtracting discount from total.
net = amount - discount
# Return BOTH values as a tuple (two results at once)
return discount, net
# ---------------------- MAIN PROGRAM ---------------------------
# This part of the program will execute when you run the file.
# Accept shopping amount from the user.
# float() is used because the amount can include decimals (e.g., 1250.50).
amt = float(input("Enter shopping amount: "))
# Accept membership status from the user.
# Convert input to uppercase so 'y' and 'Y' both work.
# The expression ( ... == "Y" ) becomes True if user typed Y, else False.
member = input("Member? (Y/N): ").upper() == "Y"
# Call the user-defined function to compute discount and net payable amount.
disc, net_pay = calc_discount(amt, member)
# Print results.
# Note: You can format to 2 decimal places if required; here we print raw float values.
# This makes it easy to verify the discount math during learning.
print("Discount =", disc)
print("Net Payable Amount =", net_pay)
Sample execution
Example 1: Member customer, amount = 1500
Enter shopping amount: 1500
Member? (Y/N): Y
Discount = 195.0
Net Payable Amount = 1305.0
Explanation (for understanding):
•
Festival discount for 1500 is 8% → 0.08 × 1500 = 120
•
Member extra discount is 5% → 0.05 × 1500 = 75
•
Total discount = 120 + 75 = 195
•
Net payable = 1500 − 195 = 1305
Example 2: Non-member customer, amount = 800
Enter shopping amount: 800
Member? (Y/N): N
Discount = 40.0
Net Payable Amount = 760.0
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.
Below is a complete, well-documented Python program (using user-defined functions) that helps toddlers practice 2-letter words, 3-letter words, and single-digit addition in a “play and learn” way.
It includes:
•
careful, age-appropriate question design (simple words, simple addition)
•
function definitions
•
function calls (execution)
•
extensive comments
•
sample console execution + output
✅ Program (with extensive comments)
Here is the formatted code for the Play and Learn Quiz Program
# -------------------------------------------------------------
# Play and Learn Quiz Program (Toddlers)
# -------------------------------------------------------------
# This program helps toddlers practice:
# 1) Two-letter English words (easy sight words)
# 2) Three-letter English words (simple CVC words like cat, dog)
# 3) Addition of two single-digit numbers (0 to 9)
#
# Why these questions are suitable for toddlers:
# - Two-letter words are short and help with letter recognition.
# - Three-letter words are commonly taught early (cat, dog, sun, etc.).
# - Addition uses single-digit numbers only (0–9) to keep it simple.
#
# The program uses:
# - user-defined functions (word_quiz and add_quiz)
# - random choices to make the quiz feel like a game
# - scoring to motivate learning
# -------------------------------------------------------------
import random # random helps us pick questions unpredictably (game-like fun)
# A small list of easy two-letter words toddlers can recognize and type.
# (These are common and simple: an, in, on, up, etc.)
two_letter_words = ["an", "in", "on", "up", "to", "we", "me"]
# A small list of simple three-letter words.
# These are easy noun words often taught early.
three_letter_words = ["cat", "dog", "sun", "pen", "bag", "cow"]
def word_quiz(word_list):
"""
This function conducts ONE word typing question.
Parameters:
word_list (list): a list of words (either 2-letter or 3-letter)
Working:
1) Randomly pick one word from the list
2) Ask the child to type the same word
3) If correct -> print "Correct!" and return 1
else -> print "Try again." and return 0
Returns:
int: 1 if the answer is correct, else 0
"""
# Choose a random word from the given list
word = random.choice(word_list)
# Ask the user to type the word
ans = input(f"Type this word: {word} : ")
# Check whether typed answer matches the word exactly
if ans == word:
print("Correct!")
return 1 # 1 point for correct answer
else:
print("Try again.")
return 0 # 0 point for incorrect answer
def add_quiz():
"""
This function conducts ONE single-digit addition question.
Working:
1) Generate two random numbers from 0 to 9
2) Ask the child to add them
3) If correct -> print "Correct!" and return 1
else -> print the correct answer and return 0
Returns:
int: 1 if the answer is correct, else 0
"""
# Generate two random single-digit numbers (0 to 9)
a = random.randint(0, 9)
b = random.randint(0, 9)
# Ask the question
# NOTE: We convert input to int because addition answer is numeric
ans = int(input(f"{a} + {b} = "))
# Verify the answer
if ans == a + b:
print("Correct!")
return 1
else:
print("Correct answer is", a + b)
return 0
# -------------------------------------------------------------
# MAIN PROGRAM EXECUTION (Function Calls happen here)
# -------------------------------------------------------------
# Score starts from 0
score = 0
# Ask one 2-letter word question
score += word_quiz(two_letter_words)
# Ask one 3-letter word question
score += word_quiz(three_letter_words)
# Ask one addition question
score += add_quiz()
# Print final score out of 3
# A simple score summary motivates the child
print("Final Score =", score, "/ 3")
▶️ Sample Execution (Console) + Output
Note: Because random is used, your words/numbers may differ each run. Below is an example of what it looks like when executed.
Sample Run 1
Type this word: on : on
Correct!
Type this word: cat : cot
Try again.
7 + 2 = 9
Correct!
Final Score = 2 / 3
Sample Run 2
Type this word: we : we
Correct!
Type this word: pen : pen
Correct!
4 + 6 = 15
Correct answer is 10
Final Score = 2 / 3
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.
# Program: Generate the Fibonacci sequence (starting with 1, 1)
# Documentation:
# - This program defines a function `fibonacci(n)` that returns the first `n` terms
# of the Fibonacci sequence, where each term is the sum of the previous two terms.
# - It then takes user input for how many terms to generate and prints the sequence.
def fibonacci(n):
"""Return a list containing the first n terms of the Fibonacci sequence (1, 1, 2, 3, ...)."""
series = []
a, b = 1, 1
# Build the sequence term by term
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
# Function call / execution
n = int(input("How many terms? "))
print(fibonacci(n))
Console Output (sample run)
Example input: 10
How many terms? 10
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
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)
Below is a menu-driven calculator program using user-defined functions, with proper comments (documentation), function definitions, and function calls.
✅ Python Program (Menu Driven Calculator)
# Menu Driven Calculator using User Defined Functions
# Performs: +, -, *, /, log10(x), sin(x), cos(x)
import math # Importing math module for log10, sin, cos
# -------- Basic Arithmetic Functions --------
def add(a, b):
"""Returns the sum of a and b."""
return a + b
def sub(a, b):
"""Returns the difference of a and b."""
return a - b
def mul(a, b):
"""Returns the product of a and b."""
return a * b
def div(a, b):
"""Returns the division of a by b. Handles division by zero."""
if b == 0:
return "Division by Zero Error"
return a / b
# -------- Scientific Functions --------
def log10x(x):
"""Returns log base 10 of x."""
return math.log10(x)
def sinx(x):
"""Returns sine of x (x must be in radians)."""
return math.sin(x)
def cosx(x):
"""Returns cosine of x (x must be in radians)."""
return math.cos(x)
# -------- Main Menu Loop --------
while True:
# Display menu options every iteration
print("\n1.Add 2.Sub 3.Mul 4.Div 5.log10(x) 6.sin(x) 7.cos(x) 8.Exit")
# Read user choice to decide which function to call
ch = int(input("Enter choice: "))
# Exit option
if ch == 8:
print("Exiting Calculator...")
break
# Arithmetic operations need two numbers
if ch in (1, 2, 3, 4):
a = float(input("Enter a: "))
b = float(input("Enter b: "))
if ch == 1:
print("Result:", add(a, b)) # function call
elif ch == 2:
print("Result:", sub(a, b)) # function call
elif ch == 3:
print("Result:", mul(a, b)) # function call
else:
print("Result:", div(a, b)) # function call
# Scientific operations need one number
elif ch in (5, 6, 7):
x = float(input("Enter x (in radians for sin/cos): "))
if ch == 5:
print("Result:", log10x(x)) # function call
elif ch == 6:
print("Result:", sinx(x)) # function call
else:
print("Result:", cosx(x)) # function call
else:
print("Invalid Choice! Please select from 1 to 8.")
Sample Output
1.Add 2.Sub 3.Mul 4.Div 5.log10(x) 6.sin(x) 7.cos(x) 8.Exit
Enter choice: 1
Enter a: 10
Enter b: 4.5
14.5
1.Add 2.Sub 3.Mul 4.Div 5.log10(x) 6.sin(x) 7.cos(x) 8.Exit
Enter choice: 4
Enter a: 7
Enter b: 0
Division by Zero Error
1.Add 2.Sub 3.Mul 4.Div 5.log10(x) 6.sin(x) 7.cos(x) 8.Exit
Enter choice: 5
Enter x (in radians for sin/cos): 1000
3.0
1.Add 2.Sub 3.Mul 4.Div 5.log10(x) 6.sin(x) 7.cos(x) 8.Exit
Enter choice: 6
Enter x (in radians for sin/cos): 1.5707963267948966
1.0
1.Add 2.Sub 3.Mul 4.Div 5.log10(x) 6.sin(x) 7.cos(x) 8.Exit
Enter choice: 7
Enter x (in radians for sin/cos): 0
1.0
1.Add 2.Sub 3.Mul 4.Div 5.log10(x) 6.sin(x) 7.cos(x) 8.Exit
Enter choice: 8
Exiting...
Suggested Lab Exercises
1. Write a program to check the divisibility of a number by 7 that is passed as a parameter to the user defined function.
# Program: Check divisibility of a number by 7 using a user-defined function
def is_div_by_7(n):
"""
Returns True if n is divisible by 7, otherwise returns False.
"""
# Modulo gives remainder; zero means evenly divisible
return n % 7 == 0
# ---- Execution (function call) ----
num = int(input("Enter a number: "))
result = is_div_by_7(num)
if result:
print(num, " is divisible by 7")
else:
print(num, " is not divisible by 7")
Sample Console Output (when executed)
Example 1 (divisible by 7):
Enter a number: 21
21 is divisible by 7
Example 2 (not divisible by 7):
Enter a number: 25
25 is not divisible by 7
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.
# Program: Prefix name with Mr/Ms based on gender
# Note:
# - This program contains comments (documentation),
# - uses a user-defined function,
# - and executes the function through a function call.
def prefix_name(name, gender):
"""
Accepts:
name (str): person's name
gender (str): 'M' for Male or 'F' for Female (case-insensitive)
Returns:
str: Name prefixed with 'Mr ' or 'Ms ' based on gender,
or 'Invalid gender' for any other input.
"""
# Normalize to uppercase so input is case-insensitive
if gender.upper() == "M":
return "Mr " + name
elif gender.upper() == "F":
return "Ms " + name
else:
return "Invalid gender"
# ---- Main (Function Call + Execution) ----
name = input("Enter name: ")
g = input("Enter gender (M/F): ")
print(prefix_name(name, g))
Sample Console Output (when executed)
Example 1 (Male):
Enter name: Rahul
Enter gender (M/F): M
Mr Rahul
Example 2 (Female):
Enter name: Priya
Enter gender (M/F): F
Ms Priya
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 b²-4ac. Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result.
# Program to calculate the determinant (discriminant) of a quadratic equation
# Quadratic form: ax^2 + bx + c = 0
# Determinant/Discriminant: D = b^2 - 4ac
def determinant(a, b, c):
"""
Accepts coefficients a, b, c of a quadratic equation
and returns the determinant (discriminant): b^2 - 4ac
"""
# Apply the discriminant formula D = b^2 - 4ac
d = (b * b) - (4 * a * c)
return d
# ---- Main Program (Function Call + Output) ----
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
d = determinant(a, b, c) # function call
print("Determinant =", d)
# Checking whether determinant is positive, zero, or negative
if d > 0:
print("Positive determinant (two real roots)")
elif d == 0:
print("Zero determinant (equal roots)")
else:
print("Negative determinant (no real roots)")
Sample Console Output
Example run (positive determinant):
a: 1
b: 5
c: 6
Determinant = 1.0
Positive determinant (two real roots)
Example run (zero determinant):
a: 1
b: 2
c: 1
Determinant = 0.0
Zero determinant (equal roots)
Example run (negative determinant):
a: 1
b: 2
c: 5
Determinant = -16.0
Negative determinant (no real roots)
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)
# Program: Lucky Draw Winner Token ID Generator (ABC School)
# Purpose: Generate a random winner token ID between 1 and 600 (inclusive)
# Note: Uses Python's random module
import random
def lucky_draw():
"""
Generates and returns a random token ID between 1 and 600 (inclusive).
"""
# randint includes both endpoints (1 and 600)
return random.randint(1, 600)
# Function call (execution)
print("Winner Token ID =", lucky_draw())
Output (sample console output)
Since the output depends on randomness, it may be different each time you run it.
Winner Token ID = 437
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)
# Program to calculate Compound Interest using a user-defined function
# Formula: CI = P * (1 + r/n)^(n*t) - P
# Where:
# P = Principal amount
# r = Rate of interest (annual) in percent
# t = Time (in years)
# n = Number of times interest is compounded per year
def compound_interest(P, r, t, n):
"""
Calculates and returns the compound interest.
Parameters:
P (float): Principal amount
r (float): Annual rate of interest in percent (e.g., 10 for 10%)
t (float): Time in years
n (int): Number of times interest is compounded per year
Returns:
float: Compound Interest (CI)
"""
# Convert rate from percent to decimal
r = r / 100
# Calculate final amount using compound interest formula
A = P * (1 + r / n) ** (n * t)
# Compound Interest is final amount minus principal
CI = A - P
return CI
# ---- Executing the function through a function call ----
P = float(input("Principal: "))
r = float(input("Rate (%): "))
t = float(input("Time (years): "))
n = int(input("Compounded how many times per year: "))
# Display the computed compound interest
print("Compound Interest =", compound_interest(P, r, t, n))
Sample Console Output (Example Execution)
(Assume the user enters: P=1000, r=10, t=2, n=4)
Principal: 1000
Rate (%): 10
Time (years): 2
Compounded how many times per year: 4
Compound Interest = 218.40227065164257
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.
# Program: Swap two numbers if the first is less than the second
# Description:
# This program defines a user-defined function that accepts two numbers.
# If number1 < number2, it swaps them and returns the swapped pair.
# Otherwise, it returns them in the same order.
def swap_if_needed(a, b):
"""
Accepts two numbers (a, b).
If a is less than b, swap them and return (b, a).
Otherwise, return (a, b) unchanged.
"""
if a < b:
return b, a
return a, b
# ---- Main (Function Call + Execution) ----
x = int(input("Number 1: "))
y = int(input("Number 2: "))
# Function call (executes the swapping logic)
x, y = swap_if_needed(x, y)
# Display result
# The tuple returned by the function is unpacked into x and y
print("After:", x, y)
Sample Console Output (Example Run 1: swap happens)
Number 1: 12
Number 2: 50
After: 50 12
Sample Console Output (Example Run 2: no swap)
Number 1: 80
Number 2: 20
After: 80 20
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.
(a) Create a module file `shapes.py`:
# shapes.py
# Module: shapes
# Description: User-defined functions to calculate area/perimeter/surface area for common shapes.
import math
# ---------- Square ----------
def square_area(s):
"""Return area of a square with side s."""
return s * s
def square_perimeter(s):
"""Return perimeter of a square with side s."""
return 4 * s
# ---------- Rectangle ----------
def rect_area(l, b):
"""Return area of a rectangle with length l and breadth b."""
return l * b
def rect_perimeter(l, b):
"""Return perimeter of a rectangle with length l and breadth b."""
return 2 * (l + b)
# ---------- Triangle ----------
def triangle_area(base, height):
"""Return area of a triangle using base and height."""
return 0.5 * base * height
def triangle_perimeter(a, b, c):
"""Return perimeter of a triangle with sides a, b, c."""
return a + b + c
# ---------- Circle ----------
def circle_area(r):
"""Return area of a circle with radius r."""
# Use math.pi for a more accurate value of pi
return math.pi * r * r
def circle_circumference(r):
"""Return circumference of a circle with radius r."""
# Circumference formula: 2 * pi * r
return 2 * math.pi * r
# ---------- Cylinder ----------
def cylinder_surface_area(r, h):
"""
Return total surface area of a cylinder with radius r and height h.
TSA = 2πrh + 2πr²
"""
return (2 * math.pi * r * h) + (2 * math.pi * r * r)
✅ (b) Program using the module: use_shapes.py
# use_shapes.py # Description: Import the shapes module and use its functions.
import shapes
# Function calls (execution)
# These calls demonstrate how to reuse functions from a module.
print("Square area (s=4) =", shapes.square_area(4))
print("Square perimeter (s=4) =", shapes.square_perimeter(4))
print("Rectangle area (l=10, b=5) =", shapes.rect_area(10, 5))
print("Rectangle perimeter (l=10, b=5) =", shapes.rect_perimeter(10, 5))
print("Triangle area (base=8, height=6) =", shapes.triangle_area(8, 6))
print("Triangle perimeter (3, 4, 5) =", shapes.triangle_perimeter(3, 4, 5))
print("Circle area (r=7) =", shapes.circle_area(7))
print("Circle circumference (r=7) =", shapes.circle_circumference(7))
print("Cylinder surface area (r=3, h=10) =", shapes.cylinder_surface_area(3, 10))
✅ Output (as shown in the console)
Square area (s=4) = 16
Square perimeter (s=4) = 16
Rectangle area (l=10, b=5) = 50
Rectangle perimeter (l=10, b=5) = 30
Triangle area (base=8, height=6) = 24.0
Triangle perimeter (3, 4, 5) = 12
Circle area (r=7) = 153.93804002589985
Circle circumference (r=7) = 43.982297150257104
Cylinder surface area (r=3, h=10) = 245.04422698000386
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.
# GK Quiz Program (5 Questions)
# Requirements implemented:
# 1) Comments as documentation
# 2) User-defined function definitions: score() and remark()
# 3) Executing functions through function calls
import random
# List of (question, correct_answer) pairs
questions = [
("Capital of India?", "DELHI"),
("5 + 7 = ?", "12"),
("National Animal of India?", "TIGER"),
("Largest planet?", "JUPITER"),
("Opposite of HOT?", "COLD"),
]
# Shuffle to display questions randomly
random.shuffle(questions)
def score(marks_list):
"""
Calculates the total score from a list containing 1 (correct) or 0 (wrong).
"""
return sum(marks_list)
def remark(scorevalue):
"""
Returns a remark based on the final score.
"""
if scorevalue == 5:
return "Outstanding"
elif scorevalue == 4:
return "Excellent"
elif scorevalue == 3:
return "Good"
elif scorevalue == 2:
return "Read more to score more"
elif scorevalue == 1:
return "Needs to take interest"
else:
return "General knowledge will always help you. Take it seriously."
# --- Quiz Execution ---
marks_list = []
for q, correct in questions:
# Normalize input so case/extra spaces do not affect scoring
user_answer = input(q + " ").strip().upper()
# Store 1 for correct and 0 for wrong
marks_list.append(1 if user_answer == correct else 0)
# Function calls to compute score and remark
final_score = score(marks_list)
final_remark = remark(final_score)
print("Marks =", final_score)
print("Remark =", final_remark)
Sample Output (console run)
(Since questions are shuffled, order can vary. Below is one possible run.)
National Animal of India? tiger
Largest planet? Jupiter
Opposite of HOT? cold
Capital of India? Mumbai
5 + 7 = ? 12
Marks = 4
Remark = Excellent
Case Study-based Question (SMIS)
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.
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.
Below is a single menu-driven SMIS program where everything is done using user defined functions:
Chapter 5:
Accept student identity details + display in bordered format
Chapter 6:
Accept marks (5 subjects), calculate total/percentage, find grade
Chapter 7.2:
short_attendance() function returning 1 or 0
"""
SMIS (Student Management Information System)
Chapter 5 + Chapter 6 + Chapter 7 Extension (7.1 + 7.2)
Program features (as required):
✅ Uses user-defined functions for all functionality
✅ Includes comments/documentation
✅ Uses a menu-driven approach
✅ Executes via a function call at the end
"""
# -----------------------------
# Global Constant (Card Width)
# -----------------------------
CARD_WIDTH = 56 # total width of the card including borders
# =========================================================
# Chapter 5: Student Identity Card (Using Functions)
# =========================================================
def border():
"""Prints the top/bottom border of the student card."""
print("+" + "-" * (CARD_WIDTH - 2) + "+")
def empty_line():
"""Prints an empty line inside the student card."""
print("|" + " " * (CARD_WIDTH - 2) + "|")
def center_line(text):
"""Prints a centered line inside the student card."""
print("|" + str(text).center(CARD_WIDTH - 2) + "|")
def left_line(text):
"""Prints a left-aligned line inside the student card."""
text = str(text)
if len(text) > (CARD_WIDTH - 2):
text = text[:CARD_WIDTH - 2]
print("|" + text.ljust(CARD_WIDTH - 2) + "|")
def two_side_line(left, right):
"""
Prints a line with left text and right text on the same row.
Example: Student Name: X Roll No: Y
"""
left = str(left)
right = str(right)
space = (CARD_WIDTH - 2) - len(left) - len(right)
if space < 1:
space = 1
print("|" + left + (" " * space) + right + "|")
def accept_student_details():
"""
Accepts student details from user and returns a student dictionary.
(Chapter 5 input + fields for Chapter 6 & 7)
"""
student = {}
student["school"] = input("Name of School: ").strip()
student["student_name"] = input("Student Name: ").strip()
student["roll_no"] = input("Roll No: ").strip()
student["student_class"] = input("Class: ").strip()
student["section"] = input("Section: ").strip()
student["addr1"] = input("Address Line 1: ").strip()
student["addr2"] = input("Address Line 2: ").strip()
student["city"] = input("City: ").strip()
student["pin_code"] = input("Pin Code: ").strip()
student["parent_contact"] = input("Parent/Guardian Contact No: ").strip()
# Chapter 6: marks
student["marks"] = [] # store 5 subject marks
# Chapter 7: attendance
student["present_days"] = None
student["working_days"] = None
return student
def print_card(student):
"""Prints the student identity card in bordered format (Chapter 5 style)."""
border()
center_line(student["school"])
empty_line()
two_side_line(f"Student Name: {student['student_name']}", f"Roll No: {student['roll_no']}")
two_side_line(f"Class: {student['student_class']}", f"Section: {student['section']}")
left_line(f"Address : {student['addr1']}")
left_line(f" {student['addr2']}")
empty_line()
two_side_line(f"City: {student['city']}", f"Pin Code: {student['pin_code']}")
left_line(f"Parent's/ Guardian's Contact No: {student['parent_contact']}")
border()
def find_student_by_roll(students, roll_no):
"""Returns the student dictionary matching roll_no, otherwise None."""
for s in students:
if s["roll_no"] == roll_no:
return s
return None
def list_students(students):
"""Lists basic info of all saved students."""
if len(students) == 0:
print("No students available.")
return
print("\nSaved Students:")
for s in students:
print(f"- Roll No: {s['roll_no']} | Name: {s['student_name']} | Class: {s['student_class']}-{s['section']}")
# =========================================================
# Chapter 6: Marks, Total, Percentage, Grade (Using Functions)
# =========================================================
def accept_marks(student):
"""Accepts marks for 5 subjects and stores them in student['marks']."""
marks = []
for i in range(5):
while True:
try:
m = float(input(f"Enter marks for subject {i + 1}: "))
if m < 0 or m > 100:
print("Marks should be between 0 and 100.")
continue
marks.append(m)
break
except ValueError:
print("Please enter a valid number.")
student["marks"] = marks
print("Marks saved:", student["marks"])
def display_marks(student):
"""Displays marks if entered, otherwise prints a warning."""
if len(student["marks"]) != 5:
print("Marks not entered yet. Use 'Accept marks' option first.")
else:
print("Marks entered:", student["marks"])
def calculate_total_and_percentage(student):
"""
Calculates and returns (total, percentage).
percentage = total / 5 (since 5 subjects)
"""
if len(student["marks"]) != 5:
print("Marks not entered yet. Use 'Accept marks' option first.")
return None, None
total = sum(student["marks"])
percentage = total / 5
return total, percentage
def find_grade(percentage):
"""
Returns grade based on percentage.
A: >= 85
B: 75 to < 85
C: 50 to < 75
D: 30 to < 50
Reappear: < 30
"""
if percentage >= 85:
return "A"
elif 75 <= percentage < 85:
return "B"
elif 50 <= percentage < 75:
return "C"
elif 30 <= percentage < 50:
return "D"
else:
return "Reappear"
# =========================================================
# Chapter 7.2: Attendance (User Defined Function)
# =========================================================
def short_attendance(present_days, working_days):
"""
7.2: Returns 1 if attendance < 78%, else returns 0.
attendance = present_days / working_days
If attendance < 0.78 => return 1 (short attendance / defaulter)
Else return 0
"""
if working_days <= 0:
return 1 # invalid working days => treat as defaulter
attendance = present_days / working_days
if attendance < 0.78:
return 1
return 0
def accept_attendance(student):
"""Accepts attendance and displays whether student is defaulter or not."""
while True:
try:
present = int(input("Enter days present in the month: "))
working = int(input("Enter total working days in the month: "))
if present < 0 or working <= 0 or present > working:
print("Invalid input. Ensure 0 <= present_days <= working_days and working_days > 0.")
continue
student["present_days"] = present
student["working_days"] = working
result = short_attendance(present, working)
attendance_percent = (present / working) * 100
print(f"Attendance = {attendance_percent:.2f}%")
if result == 1:
print("Defaulter: short attendance (returns 1)")
else:
print("Attendance is not short (returns 0)")
break
except ValueError:
print("Please enter valid integer values.")
# =========================================================
# Main Menu (All Chapters Combined)
# =========================================================
def smis_menu():
"""Menu-driven SMIS system (Ch 5 + 6 + 7) using user-defined functions."""
# Store all student records in memory during this run
students = []
while True:
print("\n--- SMIS MENU (Chapter 5 + 6 + 7) ---")
print("1. Add student (accept identity details)")
print("2. Display student identity card (bordered format)")
print("3. Accept marks (5 subjects) for a student")
print("4. Display marks of a student")
print("5. Calculate total and percentage of a student")
print("6. Display grade of a student")
print("7. Check short attendance of a student")
print("8. List saved students")
print("9. Exit")
try:
choice = int(input("Enter your choice (1-9): "))
except ValueError:
print("Wrong choice. Please enter a number between 1 and 9.")
continue
if choice == 1:
print("\nEnter details for new student:")
s = accept_student_details()
# prevent duplicate roll numbers
if find_student_by_roll(students, s["roll_no"]) is not None:
print("This Roll No already exists. Student not added.")
else:
students.append(s)
print("Student added successfully.")
elif choice == 2:
roll = input("Enter Roll No of student to display card: ").strip()
s = find_student_by_roll(students, roll)
if s is None:
print("Student not found.")
else:
print("\nOutput Card:")
print_card(s)
elif choice == 3:
roll = input("Enter Roll No of student to accept marks: ").strip()
s = find_student_by_roll(students, roll)
if s is None:
print("Student not found.")
else:
accept_marks(s)
elif choice == 4:
roll = input("Enter Roll No of student to display marks: ").strip()
s = find_student_by_roll(students, roll)
if s is None:
print("Student not found.")
else:
display_marks(s)
elif choice == 5:
roll = input("Enter Roll No of student to calculate total & percentage: ").strip()
s = find_student_by_roll(students, roll)
if s is None:
print("Student not found.")
else:
total, percentage = calculate_total_and_percentage(s)
if total is not None:
print("Total marks =", total)
print("Percentage =", percentage)
elif choice == 6:
roll = input("Enter Roll No of student to display grade: ").strip()
s = find_student_by_roll(students, roll)
if s is None:
print("Student not found.")
else:
total, percentage = calculate_total_and_percentage(s)
if percentage is not None:
grade = find_grade(percentage)
print("Percentage =", percentage)
print("Grade =", grade)
elif choice == 7:
roll = input("Enter Roll No of student to check attendance: ").strip()
s = find_student_by_roll(students, roll)
if s is None:
print("Student not found.")
else:
accept_attendance(s)
elif choice == 8:
list_students(students)
elif choice == 9:
print("Exiting... Bye Bye!!")
break
else:
print("Wrong choice. Please enter between 1 and 9.")
# -----------------------------
# Function Call (Program Run)
# -----------------------------
# Start the interactive menu
smis_menu()
Sample Console Output (as if executed)
(User inputs are shown after prompts on the same line.)
--- SMIS MENU (Chapter 5 + 6 + 7) ---
1. Add student (accept identity details)
2. Display student identity card (bordered format)
3. Accept marks (5 subjects) for a student
4. Display marks of a student
5. Calculate total and percentage of a student
6. Display grade of a student
7. Check short attendance of a student
8. List saved students
9. Exit
Enter your choice (1-9): 1
Enter details for new student:
Name of School: ABC Public School
Student Name: Riya Sharma
Roll No: 101
Class: 10
Section: A
Address Line 1: 21 Green Park
Address Line 2: Near City Mall
City: Delhi
Pin Code: 110016
Parent/Guardian Contact No: 9876543210
Student added successfully.
--- SMIS MENU (Chapter 5 + 6 + 7) ---
1. Add student (accept identity details)
2. Display student identity card (bordered format)
3. Accept marks (5 subjects) for a student
4. Display marks of a student
5. Calculate total and percentage of a student
6. Display grade of a student
7. Check short attendance of a student
8. List saved students
9. Exit
Enter your choice (1-9): 2
Enter Roll No of student to display card: 101
Output Card:
+-------------------------------------------------------+
| ABC Public School |
| |
|Student Name: Riya Sharma Roll No: 101|
|Class: 10 Section: A|
|Address : 21 Green Park |
| Near City Mall |
| |
|City: Delhi Pin Code: 110016|
|Parent's/ Guardian's Contact No: 9876543210 |
+-------------------------------------------------------+
--- SMIS MENU (Chapter 5 + 6 + 7) ---
1. Add student (accept identity details)
2. Display student identity card (bordered format)
3. Accept marks (5 subjects) for a student
4. Display marks of a student
5. Calculate total and percentage of a student
6. Display grade of a student
7. Check short attendance of a student
8. List saved students
9. Exit
Enter your choice (1-9): 3
Enter Roll No of student to accept marks: 101
Enter marks for subject 1: 89
Enter marks for subject 2: 76
Enter marks for subject 3: 92
Enter marks for subject 4: 68
Enter marks for subject 5: 80
Marks saved: [89.0, 76.0, 92.0, 68.0, 80.0]
--- SMIS MENU (Chapter 5 + 6 + 7) ---
1. Add student (accept identity details)
2. Display student identity card (bordered format)
3. Accept marks (5 subjects) for a student
4. Display marks of a student
5. Calculate total and percentage of a student
6. Display grade of a student
7. Check short attendance of a student
8. List saved students
9. Exit
Enter your choice (1-9): 6
Enter Roll No of student to display grade: 101
Percentage = 81.0
Grade = B
--- SMIS MENU (Chapter 5 + 6 + 7) ---
1. Add student (accept identity details)
2. Display student identity card (bordered format)
3. Accept marks (5 subjects) for a student
4. Display marks of a student
5. Calculate total and percentage of a student
6. Display grade of a student
7. Check short attendance of a student
8. List saved students
9. Exit
Enter your choice (1-9): 7
Enter Roll No of student to check attendance: 101
Enter days present in the month: 18
Enter total working days in the month: 24
Attendance = 75.00%
Defaulter: short attendance (returns 1)
--- SMIS MENU (Chapter 5 + 6 + 7) ---
1. Add student (accept identity details)
2. Display student identity card (bordered format)
3. Accept marks (5 subjects) for a student
4. Display marks of a student
5. Calculate total and percentage of a student
6. Display grade of a student
7. Check short attendance of a student
8. List saved students
9. Exit
Enter your choice (1-9): 9
Exiting... Bye Bye!!