This page contains the CBSE Computer Science with Python class 11 Unit-3 chapter 2 Functions. You can find the solutions for chapter 2 of CBSE class 11 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 11 Computer Science with Python related topic Functions questions and answers for the Exercise.
Question 1
1. The place where a variable can be used is called its
a)
area
b)
block
c)
function
d)
Scope
Answer 1
Answer: (d) Scope. A variable’s scope means the part of the program where that variable is visible and can be used.
Question 2
2. True or False
i.
Every variable has a scope associated with it.
ii.
! (p or q) is same as !p or !q
Answer 2
i) Every variable has a scope associated with it.
Answer: True
Every variable can be used only in a particular part of the program, so each variable has a scope.
ii) ! (p or q) is same as !p or !q
Answer: False
By De Morgan’s law:
not (p or q) = not p and not qSo, it is not the same as
not p or not q.Question 3
3. What will be the output of the following? Explain:
def f1 ():n = 44def f2( ):n=77print “value of n”, nprint “value of n”, nAnswer 3
For the code exactly as written here, there will be no output.
This is because the code only defines the functions
f1() and f2(), but does not call either of them. In Python, the statements inside a function are not executed at the time of definition. They are executed only when that function is called.So, just writing:
•
def f1(): ...•
def f2(): ...creates the functions, but nothing is printed on the screen.
Important point
Inside
f2(), the variable n has the value 77, and both print statements are inside f2(). Therefore, if f2() were called, the output would be:value of n 77
value of n 77
This happens because the local variable
n = 77 is used by both print statements inside f2().Final answer
•
Output for the code as given:No output
•
Reason: The functions are only defined, not called.
Question 4
4. For each of the following functions, specify the type of its output. You can assume each function is called with an appropriate argument, as specified by its docstrings.
a)
def a(x):"""x: int or float."""return x + 1b)
def b(x):"""x: int or float."""return x + 1.0c)
def c(x, y):"""x: int or float.y: int or float."""return x + yd)
def e(x, y, z):"""x: can be of any type.y: can be of any type.z: can be of any type."""return x >= y and x <= ze)
def d(x, y):"""x: can be of any type.y: can be of any type."""return x > yAnswer 4
To find the type of output of a function, we look at the kind of value returned by the
return statement. The output type depends on the expression written after return. In some functions, the type is fixed, while in some others it depends on the type of the input values.a)
def a(x): return x+1This function adds
1 to x. So, the output type depends on the type of x.•
If
x is an integer, the result will be an integer•
If
x is a float, the result will be a floatThus, the output type is the same as the type of
x.b)
def b(x): return x+1.0In this function,
1.0 is a float. Whenever a number is added to a float, the result becomes a float.So, the output type is always float.
c)
def c(x, y): return x+yThis function adds
x and y. So, the output type depends on the values passed to the function.•
If both
x and y are integers, the result will be an integer•
If one of them is a float, the result will be a float
Thus, the output can be int or float, depending on the arguments.
d)
def e(x, y, z): return x >= y and x <= zThis function checks conditions using relational and logical operators. The expression will return either True or False.
So, the output type is bool.
e)
def d(x, y): return x > yThis function compares two values. A comparison always gives a result in the form of True or False.
So, the output type is bool.
Question 5
5. Below is a transcript of a session with the Python shell. Assume the functions in previous question (Q 4) have been defined. Provide the type and value of the expressions being evaluated.
i)
a (6)
ii)
a (-5. 3)
iii)
a (a(a(6)))
iv)
c (a(1), b(1))
v)
d (“apple”, 11.1)
Answer 5
For these expressions, the functions from Question 4 are assumed to be already defined. The value of each expression is found by substituting the input into the function, and then the type is determined from the result obtained.
i)
a(6)The function
a(x) returns x + 1.So,
a(6) = 6 + 1 = 7•
Value:
7•
Type:
intii)
a(-5.3)Again,
a(x) returns x + 1.So,
a(-5.3) = -5.3 + 1 = -4.3•
Value:
-4.3•
Type:
floatiii)
a(a(a(6)))This expression applies the function
a() three times.•
First,
a(6) = 7•
Then,
a(7) = 8•
Then,
a(8) = 9So,
•
Value:
9•
Type:
intiv)
c(a(1), b(1))First evaluate the inner functions:
•
a(1) = 1 + 1 = 2•
b(1) = 1 + 1.0 = 2.0Now substitute into
c(x, y):c(2, 2.0) = 2 + 2.0 = 4.0So,
•
Value:
4.0•
Type:
floatv)
d("apple", 11.1)The function
d(x, y) returns x > y.So here the expression becomes:
"apple" > 11.1This is a comparison, so the result is a Boolean value.
•
Type:
boolIn the Python shell style used in this chapter, this evaluates to:
•
Value:
TrueThus, the answers are:
•
i) Value =
7, Type = int•
ii) Value =
-4.3, Type = float•
iii) Value =
9, Type = int•
iv) Value =
4.0, Type = float•
v) Value =
True, Type = boolQuestion 6
6. Define a function
getBiggerNumber(x,y) to take in two numbers and return the bigger of them.Answer 6
This function should compare the two given numbers and return the one that is greater. If
x is greater than y, then x should be returned. Otherwise, y should be returned. In this way, the function gives the bigger of the two numbers.Function definition
# Function to return the bigger of two numbers
def getBiggerNumber(x, y):
if x > y:
return x
else:
return y
Explanation
•
The function takes two arguments,
x and y.•
The
if statement checks whether x is greater than y.•
If the condition is true, the function returns
x.•
If the condition is false, the function returns
y.Thus, the function compares both numbers and returns the larger value.
Example
print getBiggerNumber(8, 5)
print getBiggerNumber(3, 9)
Sample Output
8
9
So, this is a simple user-defined function that uses a decision statement to find and return the bigger number.
Question 7
7. What is the difference between methods, functions & user defined functions.
Answer 7
Methods, functions, and user-defined functions are all used to perform specific tasks in a program, but they are used in slightly different ways. A function is a general block of code that performs a task, a method is linked with an object, and a user-defined function is one that is created by the programmer.
Basis
Function
Method
User Defined Function
Meaning
A function is a named block of code used to perform a task.
A method is a function that is associated with an object or data type.
A user-defined function is a function written by the programmer.
Source
It may be built-in or taken from a module.
It belongs to an object such as a string, list, etc.
It is created in the program using the
def statement.How it is called
It is called directly by its name.
It is called by using dot notation with the object name.
It is called like a normal function after it has been defined.
Example
len(name)name.upper()getBiggerNumber(8, 5)A function is used as a general term for a reusable piece of code. Some functions are already available in Python, such as
len() or type(). A method is similar, but it works with a particular object. For example, in name.upper(), the method upper() works on the string object name.A user-defined function is a function created by the programmer to solve a specific problem. It is defined using the
def keyword and usually contains a function header and a function body. This helps in reducing repetition and makes the program more organized.Thus, all three are related to performing tasks, but the main difference is in how they are created and how they are called.
Question 8
8. Open help for math module
i.
How many functions are there in the module?
ii.
Describe how square root of a value may be calculated without using a math module.
iii.
What are the two data constants available in math module.
Answer 8
This question is based on the
math module, which contains many useful mathematical functions and constants. To use the functions of this module, it must first be imported, and then its help can be viewed in the Python shell. The exercise asks three things related to this module.A common way to begin is:
import math
help(math)
The
help(math) command displays the list of functions, constants, and other details available in the module.i) How many functions are there in the module?
The math module contains many functions. The exact number may vary depending on the Python version being used. Therefore, the number is best found by opening the help of the module in the Python shell using
help(math).So, the answer is that the module has many mathematical functions, and the exact count can be checked from the help screen.
Here’s a quick overview of the number of functions/constants in Python’s
math module across versions:Python Version
Approximate Count
2.7
~42
3.2
~44
3.5
~46
3.6
~47
3.8
~50
3.9
~51
3.11
~53
3.12
~54
3.13
~55
A few notes:
To check yourself, run this in any Python version:
import math
print(len(dir(math))) # all attributes
print([x for x in dir(math) if not x.startswith('_')]) # public only
ii) Describe how square root of a value may be calculated without using a math module.
The square root of a number can be calculated without using the math module by using the power operator
**.For example:
25 ** 0.5
This gives the square root of
25, which is 5.0.This works because raising a number to the power
1/2 (or 0.5) gives its square root.So, in general:
x ** 0.5
gives the square root of
x.iii) What are the two data constants available in math module?
The two important data constants available in the math module are:
•
math.pi•
math.e•
math.pi represents the value of pi•
math.e represents the value of the natural exponential constantThese constants are commonly used in mathematical calculations.
Thus, the math module is useful because it provides many ready-made mathematical functions and important constants, which make calculations easier in Python.
Question 9
9. Generate a random number n such that
i.
0 ≤ n < 6
ii.
2 ≤ n < 37 and n is even
Answer 9
This question asks to generate random numbers using Python. For this, the
random module is used. A random number means a number chosen automatically by the computer from a given range. In this question, the value of n must satisfy the conditions given in each part.Before generating random numbers, the module should be imported.
import random
i)
0 ≤ n < 6Here, the value of
n should be greater than or equal to 0 and less than 6. So, possible values are:0, 1, 2, 3, 4, 5A suitable program is:
import random
n = random.randrange(6)
print n
Explanation
•
random.randrange(6) generates a random number starting from 0•
It stops before
6•
Therefore, the generated number can be any one of
0 to 5So, this statement satisfies the condition
0 ≤ n < 6.ii)
2 ≤ n < 37 and n is evenHere, the value of
n should:•
be greater than or equal to 2
•
be less than 37
•
be an even number
So, possible values are:
2, 4, 6, 8, ... , 36A suitable program is:
import random
n = random.randrange(2, 37, 2)
print n
Explanation
•
The first value
2 is the starting point•
37 is the stopping value, so 37 itself is not included•
The step value
2 means only every second number is chosen•
Therefore, only even numbers are generated
So, this statement generates an even random number between
2 and 36, which satisfies the condition 2 ≤ n < 37.Thus, by using the
random.randrange() function with suitable arguments, random numbers can be generated according to the required range and condition.Lab Exercise
Question 1 (Lab)
1. Write a program to ask for following as input
•
Enter your first name: Rahul
•
Enter your last name: Kumar
•
Enter your date of birth
•
Month? March
•
Day? 10
•
Year? 1992
And display following on screen
•
Rahul Kumar was born on March 10, 1992.
Answer 1 (Lab)
This program asks the user to enter the first name, last name, and date of birth separately. After taking all the inputs, it displays them together in one complete sentence. The lab exercise specifically asks for these inputs and the final display in the shown format.
A simple program is:
# Program to input name and date of birth and display it
firstName = raw_input("Enter your first name: ")
lastName = raw_input("Enter your last name: ")
print "Enter your date of birth"
month = raw_input("Month? ")
day = raw_input("Day? ")
year = raw_input("Year? ")
print firstName, lastName, "was born on", month, day + ",", year + "."
Sample Output
Enter your first name: Rahul
Enter your last name: Kumar
Enter your date of birth
Month? March
Day? 10
Year? 1992
Rahul Kumar was born on March 10, 1992.
Explanation
•
The program uses
raw_input() to accept all the values from the keyboard.•
The first name and last name are stored in separate variables.
•
The month, day, and year of birth are also stored separately.
•
After that, the
print statement joins all these values and displays one proper sentence.Thus, this program shows how to take multiple inputs, store them in variables, and display a formatted message on the screen.
Question 2 (Lab)
2. Consider the following function definition:
def intDiv (x, a):“””x: a non-negative integer argumentreturns: integer, the integer division of x divided by a.“””while x>=a:count +=1x = x-areturn countwhen we call
print intDiv (5, 3)We get an error message. Modify the code so that error does not occur.
Answer 2 (Lab)
The error occurs because the variable
count is used inside the loop before any value is assigned to it. In Python, a variable must be initialized before it is used. Since count += 1 comes before giving count an initial value, Python shows an error.To remove the error,
count should be initialized to 0 before the while loop starts.Corrected code
# Function to find integer division
def intDiv(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the integer division of x divided by a
"""
count = 0
while x >= a:
count += 1
x = x - a
return count
Example
print intDiv(5, 3)
Output
1
Explanation
•
count = 0 is used to start the counting from zero.•
As long as
x >= a, the value of a is repeatedly subtracted from x.•
Each time subtraction happens,
count is increased by 1.•
When
x becomes smaller than a, the loop stops.•
The final value of
count gives the integer division result.For
intDiv(5, 3):•
First subtraction:
5 - 3 = 2, so count = 1•
Now
2 < 3, so the loop stopsTherefore, the function returns 1.
Thus, the error is removed by initializing
count before the loop.Question 3 (Lab)
3. Write a script that asks a user for a number. Then adds 3 to that number, and then multiplies the result by 2, subtracts twice the original number, then prints the result.
Answer 3 (Lab)
This program should first take a number from the user, then perform the operations in the given order, and finally display the result. The steps are: add 3 to the number, multiply that result by 2, and then subtract twice the original number.
A simple program is:
# Program to perform the required calculation
num = int(raw_input("Enter a number: "))
result = num + 3
result = result * 2
result = result - (2 * num)
print "Result =", result
Sample Output
Enter a number: 5
Result = 6
Explanation
Suppose the user enters 5.
•
First,
3 is added: 5 + 3 = 8•
Then the result is multiplied by
2: 8 * 2 = 16•
Then twice the original number is subtracted:
16 - (2 * 5) = 16 - 10 = 6So, the final result printed is 6.
This program shows how input can be taken from the user, stored in a variable, and then used step by step in calculations. It also follows the exact sequence of operations given in the question.
Question 4 (Lab)
4. In analogy to the example, write a script that asks users for the temperature in F and prints the temperature in C. (Conversion: Celsius = (F – 32) * 5/9).
Answer 4 (Lab)
This program should ask the user to enter the temperature in Fahrenheit (F) and then convert it into Celsius (C) using the given formula:
Celsius = (F – 32) * 5 / 9
The value entered from the keyboard is taken as input, then the formula is applied, and finally the temperature in Celsius is displayed.
Program
# Program to convert temperature from Fahrenheit to Celsius
f = float(raw_input("Enter temperature in Fahrenheit: "))
c = (f - 32) * 5 / 9
print "Temperature in Celsius =", c
Sample Output
Enter temperature in Fahrenheit: 98.6
Temperature in Celsius = 37.0
Explanation
•
The program uses
raw_input() to accept the temperature from the user.•
Since temperature may contain a decimal value, the input is converted to float.
•
Then the formula
(F - 32) * 5 / 9 is used to calculate the Celsius value.•
Finally, the converted temperature is printed on the screen.
If the user enters 98.6°F, the program calculates:
•
98.6 - 32 = 66.6•
66.6 * 5 = 333.0•
333.0 / 9 = 37.0So, the result is 37.0°C.
Thus, this program shows how to take numeric input, apply a formula, and display the converted result clearly.
Question 5 (Lab)
5. Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise. You should use the % (mod) operator, not if.
Answer 5 (Lab)
This function should check whether the given number is odd or not. The question clearly says that the
% (mod) operator should be used and if should not be used. The mod operator gives the remainder after division. A number is odd if it leaves a remainder of 1 when divided by 2.Function definition
# Function to check whether a number is odd
def odd(n):
return n % 2 == 1
Explanation
•
n % 2 finds the remainder when n is divided by 2.•
If the remainder is
1, the expression n % 2 == 1 becomes True.•
If the remainder is
0, the expression becomes False.So, the function directly returns a Boolean value without using an
if statement.Example
print odd(7)
print odd(10)
Sample Output
True
False
•
7 is odd, so the function returns True.•
10 is even, so the function returns False.Thus, this is a simple function that uses the mod operator to test whether a number is odd and returns the result directly.
Question 6 (Lab)
6. Define a function
"SubtractNumber(x,y)‟ which takes in two numbers and returns the difference of the two.Answer 6 (Lab)
This function should take two numbers as input and return their difference. The difference is obtained by subtracting the second number
y from the first number x. Therefore, the function should return the value of x - y.Function definition
# Function to return the difference of two numbers
def SubtractNumber(x, y):
return x - y
Explanation
•
The function takes two arguments,
x and y.•
It performs the subtraction operation
x - y.•
The
return statement sends the result back to the place from where the function was called.Thus, this function simply finds the difference between the two given numbers.
Example
print SubtractNumber(10, 4)
print SubtractNumber(7, 12)
Sample Output
6
-5
•
In the first case,
10 - 4 = 6•
In the second case,
7 - 12 = -5So, this is a simple user-defined function that performs subtraction and returns the result.
Question 7 (Lab)
7. Write a Python function, fourthPower( ), that takes in one number and returns that value raised to the fourth power.
Answer 7 (Lab)
This function should take one number as input and return that number raised to the fourth power. Raising a number to the fourth power means multiplying the number by itself four times. For example, if the number is
2, then its fourth power is 2 × 2 × 2 × 2 = 16.A simple function is:
# Function to return the fourth power of a number
def fourthPower(x):
return x ** 4
Explanation
•
The function takes one argument,
x.•
The operator
** is used for exponentiation.•
x ** 4 means x raised to the power 4.•
The
return statement sends the result back to the calling statement.Thus, the function calculates and returns the fourth power of the given number.
Example
print fourthPower(2)
print fourthPower(3)
Sample Output
16
81
•
2 ** 4 = 16•
3 ** 4 = 81So, this is a simple user-defined function that returns the fourth power of the number passed to it.
Question 8 (Lab)
8. Write a program that takes a number and calculate and display the log, square, sin and cosine of it.
Answer 8 (Lab)
This program should take one number as input and then calculate four values based on that number:
•
logarithm
•
square
•
sine
•
cosine
To calculate log, sin, and cosine, the
math module is used. The square can be found by multiplying the number by itself or by using ** 2. The lab exercise asks for exactly these four calculations.Program
# Program to calculate log, square, sine and cosine of a number
import math
n = float(raw_input("Enter a number: "))
logValue = math.log(n)
squareValue = n ** 2
sinValue = math.sin(n)
cosValue = math.cos(n)
print "Log =", logValue
print "Square =", squareValue
print "Sin =", sinValue
print "Cosine =", cosValue
Sample Output
Enter a number: 3
Log = 1.09861228867
Square = 9.0
Sin = 0.14112000806
Cosine = -0.9899924966
Explanation
•
import math is used to access mathematical functions.•
math.log(n) gives the natural logarithm of the number.•
n ** 2 gives the square of the number.•
math.sin(n) gives the sine of the number.•
math.cos(n) gives the cosine of the number.Since the sin and cos functions in the
math module work with radians, the input number is treated as a radian value. Also, the logarithm is defined only for positive numbers, so the input should be greater than zero for math.log(n) to work properly.Thus, this program shows how one input value can be used to calculate and display several mathematical results.
Question 9 (Lab)
9 a)
Write a program, to display a tic-tac-toe board on screen, using print statement.
b)
Write a program to display a tic-tac-toe board on screen using variables, so that you do not need to write many print statements?
Answer 9 (Lab)
This question asks to display a simple tic-tac-toe board on the screen. In part (a), the board is printed directly by using print statements. In part (b), variables are used so that the same pattern can be reused, and the number of print statements can be reduced.
a) Using print statements
In this method, each line of the board is printed separately.
# Program to display a tic-tac-toe board using print statements
print " | | "
print "---+---+---"
print " | | "
print "---+---+---"
print " | | "
Output
| |
---+---+---
| |
---+---+---
| |
Explanation
•
The vertical bars
| divide the board into three columns.•
The line
---+---+--- divides the board into three rows.•
By printing these lines in the correct order, the tic-tac-toe board is formed.
b) Using variables
In this method, the repeated lines are stored in variables. This makes the program shorter and easier to understand.
# Program to display a tic-tac-toe board using variables
row = " | | "
line = "---+---+---"
print row
print line
print row
print line
print row
Output
| |
---+---+---
| |
---+---+---
| |
Explanation
•
The variable
row stores the row pattern of the board.•
The variable
line stores the separator line.•
Since the same two patterns are used again and again, keeping them in variables avoids rewriting the full text each time.
•
This makes the program simpler, shorter, and easier to modify.
Thus, both programs display the same tic-tac-toe board, but the second method is better because it uses variables and reduces repetition.
Question 10 (Lab)
10. Write a function roll_D ( ), that takes 2 parameters- the no. of sides (with default value 6) of a dice, and the number of dice to roll-and generate random roll values for each dice rolled. Print out each roll and then return one string “That‟s all”.
Example roll_D (6, 3)
4
1
6
That‟s all
Answer 10 (Lab)
This function should simulate the rolling of dice. It takes:
1.
the number of sides on the dice (with a default value of 6), and
2.
the number of dice to roll.
For each dice roll, the function should generate one random value, print it on the screen, and after all the rolls are completed, it should return the string “That’s all”. The lab exercise gives this exact requirement and sample pattern.
A simple function is:
# Function to roll dice and print each result
import random
def roll_D(sides=6, numberOfDice=1):
count = 0
while count < numberOfDice:
value = random.randint(1, sides)
print value
count += 1
return "That's all"
Example
print roll_D(6, 3)
Sample Output
4
1
6
That's all
Explanation
•
import random is used because random values are needed.•
The parameter
sides=6 means that if no value is given for the number of sides, the dice is treated as a normal 6-sided dice.•
The parameter
numberOfDice tells how many times the dice should be rolled.•
random.randint(1, sides) generates a random integer from 1 up to the given number of sides.•
The
while loop repeats until the required number of rolls is completed.•
Each random value is printed immediately.
•
After all the rolls are printed, the function returns the string “That’s all”.
Thus, this function demonstrates the use of a default argument, looping, and random number generation in a simple way.