liveBook · Manning

Random module

As explained in Python Workout: 50 ten-minute exercises

Python's standard-library module for generating pseudorandom values and selecting elements.

Use Python’s random module when a program must choose a value without knowing it in advance. In a number-guessing game, random.randint(0, 100) selects an integer, and a loop compares each user guess until it is correct. section 1.2 section 1.3

The module supports several practical selection patterns:

  • random.randint(a, b) returns an integer from a through b; the upper bound is inclusive. section 1.2 section 1.3
  • random.choice(sequence) returns one randomly chosen element, making it useful for selecting characters or other sequence values. section 1.3 section 6.11

Generate passwords from a chosen character set

def create_password_generator(chars): def generate(length): return ''.join(random.choice(chars) for _ in range(length)) return generate alpha_password = create_password_generator('abcdef') symbol_password = create_password_generator('!@#$%') print(alpha_password(5)) print(symbol_password(5)) section 6.11

import random
number = random.randint(10, 30)

A minimal randint call shows the import, function name, arguments, and inclusive range in executable form. section 1.2

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains randint and choice through complete exercises, including inclusive bounds, but does not detail module internals.
Examples
Demonstrates a number-guessing game, randint range selection, and password generation with alphabetic or symbolic characters.
What it assumes
Assumes basic functions and control flow while teaching integer conversion for user-entered guesses.
What you can do after
Apply it via randint and choice to build guessing games and configurable password generators.
How it connects
Connects random selection with loops, comparison operators, sequences, input conversion, and inner functions.

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 Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.