Page 284 - Computer Science Class 11 With Functions
P. 284
Suppose we are playing a game between n players and need to randomly decide the player who will play at position
first, second, third, etc. For this purpose, we need a function that can randomly generate a value between 1 to n. The
function randint() of the random module enables us to generate a random number between a and b, both
inclusive.
>>> help(random.randint)
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
>>> random.randint(1,10)
4
Write a function call that would randomly generate 0 or 1.
The randrange(start, stop=None, step=1) function of the random module enables us to generate a
random number between start and stop, not including stop.
>>> help(random.randrange)
Help on method randrange in module random:
randrange(start, stop=None, step=1) method of random.Random instance
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
>>> random.randrange(1,11,2) # outputs any one odd number excluding 11.
5
11.1.2 statistics Module
Python module statistics enables us to compute statistical quantities like mean, median, and mode. Let us recall
the terms mean, median, and mode. Mean refers to the average value in a dataset. Median refers to the middle value
in a dataset arranged in ascending or descending order. Mode refers to the value that occurs most frequently in the
dataset. Next, let us examine some examples of the use of statistical functions:
>>> import statistics
>>> statistics.mean([5, 3, 1, 2, 4, 7, 6, 8, 10, 9])
5.5
>>> statistics.median([5, 3, 6, 8, 9, 12, 5])
6
>>> statistics.mode([5, 3, 6, 8, 9, 12, 5])
5
Of course, there are many more functions included in the statistics module, and you may find details of those
functions by invoking the help function as help(statistics).
1. What value will the following function call yield?
statistics.median([2, 4, 6, 8])
2. What value will the following function call yield?
statistics.mode([2, 4, 2, 6, 6, 2, 8])
282 Touchpad Computer Science-XI

