{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"booleans-and-truth","title":"True, False, and what Python counts as nothing","url":"https://addaly.com/learn/python-for-ai/booleans-and-truth","position":8,"of":89,"minutes":7,"answer":"or returns an operand rather than a boolean, so x or default quietly replaces a legitimate 0 or empty string, and is should be reserved for None.","keyIdea":"`or` returns an operand rather than a boolean, so `x or default` quietly replaces a legitimate 0 or empty string, and `is` should be reserved for None."},"body":{"format":"markdown","text":"## Comparisons produce a value you can store\n\n```python\n>>> 5 > 3\nTrue\n>>> age = 17\n>>> can_vote = age >= 18\n>>> can_vote\nFalse\n```\n\n`True` and `False` are values like any other. You can put them in a variable, in a list, pass them to a function. They are capitalised: `true` is a `NameError`.\n\nThe comparison operators: `==` equal, `!=` not equal, `<`, `>`, `<=`, `>=`. And two that read like English: `in` for membership, `not in` for its opposite.\n\n```python\n\"a\" in \"cat\"                 # True\n3 in [1, 2, 3]               # True\n\"rent\" in {\"food\": 200}      # False — dicts check keys\n```\n\nPython allows chained comparisons, which most languages do not:\n\n```python\nscore = 85\nif 0 <= score <= 100:\n    print(\"score is in range\")\n```\n\nThat means what it looks like. C evaluates that line differently. Java rejects it at compile time.\n\n## `==` against `is`\n\n`==` asks *are these values equal*. `is` asks *are these the same object in memory*. They are different questions and only one of them is usually the one you want.\n\n```python\na = [1, 2, 3]\nb = [1, 2, 3]\na == b     # True  — same contents\na is b     # False — two separate lists\n```\n\nWhat makes this dangerous is that `is` appears to work on small numbers and short strings:\n\n```python\nx = 256\ny = 256\nx is y     # True on CPython\nx = 257\ny = 257\nx is y     # do not rely on this result\n```\n\nCPython commonly reuses small integer objects. It can also reuse larger integer literals compiled together, so the `257` example may be `True` in a script even when separate interactive statements give `False`. These are implementation details, not guarantees about numeric equality. Use `==` to compare values. See the [Python language reference on literals and identity](https://docs.python.org/3/reference/expressions.html#literals-and-object-identity).\n\n**For numeric and text values, use `==`.** Use `is None` for a missing-value sentinel; use identity for other objects only when object identity is the question you mean to ask.\n\n## Truthiness: what counts as nothing\n\nAny value can be used where a condition is expected. Python treats these as false:\n\n- `False`\n- `None`\n- zero of any numeric type: `0`, `0.0`\n- empty containers: `\"\"`, `[]`, `{}`, `()`, `set()`\n\nEverything else is true, including `\"0\"`, `\"False\"` and `[0]`: each of those is a non-empty container or string. That first one bites when reading text files: the string `\"0\"` from a CSV is true.\n\nSo the idiomatic test for an empty list is:\n\n```python\nitems = []\nif not items:\n    print(\"nothing to do\")\n```\n\nrather than `if len(items) == 0`. Both work; the first is what Python code looks like.\n\n## `and` and `or` do not return booleans\n\nThis surprises people who know other languages. `and` and `or` return **one of the operands**, not `True`/`False`:\n\n```python\n>>> \"\" or \"default\"\n'default'\n>>> \"Asha\" or \"default\"\n'Asha'\n>>> 0 or \"default\"\n'default'\n```\n\nThat gives the common idiom `name = user_input or \"guest\"`, which fills in a default when the input is empty.\n\nAnd it gives the bug: if the legitimate value is `0`, `\"\"` or an empty list, the default silently replaces it.\n\n```python\nform_value = 0                 # the customer really ordered none\nquantity = form_value or 1     # a genuine order of 0 becomes 1\n```\n\nWhen zero is a real answer, test for `None` explicitly:\n\n```python\nquantity = 1 if form_value is None else form_value\n```\n\nThey also **short-circuit**: `a and b` never evaluates `b` if `a` is false. This is not an optimisation detail, it is how you write safe checks:\n\n```python\nitems = []\nif items and items[0] == \"x\":     # safe on an empty list\n    print(\"the first item is x\")\n```\n\nReverse the two halves and an empty list raises `IndexError`.\n\n## Booleans are integers\n\n`True == 1` and `False == 0`, genuinely, and this is occasionally useful:\n\n```python\nflags = [True, False, True, True]\nsum(flags)      # 3\n```\n\nCounting how many things passed a test is `sum(1 for x in items if test(x))` or just `sum(test(x) for x in items)`.\n\n## The comparison that quietly lies\n\n```python\n>>> \"10\" < \"9\"\nTrue\n```\n\nStrings compare character by character, left to right, so `\"1\"` sorts before `\"9\"` and the whole string does too. Nothing errors. A list of version numbers or ages read from a file and never converted will sort in an order that looks random and is perfectly consistent. This is the same failure as the one in the `input()` lesson, showing up in sorting rather than in arithmetic.\n\nOrdering a string against a number raises a TypeError. Equality still returns a value, so `\"10\" == 10` is `False`.\n\n```python\n>>> \"10\" < 9\nTypeError: '<' not supported between instances of 'str' and 'int'\n```\n\nPython 3 refuses rather than inventing an ordering. Python 2 did invent one, which is why old code silently produced nonsense."},"check":{"question":"A form handler writes `discount = entered or 10` so that a blank field becomes 10 percent. A shopkeeper enters 0 to mean no discount and is charged 10 percent off anyway. Why?","options":[{"text":"`or` returns its second operand whenever the first is falsy, and 0 is falsy, so a deliberate zero is indistinguishable from a blank field.","correct":true},{"text":"The entered value arrived as the string \"0\", which Python treats as false, so converting it to an int first would fix the bug.","correct":false,"tempting":"Gets the direction of truthiness backwards: the string \"0\" is non-empty and therefore true, so this conversion would change the behaviour, not fix it."},{"text":"`or` always returns a boolean, so `discount` became `True` and was coerced to 1 during the calculation.","correct":false,"tempting":"Applies the boolean-returning behaviour of other languages, which is exactly what Python's `or` does not do."},{"text":"The comparison should have used `is not None`, because `or` cannot be used with numbers at all.","correct":false,"tempting":"Names the right fix for the wrong reason, and states a restriction on `or` that does not exist."}]},"prev":{"slug":"formatting-output","title":"Building the output a person will read","url":"https://addaly.com/learn/python-for-ai/formatting-output"},"next":{"slug":"if-and-branching","title":"Making a decision: if, elif, else","url":"https://addaly.com/learn/python-for-ai/if-and-branching"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'True, False, and what Python counts as nothing', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/booleans-and-truth (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"True, False, and what Python counts as nothing","courseTitle":"Python, from Zero, for AI","module":{"index":1,"slug":"getting-python-running","title":"Getting Python running, and your first working code"},"answer":null,"keyIdea":"`or` returns an operand rather than a boolean, so `x or default` quietly replaces a legitimate 0 or empty string, and `is` should be reserved for None.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"comparisons-produce-a-value-you-can-store","runs":[{"text":"Comparisons produce a value you can store"}]},{"t":"code","lang":"python","label":"Python","text":">>> 5 > 3\nTrue\n>>> age = 17\n>>> can_vote = age >= 18\n>>> can_vote\nFalse"},{"t":"p","runs":[{"text":"True","code":true},{"text":" and "},{"text":"False","code":true},{"text":" are values like any other. You can put them in a variable, in a list, pass them to a function. They are capitalised: "},{"text":"true","code":true},{"text":" is a "},{"text":"NameError","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"The comparison operators: "},{"text":"==","code":true},{"text":" equal, "},{"text":"!=","code":true},{"text":" not equal, "},{"text":"<","code":true},{"text":", "},{"text":">","code":true},{"text":", "},{"text":"<=","code":true},{"text":", "},{"text":">=","code":true},{"text":". And two that read like English: "},{"text":"in","code":true},{"text":" for membership, "},{"text":"not in","code":true},{"text":" for its opposite."}]},{"t":"code","lang":"python","label":"Python","text":"\"a\" in \"cat\"                 # True\n3 in [1, 2, 3]               # True\n\"rent\" in {\"food\": 200}      # False — dicts check keys"},{"t":"p","runs":[{"text":"Python allows chained comparisons, which most languages do not:"}]},{"t":"code","lang":"python","label":"Python","text":"score = 85\nif 0 <= score <= 100:\n    print(\"score is in range\")"},{"t":"p","runs":[{"text":"That means what it looks like. C evaluates that line differently. Java rejects it at compile time."}]},{"t":"h2","id":"against-is","runs":[{"text":"==","code":true},{"text":" against "},{"text":"is","code":true}]},{"t":"p","runs":[{"text":"==","code":true},{"text":" asks "},{"text":"are these values equal","i":true},{"text":". "},{"text":"is","code":true},{"text":" asks "},{"text":"are these the same object in memory","i":true},{"text":". They are different questions and only one of them is usually the one you want."}]},{"t":"code","lang":"python","label":"Python","text":"a = [1, 2, 3]\nb = [1, 2, 3]\na == b     # True  — same contents\na is b     # False — two separate lists"},{"t":"p","runs":[{"text":"What makes this dangerous is that "},{"text":"is","code":true},{"text":" appears to work on small numbers and short strings:"}]},{"t":"code","lang":"python","label":"Python","text":"x = 256\ny = 256\nx is y     # True on CPython\nx = 257\ny = 257\nx is y     # do not rely on this result"},{"t":"p","runs":[{"text":"CPython commonly reuses small integer objects. It can also reuse larger integer literals compiled together, so the "},{"text":"257","code":true},{"text":" example may be "},{"text":"True","code":true},{"text":" in a script even when separate interactive statements give "},{"text":"False","code":true},{"text":". These are implementation details, not guarantees about numeric equality. Use "},{"text":"==","code":true},{"text":" to compare values. See the "},{"text":"Python language reference on literals and identity","href":"https://docs.python.org/3/reference/expressions.html#literals-and-object-identity"},{"text":"."}]},{"t":"p","runs":[{"text":"For numeric and text values, use ","b":true},{"text":"==","b":true,"code":true},{"text":".","b":true},{"text":" Use "},{"text":"is None","code":true},{"text":" for a missing-value sentinel; use identity for other objects only when object identity is the question you mean to ask."}]},{"t":"h2","id":"truthiness-what-counts-as-nothing","runs":[{"text":"Truthiness: what counts as nothing"}]},{"t":"p","runs":[{"text":"Any value can be used where a condition is expected. Python treats these as false:"}]},{"t":"ul","items":[[{"text":"False","code":true}],[{"text":"None","code":true}],[{"text":"zero of any numeric type: "},{"text":"0","code":true},{"text":", "},{"text":"0.0","code":true}],[{"text":"empty containers: "},{"text":"\"\"","code":true},{"text":", "},{"text":"[]","code":true},{"text":", "},{"text":"{}","code":true},{"text":", "},{"text":"()","code":true},{"text":", "},{"text":"set()","code":true}]]},{"t":"p","runs":[{"text":"Everything else is true, including "},{"text":"\"0\"","code":true},{"text":", "},{"text":"\"False\"","code":true},{"text":" and "},{"text":"[0]","code":true},{"text":": each of those is a non-empty container or string. That first one bites when reading text files: the string "},{"text":"\"0\"","code":true},{"text":" from a CSV is true."}]},{"t":"p","runs":[{"text":"So the idiomatic test for an empty list is:"}]},{"t":"code","lang":"python","label":"Python","text":"items = []\nif not items:\n    print(\"nothing to do\")"},{"t":"p","runs":[{"text":"rather than "},{"text":"if len(items) == 0","code":true},{"text":". Both work; the first is what Python code looks like."}]},{"t":"h2","id":"and-and-or-do-not-return-booleans","runs":[{"text":"and","code":true},{"text":" and "},{"text":"or","code":true},{"text":" do not return booleans"}]},{"t":"p","runs":[{"text":"This surprises people who know other languages. "},{"text":"and","code":true},{"text":" and "},{"text":"or","code":true},{"text":" return "},{"text":"one of the operands","b":true},{"text":", not "},{"text":"True","code":true},{"text":"/"},{"text":"False","code":true},{"text":":"}]},{"t":"code","lang":"python","label":"Python","text":">>> \"\" or \"default\"\n'default'\n>>> \"Asha\" or \"default\"\n'Asha'\n>>> 0 or \"default\"\n'default'"},{"t":"p","runs":[{"text":"That gives the common idiom "},{"text":"name = user_input or \"guest\"","code":true},{"text":", which fills in a default when the input is empty."}]},{"t":"p","runs":[{"text":"And it gives the bug: if the legitimate value is "},{"text":"0","code":true},{"text":", "},{"text":"\"\"","code":true},{"text":" or an empty list, the default silently replaces it."}]},{"t":"code","lang":"python","label":"Python","text":"form_value = 0                 # the customer really ordered none\nquantity = form_value or 1     # a genuine order of 0 becomes 1"},{"t":"p","runs":[{"text":"When zero is a real answer, test for "},{"text":"None","code":true},{"text":" explicitly:"}]},{"t":"code","lang":"python","label":"Python","text":"quantity = 1 if form_value is None else form_value"},{"t":"p","runs":[{"text":"They also "},{"text":"short-circuit","b":true},{"text":": "},{"text":"a and b","code":true},{"text":" never evaluates "},{"text":"b","code":true},{"text":" if "},{"text":"a","code":true},{"text":" is false. This is not an optimisation detail, it is how you write safe checks:"}]},{"t":"code","lang":"python","label":"Python","text":"items = []\nif items and items[0] == \"x\":     # safe on an empty list\n    print(\"the first item is x\")"},{"t":"p","runs":[{"text":"Reverse the two halves and an empty list raises "},{"text":"IndexError","code":true},{"text":"."}]},{"t":"h2","id":"booleans-are-integers","runs":[{"text":"Booleans are integers"}]},{"t":"p","runs":[{"text":"True == 1","code":true},{"text":" and "},{"text":"False == 0","code":true},{"text":", genuinely, and this is occasionally useful:"}]},{"t":"code","lang":"python","label":"Python","text":"flags = [True, False, True, True]\nsum(flags)      # 3"},{"t":"p","runs":[{"text":"Counting how many things passed a test is "},{"text":"sum(1 for x in items if test(x))","code":true},{"text":" or just "},{"text":"sum(test(x) for x in items)","code":true},{"text":"."}]},{"t":"h2","id":"the-comparison-that-quietly-lies","runs":[{"text":"The comparison that quietly lies"}]},{"t":"code","lang":"python","label":"Python","text":">>> \"10\" < \"9\"\nTrue"},{"t":"p","runs":[{"text":"Strings compare character by character, left to right, so "},{"text":"\"1\"","code":true},{"text":" sorts before "},{"text":"\"9\"","code":true},{"text":" and the whole string does too. Nothing errors. A list of version numbers or ages read from a file and never converted will sort in an order that looks random and is perfectly consistent. This is the same failure as the one in the "},{"text":"input()","code":true},{"text":" lesson, showing up in sorting rather than in arithmetic."}]},{"t":"p","runs":[{"text":"Ordering a string against a number raises a TypeError. Equality still returns a value, so "},{"text":"\"10\" == 10","code":true},{"text":" is "},{"text":"False","code":true},{"text":"."}]},{"t":"code","lang":"python","label":"Python","text":">>> \"10\" < 9\nTypeError: '<' not supported between instances of 'str' and 'int'"},{"t":"p","runs":[{"text":"Python 3 refuses rather than inventing an ordering. Python 2 did invent one, which is why old code silently produced nonsense."}]}],"check":{"question":[{"text":"A form handler writes "},{"text":"discount = entered or 10","code":true},{"text":" so that a blank field becomes 10 percent. A shopkeeper enters 0 to mean no discount and is charged 10 percent off anyway. Why?"}],"options":[{"text":[{"text":"or","code":true},{"text":" returns its second operand whenever the first is falsy, and 0 is falsy, so a deliberate zero is indistinguishable from a blank field."}],"correct":true,"tempting":null},{"text":[{"text":"The entered value arrived as the string “0”, which Python treats as false, so converting it to an int first would fix the bug."}],"correct":false,"tempting":[{"text":"Gets the direction of truthiness backwards: the string “0” is non-empty and therefore true, so this conversion would change the behaviour, not fix it."}]},{"text":[{"text":"or","code":true},{"text":" always returns a boolean, so "},{"text":"discount","code":true},{"text":" became "},{"text":"True","code":true},{"text":" and was coerced to 1 during the calculation."}],"correct":false,"tempting":[{"text":"Applies the boolean-returning behaviour of other languages, which is exactly what Python’s "},{"text":"or","code":true},{"text":" does not do."}]},{"text":[{"text":"The comparison should have used "},{"text":"is not None","code":true},{"text":", because "},{"text":"or","code":true},{"text":" cannot be used with numbers at all."}],"correct":false,"tempting":[{"text":"Names the right fix for the wrong reason, and states a restriction on "},{"text":"or","code":true},{"text":" that does not exist."}]}],"order":[2,0,3,1],"why":null},"prev":{"slug":"formatting-output","title":"Building the output a person will read","minutes":7},"next":{"slug":"if-and-branching","title":"Making a decision: if, elif, else","minutes":7}}}