In [ ]:
#random Module
#Python offers random module that can generate random numbers.
In [1]:
import random
In [23]:
#random() generates floating value between 0 and 1. where 0 is exclusive and 1 is inclusive.
value=random.random()
print(value)
0.37848606200025825
In [30]:
#uniform() generates floating value between provided range. where 0 is exclusive and 10 is inclusive.
value=random.uniform(1,10)
print(value)
5.8478973873823294
In [39]:
#randint() generates integer value between provided. range where both are inclusive.
value=random.randint(1,6)
print(value)
4
In [53]:
#choice() generates value from the given list
greetings= ['Hello', 'Hi', 'Hey', 'Hola', 'Howdy']
value=random.choice(greetings)
print(value + ', Kushagra!')
Hello, Kushagra!
In [54]:
#choices() generates multiple values from the list
#k represent the number of times you want the result to generated. here it generates the list of results.
colors=['Red', 'Black', 'Green']
results= random.choices(colors, k=10)
print(results)
['Green', 'Green', 'Black', 'Black', 'Red', 'Green', 'Green', 'Red', 'Black', 'Black']
In [62]:
#using weight we can assign the weightage to each element. here it means 18Red balls, 18 Black balls, 4 Green balls.Total=40balls
colors=['Red', 'Black', 'Green']
results= random.choices(colors,weights=[18,18,4], k=10)
print(results)
['Black', 'Black', 'Black', 'Black', 'Red', 'Red', 'Black', 'Red', 'Black', 'Black']
In [64]:
#53 is not inclusive
deck =list(range(1,53))
print(deck)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
In [65]:
#shuffle will shuffle the deck
random.shuffle(deck)
print(deck)
[12, 44, 2, 24, 43, 7, 25, 22, 32, 38, 36, 1, 52, 35, 37, 14, 47, 42, 29, 51, 18, 40, 4, 21, 5, 8, 49, 20, 15, 27, 11, 34, 31, 45, 26, 39, 3, 19, 9, 6, 50, 28, 30, 23, 46, 13, 10, 48, 16, 41, 17, 33]
In [70]:
#sample() will generate not repeated values
hand=random.sample(deck, k=5)
print(hand)
[3, 52, 28, 37, 40]