Basics of the random library in python

# Basics of the random library in python

The native random library in python easily helps us implement random behavior in our programs. In this article, I'll go over the most basic functions of the random library.

For the rest of the article, in every piece of code, suppose the `random` has already been imported:
`import random`

## random.random()

This function is the most basic use of the random library, it randomly returns a value between 0 and 1. The value can be stored in a variable.

``````a = random.random()
b = random.random()
c = random.random()

print(a, b, c)``````

Output :

`0.5484521515800819 0.3345944853975046 0.817796559457169`

This can also be used to give random numbers between 0 and 10, 0 and 100, 0 and 500, etc... by multiplying the result by the desired number:

``````a = random.random()*5 #random number from 0 to 5
b = random.random()*10 #random number from 0 to 10
c = random.random()*200 #random number from 0 to 200

print(a, b, c)``````

Output :

`1.1115555716090353 5.898206231698487 67.44545299738458`

Another common use of this function is executing a task with a certain probability (1%, 2%,..., 50%, etc...). If, for example, we wanted to write a heads or tails program, (which has 50% to return either heads or tails), we could write:

``````def heads_or_tails():
if random.random()<0.5:
return "tails"

for _ in range(10):

Results :

``````heads
tails
tails
tails
tails
tails
tails
tails

## random.randint()

This function takes two arguments, a:int and b:int and returns a random integer between a and b, with a and b included. This can be problematic however because in python we are used to the endpoint not being included, the `random.randrange()` function takes care of this problem.

## random.randrange()

This function takes two arguments, a:int and b:int and returns a random integer between a and b. a is included, and b is not included. Here is an example:

``````a = random.randrange(0,10)
b = random.randrange(1200, 1350)
c = random.randrange(7,8) #will always return 7 as 8 is excluded

print(a, b, c)``````

Result :

`6 1280 7`

## random.choice()

This function randomly selects an element in a list, the result can be stored in a variable. Here is an example:

``````selections = ['x', 'y', 'z', 1, 2, 3]
a = random.choice(selections)
b = random.choice(selections)
c = random.choice(selections)
d = random.choice(selections)
e = random.choice(selections)
f = random.choice(selections)

print(a, b, c, d, e, f)``````

Output :

`1 3 y z x 1`

## random.shuffle()

This function shuffles a list, it does not return the shuffled list but shuffles the list in itself. Here is how it is used:

``````x = [1,2,3,'a', 'b', 'c']

print(x)
random.shuffle(x)
print(x)
random.shuffle(x)
print(x)``````

Output :

``````[1, 2, 3, 'a', 'b', 'c']
[2, 'a', 'c', 1, 'b', 3]
[3, 2, 'a', 'b', 'c', 1]``````

Thanks a lot for reading, consider subscribing to my newsletter, it's free and keeps me motivated!