Python Module
A module is a logical organization of Python code. Related code are grouped into a module which makes the code easier to understand and use. Any python module is an object with different attributes which can be bind and referenced. Simply, it is a file containing a set of functions which can be included in our application. Python provide inbuilt standard modules, like math, random etc.
Math Module
The math module is a standard module in Python and is always available. To use mathematical functions under this module, you have to import the module using import math.
How to use math function
import math
math.sqrt(4)
math.sqrt()
The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
math.ceil ()
The ceil() function approximates the given number to the smallest integer, greater than or equal to the given floating point number.
>>>math.ceil(4.5867)
5
math.floor ()
The floor() function returns the largest integer less than or equal to the given number.
>>>math.floor(4.5687)
4
math.pow()
The math.pow() method receives two float arguments, raises the first to the second and returns the result. In other words, pow(2,3) is equivalent to 2**3.
>>>math.pow(2,4)
16.0
math.fabs()
math.fabs() Returns the absolute value of x
>>> import math
>>> math.fabs(-5.5)
5.5
The math module contains functions for calculating various trigonometric ratios for a given angle. The functions (sin, cos, tan, etc.) need the angle in radians as an argument.
>>> math.sin(270)
-0.1760459464712114
pi: - It is a mathematical constant, the ratio of the circumference of a circle to its diameter(3.14159...)
import math
print ("The value of pi is :", math.pi)
The value of pi is: 3.141592653589793
e: - It is a mathematical constant that returns e raised to the power x, where e=2.718281. It is the base of natural logarithms. It is also called Euler's number.
>>>print("The value of e is :", math.e)
The value of e is :2.718281828459045
Random Module
The random module provides access to functions that support many operations.Perhaps the most important thing is that it allows us to generate random numbers.
random.randint()
randint accepts two parameters: a lowest and a highest number.
import random
print (random.randint(0, 5))
This will output either 1, 2, 3, 4 or 5.
random.random() Generate random number from 0.01 to 1.
If we want a larger number, we can multiply it.
import random
print(random.random() * 100)
randrange() generate random numbers from a specified range and also allowing rooms for steps to be included.
Syntax : random.randrange(start(opt),stop,step(opt))
import random # Using randrange() to generate numbers from 0-100
print ("Random number from 0-100 is : ",end="")
print (random.randrange(100)) # Using randrange() to generate numbers from 50-100
print ("Random number from 50-100 is : ",end="")
print (random.randrange(50,100)) # Using randrange() to generate numbers from 50-100 # skipping 5 print ("Random number from 50-100 skip 5 is : ",end="")
print (random.randrange(50,100,5))
OUTPUT
Random number from 0-100 is : 27
Random number from 50-100 is : 58
Random number from 50-100 skip 5 is : 80
Statistics Module
This module provides functions for calculating mathematical statistics of numeric (Real-valued) data.
1. statistics.mean(data)
- Return the sample arithmetic mean of data which can be a sequence or iterator.The arithmetic mean is the sum of the data divided by the number of data points(AVERAGE).
import statistics
print(statistics.mean([5,3,2]))
OUTPUT
3.3333333333333335
2. statistics.median(data)
- Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised.
import statistics
print(statistics.median([5,5,4,4,3,3,2,2]))
OUTPUT
3.5
3. statistics.mode(data)
- Return the most common data point from discrete or nominal data. The mode (when it exists) is the most typical value, and is a robust measure of central location.If data is empty, or if there is not exactly one most common value, StatisticsError is raised.
import statistics
print(statistics.mode([1, 1, 2, 3, 3, 3, 3, 4]))
OUTPUT
3
Important Questions and Answers
Q1. Which of these definitions correctly describe a module?
a) Denoted by triple quotes for providing the specifications of certain program elements.
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specifications of how it is to be used.
d) Any program that reuses code.
Q2. If a,b,c=3,4,1 then what will be the value of math.sqrt(b)*a-c
a) 5.0 b) 5 c) 2 d) 4.0
Q3. What is displayed on executing print(math. fabs(-3.4))?
a) -3.4 b) 3.4 c) 3 d) -3
Q4. Which of the following is not an advantage of using modules?
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program
Q5. Which operator is used in the python to import all modules from packages?
(a) . operator (b) * operator (c) ‐> symbol (d) , operator
Q6. Write two forms of import statement.
1. import <modulename>
2. from <module> import <function>
Q7. Write a python program to calculate the square root of given number n.
import math
n=float(input('Enter n='))
ans=math.sqrt(n)
print('Square root of',n,' = ',ans)
Q8. What is the utility of Python standard library's math module and random module?
(i)
The math module is used for math related
functions that work with all number
except complex numbers.
(ii)
The Random module is used for different random
number generator functions.
Q9. Define 'module' and 'package'.
Each
python program file is a module which imports other modules like objects
and attributes. A python program
folder is a package of modules. A package can have modules or sub folders.
Q10. Which of the following is the same as math.exp(p)? Also give the explanation.
a) e ** p b) math.e ** p c) p ** e d) p ** math.e
EXPLANATION: math.e is the constant defined
in the math module
Q11. How is math.ceil (89.7) different from math.floor (89.7)?
Ceil: The function 'ceil(x)' in Python returns the smallest integer not less than x i.e., the next integer on the RHS of the number line. Hence, 'math. ceil(89.7)' will return 90whereas 'math. floor(89.7)' will return 89.
Q12. Select the possible output(s) of the following code from the given option. Also, specify the maximum and minimum value that can be assigned to variable NUM.
import random
cities = [‘Agra’, ‘Delhi’, ‘Chennai’, ‘Bhopal’]
NUM = random.randint(1,2)+1
for city in cities:
for I in range(1,NUM):
pint(city, end=‘’)
print(‘\n’)
a) Agra
|
C)
|
Agra
|
DelhiDelhi
|
|
Delhi
|
ChennaiChennaiChennai
|
|
Chennai
|
BhopalBhopalBhopalBhopal
|
|
Bhopal
|
b) Agra
|
d)
|
ChennaiChennai
|
Agra
|
|
BhopalBhopal
|
DelhiDelhi
|
|
|
Ans:
Options b and c are correct. Maximum and Minimum value assigned to NUM are 3 and2 respectively.
CASE STUDY BASED QUESTION
Q. 13 Write a python program that takes a number from 1 to 9 and stored inside the variable “guess_num”. If the user guesses wrong then the prompt appears again and the user continues to input another number repetitively until the guess is correct. On successful guess, the user will get a “Well guessed!” message, and the program will exit.Write a program to perform insertion sorting on a given list of strings, on the basis of length of strings. That is, the smallest length string should be the first string in the listand the largest length string should be the last string in the sorted list.
import random
target_num,
guess_num =random.randint(1, 10),
while target_num != guess_num:
guess_num = int(input("Guess a number between 1 and 10 \ until you get it right:"))
print(target_num)
target_num = random.randint(1, 10)
print('Congratulation both target and guess numbers are same',target_num,guess_num)
print('Well guessed!')
*************
No comments:
Post a Comment