Random Module
Python - Random Module
Section titled “Python - Random Module”The random module is a built-in module to generate the pseudo-random variables. It can be used perform some action randomly such as to get a random number, selecting a random elements from a list, shuffle elements randomly, etc.
random
Generate Random Floats
Section titled “Generate Random Floats”The random.random() method returns a random float number between 0.0 to 1.0. The function doesn’t need any arguments.
random.random()
import random
print(random.random())`import random
print(random.random())`Try it
Generate Random Integers
Section titled “Generate Random Integers”The random.randint() method returns a random integer between the specified integers.
random.randint()
import random
print(random.randint(1, 100))print(random.randint(1, 100))`import random
print(random.randint(1, 100))
print(random.randint(1, 100))`Try it
Generate Random Numbers within Range
Section titled “Generate Random Numbers within Range”The random.randrange() method returns a randomly selected element from the range created by the start, stop and step arguments. The value of start is 0 by default. Similarly, the value of step is 1 by default.
random.randrange()
import random
print(random.randrange(1, 10))print(random.randrange(1, 10, 2))print(random.randrange(0, 101, 10))`import random
print(random.randrange(1, 10)) print(random.randrange(1, 10, 2)) print(random.randrange(0, 101, 10))`Try it
Select Random Elements
Section titled “Select Random Elements”The random.choice() method returns a randomly selected element from a non-empty sequence. An empty sequence as argument raises an IndexError.
random.choice()
import random
print(random.choice('computer'))print(random.choice([12,23,45,67,65,43]))print(random.choice((12,23,45,67,65,43)))`import random
print(random.choice(‘computer’))
print(random.choice([12,23,45,67,65,43]))
print(random.choice((12,23,45,67,65,43)))`Try it
Shuffle Elements Randomly
Section titled “Shuffle Elements Randomly”The random.shuffle() method randomly reorders the elements in a list.
random.shuffle()list
numbers=[12,23,45,67,65,43]
random.shuffle(numbers)print(numbers)
random.shuffle(numbers)print(numbers)`numbers=[12,23,45,67,65,43]
random.shuffle(numbers) print(numbers)
random.shuffle(numbers) print(numbers)`Try it Learn more about the random module in Python docs. random module in Python docs