Unit-8 Introduction To Python Modules
Unit-8 Introduction To Python Modules
Question 1
Question 2
Question 3
The import statement reads a module file and makes its contents available
for use.
Question 4
Question 5
ceil() function returns the closest integer value greater than or equal to a
floating point number.
Question 6
mode() function returns a set of data values that appear most often in a
data set.
Question 7
Question 9
Question 10
Question 11
help() function is used to get all information about module, i.e., name of all
functions, variables, etc, available in that module.
Question 1
A module line (header) is written only once at the top of the program.
Answer
True
Reason — The module line or import statement is written once at the top of
a program to include necessary modules.
Question 2
Answer
True
Reason — A function call can be made multiple times within a Python
module. Each time the function is called, the code within the function is
executed.
Question 3
Answer
True
Question 4
Answer
False
Question 5
Answer
False
Question 6
floor() returns the closest integer value less than or equal to a floating point
number.
Answer
True
Reason — The floor() function in Python returns the closest integer value
that is less than or equal to the given floating-point number.
Question 7
Answer
False
Reason — The fabs() function returns the absolute value of a number, which
means it converts any negative number to its positive equivalent.
Question 8
Answer
True
Question 9
The mean() method calculates the arithmetic mean of the numbers in a list.
Answer
True
Reason — The mean() method calculates the arithmetic mean of the
numbers in a list.
Question 10
Answer
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.
Question 1
1. 5
2. 4
3. 4.0
4. 5.0
Answer
Reason — The [Link]() function returns the smallest integer greater than
or equal to the given number. For [Link](4.4), it returns 5, which is the
smallest integer greater than 4.4.
Question 2
1. -6.4
2. 6.4
3. 4
4. 6
Answer
6.4
Question 3
1. 5.0
2. 5
3. 2
4. 4.0
Answer
5.0
Question 4
1. 1
2. 0
3. Error
4. None of these
Answer
Answer
5.0
Reason — The [Link]() function returns the square root of a number. For
[Link](25.0), the result is 5.0, which is the positive square root of 25.0.
Question 6
1. 24.6
2. -24
3. -25
4. -24.6
Answer
-25
Reason — The [Link]() function returns the largest integer less than or
equal to the given number. For [Link](-24.6), the result is -25, which is
the largest integer less than -24.6.
Question 7
x = [Link] (0,-4)
1. 1
2. 16
3. DomainError
4. None of these
Answer
DomainError
Question 8
1. 28.5
2. 38.5
3. 5.5
4. 6.5
Answer
38.5
Question 9
1. 2.5
2. 3.2
3. 5.1
4. 8.1
Answer
2.5
Question 10
1. 10.5
2. 10.6
3. Error
4. None of these
Answer
10.5
Question 11
To include the use of functions which are present in the random library, we
must use the option:
Answer
import random
Reason — To use functions from the random library in Python, we must
include the line import random at the beginning of code.
Question 12
1. 2
2. 3
3. 5
4. 6
Answer
Question 1
Answer
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.
Question 2
Assertion (A): The randint() method returns an integer from the specified
range.
Answer
Explanation
The randint() method generates a random integer number from the specified
range. The syntax for randint() is [Link](a, b), where a is the lower
bound and b is the upper bound.
Question 3
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.
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 [Link](x).
Question 4
import random
from random import*
Answer
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 *
Question 5
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.
Answer
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.
Question 6
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.
Answer
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.
Question 7
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.
Answer
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.
Question 8
Answer
Explanation
The [Link]() 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.
Question 1
Answer
Question 2
Write a module to input total number of days and find the total number of
months and remaining days and display it in another program.
Answer
# [Link]
def calculate(total_days):
months = total_days // 30
remaining_days = total_days % 30
return months, remaining_days
# [Link]
from days import calculate
Output
Question 3
Answer
Question 4
Answer
Question 5
Answer
Question 6
How are the following two statements different from each other?
Answer
(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([Link](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,
Question 7
Answer
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.
Question 8
Answer
Question 9
Answer
Question 10
Answer
# calculate_area.py
def area(base, height):
area = (1/2) * base * height
return area
# [Link]
from calculate_area import area
Output
Question 11
Rewrite the following Python code after removing all syntax error(s).
Underline the corrections done.
def main():
r = input('enter any radius:')
a = pi * [Link](r, 2)
Print("Area = "+a)
Main()
Answer
def main():
r = input('enter any radius:') #Error 2
a = pi * [Link](r, 2) #Error 3
Print("Area = "+a) #Error 4
Main() #Error 5
Error 2 — The input() function returns a string, but the radius should be a
floating-point number, so added float() function to convert it.
import math
def main():
r = float(input('enter any radius:'))
a = [Link] * [Link](r, 2)
print("Area = ", a)
main()
Question 12
Answer
Question 13
Answer
Question 14
Answer
This approach does not cause any This approach can lead to
problems. namespace pollution and
name clashes if multiple
modules import items with
the same name.
Question 15
Answer
Solution
default_volume = calculate_volume()
print("Volume of the box: ", default_volume)
v = calculate_volume(10, 7, 15)
print("Volume of the box: ", v)
b = calculate_volume(width = 19)
print("Volume of the box: ", b)
Output
Question 17
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.
Solution
import statistics
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
average_amount = [Link](donations)
median_amount = [Link](donations)
print("Average amount:", average_amount)
print("Median amount:", median_amount)
Output
Question 18
Solution
import random
random_number = [Link](0, 9)
print("Random number between 0 and 9:", random_number)
Output
Solution
def print_fibonacci(n):
a, b = 0, 1
while a <= n:
print(a, end=' ')
a, b = b, a + b
Output
Enter a number: 10
0112358
Question 20
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.
Delhi 41
Shimla 32
Chandigarh 43
Rohtak 40
Srinagar 28
Sri Ganganagar 45
Solution
import statistics
temp_jun = [41, 32, 43, 40, 28, 45]
avg_jun = [Link](temp_jun)
median_jun = [Link](temp_jun)
temp_dec = []
for temp in temp_jun:
temp_dec.append(temp - 20)
avg_dec = [Link](temp_dec)
median_dec = [Link](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)
Output
Question 21
Create a menu-driven program using user-defined functions to implement a
calculator that performs the following:
Solution
import math
def arithmetic_operations():
print("Select operation:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
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)")
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 = [Link](angle)
print("Result:", [Link](radians))
elif choice == '3':
angle = float(input("Enter the angle in degrees: "))
radians = [Link](angle)
print("Result:", [Link](radians))
else:
print("Invalid input")
while True:
print("\nCalculator Menu:")
print("1. Basic Arithmetic Operations")
print("2. Mathematical Functions")
print("3. Exit")
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.")
Output
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.
Question 22
Answer
# shape_calculator.py
import math
def area_square(side):
return side * side
def perimeter_square(side):
return 4 * side
def area_circle(radius):
return [Link] * radius * radius
def perimeter_circle(radius):
return 2 * [Link] * radius
# [Link]
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")
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.")
Output