Python is practical language which provides different functions in practical way. Random number are generally used in security related issues but there are other areas too. In this post we will look different random number generation examples about python.
Generate Random Number Between 0 and 1
Python provides a library named random
by default. This library is used to provide different type of random functions according to given parameters. We will use random
function in order to generate random numbers in this example. This function generates floating point values between 0 and 1
from random import random random()

As we can see produces random numbers are like 0.476250741043003
Generate Random Number with Randint Between 0 and 10
What if we need to generate integer numbers in specified range. We can not use random
function in a practical and efficient way. We will use randint
function in order to generate random numbers between 1 and 10 by specifying range.
from random import randint randint(0,10)

We can see that generated numbers are between 1 and 10
Generate Random Number with Randint Between 0 and 100
Another useful example is generating random integers between 0 and 100. As you see we can change the range start and end whatever we want.
from random import randint randint(0,10)

Generate Random Floating Number In Specified Range
We have generated floating random number in 0 and 1 . But we may need more options about the range. For example we may need to generate floating random number between 5.0
and 7.0
. In this situations we will us uniform
function.
from random import uniform uniform(5.0,7.0)

Select Random Element From Given List
Another useful function is choice
which selects element from given list randomly. We just provide the list and selected element will be returned. In this example we will use one
, two
and three
as a list.
from random import choice choice(['one','two','three'])
