liveBook · Manning

Randint

As explained in Python Workout, Second Edition

random.randint is a Python standard-library function that returns a pseudorandom integer between two specified inclusive bounds.

Use random.randint when a program needs an integer selected between two bounds, including both endpoints. A focused exercise is a number-guessing game: choose a value from 0 through 100, repeatedly request guesses, and report whether each guess is too high, too low, or correct. section 2.2 section 2.3

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

Import random, call random.randint with two parameters, and store the returned integer for later use. section 2.2

The upper bound is inclusive, unlike most Python ranges. Since input always returns a string, convert each guess with int before comparing it with the selected integer. section 2.3

Number-guessing loop

import random def guessing_game(): 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 section 2.2 section 2.3

How Python Workout, Second Edition covers it

How deep it goes
Defines two-parameter invocation and inclusive bounds, then applies the result in a comparison loop.
Examples
Uses a 0-to-100 guessing game and a smaller random.randint(10, 30) assignment.
What it assumes
Assumes basic function calls and comparisons while teaching that input strings require conversion before numeric comparison.
What you can do after
Build a guessing loop that generates a bounded integer, classifies guesses, and exits on an exact match.
How it connects
Connects random.randint with the random module, input, integer conversion, comparison operators, while loops, and break.

Also explained in

Compare how 2 books explain randint →

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.