Low Orbit Flux Logo 2 D

Python How To Use Random

Python provides a library called random. It is used for random number generation. We are going to show you the basics of how you can use this library.

This is a pseudo-random number generator because the numbers are not really completely random. Don’t use this for security purposes because it is not truly random or secure.

The function random.random() will give you a random number each time you call it. This number depends on the value of the seed. The sequence of random numbers returned by this function will always be the same for each given seed.

Here is an example showing how you could use the random() function:


import random
random.seed(5)

random.random()
random.random()
random.random()

The output for the above code will always look like this:


0.6229016948897019
0.7417869892607294
0.7951935655656966

If we change the seed the values will change.

Python - How to Use Random - Examples

Select a random number from 0 to 1:


print(random.random())

Pick a random number from 5 to 25:


print(random.randint(5, 25))

Pick a random number from 40 to 100 but set step to 2:


print(random.randrange(40, 10, 2))

Randomly pick one of the options in a sequence like this:


print(random.choice([1, 2, 3, 4, 5]))

Pick a random sample of 4 elements from a sequence like this:


print(random.sample([1, 2, 3, 4, 5, 6, 7, 8], k=4))

You can shuffle the order of the elements in an array like this:


x = [1, 2, 3, 4, 5, 6]
random.shuffle(x)
print(x)