Python Random Numbers

In this tutorial, we will learn how to generate a sequence of random numbers in python. Python provides a list of functions to generate a random floating point, integer and string.

randrange(start, stop, step)

Python randrange() expects three parameters.

  1. Start: We need to specify an integer from which number to start. it is optional and the default is 0
  2. Stop: This parameter is required, and we need to specify an integer where to stop.
  3. step: This parameter is optional and is for incremental
import random

print "Randrange between 1 and 500: ", random.randrange(1, 500)

# Output
# Randrange between 1 and 500:  402


Python choice() method expects one required parameter seq. That can be string, tuple or list. Below is the example of choice() method

import random

# choice method with string
string1 = "desertebs"
print "Random value of string: ", random.choice(string1)

# choice method with list
list1 = ["this", "is", "test", "list"]
print "Random value of list: ", random.choice(list1)

# choice method with tuple
tuple1 = ("some", "random", "tuple")
print "Random value of list: ", random.choice(tuple1)

# Output
# Random value of string:  e
# Random value of list:  test
# Random value of list:  some


Python random() method returns floating random value from greater than 0 and less than 1. Below is an example for random() method

import random

# random method
print "Random value is: ", random.random()

# Output
# Random value is: 0.0913204361536


Python Seed() method is used to initialize your own random number. By default Python random() method generates current timestamp value. Below is the example of seed method

import random

# Python seed method
print "Python method with seed: ", random.random()

# Output
# Python method with seed:  0.62290169489


Python shuffle() method takes a parameter as a sequence that can be (list, tuple or string) and reorganize the lists. Below is the example

import random

# Python shuffle method
list1 = ["card", "house", "of"]
print "Python shuffle method: ", list1

# Output
# Python shuffle method:  ['house', 'of', 'card']

uniform(a, b)

Python uniform method takes two-parameter and returns random floating-point numbers between two given numbers. Both parameter is required. Below is the example


import random

# Python uniform. method
print "Python uniform method: ", random.uniform(10, 20)

# Output
# Python uniform method:  10.2480249154