BYU logo Computer Science

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

To choose a random item from a list, use random.choice():

import random

fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)

This will choose a random fruit from the list.

Random integer

To choose a random integer between (and including) a low value and a high value, use random.randint():

import random

number = random.randint(1, 10)

Random float

To choose a random float between (and including) 0 and 1, use random.random():

import random

number = random.random()

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

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

number = random.random()
if number <= 0.2:
    print("This should print one in 5 times.")
else:
    print("This should print 4 in 5 times.")

Here is a more complete example:

def apples(size):
    result = []
    while len(result) < size:
        if random.random() < 0.1:
            result.append('bananas!')
        else:
            result.append('apples')
    return result


fruits = apples(40)

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

To sample letters from a string, use random.sample():

import random

name = 'Washington'
letter = random.sample(name, 2)

This will choose 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.

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 <= 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

Here is 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)