Functions  Class 11 Computer Science  Chapter 7  Notes, NCERT Solutions & Extra Questions
Renews every month. Cancel anytime
Your personal doubtsolving assistant
Chatterbot AI gives you 100% accurate answers to your questions in an instant.
Notes  Functions  Class 11 NCERT  Computer Science
Understanding Functions in Python: Class 11 Notes
Functions in Python are an essential concept, especially for students in Class 11. They help in breaking down complex problems into manageable blocks of code and promoting code reuse and organisation. This guide will walk you through everything you need to know about functions in Python.
What are Functions in Python?
Functions are reusable pieces of code that perform a specific task. Rather than writing the same code multiple times, you can define a function once and call it whenever needed. Functions help in making the code organised, readable, and easy to maintain.
Types of Functions in Python
Builtin Functions
Python comes with a rich set of builtin functions, such as print()
, len()
, input()
, etc. These functions are always available to use without the need for any import.
Userdefined Functions
In addition to builtin functions, you can also create your own functions known as userdefined functions. These are created to perform specific tasks as per your requirements.
Creating UserDefined Functions
Creating a userdefined function in Python involves using the def
keyword followed by the function name and parameters (if any).
Syntax:
def function_name(parameters):
# Function body
return [expression]
Components:

def
: This keyword is used to declare a function.  Function Name: A unique identifier to name the function.
 Parameters: Inputs to the function (optional), enclosed in parentheses.
 Function Body: Indented block of code that performs a task.
 Return Statement: Optional, used to return values from the function.
Parameters and Arguments
Parameters:
Parameters are variables listed inside the parentheses in the function definition. They act as placeholders for the inputs the function expects.
Arguments:
Arguments are the actual values passed to the function when calling it. They replace the parameters during execution.
def add(a, b): # a and b are parameters
return a + b
result = add(5, 3) # 5 and 3 are arguments
print(result) # Output: 8
Returning Values from Functions
A function can send back data to the caller using the return
statement. If a function does not have a return statement, it defaults to returning None
.
Returning Multiple Values:
Python functions can return multiple values using tuples.
def operations(a, b):
return a + b, a  b, a * b, a / b
result = operations(10, 2)
print(result) # Output: (12, 8, 20, 5.0)
Scope of a Variable
Global Variables:
Variables defined outside any function and accessible throughout the program are global variables.
x = "global"
def my_function():
print(x) # Will print "global"
my_function()
Local Variables:
Variables defined inside a function are local to that function and cannot be accessed outside.
def my_function():
x = "local"
print(x)
my_function()
print(x) # Error: NameError: name 'x' is not defined
The Flow of Execution in Functions
The flow of execution refers to the order in which statements are executed in a program. When the Python interpreter encounters a function call, it jumps to the function definition, executes it, and then returns to the point where the function was called.
Python Standard Library and Modules
Python's standard library is extensive and includes many modules that provide various functionalities. To use these modules, you need to import them into your program.
Importing Modules:
import math
print(math.sqrt(16)) # Output: 4.0
Commonly Used Builtin Modules:
 math: Provides mathematical functions.
 random: Used for generating random numbers.
 statistics: Offers functions for statistical operations.
Documenting Functions
Documenting your functions using docstrings is a good practice. It helps in understanding the purpose and usage of the function.
def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
Advanced Topics
Default Parameters:
Python allows setting default values for parameters. If an argument is not provided, the default value is used.
def greet(name="Student"):
print("Hello, " + name)
greet() # Output: Hello, Student
greet("John") # Output: Hello, John
Void Functions:
These functions do not return any value.
def print_message(message):
print(message)
print_message("Hello, World!")
Conclusion
Functions are the building blocks of a wellstructured program. They enhance code readability, reusability, and organisation. Mastering the use of functions is crucial for efficient coding and problemsolving.
By understanding functions, you can break down complex problems and make your programs more modular and easier to maintain. Happy coding!
🚀 Learn more about Notes with Chatterbot AI
Extra Questions  Functions  NCERT  Computer Science  Class 11
Let $f$ be a realvalued function satisfying $f(x+y)=f(x)+f(y)$ for all $x$, y. If $f(1)=\frac{1}{2}$, then the value of $f(16)$ is:
A. 16
B. 8
C. 4
D. 2
Given a realvalued function $f$ such that $f(x+y) = f(x) + f(y)$ for all real numbers $x$ and $y$, and given that $f(1) = \frac{1}{2}$, we are asked to find the value of $f(16)$.
Let's examine this stepbystep.
First, let's express $f(mx)$ where $m$ is an integer: $$ f(x + (m1)x) = f(x) + f((m1)x) $$ Using the given property repeatedly, $$ = f(x) + f(x + (m2)x) = f(x) + f(x) + f((m2)x) = \cdots = m f(x) + f(0) $$
Determining $f(0)$
Using the property $f(x+y) = f(x) + f(y)$: $$ \text{Putting } x = 0 \text{ and } y = 0, $$ $$ f(0+0) = f(0) + f(0) $$ $$ f(0) = 2f(0) \Rightarrow f(0) = 0 $$
Thus, the above expression simplifies to: $$ f(mx) = m f(x) \quad \text{where } m \text{ is an integer} $$
Finding $f(16)$
Given $f(1) = \frac{1}{2}$, $$ f(16 \times 1) = 16 f(1) $$ $$ f(16) = 16 \times \frac{1}{2} = 8 $$
Verification (Alternate )
Calculating successively: $$ f(2) = f(1) + f(1) = \frac{1}{2} + \frac{1}{2} = 1 $$ $$ f(4) = f(2) + f(2) = 1 + 1 = 2 $$ $$ f(8) = f(4) + f(4) = 2 + 2 = 4 $$ $$ f(16) = f(8) + f(8) = 4 + 4 = 8 $$
Therefore, the value of $f(16)$ is 8.
💡 Have more questions?
Ask Chatterbot AINCERT Solutions  Functions  NCERT  Computer Science  Class 11
Observe the following programs carefully, and identify the error:
a)
def create (text, freq):
for i in range (1, freq):
print text
create(5) # function call
b)
from math import sqrt, ceil
def calc():
print cos (0)
calc() #function call
c)
mynum = 9
def add9():
mynum = mynum + 9
add9() # function call
d)
def findValue(val1 = 1.1, val2, val3):
final = (val2 + val3) / vall1
print(final)
findValue() # function call
e)
def greet():
return("Good morning")
greet() = message # function call
Let's identify the errors in each of the provided programs:
a)
def create (text, freq):
for i in range (1, freq):
print text
create(5) # function call
Error:
Missing parentheses in the
print
statement (Python 3).Incorrect number of arguments passed to
create
.
Fix:
def create(text, freq):
for i in range(1, freq):
print(text)
create("Sample Text", 5) # function call
b)
from math import sqrt, ceil
def calc():
print cos(0)
calc() # function call
Error:
Missing import for
cos
function inmath
module.Missing parentheses for
print
(Python 3).
Fix:
from math import sqrt, ceil, cos
def calc():
print(cos(0))
calc() # function call
c)
mynum = 9
def add9():
mynum = mynum + 9
add9() # function call
Error:
mynum
inside the function is considered local, causingUnboundLocalError
because it is being used before assignment.
Fix:
mynum = 9
def add9():
global mynum
mynum = mynum + 9
add9() # function call
d)
def findValue(val1 = 1.1, val2, val3):
final = (val2 + val3) / val1
print(final)
findValue() # function call
Error:
Nondefault arguments (
val2
,val3
) cannot follow default arguments (val1
).
Fix:
def findValue(val2, val3, val1=1.1):
final = (val2 + val3) / val1
print(final)
findValue(1, 2) # function call
e)
def greet():
return "Good morning"
greet() = message # function call
Error:
Incorrect assignment syntax.
greet()
returns a value, it cannot be assigned to.
Fix:
def greet():
return "Good morning"
message = greet() # function call
How is math.ceil(89.7) different from math.floor (89.7)?
The **math.ceil**
and **math.floor**
functions in Python's math module perform rounding operations, but they do so differently:
math.ceil(89.7): This function returns the smallest integer greater than or equal to 89.7, which is 90.
math.floor(89.7): This function returns the largest integer less than or equal to 89.7, which is 89.
In summary:
math.ceil(89.7) = 90
math.floor(89.7) = 89
Out of random() and randint(), which function should we use to generate random numbers between 1 and 5 . Justify.
To generate random numbers between 1 and 5, we should use the randint()
function.
Justification:
The **randint(x, y)**
function from the random
module:
Arguments: Takes two integers ( x ) and ( y ) as arguments.
Return: Generates a random integer between ( x ) and ( y ) (both inclusive).
Example:
import random
random_number = random.randint(1, 5) # Generates a random integer between 1 and 5
The random()
function:
Arguments: Takes no arguments.
Return: Generates a random floatingpoint number between 0.0 and 1.0.
Example:
import random
random_number = random.random() # Generates a random float between 0.0 and 1.0
To generate an integer in the range 1 to 5 using random()
, additional manipulation would be required.
Conclusion: Since randint()
directly provides a random integer between the specified range, it is more straightforward and convenient for our requirement.
How is builtin function pow() function different from function math.pow() ? Explain with an example.
The builtin function pow()
and the function math.pow()
both serve the purpose of calculating the power of a number, but they have some differences:
pow()
Function:
Syntax:
pow(base, exp[, mod])
Description: Takes two or three parameters: the base, exponent, and optionally a modulus. If a modulus is provided,
pow()
computes(base ** exp) % mod
.Type: Builtin function.
Return Value: Integer if all arguments are integers, otherwise a float.
math.pow()
Function:
Syntax:
math.pow(x, y)
Description: Takes two parameters: the base
x
and the exponenty
. It always returnsx
raised to the power ofy
.Type: Part of the
math
module.Return Value: Always returns a float, regardless of input types.
Example:
import math
# Using builtin pow()
result1 = pow(2, 3) # 2^3 = 8
mod_result = pow(2, 3, 3) # (2^3) % 3 = 8 % 3 = 2
# Using math.pow()
result2 = math.pow(2, 3) # 2^3 = 8.0
print("Builtin pow:", result1) # Output: 8
print("Builtin pow with modulus:", mod_result) # Output: 2
print("math.pow:", result2) # Output: 8.0
pow(2, 3)
returns8
(an integer).pow(2, 3, 3)
returns2
(it calculates (8 % 3)).math.pow(2, 3)
returns8.0
(a float).
In summary:
The
builtin pow()
can take an optional thirdmod
argument and returns an integer if all inputs are integers.The
math.pow()
always returns a float and does not accept a modulus argument.
Using an example show how a function in Python can return multiple values.
A function in Python can return multiple values using a tuple. Here's an example to demonstrate this:
Example: Calculating Area and Perimeter of a Rectangle
We'll write a function that calculates both the area and the perimeter of a rectangle and then returns these two values.
# Function to calculate area and perimeter of a rectangle
def calcAreaPeri(length, breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
# Returning multiple values using a tuple
return area, perimeter
# Taking inputs for length and breadth
l = float(input("Enter length of the rectangle: "))
b = float(input("Enter breadth of the rectangle: "))
# Calling the function and unpacking the returned values
area, perimeter = calcAreaPeri(l, b)
# Displaying the results
print("Area is:", area)
print("Perimeter is:", perimeter)
Output:
Enter length of the rectangle: 45
Enter breadth of the rectangle: 66
Area is: 2970.0
Perimeter is: 222.0
In this example:
The function
calcAreaPeri(length, breadth)
computes the area and perimeter of a rectangle.It returns both values as a tuple.
The return values are unpacked into the variables
area
andperimeter
when the function is called.
This shows how multiple values can be returned and used from a single function in Python.
Differentiate between following with the help of an example:
a) Argument and Parameter
b) Global and Local variable
a) Argument and Parameter
Parameter: A parameter is a variable in the function definition. It is a placeholder for the value that will be passed when the function is called.
Argument: An argument is the actual value passed to the function when it is invoked.
Example:
# Function definition with parameters
def greet(name, age):
print("Hello", name, "you are", age, "years old")
# Function call with arguments
greet("Alice", 30)
In this example:
name
andage
are parameters in the function definition."Alice"
and30
are arguments in the function call.
b) Global and Local variable
Global Variable: A global variable is defined outside of any function and can be accessed by any function within the same module.
Local Variable: A local variable is defined inside a function and can only be accessed within that function.
Example:
# Global variable
count = 10
def increment():
# Local variable
value = 5
print("Inside increment function, value =", value)
# Accessing global variable within a function
global count
count += 1
print("Inside increment function, count =", count)
# Calling the function
increment()
# Accessing global variable outside all functions
print("Outside any function, count =", count)
# Trying to access local variable outside its function will raise an error
print("Outside any function, value =", value) # This will cause an error
In this example:
count
is a global variable that is defined outside the function and accessed both inside and outside the function.value
is a local variable that is defined inside theincrement
function and can only be accessed within that function.The last print statement will raise a
NameError
becausevalue
is not accessible outside theincrement
function.
Does a function always return a value? Explain with an example.
No, a function does not always return a value. In Python, functions can be categorized into two types based on whether they return a value or not:
Void Functions: These functions do not return any value. They perform actions but do not give back any result to the caller.
NonVoid Functions: These functions return a value using the
return
statement.
Here's an example to illustrate both types:
Example of a Void Function:
A function that prints the square of a number but does not return the result.
def print_square(num):
square = num * num
print(f"The square of {num} is {square}")
# Function call
print_square(4)
# Output:
# The square of 4 is 16
In this case, print_square
is a void function because it only prints the result and does not return any value to the caller.
Example of a NonVoid Function:
A function that calculates and returns the square of a number.
def calculate_square(num):
square = num * num
return square
# Function call
result = calculate_square(4)
print(f"The square of 4 is {result}")
# Output:
# The square of 4 is 16
In this case, calculate_square
is a nonvoid function because it returns the computed value of the square to the caller, which can then be used in further computation or output.
Important Points:
Void Functions: Useful when you only need to perform an action like printing or updating a value.
NonVoid Functions: Useful when you need the result of a computation to be used elsewhere in your program.
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 "StOrE@1". On successful login, display a message "login successful".
Here is a Python program using the login
function to authenticate a user with three attempts:
# Define login function
def login(uid, pwd):
# Initialize attempt counter
attempts = 0
while attempts < 3:
# Increment attempts
attempts += 1
# Check if the provided credentials match the correct ones
if uid == "ADMIN" and pwd == "StOrE@1":
print("login successful")
return
# If credentials don't match, ask for them again
print("Invalid credentials. Try again.")
# Allow user to retry if attempts are less than 3
if attempts < 3:
uid = input("Enter user ID: ")
pwd = input("Enter password: ")
# If three attempts are exhausted, block the account
print("account blocked")
# Take user input for user ID and password
input_uid = input("Enter user ID: ")
input_pwd = input("Enter password: ")
# Call the login function with the provided inputs
login(input_uid, input_pwd)
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% 
# Program to calculate discount and net amount payable using user defined function
def calculate_discount(shopping_amount):
"""
This function calculates the discount and net amount payable
based on the given criteria.
"""
if shopping_amount >= 2000:
discount = 10
elif shopping_amount >= 1000:
discount = 8
elif shopping_amount >= 500:
discount = 5
else:
discount = 0
discount_amount = (discount / 100) * shopping_amount
net_payable_amount = shopping_amount  discount_amount
return discount, net_payable_amount
# Main Program
shopping_amount = float(input("Enter the shopping amount: "))
discount, net_payable_amount = calculate_discount(shopping_amount)
print(f"Discount Offered: {discount}%")
print(f"Net Payable Amount: {net_payable_amount:.2f} Rupees")
Explanation:
Function Definition (
calculate_discount
):Parameters:
shopping_amount
to determine the discount.Logic: Based on the
shopping_amount
, a discount percentage is assigned.Calculations:
discount_amount
: The actual discount in monetary terms.net_payable_amount
: Shopping amount minus the discount amount.
Return Values: Discount percentage and net payable amount.
Main Program:
Prompts user for the
shopping_amount
.Calls the
calculate_discount
function to compute the discount and net payable amount.Prints the results.
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.
Here is a Python program to calculate the discount and net payable amount based on the provided criteria using a userdefined function:
def calculate_discount(shopping_amount, is_member):
"""
This function calculates the discount and the net payable amount.
:param shopping_amount: Total shopping amount
:param is_member: Boolean indicating if the customer is a store member
:return: Net payable amount
"""
discount = 0
if shopping_amount >= 2000:
discount = 0.10
elif shopping_amount >= 1000:
discount = 0.08
elif shopping_amount >= 500:
discount = 0.05
if is_member:
discount += 0.05
discounted_amount = shopping_amount * discount
net_payable_amount = shopping_amount  discounted_amount
return net_payable_amount
# Example Usage
amount = float(input("Enter the shopping amount: "))
member_status = input("Is the customer a member (yes/no)? ").strip().lower()
if member_status == 'yes':
is_member = True
else:
is_member = False
net_amount = calculate_discount(amount, is_member)
print(f"Net Payable Amount: {net_amount:.2f}")
Explanation:
Function Definition:
calculate_discount
: This function calculates the net payable amount after applying applicable discounts.Parameters:
shopping_amount
: The total shopping amount.is_member
: Boolean indicating whether the customer is a store member.
Logic:
Based on the shopping amount and whether the customer is a member, it calculates the discount.
It then returns the net payable amount after discount.
User Inputs:
amount
: Input for the total shopping amount.member_status
: Input to check if the customer is a member.
Calling the function and displaying the result:
Pass the inputs to the
calculate_discount
function.Print the net payable amount formatted to 2 decimal places.
'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 threeletter 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.
To create a program that helps children master two and threeletter words using English alphabets and addition of single digit numbers, you can use userdefined functions in Python. Below is an example of how you can structure such a program:
# Function to generate questions for two and threeletter words
def word_quiz():
two_letter_words = ["an", "at", "be", "he", "in", "is", "it", "me", "my", "no", "on", "we"]
three_letter_words = ["bat", "cat", "dog", "hat", "man", "mat", "net", "pen", "rat", "sun"]
print("Twoletter words quiz:")
for word in two_letter_words:
print(f"What is the next letter after '{word[0]}' to form the word '{word}'?")
answer = input("Your answer: ")
if answer == word[1]:
print("Correct!")
else:
print(f"Wrong! The correct letter is '{word[1]}'")
print("\nThreeletter words quiz:")
for word in three_letter_words:
print(f"What are the next two letters after '{word[0]}' to form the word '{word}'?")
answer = input("Your answer: ")
if answer == word[1:]:
print("Correct!")
else:
print(f"Wrong! The correct letters are '{word[1:]}'")
# Function to generate questions for addition of single digit numbers
def addition_quiz():
from random import randint
for _ in range(5):
num1 = randint(0, 9)
num2 = randint(0, 9)
print(f"What is {num1} + {num2}?")
answer = int(input("Your answer: "))
if answer == num1 + num2:
print("Correct!")
else:
print(f"Wrong! The correct answer is {num1 + num2}")
# Main function to run the quizzes
def main():
print("Welcome to the Play and Learn program!")
print("Select a quiz:")
print("1. Two and Threeletter words")
print("2. Addition of single digit numbers")
choice = int(input("Enter your choice (1 or 2): "))
if choice == 1:
word_quiz()
elif choice == 2:
addition_quiz()
else:
print("Invalid choice! Please enter 1 or 2.")
if __name__ == "__main__":
main()
Explanation
Word Quiz:
The
word_quiz
function includes lists of twoletter and threeletter words.It asks the user to input the missing letters needed to complete the words.
Addition Quiz:
The
addition_quiz
function generates random questions for adding two singledigit numbers using therandint()
function from therandom
module.
Main Function:
The
main
function provides the user with a choice to select between the word quiz and the addition quiz.
Take a look at the series below:
$1,1,2,3,5,8,13,21,34,55 \ldots$
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.
The sequence provided is an example of the Fibonacci sequence where each number is the sum of the two preceding ones. Here's how the sequence is generated:
Start with the numbers 1 and 1.
To get the next number in the series, add the two previous numbers.
Here is the stepbystep formation of the sequence:
Start: (1, 1)
$1 + 1 = 2 \rightarrow 1, 1, 2$
$1 + 2 = 3 \rightarrow 1, 1, 2, 3$
$2 + 3 = 5 \rightarrow 1, 1, 2, 3, 5$
$3 + 5 = 8 \rightarrow 1, 1, 2, 3, 5, 8$
$5 + 8 = 13 \rightarrow 1, 1, 2, 3, 5, 8, 13$
$8 + 13 = 21 \rightarrow 1, 1, 2, 3, 5, 8, 13, 21$
$13 + 21 = 34 \rightarrow 1, 1, 2, 3, 5, 8, 13, 21, 34$
$21 + 34 = 55 \rightarrow 1, 1, 2, 3, 5, 8, 13, 21, 34, 55$
Important Points:
This pattern is known as the Fibonacci sequence.
Each number is the sum of the previous two numbers.
The sequence is often started with 0 and 1 in some variations, but the principle remains the same.
By continuing this process, you can generate as many Fibonacci numbers as needed.
Create a menu driven program using user defined functions to implement a calculator that performs the following:
a) Basic arithmetic operations(+,,*,/)
b) $\log _{10}(\mathrm{x}), \sin (\mathrm{x}), \cos (\mathrm{x})$
Here’s a basic menudriven calculator program implemented using userdefined functions in Python:
import math
# Function to add two numbers
def add(a, b):
return a + b
# Function to subtract two numbers
def subtract(a, b):
return a  b
# Function to multiply two numbers
def multiply(a, b):
return a * b
# Function to divide two numbers
def divide(a, b):
if b == 0:
return "Division by zero is undefined"
return a / b
# Function to calculate log base 10
def log10(x):
return math.log10(x)
# Function to calculate sine of an angle in radians
def sine(x):
return math.sin(x)
# Function to calculate cosine of an angle in radians
def cosine(x):
return math.cos(x)
# Menu driven program
def calculator():
while True:
print("\nMenu:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. log10")
print("6. sin")
print("7. cos")
print("8. Exit")
choice = int(input("Select operation: "))
if choice == 8:
print("Exiting...")
break
if choice in [1, 2, 3, 4]:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if choice == 1:
print("Result: ", add(a, b))
elif choice == 2:
print("Result: ", subtract(a, b))
elif choice == 3:
print("Result: ", multiply(a, b))
elif choice == 4:
print("Result: ", divide(a, b))
elif choice in [5, 6, 7]:
x = float(input("Enter the number/angle in radians: "))
if choice == 5:
print("Result: ", log10(x))
elif choice == 6:
print("Result: ", sine(x))
elif choice == 7:
print("Result: ", cosine(x))
else:
print("Invalid choice, please try again.")
# Run the calculator program
calculator()
Explanation:
Basic Arithmetic Functions:
add(a, b)
,subtract(a, b)
,multiply(a, b)
, anddivide(a, b)
.Mathematical Functions:
log10(x)
,sine(x)
, andcosine(x)
use themath
module to perform these operations.The Menu Driven Program interacts with the user to select an operation, takes input numbers, performs the operations, and displays results.
The program will run in a loop until the user selects the option to exit.
Write a program to check the divisibility of a number by 7 that is passed as a parameter to the user defined function.
Here is a simple Python program that defines a function to check if a number is divisible by 7:
# Function to check if a number is divisible by 7
def is_divisible_by_7(number):
if number % 7 == 0:
return True
else:
return False
# Input from the user
num = int(input("Enter a number to check divisibility by 7: "))
# Calling the function and displaying the result
if is_divisible_by_7(num):
print(f"{num} is divisible by 7.")
else:
print(f"{num} is not divisible by 7.")
Explanation:
Function Definition: We define a function
is_divisible_by_7
that takes one parameter,number
.Divisibility Check: Inside the function, the modulus operator
%
is used to check if the remainder whennumber
is divided by 7 is zero.User Input: The program prompts the user to enter a number.
Function Call: The
is_divisible_by_7
function is called with the user input, and the result is printed.
Write a program that uses a user defined function that accepts name and gender (as $\mathrm{M}$ for Male, $\mathrm{F}$ for Female) and prefixes $\mathrm{Mr} / \mathrm{Ms}$ on the basis of the gender.
Here is a Python program that uses a userdefined function to prefix "Mr" or "Ms" based on gender:
# Userdefined function to prefix Mr or Ms based on gender
def prefix_name(name, gender):
if gender == 'M':
prefix = "Mr"
elif gender == 'F':
prefix = "Ms"
else:
prefix = ""
return f"{prefix} {name}"
# Accepting user input for name and gender
name = input("Enter your name: ")
gender = input("Enter your gender (M/F): ")
# Calling the function and displaying the result
full_name = prefix_name(name, gender)
print(full_name)
Key Points:
The function
prefix_name
accepts two parameters:name
andgender
.It checks the gender and assigns the appropriate prefix.
The name is returned with the prefix appended.
Sample Output:
Enter your name: John
Enter your gender (M/F): M
Mr John
Enter your name: Jane
Enter your gender (M/F): F
Ms Jane
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 $\mathrm{a}, \mathrm{b}, \mathrm{c}$ then calculate determinant as $\mathrm{b}^{2}$4ac. Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result.
Here's a program that defines a userdefined function to calculate and check the determinant of a quadratic equation. The function accepts the coefficients (a), (b), and (c), calculates the determinant, and checks if the determinant is positive, zero, or negative.
# Program to calculate the determinant of a quadratic equation
def calculate_determinant(a, b, c):
"""
Function to calculate the determinant of a quadratic equation
with coefficients a, b, and c.
"""
determinant = b**2  4*a*c
return determinant
def check_determinant(determinant):
"""
Function to check if the determinant is positive, zero, or negative,
and print the appropriate result.
"""
if determinant > 0:
print("The determinant is positive. The quadratic equation has two distinct real roots.")
elif determinant == 0:
print("The determinant is zero. The quadratic equation has one real root.")
else:
print("The determinant is negative. The quadratic equation has complex roots.")
# Accept coefficients of the quadratic equation from the user
a = float(input("Enter the coefficient a: "))
b = float(input("Enter the coefficient b: "))
c = float(input("Enter the coefficient c: "))
# Calculate the determinant
det = calculate_determinant(a, b, c)
# Check and print the result
check_determinant(det)
Explanation:
Function
calculate_determinant(a, b, c)
:This function calculates the determinant of the quadratic equation using the formula $\text{determinant} = b^2  4ac$.
It returns the calculated determinant.
Function
check_determinant(determinant)
:This function checks if the given determinant is positive, zero, or negative.
It prints the appropriate message based on the value of the determinant.
Main Program:
The program accepts the coefficients (a), (b), and (c) as input from the user.
It calls
calculate_determinant(a, b, c)
to calculate the determinant.It then calls
check_determinant(det)
to check and print the result.
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)
Here's a Python program that uses the random
module to select a random winner from the token IDs ranging from 1 to 600:
import random
def select_winner():
# Define the range of token IDs
token_ids = range(1, 601)
# Select a random token ID
winner = random.choice(token_ids)
# Announce the winner
print(f"The lucky draw winner is token ID: {winner}")
# Call the function to select and announce the winner
select_winner()
In this program:
The range
1 to 600
is created usingrange(1, 601)
.The
random.choice()
function is used to select a random token ID from this range.The selected winner is then printed as the output.
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: $\mathrm{CI}=\mathrm{P} *(1+\mathrm{r} / \mathrm{n})^{\mathrm{nt}}$ )
Below is a Python program that implements a userdefined function to calculate and display compound interest:
# Program to calculate and display compound interest
def calculate_compound_interest(P, r, t, n):
"""
Calculate the compound interest based on the given parameters.
P: Principal amount
r: Annual interest rate (in decimal form)
t: Time the money is invested for (in years)
n: Number of times the interest is compounded per year
"""
CI = P * (1 + r / n) ** (n * t)
return CI
# Taking user inputs for the parameters
principal = float(input("Enter the Principal amount: "))
rate = float(input("Enter the annual interest rate (e.g., for 5% enter 0.05): "))
time = float(input("Enter the time in years: "))
compoundings_per_year = int(input("Enter the number of times the interest is compounded per year: "))
# Calculate the compound interest
compound_interest = calculate_compound_interest(principal, rate, time, compoundings_per_year)
# Display the result
print(f"The Compound Interest is: {compound_interest:.2f}")
Explanation:
The function
calculate_compound_interest
takes four parameters: Principal amount (P), annual interest rate (r), time in years (t), and the number of times the interest is compounded per year (n).It then calculates the compound interest using the formula provided and returns the computed value.
The user is prompted to enter the values for principal, rate, time, and the number of compoundings per year.
The calculated compound interest is then displayed to the user.
Make sure to test the code with different inputs to verify its correctness.
Write a program that has a user defined function NOTES 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 reformed in place of number 2 , otherwise the same order is returned.
Here is a simple Python program that includes a userdefined function called swap_if_needed
to accept 2 numbers as parameters, swap them if the first number is less than the second number, and return them in the appropriate order:
# Function to accept 2 numbers and swap them if the first is less than the second
def swap_if_needed(num1, num2):
if num1 < num2:
# Swapping the numbers
return num2, num1
else:
# Returning the numbers in the same order
return num1, num2
# Taking input from the user
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))
# Calling the function and storing the result
result1, result2 = swap_if_needed(number1, number2)
# Displaying the result
print("After swap (if needed):")
print("First Number:", result1)
print("Second Number:", result2)
Explanation:
The function
swap_if_needed
checks ifnum1
is less thannum2
.If the condition is true, it swaps the numbers and returns them.
If the condition is false, it returns the numbers in the same order.
The user is prompted to input two numbers.
The function is called with these user inputs, and the returned values (in the appropriate order) are stored in
result1
andresult2
.Finally, the results are printed.
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.
Below is an example of a Python program that contains userdefined functions to calculate the area, perimeter, or surface area for various shapes such as a square, rectangle, triangle, circle, and cylinder:
# Create a module shapes_calculations.py that contains all the functions
# Save this file as shapes_calculations.py
"""
This module contains functions to calculate area, perimeter,
or surface area for various shapes.
"""
# Function to calculate the area and perimeter of a square
def square(side):
area = side ** 2
perimeter = 4 * side
return area, perimeter
# Function to calculate the area and perimeter of a rectangle
def rectangle(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter
# Function to calculate the area and perimeter of a triangle
def triangle(base, height):
area = 0.5 * base * height
# perimeter calculation is not accurate without all sides
perimeter = "Perimeter requires all three sides"
return area, perimeter
# Function to calculate the area and perimeter of a circle
def circle(radius):
area = 3.14 * radius ** 2 # Alternatively, use math.pi for precise value
circumference = 2 * 3.14 * radius # Alternatively, use math.pi for precise value
return area, circumference
# Function to calculate the surface area and volume of a cylinder
def cylinder(radius, height):
surface_area = 2 * 3.14 * radius * (radius + height) # Alternatively, use math.pi for precise value
volume = 3.14 * radius ** 2 * height # Alternatively, use math.pi for precise value
return surface_area, volume
# Main program to use the above module
if __name__ == "__main__":
import shapes_calculations as sc
# Display options
print("Select the shape to calculate area and perimeter/surface area:")
print("1. Square")
print("2. Rectangle")
print("3. Triangle")
print("4. Circle")
print("5. Cylinder")
# Get the user's choice
choice = int(input("Enter your choice (15): "))
if choice == 1:
side = float(input("Enter the side length of the square: "))
area, perimeter = sc.square(side)
print(f"Area of the square: {area}")
print(f"Perimeter of the square: {perimeter}")
elif choice == 2:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area, perimeter = sc.rectangle(length, width)
print(f"Area of the rectangle: {area}")
print(f"Perimeter of the rectangle: {perimeter}")
elif choice == 3:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area, perimeter = sc.triangle(base, height)
print(f"Area of the triangle: {area}")
print(f"Perimeter of the triangle: {perimeter} (requires all three sides)")
elif choice == 4:
radius = float(input("Enter the radius of the circle: "))
area, circumference = sc.circle(radius)
print(f"Area of the circle: {area}")
print(f"Circumference of the circle: {circumference}")
elif choice == 5:
radius = float(input("Enter the radius of the cylinder: "))
height = float(input("Enter the height of the cylinder: "))
surface_area, volume = sc.cylinder(radius, height)
print(f"Surface area of the cylinder: {surface_area}")
print(f"Volume of the cylinder: {volume}")
else:
print("Invalid choice!")
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  Take it seriously. 
Here's a Python program to create a GK quiz with five random questions. It includes userdefined functions for calculating the score and providing remarks based on the score.
import random
# Function to ask questions and return score
def score():
questions = {
"What is the capital of France?": "Paris",
"In which year did World War I begin?": "1914",
"What is the largest planet in our solar system?": "Jupiter",
"Who wrote 'Romeo and Juliet'?": "Shakespeare",
"What is the chemical symbol for water?": "H2O"
}
# Shuffle and get the first 5 questions
selected_questions = random.sample(list(questions.items()), 5)
correct_answers = 0
for question, answer in selected_questions:
user_answer = input(question + " ")
if user_answer.strip().lower() == answer.lower():
correct_answers += 1
return correct_answers
# Function to provide remarks based on score
def remark(scorevalue):
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 "Take it seriously."
# Main program execution
final_score = score()
print(f"Your score is: {final_score}/5")
print(remark(final_score))
How It Works:
score()
Function: This function contains a dictionary of five questions and their correct answers. It selects 5 random questions, prompts the user for answers, and calculates the number of correct responses.remark(scorevalue)
Function: Based on the input score, it returns an appropriate message.Main Execution: The program calculates the score and prints both the score and the remark.
Key Points:
Randomization: The
random.sample
function ensures that different questions are asked each time the quiz is taken.Input Matching: User inputs are compared to the correct answers in a caseinsensitive manner.
Structured Output: The score and corresponding remarks are displayed at the end.
💡 Have more questions?
Ask Chatterbot AI