importing random
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__',
'__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',
'__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp',
'_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin',
'_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate',
'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits',
'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint',
'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular',
'uniform', 'vonmisesvariate', 'weibullvariate']
>>> print(random.randint.__doc__)
Return random integer in range [a, b], including both end points.
Generating Pseudorandom Integers We will use this to roll a single die and then to shake dem bonz.
>>> random.randint(1,6)
2
>>> random.randint(1,6)
1
>>> random.randint(1,6)
4
>>> random.randint(1,6)
6
>>> random.randint(1,6)
2
>>> (random.randint(1,6),random.randint(1,6))
(2, 5)
>>> (random.randint(1,6),random.randint(1,6))
(3, 3)
Shuffling a List Pass a list to
random.shuffle
and it will be shuffled using
the Fischer-Yates algorithm.
>>> x = [1,2,3,4,5,6]
>>> random.shuffle(x)
>>> x
[1, 4, 6, 2, 5, 3]
>>> random.shuffle(x)
>>> x
[6, 4, 3, 1, 2, 5]
Random Sampling from a List Here we pluckk out a single element at random.
>>> random.choice(x)
6
>>> random.choice(x)
1
>>> random.choice(x)
5
Now we pick three elements without replacement.
>>> random.sample(x, 3)
[3, 2, 4]
>>> random.sample(x, 3)
[5, 4, 1]
>>> random.sample(x, 3)
[3, 6, 5]
Flipping a Coin: Do this by making a random choice from the
list ["H", "T"]
.
Roll an exotic die from an RPG, say 20-sided. This is just the tool.
Making a Magic 8 Ball
Here is a list with its replies.
replies = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "It is certain.", "It is decidedly so."]
Our program will ignore the question entered by the user and it will spit out one of its cryptic replies.
import random
question = input("Enter your question: ")
replies = ["As I see it, yes.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "It is certain.", "It is decidedly so."]
print("The answer to your question")
print(question)
print (f"is: {random.choice(replies)}")
unix> python eightball.py Enter your question: Is is raining outside? The answer to your question Is is raining outside? is: Don't count on it.
Generating Uniform Variates Here we get a random floating-point number in the interval [0, 1).
>>> random.random()
0.13212661879466792
>>> random.random()
0.8637168910820039
>>> random.random()
0.982909339902225
We can do this for any range we'd like as follows.
>>> random.uniform(0,10)
8.579159479118163
>>> random.uniform(0,10)
3.8694437072194834
>>> random.uniform(0,10)
6.754578729500322
>>> random.uniform(0,10)
1.6187927982936734
>>> random.uniform(0,10)
9.929038622798107
- strings This iterator walks through a string one character at a time in index order.
- lists and tuples Their iterators walk through one element at a time in index order.
- sets The iterator walks through the set in no particular order.
- dictionaries The iterator walks the keys of a dictionary one key at a time in no particular order.
- file objects The iterator walks through a file one line at a time.
Here are some other iterables.
- range objects
- dictionary_keys object
- dictionary_values object
We will do tons of examples.
enumerate
and reversed
are very handy
for altering the behavior of iterators.