liveBook · Manning

Comparison

As explained in Learn AI-Assisted Python Programming, Second Edition

A comparison is a language operation that tests a relationship between values or expressions, such as equality or ordering, and produces a result.

A comparison evaluates a relationship between values and produces a Boolean result: True or False. Python uses symbols such as >, <, >=, <=, ==, and != to compare values. section 4.3.3

Use comparisons to control decisions and check boundaries:

  • Place a comparison in an if statement to choose which code runs; else is optional. section 4.3.3
  • Combine comparisons with and when a value must satisfy multiple conditions, such as being within a range. section 8.3.4
  • Choose > and < for an exclusive range, or >= and <= when the boundary values count. section 8.3.4
  • Write == to test equality; a single = is not the equality comparison shown here. section 4.3.3

Selecting values between two bounds

A function can count values strictly between x and y with `if number > x and number < y:`. Changing the conditions to `>=` and `<=` includes the endpoints. Testing a list from 1 through 9 with bounds 3 and 7 exposes the difference: inclusive comparisons count 5 values, while exclusive comparisons count 3. section 8.3.4

Listing 4.2 Function to determine the larger of two values
def larger(num1, num2):
    if num1 > num2:     #1
        return num1           #2
    else:                    #3
        return num2     #4

Inspect a small function that compares two values and returns the larger one. section 4.3.3

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Defines Boolean comparisons and demonstrates them in conditionals, but does not develop identity or membership comparisons.
Examples
Demonstrates larger-value selection, age-based prompts, longest-word tests, and inclusive versus exclusive numeric ranges.
What it assumes
Teaches Boolean conditions, comparison symbols, indentation, and the distinction between assignment and equality.
What you can do after
Diagnose boundary bugs and apply comparisons in Python conditionals and doctest-backed functions.
How it connects
Connects comparisons with Boolean expressions, conditionals, functions, testing, and debugging.

Also explained in

Compare how 8 books explain comparison →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.