{"assignment":{"_schema_version":2,"course_id":37,"date_created":"2022-06-28T19:00:00+00:00","date_modified":"2025-09-14T15:05:16.682175+00:00","extra_instructor_files":"","extra_starting_files":"","forked_id":null,"forked_version":null,"hidden":false,"id":968,"instructions":"# Functions\n\n## Introduction to Functions\n\n* Functions: Reusable chunks of code that can be used to build up more complicated programs.\n\nFunctions are one of the most important concepts in this entire book, so we start off with them here in the second chapter.\nSome people refer to functions as the \"atomic unit of a program\", since programs are built out of functions.\nIn fact, functions have many of the same properties and affordances as programs.\nFundamentally, you can think of a function as a miniature program with its own input, processing, output workflow.\nIn other words, they are reusable chunks of code.\nFunctions are critically important not only to this chapter, but to this course, and even to the rest of your career as a computer scientist.\n\n## Calling Functions\n\n```python example-calling\n# The `input` function\nheight = input(\"How tall are you, in inches?\")\n# The `int` function\nheight = int(height)\n# The `round` function\nfeet = round(height / 12)\n# The `print` function\nprint(\"You are\", feet, \"feet tall, rounded to the nearest foot.\")\n```\n\nThe first two sections of this chapter are dedicated to *calling* functions, which is how functions are used.\nWhen you call a function, you put parentheses after the name of the function.\nSometimes you also provide *arguments*, which are values that go inside the parentheses.\nYou might think of a function as a mysterious box that you cannot see inside of.\nThe arguments are slots on top of the box that you can put data into.\nThen, more data will come out of the bottom of the box, which we call the *returned* values.\nThese values are substituted back into the program, just like how other operations evaluate to other values.\nPython has many built-in functions, some of which you are already familiar with: `input`, `int`, `round`, and `print` are four examples shown here.\n\n## Defining Functions\n\n```python example-defining\ndef average(num1: int, num2: int) -> int:\n    \"\"\"\n    Calculate the average of two integers, returning an integer.\n    \"\"\"\n    return (num1 + num2) // 2\n\nresult = average(5, 10)\nprint(result)\n```\n\nThe subsequent two sections are about how to define your own functions.\nCritically, the programmer must use the `def` keyword and provide a lot of information about the function.\nOne of the most important pieces of information is the name of the function, which in the example shown is `average`.\nThe programmer must also provide formal names for the expected arguments to the function, and the expected types of those names.\nThese names are called *parameters*, and they become variables for the function to use.\nThe programmer must also include the expected return type for when the function is called, which in this case is the `-> int` part.\nThe line with the `def` keyword is known as the *header* of the function, and the following indented lines below it are the *body*.\nThe first line of the body is string literal value, known as a docstring, that explains the function's purpose.\nSubsequent lines of the body are the instructions that will be executed when the function is called, with the final line being the `return` statement.\nOnce defined, functions can be called just like the built-in functions.\n\n## Testing Functions\n\n```python example-testing\nfrom bakery import assert_equal\n\ndef average(num1: int, num2: int) -> int:\n    \"\"\"\n    Calculate the average of two integers, returning an integer.\n    \"\"\"\n    return (num1 + num2) // 2\n\nassert_equal(average(5, 10), 7)\nassert_equal(average(0, 0), 0)\nassert_equal(average(1, 3), 2)\n```\n\nJust because you wrote a function, does not mean the function works correctly.\nAn entire section is dedicated to talking about how functions must be unit tested to try to prove their correctness.\nA unit test is a special line provided in the program that shows an example input and the expected output when the function is working correctly.\nUnit testing requires strong critical thinking skills.\nIn this course, we use a library named `bakery` that has a special function named `assert_equal` that can be used to test your programs.\nGoing forward, we will expect you to test all of your functions!\n\n## Debugging\n\n* Unit Testing\n* Tracing\n* Wolf-fence Debugging\n* Rubber-duck Debugging\n* Scientific Method\n\nAt the end of Part A, there is a quick chapter about different debugging strategies.\nSince programs get significantly more complicated around now, it is useful to learn how professional programmers go about figuring out how to make their programs work correctly.\nStrategies covered include learning how to talk to rubber ducks, fencing in wolves, and making random guesses.\n\n## Scopes and Bodies\n\n```python example-scope\n# num1 and num2 are local variables for average\n\ndef average(num1: int, num2: int) -> int:\n    return (num1 + num2) // 2\n\n# my_height, your_height, and averaged_height are global variables\nmy_height = 40\nyour_height = 62\naveraged_height = average(my_height, your_height)\n```\n\nThe indented region under the header of a function is known as the *body* of the function.\nThe body of the function is the same concept as the body of a module.\nIn other words, every program has at least one body, and then every function also has its own body.\nA separate-but-related concept is the idea of Scope, which is a body that controls the lifetime of variables.\nAny variable inside of a scope will only be available inside of that scope, so when that scope ends, the variable is no longer available.\nThere is also a special global scope for the entire program, but you must be especially careful to avoid global variables inside of your functions.\n\n## Docstrings\n\n```python example-docstring\ndef average(num1: int, num2: int) -> int:\n    \"\"\"\n    Calculate the average of two integers, returning an integer.\n    \"\"\"\n```\n\nWe previously mentioned that the first line of the function's body should always be a string literal.\nSpecifically, it should always be a triple-quoted string with specially formatted contents.\nThis is a special kind of comment that Python recognizes as the function's docstring.\nA docstring is a very important kind of documentation that helps explain the purpose of a function for other programmers.\nEach line of the string should be indented to match the body of the function.\nA common mistake is to try to put the docstring before or after the function.\nHowever, docstrings only count if they are the first line of the body of the function!\n\n## Data Flow\n\n```python example-flow\ndef add5(number: int) -> int:\n    result = number + 5\n    return result\n\ndef double_and_add5(value: int) -> int:\n    answer = 2 * add5(value)\n    return answer\n\nfinal = double_and_add5(7)\nprint(final)\n```\n\nThe third section of Part B is one of the most critical and confusing ideas, which is Data Flow.\nMetaphorically, data flows through a program from its inputs to its outputs, being transformed and modified along the way.\nUp until now, that flow went from the top of the module to the bottom.\nBut now, program execution will actually jump around according to the rules of function calls and returns.\nIt is critical to track what data is available at each step of the program.\nThis is especially true when we start calling functions from within functions.\n\n## External Functions\n\n```python example-externals\nfrom drafter import *\n\n@route\ndef index() -> Page:\n    return Page(Div(\n        italic(\"This\"),\n        \" is \",\n        bold(\"exciting!\"),\n    ))\n\nstart_server()\n```\n\nThe final section of this chapter acknowledges that although Python has a lot of useful built-in functions, we will often need even more functions.\nJust like how variables can be defined in other modules, functions can also be defined externally in modules and then imported.\nOnce imported, they can be used to build truly magical programs.\nSome of the examples in this section involve creating web applications using a library named `drafter`.\nWe will learn more about Drafter in subsequent chapters and activities.","ip_ranges":"","name":"2) Primer","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 2 Primer) Functions\"\n}","starting_code":"","subordinate":true,"tags":[],"type":"reading","url":"bakery_functions_primer_read","version":10},"ip":"216.73.216.157","submission":{"_schema_version":3,"assignment_id":968,"assignment_version":10,"attempts":0,"code":"","correct":false,"course_id":37,"date_created":"2026-05-20T16:04:50.434111+00:00","date_due":"","date_graded":"","date_locked":"","date_modified":"2026-05-20T16:04:50.434111+00:00","date_started":"","date_submitted":"","endpoint":"","extra_files":"","feedback":"","grading_status":"NotReady","id":2037048,"score":0.0,"submission_status":"Started","time_limit":"","url":"submission_url-ca878873-eab7-4081-9f7e-26dc340cd19d","user_id":2044700,"user_id__email":"","version":0},"success":true}
