Python random module

The random module in Python is used to form random numbers. Here, we will see how to import a random module in a Python program. We will also work on some built-in functions of the random module.

How to import random module in Python

To import the random module and use its functions, write the following at the start of the Python program:

import random

Examples – random module functions

Let us see the following examples of the random module:

  1. random()
  2. randint()
  3. choice()
  4. randrange()

random() function in Python

To return a random float number between 0 & 1, use the random() function in Python. Let us see an example:

Demo186.py

# random() function in Python random module
# Code by studyopedia

import random as rd

print(rd.random())

The output is as follows:

0.29906270115733213

randint() function in Python

To return a random integer number between a range, use the randit() function in Python. Let us see an example:

Demo187.py

# randint() function in Python random module
# Code by studyopedia

import random as rd

print(rd.randint(5, 10))
print(rd.randint(7, 20))

The output is as follows:

8
19

choice() function in Python

To return a random element from a sequence, use the choice() function in Python. Let us see an example:

Demo188.py

# choice() method in Python random module
# Code by studyopedia

import random as rd

mylist = ["John","Amit","Mark","Warner","Smith"]

print(mylist)

print(rd.choice(mylist))

The output is as follows:

['John', 'Amit', 'Mark', 'Warner', 'Smith']
Smith

randrange() function in Python

To return a random number between a range, use the randrange() function in Python. Let us see an example:

Demo189.py

# randrange() method in Python random module
# Code by studyopedia

import random as rd

print(rd.randrange(5, 10))
print(rd.randrange(5, 10, 2))

The output is as follows:

7
9

Python Tutorial (English)

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Python math module
Python Programming Examples
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment