Preview

## Working With random module in python 3

Python has a predefined module random that provides random-number generator functions. A random number is a number generated randomly.

To use random number generator functions  in our Python program, we first need to import module random by using import statement as:

import random

There are three random number generators functions in Python as

• random()
• randint()
• randrange()  ### i. random()

It returns a random floating point number in the between 0.0 and 1.0 (0.0, 1.0)

Number generated with random() will always be less than 1.0.

### Example 1:

 >>> import random >>> print(random.random()) 0.13933824915500237 #It will produce a different random value when we run it.

### Example 2:

 >>> import random >>> print(random.random()*10) #Value generated between 0 and 10 9.857759779259172

### ii. randint(a, b)

it returns a random integer number in the range (a, b). a and b are both included in the range.

### Example:

 >>> import random >>> print(random.randint(2,6)) 5#It may produce a different random value between 2 and 6.

### iii. randrange(start,stop,step)

it returns a random integer number in the range  start and stop  values, both are included in the range. We can also give step size in this function

### Example 1:

 >>> import random >>> print(random.randrange(6)) 5#It may produce a different random value between 0 and 6.

### Example 2:

 >>> import random >>> print(random.randrange(2,6)) 4#It may produce a different random value between 2 and 6.

### Example 3:

 >>> import random >>> print(random.randrange(1,7,2))  #2 is the step size. 3#It may produce a different random value among 1,3,5,7.

Lesson tags: create random number in python, randint() function in python, random module in python 3, random number generator functions in python, random() function in python, randrange function in python3
Back to: Python Programming Tutorial