functions(): the silent heroes of programming

academics computer science functions

Are you ever nostalgic of the days of long division? Or annoyed that a tape measure makes determining the dimensions of a new couch so simple?

If you’re like me, the answer is no. Sure, I might be able to convince myself that doing a few division problems by hand would be fun or that I might enjoy measuring my new couch in terms of bowtie pasta, rather than inches. But I couldn’t imagine doing every division problem by hand or always bringing a bag of pasta with me when I need to measure something. Just like calculators and rulers are tools that make our lives easier, functions make programming easier. 

But what is a function, anyway? Functions are pieces of code that you can use over and over again. For example, say that you want to calculate how long your readings for the week will take you. You know that you have 30 pages of readings for history, 10 pages of reading for psychology, and 22 pages for biology. You also know that you are faster at finishing your readings for history (90 seconds/page) and psychology (100 seconds/page) than for biology (120 seconds/page), so you can calculate your total reading time with the following equation:

Screen Shot 2023-08-10 at 11.36.09 AM

If you only had to do this calculation once, then writing this formula by hand makes sense. But imagine you want to calculate your reading time every week and the number of pages you are assigned is constantly changing! To save time, you could write a function. Just like an online cookie recipe changes the number of teaspoons of vanilla from 1 to 1.5 when you increase the servings from 12 to 18, your function would update the total reading time based on the number of pages you were assigned for the week. How?

Rather than using specific numbers, like 30 pages of history readings, functions rely on global variables. Global variables are essentially placeholder text that can take on different values. In our example, we might have a global variable for the number of history pages, the number of psychology pages, and the number of biology pages because these values change every week! We can re-write our formula using global variables like this:

Screen Shot 2023-08-10 at 11.38.16 AM

With this new formula, all we have to do is assign a value to each global variable (e.g., # history pages = 25, # psychology pages = 45, and # biology pages = 7), and voilà! We have a new weekly reading time.

Now that we have the intuition, how do we translate our formula into a function? First, we need to put our formula inside code that can tell our computer that we are writing a function. In R, our function (named weeklyTime, but you can name your function anything!) would look like this:

Screen Shot 2023-08-10 at 11.38.52 AM

The block of code might look scary but let us focus on three things. First, we have stored (i.e., saved for later use) our function by naming it “weeklyTime” and assigning it the values on the right of the carrot. Second, our global variables appear in two places, in the formula (just like we did above) and, newly, on the first line. The global variables on the first line are the function’s arguments or the values that a user can change every time they use the function (e.g., 30 versus 25 pages of history readings). The arguments have the same name as the global variables in our formula because if you tell your computer that you have 25 pages of history readings, then it should use 25 within the formula. Third, you only have to write this block of code once. After it is written, you can calculate your reading time by calling the function and specifying the value for each global variable. 

To illustrate, if you had 25 pages of history readings, 45 pages of psychology readings, and 7 pages of biology readings, you would write the following line of code: weeklyTime(25, 45, 7). This time, the code is much shorter because your computer already remembers the formula; all you must specify is the number of pages for each subject (other example inputs and outputs are below). Do you see how much shorter this code is than writing out the full formula – e.g., (25*90) + (45*100) + (7*120) – every time? And imagine how much more arduous the process would be with a more complicated computation.

Screen Shot 2023-08-10 at 11.39.32 AM

In summary, functions are shortcuts that allow us to use the same block of code over and over, but with different values. In the example above, we created our own function. But the beauty of programming languages is that you don’t have to do everything yourself! Many functions are pre-programmed for you, and you can use them by calling the function and specifying the value for each argument – just like we did for our handmade function. 

So, the next time you are writing code, ask yourself: Will I have to do this again? Do many people do this computation? If the answer is yes to either question, then a function might be your friend.


academics study skills MCAT medical school admissions SAT college admissions expository writing English MD/PhD admissions writing LSAT GMAT strategy GRE physics chemistry math biology graduate admissions ACT law school admissions interview prep test anxiety language learning academic advice MBA admissions premed personal statements homework help career advice AP exams creative writing MD study schedules Common Application summer activities test prep history computer science philosophy organic chemistry secondary applications supplements economics PSAT admissions coaching grammar mathematics research law statistics & probability psychology 1L ESL CARS SSAT covid-19 dental admissions legal studies logic games reading comprehension USMLE engineering Spanish calculus parents Latin verbal reasoning DAT PhD admissions case coaching excel mentorship political science AMCAS French Linguistics MBA coursework Tutoring Approaches academic integrity chinese medical school Anki DO English literature Social Advocacy admissions advice algebra astrophysics biochemistry business classics diversity statement genetics geometry kinematics mental health presentations quantitative reasoning skills study abroad time management work and activities IB exams ISEE MD/PhD programs STEM adjusting to college algorithms art history artificial intelligence athletics business skills careers cold emails data science functions gap year international students internships letters of recommendation logic mechanical engineering poetry resume science social sciences software engineering tech industry technical interviews trigonometry 2L 3L AAMC Academic Interest DMD EMT FlexMed Fourier Series Greek Health Professional Shortage Area Italian Lagrange multipliers London MD vs PhD MMI Montessori National Health Service Corps Pythagorean Theorem Python Sentence Correction Step 2 TMDSAS Taylor Series Zoom acids and bases amino acids analysis essay architecture argumentative writing art art and design schools art portfolios biomedicine brain teaser campus visits cantonese capacitors capital markets cell biology central limit theorem centrifugal force chemical engineering chess chromatography class participation climate change clinical experience community service constitutional law consulting cover letters curriculum dementia demonstrated interest dental school dimensional analysis distance learning electric engineering electricity and magnetism enrichment escape velocity european history executive function finance first generation student freewriting fun facts genomics graphing harmonics health policy history of medicine history of science hybrid vehicles hydrophobic effect ideal gas law induction infinite information sessions institutional actions integrated reasoning intern investing investment banking lab reports linear algebra linear maps mandarin chinese matrices mba medical physics meiosis microeconomics mitosis music music theory neurology neuroscience office hours operating systems organization pedagogy phrase structure rules plagiarism potential energy pre-dental proofs pseudocode psych/soc qualifying exams quantum mechanics relativity