Explanation
Python has few functions for generating random numbers. They can be used in a lot of games, lotteries etc. where random numbers are required to get generate.
There are some functions which generates the random numbers −
choice()
This function can be used to generate one random number from a collection of numbers.
Example
print ("A random number from list : ",end="") print (random.choice([1, 4, 6, 100, 31]))
Output
A random number from list : 100
randrange(beg, end, step)
This function is used to generate number randomly but within a specific range in its arguments. This function takes 3 arguments, beginning number, last number and step.
Example
print ("A random number from range : ",end="") print (random.randrange(2, 10, 3))
Output
A random number from range : 8
random()
This function generates a float random number less than 1 and also greater than or equal to 0.
Example
print ("A random number between 0 to 1 : ", end="") print (random.random())
Output
A random number between 0 to 1 :0.42487645546
shuffle()
This function shuffle the list and randomly arrange them.
Example
list = [1, 3, 5, 10, 4] print (" list before shuffling : ", end="") for j in range(0, len(list)): print (list[j], end=" ") print("\r") random.shuffle(list) print ("list after shuffling : ", end="") for j in range(0, len(list)): print (list[j], end=" ") print("\r")
Output
list before shuffling : 1 3 5 10 4 list after shuffling : 3 10 1 4 5
uniform(a, b)
This function generates a floating point number randomly between the numbers mentioned in arguments. It takes two arguments, lower limit and upper limit.
Example
print (" random floating point number between 6 and 11 is : ",end="") print (random.uniform(6,11))
Output
The random floating point number between 6 and 11 is : 7.18036982355346