liveBook · Manning

Random module

As explained in Python Workout, Second Edition

The random module is Python's standard-library module for generating pseudorandom values and making pseudorandom selections.

The random module generates pseudorandom values and supports random selection. Its randint function returns an integer between two bounds, including both endpoints. section 2.2 section 2.3

Number guessing game

Use the module to choose a hidden number, then combine input, integer conversion, comparisons, and a loop: import random answer = random.randint(0, 100) while True: guess = int(input('Guess: ')) if guess < answer: print('Too low') elif guess > answer: print('Too high') else: print('Just right') break Remember that randint(0, 100) can return 0 or 100. The input function returns a string, so convert the response before comparing it with the integer answer. section 2.2 section 2.3

When applying the module, keep these details in view:

  • Import random before calling random.randint. section 2.3
  • Treat the upper randint bound as inclusive, unlike many Python ranges. section 2.3
  • Explore other random functions for choosing elements from Python sequences. section 2.3

How Python Workout, Second Edition covers it

How deep it goes
Explains randint calls, inclusive bounds, and sequence selection, but does not discuss pseudorandom algorithms or seeding.
Examples
Uses a number-guessing game with a hidden integer from 0 through 100 and high, low, or correct feedback.
What it assumes
Assumes basic Python functions and variables while reinforcing input conversion, comparisons, loops, and break.
What you can do after
Apply it via Python's random module to generate bounded integers and choose random values.
How it connects
Connects random.randint with input, integer conversion, comparison operators, while loops, and break.

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, Second Edition. The section links point to the parts of the book it draws on.