Boolean Logic and Comparison

Boolean data has two values, True and False, which are the results of the built-in comparisons shown here. The comparison operators are == (equal), != (not equal), and >, >=, <, <= for ordering. In Python, bool is a subtype of int, so True equals 1 and False equals 0 in arithmetic, which makes sum() a convenient way to count how many comparisons were true.

Equality and ordering behave differently across types. 3 == "3" is simply False, because an integer and its text representation are not equal. Different types can still compare equal: 3 == 3.0 is True. Ordering has no defined meaning between a number and text, so 3 < "4" raises TypeError. Built-in integers and floats support mixed ordering, so 1 < 2.5 is true; complex numbers do not support ordering.

Strings compare character by character using each characterโ€™s Unicode code point, which is not dictionary order. Every uppercase ASCII letter precedes every lowercase one, so "Apple" < "apple" and "Zoo" < "apple". Digits inside text compare as characters, so "10" < "9" even though 10 is greater than 9. Convert numeric text before comparing it, and apply casefold() before comparing names when capitalization should not matter; language-specific ordering needs a proper collation library.

and, or, and not combine conditions. Python also treats other values as true or false in a condition: False, zero, None, and empty built-in strings and collections are false; custom types can define their own truth test, so the non-empty string "0" is true. and and or stop as soon as the answer is known and return the deciding operand, which need not be a boolean: "" or "fallback" is "fallback". That short-circuiting is useful for defaults and for guarding an expensive or failing check, and it surprises code that expected exactly True.

Further reading

See the worked examples in Python Strings, Conditions, and Loops.


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.