{"assignment":{"_schema_version":2,"course_id":37,"date_created":"2022-06-28T19:00:00+00:00","date_modified":"2024-10-03T15:11:01.162213+00:00","extra_instructor_files":"","extra_starting_files":"","forked_id":null,"forked_version":null,"hidden":false,"id":998,"instructions":"## Bodies and Scopes\n\n* Body: An indented region of code.\n* Scope: A region describing the lifetime of a variable.\n\nTwo related but distinct ideas are Bodies and Scopes.\nPrograms have both bodies and scopes, and so do functions.\nBut scope and bodies are not the same thing.\nBodies describe a region of code based on indentation.\nScopes describe a region of code where variables exist or do not exist.\nUsually, scopes are a subset of the bodies of the program.\n\n## Bodies\n\n![A block of code is shown with a function definition inside. Markers indicate the entire global body of the program and the body of the function.](functions_scopes_bodies.png)\n\nPrograms are organized into lines called statements.\nEvery program has at least one **body**, which is the main global body.\nPrograms can also have additional bodies, though, through indentation.\nThe statements inside of a function are indented, meaning they have four spaces in front of them.\nThese spaces are not just to help make the program more readable, they have a strict influence on the syntactic correctness of the program.\nImproper number of spaces, or blocks being indented in the wrong places, is a common source of syntax errors.\nEventually, we will learn different ways that bodies can be used, but for now they are almost one-to-one with scopes.\n\n## Scope\n\n* \"Lifetime\"\n* \"Visibility\"\n* \"Availability\"\n* \"How long the variable is available\"\n\nIn a program, the **scope** of a variable indicates how long that variable is available.\nThis is also known as the \"lifetime\" or \"visibility\" of a variable.\nWhen a program is no longer in scope, that variable is no longer available.\n\n## Global Scope\n\n```python example-scope\nprint(\"Starting program\")\ngrade = 64\ngrade = grade + 5\nprint(\"Grade:\", grade)\n```\n\nVariables defined at the top level are known as global variables.\nOnce a variable is defined, it is available on subsequent lines.\nThat variable lives until the end of the program.\nIn the program shown here, the `grade` variable starts its life on the second line and is available until the end of the program.\n\n## Local Scope\n\n```python calculate_grade\ndef calculate_grade(grade:int, weight:float)->float:\n    curved = 100 * grade ** .5 \n    final = curved * weight\n    return final\n\nmy_grade = 90\nthe_weight = .1\ncalculate_grade(my_grade, the_weight)\n```\n\nEach function has its own local scope.\nVariables that are defined as parameters or within a function live until the function ends.\nThese are local variables.\nVariables defined in one function are not available outside the function.\nThis simplifies the reading of any function - you only need to worry about things defined in the function itself.\nIn the program shown here, the local variables are `grade`, `weight`, `curved`, and `final`, because they are all defined inside the body of the function or as parameters.\nOn the other hand, the `my_grade` and `the_weight` variables are global variables.\n\n## Returning Values\n\n```python get_grade\ndef get_grade(points:int, possible:int)->float:\n    grade = points / possible\n    return grade\n\nmy_grade = get_grade(70, 100)\n# This will work fine, `my_grade` is in scope!\nprint(my_grade)\n# This will cause an error, out of scope!\nprint(grade)\n```\n\nFunctions return values, not variables.\nThis is so important, I'm going to say it again: **functions return values, not variables**.\nA variable has a value, so when you write statements like the one shown on the third line, you are returning the variable's value, not the variable itself.\nWhen the program reaches that line, the variable expression is evaluated for its value, which is then returned.\nThe variable disappears after the function ends, so returning the value is the only way to make that value available outside of the function.\nThe `grade` variable has no existence or meaning outside of the function.\n\n## Same Named Variables\n\n![A block of code is shown. There are local variables named `total` and `number` inside of the `add1` function. There are global variables named `total`, `final` and `answer`. These two variables named `total` are unrelated even though they have the same name.](functions_scopes_circles_squares.png)\n\nBeginners will sometimes try to reuse a variable name.\nAny global variables with the same name are unrelated to the variable inside the function.\nIn the image above, there are squares drawn around local variables, and circles drawn around global variables.\nThe variable `total` is a global in some places, and a different local variable in others.\nThose two variables just happen to have the same name, but they are NOT the same variable as far as Python is concerned.\n\n## Scope Rule of Thumb\n\n- Variables inside a local scope should not be used outside that scope.\n- Variables outside a local scope should not be used inside that scope.\n\nHere is a simple pair of rules for working with scope: First, variables inside a local scope should not be used outside that scope.\nSecond, variables outside a local scope should not be used inside that scope.\nKeeping these two rules in mind will avoid many headaches.\nAt any time, you should be able to look at any program and determine if variables are inside or outside of a function's scope, and whether that is appropriate for that variable.\n\n## Global Variables Are Bad\n\n```python global-variables\nfrom bakery import assert_equal\n\nmy_title = \"Mr. \"\ndef add_title(name: str) -> str:\n    titled_name = my_title + name\n    return titled_name\n\nassert_equal(add_title(\"Bart\"), \"Mr. Bart\")\n# Dangerous! Do not change global constants\nmy_title = \"Dr. \"\nassert_equal(add_title(\"Bart\"), \"Dr. Bart\")\n```\n\nIt is technically possible to read a global variable inside a function.\nHowever, you must be careful to do so.\nEvery time you refer to global variables, your program becomes more complicated, and you must think about multiple levels of scope.\nIn this code example shown here, the unit tests would fail if we swapped the order of the last unit tests.\nThis may work out okay in smaller programs, but it causes huge problems as you start writing longer programs.\nSuddenly, you must keep careful track of what a variable's value at any given point in the entire program, rather than just within a function.\nWhenever you feel the urge to use a global variable, stop and reconsider.\n\n## Global Constants Are Good\n\n```python global-constants\nfrom bakery import assert_equal\n\nHOURS_IN_DAY = 24\n\ndef days_to_hours(days: int) -> int:\n    return HOURS_IN_DAY * days\n\nassert_equal(days_to_hours(4), 96)\nassert_equal(days_to_hours(0), 0)\n```\n\nThe only exception is if you are 100% certain that the global variable's value will stay constant and never change.\nWe call these global constants, and unlike global variables, they are a great idea that can dramatically improve the readability of code.\nSee the example below, where we know that the value of `HOURS_IN_DAY` will never change.\nTo make it clear for other programmers that `HOURS_IN_DAY` is a constant, we write its name in all capital letters.\nNow, instead of having the magic number `24` mysteriously in our function definition, other developers reading our code will see that the number represents the number of hours in a day.\nThat same value could be reused in other parts of the program too.\n\n\n## Summary\n\n- Code indented below a function is said to be in the \"body\" of the function. The entire program itself is also a body of code.\n- The body of a function defines a region with \"scope\", which controls the lifetime of a variable.\n- Variables defined inside of a function, as well as parameters, are considered local to the function. Variables defined at the top-level of the program are considered global to the function.\n- Functions return values, not variables. There is no way for a local variable to be used after the function has ended. However, the value inside of the variable can be evaluated and returned from the function.\n- There are two scope rules that we follow:\n  - Variables defined inside of a function cannot be used outside of a function.\n  - Variables defined outside of a function should not be used inside of the function.\n- The exception to the second scope rule is when the variable is a global constant; then it is appropriate to define the variable once outside of the function and then use it anywhere else in the program.\n- A global constant is a variable defined in the top-level whose value never changes, and has a name written in all capital letters.\n- Two variables with the same name in the same scope refer to the same variable. However, two variables in different local scopes should be treated like different variables, even if they do have the same name.\n\n","ip_ranges":"","name":"2B1) Scopes and Bodies 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\": \"Scope and Bodies\",\n  \"slides\": \"bakery_functions_scopes.pdf\",\n  \"youtube\": {\n    \"Bart\": \"QFTz7x9OVBA\",\n    \"Amy\": \"yl8RfTDyyy8\"\n  },\n  \"video\": {\n    \"Bart\": \"https://blockpy.cis.udel.edu/videos/bakery_functions_scopes-Bart.mp4\",\n    \"Amy\": \"https://blockpy.cis.udel.edu/videos/bakery_functions_scopes-Amy.mp4\"\n  },\n  \"summary\": \"In this lesson, you will learn how the \\\"scope\\\" (or availability) of a variable changes with respect to a function.\",\n  \"small_layout\": true\n}","starting_code":"","subordinate":true,"tags":[],"type":"reading","url":"bakery_functions_scopes_read","version":8},"ip":"216.73.216.157","submission":{"_schema_version":3,"assignment_id":998,"assignment_version":8,"attempts":0,"code":"","correct":false,"course_id":37,"date_created":"2026-05-20T14:01:58.440826+00:00","date_due":"","date_graded":"","date_locked":"","date_modified":"2026-05-20T14:01:58.440826+00:00","date_started":"","date_submitted":"","endpoint":"","extra_files":"","feedback":"","grading_status":"NotReady","id":2036939,"score":0.0,"submission_status":"Started","time_limit":"","url":"submission_url-d01b03f4-3e9d-47cf-9357-7927b8a24e3d","user_id":2044668,"user_id__email":"","version":0},"success":true}
