{"assignment":{"_schema_version":2,"course_id":37,"date_created":"2022-06-28T19:00:00+00:00","date_modified":"2025-09-14T15:03:08.298870+00:00","extra_instructor_files":"","extra_starting_files":"","forked_id":null,"forked_version":null,"hidden":false,"id":1016,"instructions":"## Introduction to `if` statements\n\n* `if` statement: a body of code that is executed based on a condition\n\nAlmost as fundamental to programming as the function, `if` statements let us make our programs smarter. They let code do different things based a conditional expression.\nIn this chapter, we go into the many ways that `if` statements can be used to control the flow of the program.\nWe see not only `if` statements, but also the similar `elif` and `else` statements, which can only be used in conjunction with `if` statements.\nSince these statements all have bodies, and are compatible with functions, we spend a lot of time talking about how they can be combined together in different ways.\nThe chapter also introduces a sophisticated nuance of conditionals called Truthiness, which let's us use any type (not just booleans) as if they were boolean values.\nFinally, the chapter also touches briefly on the related, advanced concept of \"Event Handling\", specifically in Designer, and how it relates to the idea of `if` statements.\n\n## `if` Statements\n\n```python example-if\nspeed_limit = 50\nweather = 'sunny'\n\nif weather == 'rainy':\n    print(\"It is raining!\")\n    speed_limit = speed_limit - 20\nelse:\n    print(\"Nice day outside!\")\n\nprint(\"Speed limit is:\", speed_limit)\n```\n\nThe first section of the chapter is all about the syntax and usage of `if` statements. The two essential parts are the conditional (which is the expression after the `if` keyword) and the body.\nThe conditional expression is meant to be a question that determines whether the body will be executed, or skipped.\nThe body of an `if` statement is very similar to the body of a function, except they do not have their own scope; they use the same scope as the enclosing body.\nAn `if` statement can also have an `else` statement afterwards, which has its own body.\nShould the conditional of an `if` statement evaluate to `False`, then the `else` body will be executed instead.\nA key insight of the `if` statement is that it let's us skip over some lines, depending on the values of the variables at that step; we call this behavior \"branching\" execution, and it makes tracing the program much more complex.\n\n## Truthiness\n\n```python example-truthiness\nmessage = \"Hello!\"\n\n# Test if `message` is not the empty string\nif message:\n    punctuation = message[-1]\nelse:\n    punctuation = \"No punctuation symbol\"\n\nprint(punctuation)\n```\n\nThe second section of the chapter is about a curious idea called Truthiness.\nConceptually, the conditional of an `if` statement is supposed to be a boolean value, like the result of using the equality operator or greater than operators.\nHowever, in Python (and many other modern languages), you can use any type of value in a conditional.\nWhen you do, Python applies the rules of Truthiness to determine if the value should be treated as `True` or `False`.\nMost values are considered true, with the exception of the empty string, the integer 0, the float 0.0, and the special value `None`.\nAll other values will be considered `True`, allowing us to write convenient shorthand when we want to test if a variable or expression is not one of those values.\nNote that the value does not actually change to become `True` or `False`, this is merely about what Python considers in its mind.\n\n## Nested `if` Statements\n\n```python example-nested-if\nfrom bakery import assert_equal\n\ndef count_sides(shape: str) -> int:\n    if shape == 'triangle':\n        return 3\n    elif shape == 'rectangle':\n        return 4\n    elif shape == 'circle':\n        return 1\n    else:\n        return 0\n\nassert_equal(count_sides('triangle'), 3)\nassert_equal(count_sides('circle'), 1)\nassert_equal(count_sides('octogon'), 0)\n```\n\nThis section covers how `if` statements can be combined together with functions and even other `if` statements to make much more complex programs.\nThe indentation rules for the bodies of these statements are consistent, but can still be tricky to follow.\nThe control flow is also a little bit tricky, since suddenly you can have more than one `return` statement inside of a function, because lines are able to be skipped based on different conditions.\nThis section also introduces the `elif` statement, which can appear any number of times after an `if` statement (but must always be before the `else` statement, if there is one).\nThe `elif` statement allows you to specify bodies that should be executed when the `if` statement (and any previous `elif` statements) are skipped.\nOnly one `if`/`elif`/`else` body will be executed in a chain.\nThe section also covers some ways that `if` statements are misused, such as in functions that return boolean values, or when programmers unnecessarily test for the equality of a boolean value.\n\n## Logical Patterns\n\n* And vs Nested If\n* Defensive Guard\n* Early Return\n* Multiple Return Spots\n* Build-Up-Return\n* Define-and-Refine\n\nTo help see the different ways that `if` statements can be used, the penultimate section covers a list of \"Logical Patterns\" that provide templates of code to you, the programmer. The idea for each pattern is to fill in the blanks of the template, modifying the structure as needed.\nThere are six patterns covered in this section.\nThey can be somewhat narrow in their use, and are more like guidelines than strict suggestions, but should help give more examples of how code can be structured.\n\n## Event Handling\n\n```python complex-route-example\nfrom drafter import *\n\n@route\ndef index(state: int) -> Page:\n    content = Div(\n        \"Current number: \",\n        bold(str(state)),\n        Button(\"Increase\", \"increase_state\"),\n        Button(\"Decrease\", \"decrease_state\"),\n    )\n    return Page(state, content)\n\n@route\ndef increase_state(state: int) -> Page:\n    return index(state + 1)\n\n@route\ndef decrease_state(state: int) -> Page:\n    return index(state - 1)\n\nstart_server(7)\n```\n\nThe final section is about how Drafter flips the usual execution model by building around `route` functions. When a user clicks a link, the corresponding `route` function is executed. This means that we must provide the functions to the `Button` component, without directly calling the function inline. These route functions allow us to have more complicated logic, such as `if` statements, in the routes. ","ip_ranges":"","name":"3) Primer Reading","on_change":"","on_eval":"","on_run":"","owner_id":1,"owner_id__email":"acbart@udel.edu","points":4,"public":true,"reviewed":false,"sample_submissions":[],"settings":"{\n  \"small_layout\": true,\n  \"header\": \"Chapter 3 Primer) If Statements\"\n}","starting_code":"","subordinate":true,"tags":[],"type":"reading","url":"bakery_if_primer_read","version":12},"ip":"216.73.216.157","submission":{"_schema_version":3,"assignment_id":1016,"assignment_version":12,"attempts":0,"code":"","correct":false,"course_id":37,"date_created":"2026-05-20T23:50:34.495386+00:00","date_due":"","date_graded":"","date_locked":"","date_modified":"2026-05-20T23:50:34.495386+00:00","date_started":"","date_submitted":"","endpoint":"","extra_files":"","feedback":"","grading_status":"NotReady","id":2037092,"score":0.0,"submission_status":"Started","time_limit":"","url":"submission_url-76974b63-e129-4721-82ef-c62aa307e68e","user_id":2044772,"user_id__email":"","version":0},"success":true}
