To start this guide, download this zip file.
Random
Sometimes we want to be able to introduce randomness into a program. For example, if you are writing a game, you may need to have a treasure or a monster appear at random times in the game. If you are writing a password manager, you may want to create random passwords.
Python has a random
module that you can import with import random
.
Random choice
Look at the code in choice.py
. To choose a random item from a list, use
random.choice()
:
import random
if __name__ == '__main__':
fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)
print(selection)
This will choose a random fruit from the list.
Random integer
Look at the code in integer.py
. To choose a random integer between (and
including) a low value and a high value, use random.randint()
:
import random
if __name__ == '__main__':
number = random.randint(1, 10)
print(number)
Random float
Look at the code in float.py
. To choose a random float between (and including)
0 and 1, use random.random()
:
import random
if __name__ == '__main__':
number = random.random()
print(number)
If you want to scale this to be between 0 and some larger number, you can scale it with multiplication. For example, to choose a float between 0 and 100:
import random
if __name__ == '__main__':
number = random.random() * 100
This is particularly useful for doing something with a random probability. For example, if you want your code to do something 20% of the time (or 1 in 5 chances), then:
import random
if __name__ == '__main__':
number = random.random()
if number <= 0.2:
print("This should print one in 5 times.")
else:
print("This should print 4 in 5 times.")
You can find a more complete example in fruits.py
:
import random
def apples(size):
"""
Collect a list of 'apples', but 10% of the time, an item is 'bananas!' instead.
"""
result = []
while len(result) < size:
if random.random() < 0.1:
result.append('bananas!')
else:
result.append('apples')
return result
if __name__ == '__main__':
fruits = apples(40)
print(fruits)
This will set fruits
to be a list of mostly apples
but 10% of the time
bananas!
(more or less, depending on how the random numbers come up).
Random sample
Look at the code in washington.py
. To sample letters from a string, use
random.sample()
:
import random
if __name__ == '__main__':
name = 'Washington'
letter = random.sample(name, 2)
print(letter)
This will return a list that has two random letters from Washington
—
removing each letter as it is chosen. This means at most you can choose 10
letters from Washington
, with no repeats. If you chose to sample all 10
letters, you would end up with Washington
scrambled.
The code in shuffle.py
has a function that does exactly this:
import random
def shuffle(string):
"""
Use random.sample to get the letters in the string in a random order.
Then join the letters together with the empty string.
"""
shuffled_letters = random.sample(string, len(string))
return ''.join(shuffled_letters)
if __name__ == '__main__':
shuffled = shuffle('Washington')
print(shuffled)
Example
Write a function that will randomly inject “umm” into a sentence at a frequency of about 20%:
def ummify(text):
"""
Randomly inject 'umm' into the given text at a frequence of 20%
"""
Here is how you might write out an algorithm to solve this problem in English:
- create a new, empty list — result
- loop through all of the words in the input string
- generate a random float
- if the float is less than or equal to 0.2, then append
umm
to the result list - append the current word to the result list
- convert the list of words back into a string
- return the new string
The file in ummify.py
has a solution that follows this algorithm:
import random
def ummify(text):
"""
Randomly inject 'umm' into the given text at a frequence of 20%
"""
words = text.split(' ')
result = []
for word in words:
if random.random() < 0.2:
result.append('umm')
result.append(word)
return ' '.join(result)
if __name__ == '__main__':
speech = ["Four score and seven years ago our fathers brought forth, on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.",
"Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war.",
"We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this."]
for line in speech:
print(ummify(line))