COGNITION FOUNDRYLEARN. BUILD. UNDERSTAND.
PY-007 / Ask useful questions◷ 17 min read + practice

Comparisons and boolean logic

Programs start to make decisions when they can answer questions. A comparison produces a Boolean value: True or False. We can combine those answers to express useful rules.

By the end, you can: Use ==, !=, <, <=, >, >=, and, or and not without confusing comparison with assignment.
Before this lesson: PY-003 · PY-006

A comparison produces a value

8 > 5 evaluates to True, while 8 == 5 evaluates to False. Use == to compare for equality; a single = assigns a value to a name. Python also provides != (not equal), < and > (less/greater), and <= and >= (inclusive bounds).

Comparisons themselves are expressions. print(8 > 5) displays the Boolean result; later an if statement can act on it. Chained comparisons such as 0 <= score <= 100 read naturally and evaluate both boundaries.

Combine questions with and, or and not

and requires both conditions to be true. or requires at least one to be true. not reverses a Boolean result. Parentheses make more complex rules easy to read; operator precedence can otherwise surprise you.

Consider a discount that applies if a person has a voucher AND the purchase is large enough. Write the individual questions first, then combine them. and and or can return operands rather than always returning a Boolean; using them with actual comparisons is often clearest for learners.

Truthiness is more than True and False

Python considers empty strings, empty containers, numeric zero and None false in conditions; non-empty strings and non-zero numbers are generally true. Use bool(value) to inspect that conversion.

An empty input is not the same thing as the string "False": a non-empty text string is true, even if its words suggest otherwise. Never use bool("False") to parse a yes/no answer supplied as text.

Compare types intentionally

"12" == 12 is False: one operand is text and the other is a number. Normal ordering comparisons between a string and an integer raise TypeError in modern Python.

For numeric comparisons, validate and convert input deliberately. We will add exception handling later so failed conversions can produce friendly messages rather than uncaught errors.

Try it yourself.

Choose a starting example or write something completely different. You control the code; the Run button executes what is in the editor, not a hidden preset.

CF Python PlaygroundBrowser-based Python
Ready to load Python
Compare two totals

See equality and ordering comparisons side by side.

Syntax colours highlight Python code. Tab inserts four spaces; press Escape then Tab to leave the editor. Ctrl+Enter runs the current code.
OUTPUT / ERRORS
Press Run Python to execute the editable code.
NOW MAKE IT YOURS

Change price to 45. Which comparisons change, and why?

Need a hint?

The <= operator includes equality but 45 is above the 40 budget.

On first Run, a pinned Python runtime downloads from jsDelivr. Code executes locally in your browser's Web Worker, not on our server. It cannot inspect your normal PC files or Windows hardware. Avoid entering secrets. Heavy/infinite loops are stopped by a time limit.

Check your understanding.

Try answering each question before opening its reference answer. Explain the idea aloud or change an example to test it for yourself.

  1. Why does 5 == 5 behave differently from x = 5?

    View answer

    == asks whether two expressions represent equal values and produces a Boolean (True or False). = is an assignment statement: x = 5 stores the integer 5 under the name x. They play different roles; using assignment where a comparison is required is a syntax error in a normal if test.

  2. Why is bool("False") True, and how could that cause a bug?

    View answer

    bool() does not parse the *meaning* of words inside a string. Any non-empty string, including "False", is true. A form that treats bool(user_text) as the answer to a yes/no question could mistakenly treat a typed “no” as yes. Compare normalised text against known accepted values instead.

Where this leads.

Comparisons provide answers; conditions let the program act on those answers.