liveBook · Manning

Random module

As explained in Get Programming: Learn to code with Python

random is a Python standard-library module that provides facilities for generating pseudorandom values and making random selections.

Python’s random module adds unpredictability without requiring you to implement random-number operations yourself. Import it, then use dot notation to call functions for numbers, selections, and rearrangements. section 34.1 section 35.3

Common operations include:

  • random.random() returns a floating-point value from 0 inclusive to 1 exclusive. section 34.1 section 35.3
  • random.randint(a, b) returns an integer from a through b, including both endpoints. section 34.1
  • random.choice(L) selects one element from a list, while random.sample(L, n) selects a specified number without repeating an element. section 34.1 section 35.3

Simulating rock-paper-scissors

import random r = random.random() if r < 1/3: computer = "rock" elif r < 2/3: computer = "paper" else: computer = "scissors" The three ranges give each choice an approximate one-third chance. Comparing the computer’s choice with the user’s input completes the game. section 35.3

import random
people = ["Ana","Bob","Carl","Doug","Elle","Finn"]
print(random.choice(people))

Run a complete small example that chooses one person from a list at random. section 35.3

Random results can make testing harder because a program may behave differently each time. Set a seed when you need a repeatable sequence while debugging. section 35.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains imports, core functions, probability ranges, sampling, and seeding, but stops short of generator internals.
Examples
Demonstrates person selection, nonrepeating samples, integer ranges, rock-paper-scissors, and seeded output.
What it assumes
Assumes basic Python variables, lists, conditionals, functions, imports, and dot notation.
What you can do after
Build random selections and chance-based programs, then diagnose inconsistent tests with a seed.
How it connects
Connects random values with imports, lists, probability, user input, games of chance, and debugging.

Also explained in

Compare how 4 books explain random module →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.