{"assignment":{"_schema_version":2,"course_id":37,"date_created":"2022-06-28T19:00:00+00:00","date_modified":"2023-09-10T02:19:27.385465+00:00","extra_instructor_files":"","extra_starting_files":"","forked_id":null,"forked_version":null,"hidden":false,"id":1025,"instructions":"## Nesting\n\n```python age-price-example\nage = 22\ncost = 45\n\nif age > 21:\n    if cost < 10:\n        print(\"Buy\")\n    else:\n        print(\"Too expensive\")\nelse:\n    print(\"Too young\")\n```\n\nA program is made up of a sequence of statements known as a _body_.\nWe sometimes refer to bodies as a block or chunk of code.\nWith `if` statements and function definitions, we have ways of putting a smaller body inside of the main global body.\nBut now, we will see that we can also put `if` statements inside of `if` statements and functions.\nWe call this _nesting_ the bodies inside of each other.\nAs you develop more complex programs, you will do a lot of nesting.\n\n## Branches\n\n![A diagram of code with an `if` statement nested inside of an `if` statement. Lines show the three branches made by the nested control flow.](bakery_if_nesting_branches.png)\n\nThe code shown here has 3 branches.\nThe outer `if` statement has two branches.\nThe inner `if` statement is on the `True` path of the outer `if` and has two branches of its own.\nThe `else` body does not have any further branches.\nThat means there are three branches in total.\nThe reason that there are three branches is because the first branch is divided into two parts.\nIn other words, each new `if` only adds one new branch to the existing number of branches.\nThe following diagram overlays the paths of the branches.\n\n## Number of Spaces\n\n![Code is shown on the right, with nested if statements. On the left, annotations point out that there are: 0 spaces on the first and sixth lines; 4 spaces on the second, fourth, and last lines; and 8 spaces on the third and fifth lines.](bakery_if_nesting_number_spaces.png)\n\nEvery time you nest a block of statements inside another block, the body of the block gets indented another 4 spaces.\nNote the Python code on the right side of the diagram and the numbers on the left.\nEach level of nesting increases the number of space characters by 4.\nThese are called _the whitespace rules_, and they can be confusing, but they are consistent.\nThe amount of whitespace controls what code is in what body.\n\n## IF and Functions\n\n```python nested-if-function\nfrom bakery import assert_equal\n\ndef adjust_price(price: float, age: int) -> float:\n    if age > 60:\n        return price * .8\n    else:\n        return price\n\nassert_equal(adjust_price(5.75, 63), 4.60)\nassert_equal(adjust_price(5.75, 45), 5.75)\n```\n\nYou can put `if` statements inside of functions.\nIn fact, this is both common and useful.\nRemember the whitespace rules when this occurs.\nEach nested block is indented another 4 spaces.\nIn the following function `adjust_price`, the first line of the body is indented four spaces, but the second line of the body is indented 8 spaces.\nThe first line after the body of the function is not indented; in fact, that's what makes it the first line AFTER the body \u2014 it's not indented.\n\n## What Goes Inside?\n\n```python inside-outside\ncost = int(input(\"What is the cost?\"))\n\n# One line in body\nif cost > 5:\n    discount = 1\nprice = 2\n\n# Two lines in body\nif cost > 5:\n    discount = 2\n    price = 3\n```\n\nIt can be difficult to know if a line of code belongs inside or outside of a block.\nYou must think critically about what you are trying to do with the `if` block.\nRemember: Statements inside the `if` block are executed _only if_ its conditional evaluates to `True`.\nIn the code shown here, the first assignment of the `price` variable is AFTER the `if` statement's body, while the second assignment is INSIDE of the `if` statement.\nThat means the first assignment will always be executed, but the second assignment may or may not be executed _depending on_ the value of `cost`.\n\n## ELIF block\n\n![Two equivalent blocks of code are shown, one with an elif statement and one with a combination of else and if statements.](bakery_if_nesting_if_elif.png)\n\nIn addition to the `if` and `else` blocks, there is a third type: `elif`.\nThe `elif` is exactly the same as _an `else` block with an `if` statement inside_.\nAlthough they do not offer any new power, they are sometimes more convenient to write.\n## Two IFs vs ELSE IF\n\n![Two NOT equivalent blocks of code are shown, one with a pair of `if` statements and one with an `if` and `elif` statement](bakery_if_nesting_if_if_elif.png)\n\nThe preceding two pieces of code may look similar, but they are quite different.\nThe first piece of code on the has two `if` statements, and both `if` statements will always be evaluated and potentially executed.\nThe second piece of code has an `elif` statement, and the `elif` statement _will only be evaluated if the_ _`if` statement evaluates_ _to false_.\n\n## Unnecessary IF\n\n```python unnecessary-if\ndef check_senior(age: int) -> bool:\n    # This `if` statement is unnecessary!\n    if age > 60:\n        return True\n    else:\n        return False\n\n# Exactly equivalent to\ndef check_senior(age: int) -> bool:\n    return age > 60\n```\n\nTwo kinds of mistakes are very common with `if` statements.\nThe first common mistake is using an `if` statement when a conditional expression is fine on its own.\nFor example, consider the following function definition that returns `True` if the parameter is greater than 5 or otherwise returns `False`.\nThe conditional expression already evaluates to either `True` or `False`, so it was unnecessary to use an `if` statement.\nInstead, you can directly return the result of the conditional expression as demonstrated in the second part of the example.\nYou do not need to use `if` statements if you are just returning `True` and `False`!\n\n## Unnecessary Test\n\n```python unnecessary-test\ndef check_toddler(age: int):\n    # The `== True` part is redundant!\n    return (age >= 5) == True\n\ndef check_toddler(age: int):\n    # Much better!\n    return age >= 5\n```\n\nA second common mistake is to test if a Boolean expression is equal to `True`.\nAlthough the following expression `age >= 5 == True` makes sense in English, it is redundant in Python.\n`age > 5` already evaluates to either `True` or `False`.\nIf you compare a Boolean value to `True`, then the result is the same Boolean value.\nNothing is accomplished; you have simply made your code more complex.\nIt's just like adding zero or multiplying by one, or adding the empty string to a string.\nLiterally nothing happens.\n`True` would become `True`, and `False` would become `False`.\n\n## Summary\n\n- An `if` statement can be nested inside of an `if` statement, allowing for more complex control flow.\n- An `if` statement can also be nested inside of a function definition.\n- Each time you nest a body inside of another body, you increase the indentation of the resulting body by four spaces.\n- Each `if` statement introduces a new branch in the code, regardless of whether there is an `else` body.\n- An `elif` body can be added after an `if` or existing `elif` statement. An `elif` is used to introduce another branch in the code with a separate condition. The body of the `elif` will only be executed if the prior `if` and `elif` statements did not execute.\n- Chained `if` statements are not equivalent to `elif` statements. However, `elif` statements are equivalent to `else` statements that have an `if` statement inside their body.\n- Special care must be taken to determine if a statement belongs before, after, or inside of a body, which is determined by the amount of indentation.\n- If a function returns a Boolean value, an `if` statement is often unnecessary compared to just directly returning the conditional.\n- If a conditional expression tests whether a value is equal to the Boolean literal value `True`, that test can often be removed since it has no effect on the outcome of the conditional.\n","ip_ranges":"","name":"3B1) Nested If Statements Reading","on_change":"","on_eval":"","on_run":"","owner_id":1,"owner_id__email":"acbart@udel.edu","points":0,"public":true,"reviewed":false,"sample_submissions":[],"settings":"{\n  \"header\": \"Nested If Statements\",\n  \"slides\": \"bakery_if_nesting.pdf\",\n  \"youtube\": {\n    \"Bart\": \"xE5tpGx9jkg\",\n    \"Amy\": \"2fpzaBueVDU\"\n  },\n  \"video\": {\n    \"Bart\": \"https://blockpy.cis.udel.edu/videos/bakery_if_nesting-Bart.mp4\",\n    \"Amy\": \"https://blockpy.cis.udel.edu/videos/bakery_if_nesting-Amy.mp4\"\n  },\n  \"summary\": \"In this lesson, you will learn about IF statements. These affect the flow of your program so that you can do different things at different times. In other words, IF statements make your program smart and adaptable to different situations.\",\n  \"small_layout\": true\n}","starting_code":"","subordinate":true,"tags":[],"type":"reading","url":"bakery_if_nesting_read","version":7},"ip":"216.73.216.157","submission":{"_schema_version":3,"assignment_id":1025,"assignment_version":7,"attempts":0,"code":"","correct":false,"course_id":37,"date_created":"2026-05-20T12:42:02.370929+00:00","date_due":"","date_graded":"","date_locked":"","date_modified":"2026-05-20T12:42:02.370929+00:00","date_started":"","date_submitted":"","endpoint":"","extra_files":"","feedback":"","grading_status":"NotReady","id":2036763,"score":0.0,"submission_status":"Started","time_limit":"","url":"submission_url-0bbe7c9d-1f90-4cab-ab0d-c3c9c0b3b5a7","user_id":2044660,"user_id__email":"","version":0},"success":true}
