Python Random Number Generation
In Python, you can use the built-in random module to generate random numbers.
import random
random.random()
random.random()Returns a random decimal between 0.0 and 1.0:
Example
random_number = random.random()
print(random_number)
Executing the above code produces the following output:
0.7597072251250637
random.randint(a, b)
random.randint(a, b) is used to return an integer between a and b (inclusive of a and b).
random.randint(a,b)
The function returns a number N, which is between a and b (a <= N <= b), inclusive of a and b.
The following example demonstrates how to generate a random number between 0 and 9:
Example
Executing the above code produces the following output:
4
random.choice(sequence)
random.choice(sequence)Used to randomly select an element from a sequence:
Example
list1 = [1, 2, 3, 4, 5]
random_element = random.choice(list1)
print(random_element)
Example
list1 = [1, 2, 3, 4, 5]
random_element = random.choice(list1)
print(random_element)
Executing the above code produces the following output:
4
random.shuffle(sequence)
random.shuffle(sequence)Used to randomly sort the elements in a sequence:
Example
list1 = [1, 2, 3, 4, 5]
random.shuffle(list1)
print(list1)
Executing the above code produces the following output:
[3, 2, 4, 5, 1]Other Extensions
Python3 Examples