Loading...
Please wait while we prepare your content
Please wait while we prepare your content
Solutions for Computer Science, Class 11, CBSE
Assertion (A): The random module is a built-in module to generate pseudorandom variables.
Reasoning (R): The randrange() function is used to generate a random number between the specified range in its parameter.
Both A and R are true but R is not the correct explanation of A.
Explanation
The random
module is a built-in module used to generate pseudorandom floating point values. The randrange()
method generates a random integer number between its lower and upper argument.
Assertion (A): The randint() method returns an integer from the specified range.
Reasoning (R): The syntax for randint() is: random.randint (start:stop)
A is true but R is false.
Explanation
The randint()
method generates a random integer number from the specified range. The syntax for randint()
is random.randint(a, b)
, where a is the lower bound and b is the upper bound.
Assertion (A): The function ceil() is a commonly used function from math module.
Reasoning (R): The ceil() function takes a numeric argument and returns the smallest integer that is greater than or equal to the argument.
Both A and R are true and R is the correct explanation of A.
Explanation
The function ceil()
is a commonly used function from math
module. The ceil()
function takes a numeric argument and returns the closest integer that is greater than or equal to the argument. The syntax is math.ceil(x)
.
Assertion (A): Some of the real-life applications of random module include CAPTCHA, OTP generation, automatic password generator and auto-filling, etc.
Reasoning (R): To import a random module, use:
import random
from random import*
Both A and R are true but R is not the correct explanation of A.
Explanation
The random module is used in various real-life applications like CAPTCHA, OTP generation, automatic password generation, and auto-filling forms. The statement to import random module is
import random
from random import *
Assertion (A): The median() method returns the middle value of numeric data in a list.
Reasoning (R): The math module contains both mathematical and statistical functions.
A is true but R is false.
Explanation
The median()
function returns the middle value of numeric data in a list. This function finds the centre value, and if the data set has an even number of values, it averages the two middle items. The math
module contains mathematical functions. The statistics
module contains statistical functions.
Assertion (A): Python has a built-in math module that you can use for mathematical tasks.
Reasoning (R): The mean() method calculates the arithmetic mean of the numbers in a list using math module.
A is true but R is false.
Explanation
Python has a built-in math
module that we can use for mathematical tasks. The mean()
method calculates the arithmetic mean of the numbers in a list using statistics
module.
Assertion (A): Python modules are .py files that contain Python code.
Reasoning (R): The import statement allows you to import all the functions from a module into your code.
Both A and R are true and R is the correct explanation of A.
Explanation
A module is created as a python (.py) file containing a collection of function definitions, classes and variables. The import statement can be used to import a module. It is the simplest and most common way to use modules in our code. It provides access to all attributes (like variables, constants etc) and methods or functions present in the module.
Assertion (A): The output of print(math.factorial(4.5)) shall generate an error.
Reasoning (R): This factorial() function belongs to the statistics module in Python.
A is true but R is false.
Explanation
The math.factorial()
function in Python requires an integer argument, so using 4.5 as an argument will generate an error. The factorial()
function belongs to the math
module.
-25
Reason — The math.floor()
function returns the largest integer less than or equal to the given number. For math.floor(-24.6)
, the result is -25, which is the largest integer less than -24.6.
DomainError
Reason — The math.pow()
function computes the power of a number. In math.pow(0, -4)
, the expression represents 0 −4, which results in DomainError.
38.5
Reason — The statistics.median()
function calculates the median of a list of numbers. For the list [11, 22, 33, 44, 55, 66], which contains an even number of elements, the median is the average of the two middle numbers. The two middle numbers are 33 and 44, so the median is (33 + 44) / 2 = 38.5.
2.5
Reason — The statistics.mode()
function returns the most frequent value in the list. In the list [2.5, 3.2, 3.3, 2.5, 8.1, 9.9, 2.5, 5.1], the value 2.5 appears most frequently (three times), so it is the mode.
10.5
Reason — The statistics.mean()
function calculates the arithmetic mean of the numbers in the list. For the list [2, 15, 6, 19], the mean is computed as (2 + 15 + 6 + 19)/4 = 42/4 = 10.5.
import random
Reason — To use functions from the random
library in Python, we must include the line import random
at the beginning of code.
2
Reason — The statistics.mode()
function returns the most frequently occurring value in a list. In the list [2, 5, 3, 2, 8, 3, 9, 4, 2, 5, 6], the value 2 appears the most times (three occurrences), so 2 is the mode.
# days.py
def calculate(total_days):
months = total_days // 30
remaining_days = total_days % 30
return months, remaining_days
# calculate.py
from days import calculate
total_days = int(input("Enter the total number of days: "))
months, remaining_days = calculate(total_days)
print("Total number of months:", months)
print("Remaining days:", remaining_days)
Enter the total number of days: 100
Total number of months: 3
Remaining days: 10
A module is a file consisting of a Python code that can define functions, classes and variables related to a particular task. A module allows us to organize our code by grouping related codes, which makes the code easier to understand and use. The file extension of a Python module is ".py".
To reuse the functions defined in a module in our program, we can import the module into our program using the import statement. Once imported, we can call the functions from the module using the module name followed by a dot (.) and the function name.
We can import objects from a module in 3 ways :
import
statement can be used to import a module. The syntax is import <module_name>
.
Python's from
statement is used to import specific attributes or individual objects from a module into the current module or namespace. The syntax is from <module_name> import <function_name(s)>
.
import *
statement can be used to import all names from a module into the current calling (namespace) module. The syntax is from <module_name> import *
.
(a) import math
— This statement is used to import entire module math
. All the functions are imported in a new namespace setup with same name as that of the module math
. To access one of the functions, we have to specify the name of the module and the name of the function, separated by a dot. This format is called dot notation.
For example,
import math
print(math.sqrt(16))
(b) from math import *
— This statement is used to import all the items from module math
in the current namespace. We can use all defined functions, variables etc from math module, without having to prefix module's name to imported item name.
For example,
from math import *
print(sqrt(16))
The math
module in Python provides access to mathematical functions like trigonometry, logarithms, factorials, and constants such as π and e. It simplifies complex calculations, offers functions for rounding, power, and square roots, and supports number-theoretic operations. This module is widely used in scientific computing, data analysis, and algorithm development, making mathematical operations more efficient and precise.
When we access a variable from within a program or function, Python follows name resolution rule, also known as LEGB rule. When Python encounters a name (variable or function), it first searches the local scope (L), then the enclosing scope (E), then the global scope (G), and finally the built-in scope (B).
A program having multiple functions is considered better designed than a program without any functions due to the following reasons:
# calculate_area.py
def area(base, height):
area = (1/2) * base * height
return area
# triangle.py
from calculate_area import area
base_value = int(input("Enter the base value: "))
height_value = int(input("Enter the height value: "))
triangle_area = calculate_area(base_value, height_value)
print("Area of the triangle:", triangle_area)
Enter the base value: 10
Enter the height value: 20
Area of the triangle: 100.0
def main():
r = input('enter any radius:') #Error 2
a = pi * maths.pow(r, 2) #Error 3
Print("Area = "+a) #Error 4
Main() #Error 5
Error 1 — The import math
statement is missing.
Error 2 — The input()
function returns a string, but the radius should be a floating-point number, so added float()
function to convert it.
Error 3 — The maths
module is incorrect, so changed it to math
and added math.
before pi
to correctly reference the mathematical constant and function.
Error 4 — The Print
function is incorrect, so changed it to print
. Instead of using +
operator, a comma (,) is used to print the string followed by value of a
.
Error 5 — The function name Main
is incorrect, so changed it to main()
to match the function definition and the indentation was corrected to ensure proper execution.
The corrected code is as follows:
import math
def main():
r = float(input('enter any radius:'))
a = math.pi * math.pow(r, 2)
print("Area = ", a)
main()
The math.ceil(x)
returns the smallest integer greater than or equal to x. In other words, it rounds up to the nearest integer. For 89.7, the smallest integer greater than 89.7 is 90. While math.floor(x)
returns the largest integer less than or equal to x. In other words, it rounds down to the nearest integer. For 89.7, the largest integer less than 89.7 is 89.
To generate random numbers between 1 and 5, we should use the randint()
function from the random
module. The randint(a, b)
function accepts two parameters, a and b, as the lowest and highest number, returns a number N in the inclusive range [a, b], which signifies a <= N <= b. This function generates a random integer number between two given numbers. In contrast, the random()
function generates a random floating point number from 0 to 1.
import statement | from import statement |
---|---|
It imports entire module. | It imports single, multiple or all objects from a module. |
To access one of the functions, we have to specify the name of the module and the name of the function, separated by a dot. This format is called dot notation. The syntax is : <module-name>.<function-name>() . | To access functions, there is no need to prefix module's name to imported item name. The syntax is : <function-name> . |
Imports all its items in a new namespace with the same name as of the module. | Imports specified items from the module into the current namespace. |
This approach does not cause any problems. | This approach can lead to namespace pollution and name clashes if multiple modules import items with the same name. |
For example:import math print(math.pi) print(math.sqrt(25)) | For example: from math import pi, sqrt print(pi) print(sqrt(25)) |
Using from module_name import *
is not recommended because it can lead to namespace pollution, reduce code readability, introduce unnecessary imports, and increase the risk of errors due to unintended or conflicting names.
Write a function to calculate volume of a box with appropriate default values for its parameters. Your function should have the following input parameters:
(a) Length of box
(b) Width of box
(c) Height of box
Test it by writing the complete program to invoke it.
def calculate_volume(length = 5, width = 3, height = 2):
return length * width * height
default_volume = calculate_volume()
print("Volume of the box: ", default_volume)
v = calculate_volume(10, 7, 15)
print("Volume of the box: ", v)
a = calculate_volume(length = 23, height = 6)
print("Volume of the box: ", a)
b = calculate_volume(width = 19)
print("Volume of the box: ", b)
Volume of the box: 30
Volume of the box: 1050
Volume of the box: 414
Volume of the box: 190
Consider the amount of donations received by a charitable organization given as under:
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
Now write a Python program to calculate the average amount obtained and median of the above data.
import statistics
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
average_amount = statistics.mean(donations)
median_amount = statistics.median(donations)
print("Average amount:", average_amount)
print("Median amount:", median_amount)
Average amount: 477.75
Median amount: 500.0
Define a function which accepts n as an argument and prints Fibonacci series till n.
def print_fibonacci(n):
a, b = 0, 1
while a <= n:
print(a, end=' ')
a, b = b, a + b
n = int(input("Enter a number: "))
print_fibonacci(n)
Enter a number: 10
0 1 1 2 3 5 8
Consider the temperature given below for the month of June in North India. Calculate the average temperature and median value. This temperature gets dipped with a variation of 20°C in the month of December. Write a Python program to calculate the changed median value and average temperature.
Location | Temperature (in °C) |
---|---|
Delhi | 41 |
Shimla | 32 |
Chandigarh | 43 |
Rohtak | 40 |
Srinagar | 28 |
Sri Ganganagar | 45 |
import statistics
temp_jun = [41, 32, 43, 40, 28, 45]
avg_jun = statistics.mean(temp_jun)
median_jun = statistics.median(temp_jun)
temp_dec = []
for temp in temp_jun:
temp_dec.append(temp - 20)
avg_dec = statistics.mean(temp_dec)
median_dec = statistics.median(temp_dec)
print("June - Average Temperature:", avg_jun)
print("June - Median Temperature:", median_jun)
print("December - Average Temperature:", avg_dec)
print("December - Median Temperature:", median_dec)
June - Average Temperature: 38.166666666666664
June - Median Temperature: 40.5
December - Average Temperature: 18.166666666666668
December - Median Temperature: 20.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)
import math
def arithmetic_operations():
print("Select operation:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result:", num1 + num2)
elif choice == '2':
print("Result:", num1 - num2)
elif choice == '3':
print("Result:", num1 * num2)
elif choice == '4':
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid input")
def mathematical_functions():
print("Select function:")
print("1. Logarithm base 10 (log10)")
print("2. Sine (sin)")
print("3. Cosine (cos)")
choice = input("Enter choice (1/2/3): ")
if choice == '1':
num = float(input("Enter a number for log10: "))
if num > 0:
print("Result:", math.log10(num))
else:
print("Error: Logarithm is defined for positive numbers only.")
elif choice == '2':
angle = float(input("Enter the angle in degrees: "))
radians = math.radians(angle)
print("Result:", math.sin(radians))
elif choice == '3':
angle = float(input("Enter the angle in degrees: "))
radians = math.radians(angle)
print("Result:", math.cos(radians))
else:
print("Invalid input")
while True:
print("\nCalculator Menu:")
print("1. Basic Arithmetic Operations")
print("2. Mathematical Functions")
print("3. Exit")
choice = input("Enter choice (1/2/3): ")
if choice == '1':
arithmetic_operations()
elif choice == '2':
mathematical_functions()
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid input. Please choose again.")
Calculator Menu:
1. Basic Arithmetic Operations
2. Mathematical Functions
3. Exit
Enter choice (1/2/3): 1
Select operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter choice (1/2/3/4): 2
Enter first number: 34
Enter second number: 7
Result: 27.0
Calculator Menu:
1. Basic Arithmetic Operations
2. Mathematical Functions
3. Exit
Enter choice (1/2/3): 2
Select function:
1. Logarithm base 10 (log10)
2. Sine (sin)
3. Cosine (cos)
Enter choice (1/2/3): 1
Enter a number for log10: 24
Result: 1.380211241711606
Calculator Menu:
1. Basic Arithmetic Operations
2. Mathematical Functions
3. Exit
Enter choice (1/2/3): 3
Exiting the program.
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 appropriate functions.
# shape_calculator.py
import math
def area_square(side):
return side * side
def perimeter_square(side):
return 4 * side
def area_rectangle(length, width):
return length * width
def perimeter_rectangle(length, width):
return 2 * (length + width)
def area_triangle(base, height):
return 0.5 * base * height
def area_circle(radius):
return math.pi * radius * radius
def perimeter_circle(radius):
return 2 * math.pi * radius
def surface_area_cylinder(radius, height):
return 2 * math.pi * radius * (radius + height)
# shape.py
from shape_calculator import (area_square, perimeter_square, area_rectangle, perimeter_rectangle,
area_triangle, area_circle, perimeter_circle, surface_area_cylinder)
while True:
print("\nShape Calculator Menu:")
print("1. Square")
print("2. Rectangle")
print("3. Triangle")
print("4. Circle")
print("5. Cylinder")
print("6. Exit")
choice = input("Enter choice (1/2/3/4/5/6): ")
if choice == '1':
print("Square:")
side = float(input("Enter the side length: "))
print("Area:", area_square(side))
print("Perimeter:", perimeter_square(side))
elif choice == '2':
print("Rectangle:")
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
print("Area:", area_rectangle(length, width))
print("Perimeter:", perimeter_rectangle(length, width))
elif choice == '3':
print("Triangle:")
base = float(input("Enter the base length: "))
height = float(input("Enter the height: "))
print("Area:", area_triangle(base, height))
elif choice == '4':
print("Circle:")
radius = float(input("Enter the radius: "))
print("Area:", area_circle(radius))
print("Circumference:", perimeter_circle(radius))
elif choice == '5':
print("Cylinder:")
radius = float(input("Enter the radius: "))
height = float(input("Enter the height: "))
print("Surface Area:", surface_area_cylinder(radius, height))
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid input. Please choose again.")
Shape Calculator Menu:
1. Square
2. Rectangle
3. Triangle
4. Circle
5. Cylinder
6. Exit
Enter choice (1/2/3/4/5/6): 1
Square:
Enter the side length: 4
Area: 16.0
Perimeter: 16.0
Shape Calculator Menu:
1. Square
2. Rectangle
3. Triangle
4. Circle
5. Cylinder
6. Exit
Enter choice (1/2/3/4/5/6): 4
Circle:
Enter the radius: 12
Area: 452.3893421169302
Circumference: 75.39822368615503
Shape Calculator Menu:
1. Square
2. Rectangle
3. Triangle
4. Circle
5. Cylinder
6. Exit
Enter choice (1/2/3/4/5/6): 6
Exiting the program.
False
Reason — A module must be imported before it can be used in a Python program. Without importing the module, the functions, classes, or variables defined within it cannot be accessed, leading to errors in the program.
True
Reason — Each time the randint()
function from the random
module is used, it produces a different random integer within the specified range. This is because randint()
generates a new random value each time it is called.