How to use random Module Full Tutorial
Today I will teach you How to use the random module in python
Import modules
We will need to Import Random module to do that write
import random
It shall now be ready for use!
Now lets get Started!
random.random()
random.random() generates a random number from 0.0-1.0
to do that you need to input
print(random.random()) # Or random.random()
Generating random numbers in ranges
To generate a random number in a range Ex 1-10 will give you something like 5 to print this random number that is in range of certain numbers use random.randint() like so
random.randint(1-10)
EX Output
5
if you want it to print and want it to be divisible number we will need to use a function that uses start stop and step. Start is where the number starts at. Stop is where the number ends. Step is the amount it goes up by each time.
EX
[0,25,5]
Start = 0
Stop = 25
Step = 5
It should look like something like this:
0 or, 5 or,10 or,15 or, 20 or, 25
To use this function we need to do random.randrange()
Example
random.randrange(0,25,5)
To generate a random float number in a certain range we need to use random.uniform()
Ex
random.uniform(8.5,30.5)
Ex output
17.55552124
and last but not least we have a function that randomly generates a floating point triangular
Ex
random.triangular(10.5, 25.5, 5.5)
Ex Ouput
16.114862085401924
Generating random string out of a list
First we should make a list
exlist = ["item1","item2","item3"]
to generate one random item from this list we need to use random.choice()
Example:
random.choice(exlist)
random.sample() lets you generate random items but you can generate a random amount
Example: we will generate 2 different numbers from exlist
random.sample(exlist,2)
EX ouput
item1,item2
Making shuffled lists
Shuffling a list is easy we just need to do random.shuffle() and enter the list we would like to shuffle
Ex
random.shuffle(exlist)
it should now be in a random order
Hope You Enjoyed smash the like button for more tutorials!
Look at the code if you are confused
Hope You Enjoyed smash the like button for more tutorials!
Hi..I need some help for this code ..I have apriciate you if you have help me
The random.randint is not working for me. I do not know why.