0% found this document useful (0 votes)
7 views33 pages

Unit-8 Introduction To Python Modules

This document provides an overview of Python modules, including definitions, functions, and examples related to the math and statistics modules. It includes fill-in-the-blank questions, true/false statements, multiple-choice questions, assertions with reasoning, and explanations of various Python functionalities. The final section poses questions about Python libraries and a practical exercise involving module creation.

Uploaded by

krishnapriyan444
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views33 pages

Unit-8 Introduction To Python Modules

This document provides an overview of Python modules, including definitions, functions, and examples related to the math and statistics modules. It includes fill-in-the-blank questions, true/false statements, multiple-choice questions, assertions with reasoning, and explanations of various Python functionalities. The final section poses questions about Python libraries and a practical exercise involving module creation.

Uploaded by

krishnapriyan444
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

GRADE-XI COMPUTER SCIENCE(083)

UNIT-8 INTRODUCTION TO PYTHON MODULES

Fill in the Blanks

Question 1

A Python library is a collection of modules and packages.

Question 2

A module is a Python file that constitutes only definitions of variables,


functions and classes.

Question 3

The import statement reads a module file and makes its contents available
for use.

Question 4

math module in Python provides mathematical functions.

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

The output of the following statement: X = [Link]([2, 15, 16, 19]


=) is 13.
Question 8

To access a method/function from a module, we have to specify the name of


the function separated by a dot(.) operator.

Question 9

A module can be classified as either built-in or user-defined.

Question 10

A module constitutes two sub-components—executable statements as well


as function definitions.

Question 11

help() function is used to get all information about module, i.e., name of all
functions, variables, etc, available in that module.

State True or False

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

A function call can be made several times in a Python module.

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

A module is loaded only once regardless of the number of times it is used.

Answer

True

Reason — A module is loaded into memory only once when it is first


imported, regardless of how many times it is used or imported in a program.

Question 4

The statement to import math module is—call math.

Answer

False

Reason — The statement to import the math module in Python is import


math.

Question 5

A module is not necessarily to be imported before being used.

Answer

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.

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

fabs() returns the same number if it is a negative value.

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

[Link](x) returns a ValueError if x is a negative number.

Answer

True

Reason — The [Link](x) function in Python returns a ValueError if x is a


negative number because the square root of a negative number is not a real
number.

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

Each time we use the randint() function, it produces different results.

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.

Multiple Choice Questions

Question 1

What is the output of [Link](4.4) ?

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

What will be the output on screen after executing: print([Link](-6.4)) ?

1.​ -6.4
2.​ 6.4
3.​ 4
4.​ 6

Answer

6.4

Reason — The [Link]() function returns the absolute value of a number.


For [Link](-6.4), it returns 6.4, which is the positive magnitude of the
number.

Question 3

If a, b, c = 3, 4, 1 then what will be the value of [Link](b)*a-c?

1.​ 5.0
2.​ 5
3.​ 2
4.​ 4.0

Answer

5.0

Reason — The expression [Link](b) * a - c evaluates to 2.0 * 3 - 1,


which equals 6.0 - 1, resulting in 5.0.

Question 4

What is the value of x, if x = [Link](0) ?

1.​ 1
2.​ 0
3.​ Error
4.​ None of these

Answer

Reason — The [Link]() function returns the factorial of a


non-negative integer. By definition, the factorial of 0 is 1. Therefore,
[Link](0) returns 1.
Question 5

What is the value of x, if x = [Link](25.0) ?

1.​ (5, -5)


2.​ 5
3.​ 5.0
4.​ (5.0, -5.0)

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

What value will be returned, if x = [Link](-24.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

What value will be displayed on executing the following arithmetic


expression?

x = [Link] (0,-4)

1.​ 1
2.​ 16
3.​ DomainError
4.​ None of these

Answer

DomainError

Reason — The [Link]() function computes the power of a number. In


[Link](0, -4), the expression represents 0 −4, which results in
DomainError.

Question 8

What output will be displayed after executing the following code?

[Link]([11, 22, 33, 44, 55, 66])

1.​ 28.5
2.​ 38.5
3.​ 5.5
4.​ 6.5

Answer

38.5

Reason — The [Link]() 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.

Question 9

On executing the following code, what output will be displayed?

[Link]([2.5, 3.2, 3.3, 2.5, 8.1, 9.9, 2.5, 5.1])

1.​ 2.5
2.​ 3.2
3.​ 5.1
4.​ 8.1

Answer

2.5

Reason — The [Link]() 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.

Question 10

What will the following code display on execution?

X = [Link]([2, 15, 6, 19])

1.​ 10.5
2.​ 10.6
3.​ Error
4.​ None of these

Answer

10.5

Reason — The [Link]() 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.

Question 11

To include the use of functions which are present in the random library, we
must use the option:

1.​ import random


2.​ random.h
3.​ [Link]
4.​ [Link]

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

What will be the output of the following code:

>>> import statistics


>>> [Link]([2, 5, 3, 2, 8, 3, 9, 4, 2, 5, 6])

1.​ 2
2.​ 3
3.​ 5
4.​ 6

Answer

Reason — The [Link]() 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.

Assertions and Reasons

Question 1

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.

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.

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.

Reasoning (R): The syntax for randint() is: [Link] (start:stop)

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.

Answer

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 [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.

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.
Answer

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 [Link](x).

Question 4

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*

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.

Answer

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 *

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.

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.

Answer

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.

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.

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.

Answer

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.

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.

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.

Answer

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.

Question 8

Assertion (A): The output of print([Link](4.5)) shall generate an


error.

Reasoning (R): This factorial() function belongs to the statistics module in


Python.

1.​ Both A and R are true and R is the correct explanation of A.


2.​ Both A and R are true but R is not the correct explanation of A.
3.​ A is true but R is false.
4.​ A is false but R is true.

Answer

A is true but R is false.

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

What is a Python library? Explain with examples.

Answer

The Python library is an extensive collection of functions and modules that


help the programmer in the faster development of programs.

For example, NumPy, Pandas etc.

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

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)

Output

Enter the total number of days: 100


Total number of months: 3
Remaining days: 10

Question 3

What is a module? What is the file extension of a Python module?

Answer

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".

Question 4

How do you reuse the functions defined in a module in your program?

Answer

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.

Question 5

In how many ways can you import objects from a module?

Answer

We can import objects from a module in 3 ways :

1.​ import statement can be used to import a module. The syntax is


import <module_name>.
2.​ 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)>.
3.​ 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 *.

Question 6

How are the following two statements different from each other?

(a) import math

(b) from math import*

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,

from math import *


print(sqrt(16))

Question 7

What is the utility of math module?

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

How does Python resolve the scope of a name or identifier?

Answer

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).

Question 9

A program having multiple functions is considered better designed than a


program without any functions. Why?

Answer

A program having multiple functions is considered better designed than a


program without any functions due to the following reasons:

1.​ Modularity — Functions break the program into smaller, manageable


pieces, making it easier to understand and maintain.
2.​ Code Reusability — Once defined, functions can be reused in different
parts of the program, reducing redundancy.
3.​ Improved Debugging — Breaking down code into functions helps in
pinpointing and fixing bugs more efficiently.
4.​ Simplified Testing — Functions can be individually tested, ensuring
each part works as expected.
5.​ Enhanced Readability — Functions improve the structure of the
program, making the code cleaner and more readable.
6.​ Reduced Program Size — Functions help in reducing the size of the
program by avoiding code duplication.

Question 10

Write a module called calculate_area() that takes base and height as an


input argument and returns an area of a triangle as output. The formula
used is

Triangle Area = 1⁄2 * base * height

Answer

# calculate_area.py
def area(base, height):
area = (1/2) * base * height
return area

# [Link]
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)

Output

Enter the base value: 10


Enter the height value: 20
Area of the triangle: 100.0

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 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 = [Link] * [Link](r, 2)
print("Area = ", a)
main()
Question 12

How is [Link](89.7) different from [Link](89.7)?

Answer

The [Link](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 [Link](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.

Question 13

Out of random() and randint(), which function should we use to generate


random numbers between 1 and 5. Justify.

Answer

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.

Question 14

What is the difference between import statement and from import


statement?

Answer

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 To access functions, there


specify the name of the module and the is no need to prefix
name of the function, separated by a dot. module's name to
This format is called dot notation. The imported item name. The
syntax is : syntax is :
<module-name>.<function-name>(). <function-name>.

Imports all its items in a new namespace Imports specified items


with the same name as of the module. from the module into the
current namespace.

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.

For example:import math print([Link]) For example: from math


print([Link](25)) import pi, sqrt print(pi)
print(sqrt(25))

Question 15

Why is from import* statement not recommended for importing Python


modules in an external program?

Answer

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.
Question 16

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.

Solution

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)

Output

Volume of the box: 30


Volume of the box: 1050
Volume of the box: 414
Volume of the box: 190

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

Average amount: 477.75


Median amount: 500.0

Question 18

Write a Python program to generate a random number between 0 and 9.

Solution

import random
random_number = [Link](0, 9)
print("Random number between 0 and 9:", random_number)

Output

Random number between 0 and 9: 2

Random number between 0 and 9: 3


Question 19

Define a function which accepts n as an argument and prints Fibonacci series


till n.

Solution

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)

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.

Location Temperature (in


°C)

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

June - Average Temperature: 38.166666666666664


June - Median Temperature: 40.5
December - Average Temperature: 18.166666666666668
December - Median Temperature: 20.5

Question 21
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)

Solution

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 = [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")

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.")

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

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.

Answer

# 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 [Link] * radius * radius

def perimeter_circle(radius):
return 2 * [Link] * radius

def surface_area_cylinder(radius, height):


return 2 * [Link] * radius * (radius + height)

# [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")

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.")

Output

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.

You might also like