Nearby lessons
101 of 108Python - Random Module
Detailed Tutorial Notes
7)
8) Output
9) 2.0
10) 11
11) 10
12) 10.6
13) 10.6Note:
We can find help for any module by using help() function
Eg:
import mathhelp(math)
Working with random module:
This module defines several functions to generate random numbers.
We can use these functions while developing games,in cryptography and to generate
random numbers on fly for authentication.
- random() function: This function always generate some float value between 0 and 1 ( not inclusive) 0
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
0.4572685609302056 0.6584325233197768 0.15444034016553587 0.18351427005232201 0.1330257265904884 0.9291139798071045 0.6586741197891783 0.8901649834019002 0.25540891083913053 0.7290504335962871
- randint() function: To generate random integer beween two given numbers(inclusive) Eg:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
51 44 39 70 49 74 52 10 40 8
- uniform(): It returns random float values between 2 given numbers(not inclusive) Eg:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
9.787695398230332 6.81102218793548 8.068672144377329 8.567976357239834 6.363511674803802 2.176137584071641 4.822867939432386 6.0801725149678445 7.508457735544763 1.9982221862917555 random() ===>in between 0 and 1 (not inclusive) randint(x,y) ==>in between x and y ( inclusive) uniform(x,y) ==> in between x and y ( not inclusive)
- randrange([start],stop,[step]) returns a random number from range start<= x < stop start argument is optional and default value is 0 step argument is optional and default value is 1 randrange(10)-->generates a number from 0 to 9 randrange(1,11)-->generates a number from 1 to 10 randrange(1,11,2)-->generates a number from 1,3,5,7,9 Eg 1:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
9 4 0 2 9 4 8 9 5 9
Eg 2:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
2 2 8 10 3 5 9 1 6 3
Eg 3:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
1 3 9 5 7 1 1 1 7 3
- choice() function: It wont return random number. It will return a random object from the given list or tuple. Eg:
1) from random import *
2) list=["Sunny","Bunny","Chinny","Vinny","pinny"]
3) for i in range(10):
4) print(choice(list))Output
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
Vinny
Bunny
Sunny
🧠 Test Your Knowledge
5 QuestionsProgress: 0 / 5
Keep Going!Python - Dates and Time