Class 12: Python Random Inbuilt Functions

Introduction:
Python defines a set of functions that are used to generate or manipulate random numbers. This particular type of functions are used in a lot of computer games involving throwing of dice, picking a number or flipping a coin, shuffling deck of playing cards etc, lotteries, Recaptcha(login forms) or any application requiring random number generation.

In python random numbers are not enabled implicitly. Therefore we need to invoke random module explicitly in order to generate random numbers.

The various functions associated wiht the random module are as follows:

random.random():
Generates a random float number between 0.0 to 1.0. The function doesn’t need any arguments.
Example:

import random
print(random.random())
#Output
0.645173684807533

random.randint():
Returns a random integer between the specified integers.
Example:

import random
print(random.randint(1,100))
#Output
95

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.
Example:

import random
print(random.randrange(1,10))
print(random.randrange(1,10,2))
print(random.randrange(0,101,10))
#Output
1
5
0
>>> 

random.choice():
Returns a randomly selected element from a non-empty sequence. An empty sequence as argument raises an IndexError.
Example:

import random
print(random.choice('computer'))
print(random.choice([12,23,45,67,65,43]))
print(random.choice((12,23,45,67,65,43)))
#Output
u
12
67
>>> 

random.shuffle():
This functions randomly reorders the elements in a list.
Example:

import random
numbers=[12,23,45,67,65,43]
random.shuffle(numbers)
print(numbers)
Output
[43, 12, 23, 67, 65, 45]
>>> 

Random.uniform():
This function returns a random floating number between two numbers.
Example:

import random
print(random.uniform(1,100))
print(random.uniform(250,350))
#Output
15.167584559148047
314.32756456453296
>>> 

Python String Inbuilt Function       Python Math Inbuilt Function       Python Data and Time Inbuilt Functions       Python Random Module Functions

Number Of Visitors

0270413