Randomness

We may want to incorporate random behavior into our program. Python offers a built-in module (think of this as a library of functions) for doing this called random.

To use a module, we'll use an import statement; by convention, these will appear at the very beginning of a Python program.

import random

Random numbers

To generate a random number, we can invoke the random.randint function, passing in two numbers that represent the range of values that should be selected from. Suppose we want to roll a traditional die; then we want a number between 1 and 6, inclusive.

  • Inclusive means that the values are included in the range; in other contexts, you may see “exclusive” indicating that a boundary value is not part of the range.

Let's see this in action!

import random


def rollDie() -> int:

'''Randomly generate a number between 1 and 6 and return it.'''

return random.randint( 1, 6 )


def main():

# Roll 2 dice and print the result.

die1:int = rollDie()

die2:int = rollDie()

total:int = die1 + die2

print( f"You rolled a {die1} and a {die2}, for a total of {total}." )


if __name__ == "__main__":

main()

Notice that each time we run the program, we get a different result!

Random seeds

It turns out getting a different result, while exciting, can make it really hard to test our code. Because this is such an important part of development, Python offers us a way of "seeding" the random number generator to have replicable behavior.

By first invoking the random.seed function and passing in a hard-coded value, we will always get the same sequence of random numbers.

Try this out! Now, we get the same result each execution.

import random


def rollDie() -> int:

'''Randomly generate a number between 1 and 6 and return it.'''

return random.randint( 1, 6 )


def main():

# Seed the random number generator to get replicable behavior.

random.seed( 1837 )


# Roll 2 dice and print the result.

die1:int = rollDie()

die2:int = rollDie()

total:int = die1 + die2

print( f"You rolled a {die1} and a {die2}, for a total of {total}." )


if __name__ == "__main__":

main()

What happens if we change the value of the seed?