17 Aug 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:
1 2 3 |
import random |
Examples – random module functions
Let us see the following examples of the random module:
- random()
- randint()
- choice()
- 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:
1 2 3 4 5 6 7 8 |
# random() function in Python random module # Code by studyopedia import random as rd print(rd.random()) |
The output is as follows:
1 2 3 |
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:
1 2 3 4 5 6 7 8 9 |
# 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:
1 2 3 4 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
# 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:
1 2 3 4 |
['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:
1 2 3 4 5 6 7 8 9 |
# 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:
1 2 3 4 |
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:
No Comments