liveBook · Manning

Comparison

As explained in Python Workout, Second Edition

A comparison operator is a Python operator that evaluates a relationship between two values and produces a Boolean result.

Comparison operators evaluate relationships between values and produce results that can control program flow. The guessing exercise applies ==, <, and > to compare a converted user guess with a randomly generated integer. section 2.3

Use the operators with these constraints and supporting techniques:

  • Use == and != to compare values regardless of type; use < and > with values of the same type. section 2.3
  • Convert input with int before comparing it with a numeric answer, because input always returns a string. section 2.3
  • Place comparisons inside while True and exit with break when the guess matches the selected answer. section 2.3

Number guessing

Generate an answer with random.randint, convert the user's input to an integer, and compare the guess with ==, <, or > until it matches. section 2.3

How Python Workout, Second Edition covers it

How deep it goes
Explains ==, !=, <, and > through a worked program and type restrictions, without surveying additional comparison behavior.
Examples
Uses a random-integer guessing exercise with converted user input and equality, less-than, and greater-than tests.
What it assumes
Explains string-to-integer conversion while using loops, input, and random number generation as supporting techniques.
What you can do after
Apply it via Python comparisons that control a loop and distinguish numeric guesses from a randomly selected answer.
How it connects
Links comparison operators with Boolean results, random number generation, input conversion, and while loops.

Also explained in

Compare how 8 books explain comparison →

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.