{"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":"if-and-branching","title":"Making a decision: if, elif, else","url":"https://addaly.com/learn/python-for-ai/if-and-branching","position":9,"of":89,"minutes":7,"answer":"In an if/elif chain only the first true branch runs, so replacing elif with separate ifs lets a later assignment overwrite an earlier correct one with no error.","keyIdea":"In an if/elif chain only the first true branch runs, so replacing elif with separate ifs lets a later assignment overwrite an earlier correct one with no error."},"body":{"format":"markdown","text":"## The shape\n\n```python\nmarks = 72\n\nif marks >= 75:\n    grade = \"distinction\"\nelif marks >= 60:\n    grade = \"first\"\nelif marks >= 40:\n    grade = \"pass\"\nelse:\n    grade = \"fail\"\n\nprint(grade)\n```\n\nFour things are load-bearing here.\n\nThe **colon** ends the condition line. Forget it and you get `SyntaxError: expected ':'`.\n\nThe **indentation** decides what belongs to the branch. Four spaces, consistently. Python does not care whether it is four or two, but it cares that you never change your mind inside one file, and mixing tabs with spaces produces `TabError` at a line that looks identical to the one above it. Set your editor to insert spaces when you press Tab and forget about it.\n\n**`elif` means \"otherwise, if\"** and only one branch ever runs. The moment a condition is true, Python executes that block and skips the rest of the chain.\n\n**`else` has no condition.** It catches everything left.\n\n## The bug that a chain of `if`s creates\n\nWrite the same logic with three separate `if` statements instead:\n\n```python\nif marks >= 75:\n    grade = \"distinction\"\nif marks >= 60:\n    grade = \"first\"\nif marks >= 40:\n    grade = \"pass\"\n```\n\nNow every mark of 80 gets tested three times, all three are true, and `grade` ends up as `\"pass\"` because the last assignment wins. The program produces a wrong answer without any error. This is one of the most common logic bugs in beginner code and it never announces itself.\n\nIf the branches are alternatives, use `elif`. Use separate `if`s only when the conditions are independent and more than one is allowed to fire.\n\n## Order matters inside a chain\n\nReverse the chain and it breaks in a different way:\n\n```python\nif marks >= 40:\n    grade = \"pass\"\nelif marks >= 75:\n    grade = \"distinction\"     # unreachable\n```\n\nEvery mark of 75 already satisfied the first test, so the second is never reached. `distinction` becomes dead code. Nothing warns you.\n\nThe rule for numeric bands: order from the most restrictive to the least, or from the largest threshold down. Then check the boundaries by hand: 39, 40, 59, 60, 74, 75. Boundary errors are where nearly all of these bugs live, and testing exactly the boundary values takes a minute.\n\n## Nesting, and how to avoid it\n\nConditions inside conditions get unreadable fast. The following two fragments preview code inside a function in a larger program. They assume `user` and `place_order()` already exist. A `return` statement exits its containing function. The functions module develops this pattern into a complete program.\n\n```python\nif user is not None:\n    if user.is_active:\n        if user.has_credit:\n            place_order()\n```\n\nTurn it inside out with **guard clauses**: deal with the reasons to stop first, then let the main path sit unindented:\n\n```python\nif user is None:\n    return \"no such user\"\nif not user.is_active:\n    return \"account suspended\"\nif not user.has_credit:\n    return \"insufficient credit\"\nplace_order()\n```\n\nSame logic, one level of indentation, and each rejection now has its own message instead of a silent fall-through. That last part is the real gain: the nested version cannot easily tell you *which* condition failed.\n\n## Two syntax notes\n\n`=` assigns, `==` compares. Writing `if x = 5:` is a `SyntaxError` in Python, which is a small mercy: in C it compiles and quietly assigns.\n\nAn `if` cannot be empty. If you want a branch that does nothing yet, write `pass`:\n\n```python\ndebug_mode = True\n\nif debug_mode:\n    pass    # TODO\n```\n\n## The conditional expression\n\nWhen you are choosing between two values rather than two actions, there is a one-line form:\n\n```python\nage = 20\nstatus = \"adult\" if age >= 18 else \"minor\"\nprint(status)    # adult\n```\n\nRead it as: the value is `\"adult\"`, if `age >= 18`, otherwise `\"minor\"`. Fine for a simple choice, unreadable once nested. If you find yourself writing two of them in one line, use a proper `if` block.\n\n## `match`, since Python 3.10\n\nFor comparing one value against many fixed possibilities there is now a `match` statement:\n\n```python\ncommand = \"stop\"\n\nmatch command:\n    case \"start\":\n        print(\"starting\")\n    case \"stop\" | \"halt\":\n        print(\"stopping\")\n    case _:\n        print(\"unknown command\")\n```\n\nIt is more than a switch (it can destructure lists and dictionaries) but for plain values it reads better than a long `elif` chain. Two honest cautions: it needs 3.10 or newer, and a bare name in a `case` pattern **binds** rather than compares, so `case ready:` matches anything and assigns to `ready`, which is a nasty surprise. Compare against literals or dotted names, and the trap never appears.\n\n## Try this now\n\nWrite the grade chain, then run it with marks of 39, 40, 74, 75 and 100. Then deliberately reverse two branches and watch a correct-looking program give a wrong grade with no error message. That failure mode is worth seeing once on purpose."},"check":{"question":"A shipping calculator uses `if weight > 0: rate = 50` then `if weight > 5: rate = 90` then `if weight > 20: rate = 200`, all as separate `if` statements, and a 3 kg parcel is charged 50 while a 25 kg parcel is charged 200. The developer concludes the logic is fine. What is the risk?","options":[{"text":"There is none: separate ifs and an elif chain are equivalent when the thresholds increase.","correct":false,"tempting":"Generalises from two passing cases; it happens to work only because the bands are ordered smallest-first and later assignments are the intended ones."},{"text":"It is correct here only by accident of ordering; reordering the three lines, or adding a band out of sequence, silently produces a wrong rate because the last matching assignment wins.","correct":true},{"text":"Separate ifs run all three branches, so the 25 kg parcel is actually charged 50 plus 90 plus 200.","correct":false,"tempting":"Confuses repeated assignment with accumulation: each line replaces `rate` rather than adding to it."},{"text":"The first condition should be `>=` rather than `>`, which is the only defect in the code.","correct":false,"tempting":"Spots a real boundary question at zero but treats a genuine structural fragility as a typo."}]},"prev":{"slug":"booleans-and-truth","title":"True, False, and what Python counts as nothing","url":"https://addaly.com/learn/python-for-ai/booleans-and-truth"},"next":{"slug":"how-python-runs-code","title":"What happens between your file and the answer","url":"https://addaly.com/learn/python-for-ai/how-python-runs-code"},"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) 'Making a decision: if, elif, else', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/if-and-branching (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":"Making a decision: if, elif, else","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":"In an if/elif chain only the first true branch runs, so replacing elif with separate ifs lets a later assignment overwrite an earlier correct one with no error.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-shape","runs":[{"text":"The shape"}]},{"t":"code","lang":"python","label":"Python","text":"marks = 72\n\nif marks >= 75:\n    grade = \"distinction\"\nelif marks >= 60:\n    grade = \"first\"\nelif marks >= 40:\n    grade = \"pass\"\nelse:\n    grade = \"fail\"\n\nprint(grade)"},{"t":"p","runs":[{"text":"Four things are load-bearing here."}]},{"t":"p","runs":[{"text":"The "},{"text":"colon","b":true},{"text":" ends the condition line. Forget it and you get "},{"text":"SyntaxError: expected ':'","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"The "},{"text":"indentation","b":true},{"text":" decides what belongs to the branch. Four spaces, consistently. Python does not care whether it is four or two, but it cares that you never change your mind inside one file, and mixing tabs with spaces produces "},{"text":"TabError","code":true},{"text":" at a line that looks identical to the one above it. Set your editor to insert spaces when you press Tab and forget about it."}]},{"t":"p","runs":[{"text":"elif","b":true,"code":true},{"text":" means “otherwise, if”","b":true},{"text":" and only one branch ever runs. The moment a condition is true, Python executes that block and skips the rest of the chain."}]},{"t":"p","runs":[{"text":"else","b":true,"code":true},{"text":" has no condition.","b":true},{"text":" It catches everything left."}]},{"t":"h2","id":"the-bug-that-a-chain-of-ifs-creates","runs":[{"text":"The bug that a chain of "},{"text":"if","code":true},{"text":"s creates"}]},{"t":"p","runs":[{"text":"Write the same logic with three separate "},{"text":"if","code":true},{"text":" statements instead:"}]},{"t":"code","lang":"python","label":"Python","text":"if marks >= 75:\n    grade = \"distinction\"\nif marks >= 60:\n    grade = \"first\"\nif marks >= 40:\n    grade = \"pass\""},{"t":"p","runs":[{"text":"Now every mark of 80 gets tested three times, all three are true, and "},{"text":"grade","code":true},{"text":" ends up as "},{"text":"\"pass\"","code":true},{"text":" because the last assignment wins. The program produces a wrong answer without any error. This is one of the most common logic bugs in beginner code and it never announces itself."}]},{"t":"p","runs":[{"text":"If the branches are alternatives, use "},{"text":"elif","code":true},{"text":". Use separate "},{"text":"if","code":true},{"text":"s only when the conditions are independent and more than one is allowed to fire."}]},{"t":"h2","id":"order-matters-inside-a-chain","runs":[{"text":"Order matters inside a chain"}]},{"t":"p","runs":[{"text":"Reverse the chain and it breaks in a different way:"}]},{"t":"code","lang":"python","label":"Python","text":"if marks >= 40:\n    grade = \"pass\"\nelif marks >= 75:\n    grade = \"distinction\"     # unreachable"},{"t":"p","runs":[{"text":"Every mark of 75 already satisfied the first test, so the second is never reached. "},{"text":"distinction","code":true},{"text":" becomes dead code. Nothing warns you."}]},{"t":"p","runs":[{"text":"The rule for numeric bands: order from the most restrictive to the least, or from the largest threshold down. Then check the boundaries by hand: 39, 40, 59, 60, 74, 75. Boundary errors are where nearly all of these bugs live, and testing exactly the boundary values takes a minute."}]},{"t":"h2","id":"nesting-and-how-to-avoid-it","runs":[{"text":"Nesting, and how to avoid it"}]},{"t":"p","runs":[{"text":"Conditions inside conditions get unreadable fast. The following two fragments preview code inside a function in a larger program. They assume "},{"text":"user","code":true},{"text":" and "},{"text":"place_order()","code":true},{"text":" already exist. A "},{"text":"return","code":true},{"text":" statement exits its containing function. The functions module develops this pattern into a complete program."}]},{"t":"code","lang":"python","label":"Python","text":"if user is not None:\n    if user.is_active:\n        if user.has_credit:\n            place_order()"},{"t":"p","runs":[{"text":"Turn it inside out with "},{"text":"guard clauses","b":true},{"text":": deal with the reasons to stop first, then let the main path sit unindented:"}]},{"t":"code","lang":"python","label":"Python","text":"if user is None:\n    return \"no such user\"\nif not user.is_active:\n    return \"account suspended\"\nif not user.has_credit:\n    return \"insufficient credit\"\nplace_order()"},{"t":"p","runs":[{"text":"Same logic, one level of indentation, and each rejection now has its own message instead of a silent fall-through. That last part is the real gain: the nested version cannot easily tell you "},{"text":"which","i":true},{"text":" condition failed."}]},{"t":"h2","id":"two-syntax-notes","runs":[{"text":"Two syntax notes"}]},{"t":"p","runs":[{"text":"=","code":true},{"text":" assigns, "},{"text":"==","code":true},{"text":" compares. Writing "},{"text":"if x = 5:","code":true},{"text":" is a "},{"text":"SyntaxError","code":true},{"text":" in Python, which is a small mercy: in C it compiles and quietly assigns."}]},{"t":"p","runs":[{"text":"An "},{"text":"if","code":true},{"text":" cannot be empty. If you want a branch that does nothing yet, write "},{"text":"pass","code":true},{"text":":"}]},{"t":"code","lang":"python","label":"Python","text":"debug_mode = True\n\nif debug_mode:\n    pass    # TODO"},{"t":"h2","id":"the-conditional-expression","runs":[{"text":"The conditional expression"}]},{"t":"p","runs":[{"text":"When you are choosing between two values rather than two actions, there is a one-line form:"}]},{"t":"code","lang":"python","label":"Python","text":"age = 20\nstatus = \"adult\" if age >= 18 else \"minor\"\nprint(status)    # adult"},{"t":"p","runs":[{"text":"Read it as: the value is "},{"text":"\"adult\"","code":true},{"text":", if "},{"text":"age >= 18","code":true},{"text":", otherwise "},{"text":"\"minor\"","code":true},{"text":". Fine for a simple choice, unreadable once nested. If you find yourself writing two of them in one line, use a proper "},{"text":"if","code":true},{"text":" block."}]},{"t":"h2","id":"match-since-python-3-10","runs":[{"text":"match","code":true},{"text":", since Python 3.10"}]},{"t":"p","runs":[{"text":"For comparing one value against many fixed possibilities there is now a "},{"text":"match","code":true},{"text":" statement:"}]},{"t":"code","lang":"python","label":"Python","text":"command = \"stop\"\n\nmatch command:\n    case \"start\":\n        print(\"starting\")\n    case \"stop\" | \"halt\":\n        print(\"stopping\")\n    case _:\n        print(\"unknown command\")"},{"t":"p","runs":[{"text":"It is more than a switch (it can destructure lists and dictionaries) but for plain values it reads better than a long "},{"text":"elif","code":true},{"text":" chain. Two honest cautions: it needs 3.10 or newer, and a bare name in a "},{"text":"case","code":true},{"text":" pattern "},{"text":"binds","b":true},{"text":" rather than compares, so "},{"text":"case ready:","code":true},{"text":" matches anything and assigns to "},{"text":"ready","code":true},{"text":", which is a nasty surprise. Compare against literals or dotted names, and the trap never appears."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Write the grade chain, then run it with marks of 39, 40, 74, 75 and 100. Then deliberately reverse two branches and watch a correct-looking program give a wrong grade with no error message. That failure mode is worth seeing once on purpose."}]}],"check":{"question":[{"text":"A shipping calculator uses "},{"text":"if weight > 0: rate = 50","code":true},{"text":" then "},{"text":"if weight > 5: rate = 90","code":true},{"text":" then "},{"text":"if weight > 20: rate = 200","code":true},{"text":", all as separate "},{"text":"if","code":true},{"text":" statements, and a 3 kg parcel is charged 50 while a 25 kg parcel is charged 200. The developer concludes the logic is fine. What is the risk?"}],"options":[{"text":[{"text":"There is none: separate ifs and an elif chain are equivalent when the thresholds increase."}],"correct":false,"tempting":[{"text":"Generalises from two passing cases; it happens to work only because the bands are ordered smallest-first and later assignments are the intended ones."}]},{"text":[{"text":"It is correct here only by accident of ordering; reordering the three lines, or adding a band out of sequence, silently produces a wrong rate because the last matching assignment wins."}],"correct":true,"tempting":null},{"text":[{"text":"Separate ifs run all three branches, so the 25 kg parcel is actually charged 50 plus 90 plus 200."}],"correct":false,"tempting":[{"text":"Confuses repeated assignment with accumulation: each line replaces "},{"text":"rate","code":true},{"text":" rather than adding to it."}]},{"text":[{"text":"The first condition should be "},{"text":">=","code":true},{"text":" rather than "},{"text":">","code":true},{"text":", which is the only defect in the code."}],"correct":false,"tempting":[{"text":"Spots a real boundary question at zero but treats a genuine structural fragility as a typo."}]}],"order":[3,2,0,1],"why":null},"prev":{"slug":"booleans-and-truth","title":"True, False, and what Python counts as nothing","minutes":7},"next":{"slug":"how-python-runs-code","title":"What happens between your file and the answer","minutes":8}}}