Try it here
Subscribe
Python module

Python - Random Module

python_-_random_module

Functions in the random module depend on a pseudo-random number generator function random(), which generates a random float number between 0.0 and 1.0.

random.random():

Generates a random float number between 0.0 to 1.0. The function doesn't need any arguments.

>>> import random
>>> random.random()
0.7452470696730384
>>> 

random.randint():

Returns a random integer between the specified integers.

>>> random.randint(1,100)
80
>>> 

random.randrange():

Returns a randomly selected element from the range created by the start, stop and step arguments. The value of start is 0 by default. Similarly, the value of step is 1 by default.

>>> random.randrange(1,5)
2
>>> random.randrange(1,5,2)
3
>>> random.randrange(1,50,5)
46
>>>

random.choice():

Returns a randomly selected element from a non-empty sequence. An empty sequence as argument raises an IndexError.

>>> random.choice("dEexams")
'E'
>>> random.choice([1,2,3,4,5])
3
>>> 
>>> random.choice([])
Traceback (most recent call last):
  File "", line 1, in 
    random.choice([])
  File "D:\PythonInstall\lib\random.py", line 261, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
>>> 

random.shuffle():

This functions randomly reorders the elements in a list.

>>> mylist=[n for n in range(20,40)]
>>> mylist
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
>>> random.shuffle(mylist)
>>> mylist
[20, 33, 37, 26, 35, 29, 36, 21, 30, 27, 22, 31, 28, 39, 38, 25, 34, 23, 32, 24]
>>> 

Writer profile pic

Sneha on Apr 27, 2020 at 12:04 am


This article is contributed by Sneha. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.