Generating Random Numbers in Python (random Module)
From making Casino Applications to Rolling a Dice, random numbers are very useful in computer programming. This tutorial is dedicated to generating random numbers in python programming language.
To work with Random Numbers, python has dedicated module called random
. We first import random module using import random
and use different method of this module for generating random numbers as required.
Here is the list of most commonly used methods of random
module with example:
random()
:random()
method returns a random number in range[0,1]
of typefloat
.SYNTAX
random.random()
PROGRAM
import random number = random.random() print('Generated random number is %f' %(number))
OUTPUT
Generated random number is 0.209876
uniform(a,b)
:uniform(a,b)
method returns a random number in range[a,b]
of typefloat
.SYNTAX
random.random(a,b)
PROGRAM
import random number = random.uniform(4,7) print('Generated random number is %f' %(number))
OUTPUT
Generated random number is 4.447908
randint(a,b)
:randint(a,b)
method returns a random number in range[a,b]
of typeint
.SYNTAX
random.randint(a,b)
PROGRAM
import random number = random.randint(1,20) print('Generated random number is %d' %(number))
OUTPUT
Generated random number is 12
getrandbits(k)
:getrandbits(k)
method returns a integer random number of bitk
.SYNTAX
random.getrandbits(k)
PROGRAM
import random number = random.getrandbits(5) print('Generated random number is %d' %(number))
OUTPUT
Generated random number is 29
choice(sequence)
:choice(sequence)
method choose a random number from a gievn non-emptysequence
.SYNTAX
random.choice(sequence)
PROGRAM
import random sequence = [2,4,6,8,10] number = random.choice(sequence) print('Generated random number is %d' %(number))
OUTPUT
Generated random number is 6