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:

  1. random(): random() method returns a random number in range [0,1] of type float.

    SYNTAX

    random.random()

    PROGRAM

    
    import random
    number = random.random()
    print('Generated random number is %f' %(number))
    

    OUTPUT

    Generated random number is 0.209876
    
  2. uniform(a,b): uniform(a,b) method returns a random number in range [a,b] of type float.

    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
    
  3. randint(a,b): randint(a,b) method returns a random number in range [a,b] of type int.

    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
    
  4. getrandbits(k): getrandbits(k) method returns a integer random number of bit k.

    SYNTAX

    random.getrandbits(k)

    PROGRAM

    
    import random
    number = random.getrandbits(5)
    print('Generated random number is %d' %(number))
    

    OUTPUT

    Generated random number is 29
    
  5. choice(sequence): choice(sequence) method choose a random number from a gievn non-empty sequence.

    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