Booleans and Comparisons
Every decision a program makes comes down to one of two values. Comparisons produce them, and and/or/not combine them.
A comparison is an expression with a value
== asks a question. = assigns. Mixing them up is the single most common beginner typo.
Combining and negating
and needs both sides true, or needs either, and not flips.
What counts as false
== compares. = assigns. Python raises a SyntaxError if you use = in an if, which is a kindness.18 < age < 65 is one expression, and means what it looks like.False, 0, "", [], {}, None. Everything else is truthy.if items: is the idiomatic way to ask "is this list non-empty?" - no length comparison needed.Booleans and Comparisons: A Practical Guide
Two values, and the rules for combining them.
Quick Context
A comparison is not a statement, it is an expression that produces a value - specifically a bool, which is either True or False. That is why you can print one, store one in a variable, or hand one to a function, not only put one in an if.
Truthiness
Python will accept any value where a True or False is expected, and it has a rule for what counts: empty things are false, and everything else is true. Zero, the empty string, the empty list and None are all falsy. This is what lets if name: mean "if name is not empty".
Interactive Exploration Guide
- Run the first editor. Every line prints True or False, and
type(age > 18)confirms the result really is abool. - Break it deliberately. Change
age == 20toage = 20and run. The SyntaxError names the exact confusion, which is worth seeing once on purpose. - Run the second editor. Check the
and/orresults against the two variables above them. - Read the bool() lines. Empty string, empty list and zero all come back False. That single rule explains most of the shortcuts you will see in real Python.
Key Takeaway
Comparisons produce real bool values you can print and store, not just conditions to put in an if. and/or/not combine them. Python also treats empty values - 0, "", [], {}, None - as false, which is why idiomatic code writes `if items:` rather than comparing a length to zero.