In this post, we will see how to generate random values in Python.
GENERATING INT NUMBERS
import random
# Creating of 10 random values from 1 to 10
print("Random values from 1 to 10")
for i in range(0, 10):
print(random.randint(1, 10))
# Creating of 10 random values from 100 to 1000
print("Random values from 100 to 1000")
for i in range(0, 10):
print(random.randint(100, 1000))
GENERATING FLOAT NUMBERS
import random
# Creating of 10 random values from 1 to 10
print("Random values from 1 to 10")
for i in range(0, 10):
print(random.uniform(1, 10))
# Creating of 10 random values from 100 to 1000
print("Random values from 100 to 1000")
for i in range(0, 10):
print(random.uniform(100, 1000))
USING SEED TO HAVE THE SAME RANDOM VALUES
import random
random.seed(100)
# Creating of 5 random values from 1 to 10
print("Random values from 1 to 10")
for i in range(0, 5):
print(random.randint(1, 10))
# Creating of 5 random values from 100 to 1000
print("Random values from 100 to 1000")
for i in range(0, 5):
print(random.randint(100, 1000))
USING RANDOM TO GET ITEMS FROM A LIST
import random
lstValue = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(1, 5):
print(lstValue[random.randint(0, 8)])
SHUFFLING A LIST
import random
lstValue = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Initial list")
print(lstValue)
print("Shuffle list")
random.shuffle(lstValue)
print(lstValue)
random.shuffle(lstValue)
print(lstValue)
random.shuffle(lstValue)
print(lstValue)