How do functions and parameters work?
A function is like a recipe in a cookbook, and parameters are the specific ingredients you choose to use. Instead of writing out the exact same instructions every time you want to bake a cake, you just refer to the recipe and specify the flavor you want.<br><br>In programming, a function is a named block of code designed to perform a specific task. Parameters are the variables listed inside the parentheses in the function definition. They act as placeholders for the actual data you pass in when you tell the program to run the function.
What is a function?
A function is a reusable sequence of statements. When you write a program, you often find yourself doing the same task multiple times. Instead of copying and pasting the same lines of code, you group them together, give them a name, and create a function. Whenever you need that task done, you simply call the function's name. This makes your code shorter, easier to read, and much easier to fix if you find a bug.
Understanding parameters and arguments
While a function is a set of instructions, parameters let you customize how those instructions run. A parameter is a variable defined in the function declaration. An argument is the actual value you supply when you call the function. Think of the parameter as a parking space and the argument as the specific car parked in it. When the function runs, it uses the arguments in place of the parameters.
Returning values
Functions do not just execute actions; they can also calculate and send information back to the main program. This is done using a return statement. If a function is like a mathematical machine, the parameters are what you drop into the top, and the return value is what pops out the bottom. For example, takes as a parameter and returns the new value.
Where students slip up
A common mistake is confusing a function's local variables with global variables. The parameters inside a function only exist while that function is running. This is called variable scope. If you try to use a parameter's name outside of its function, the program will throw an error because it has no memory of that variable outside the function's block.
Worked through
Write a function that calculates the area of a rectangle, and explain how the parameters work when finding the area of a rectangle with a width of 5 and a height of 10.
First, we define a function named calculate_area. We give it two parameters: width and height. The code inside the function multiplies width by height and returns the result. When we call the function, we write calculate_area(5, 10). The number 5 is the argument that gets assigned to the width parameter, and 10 is the argument assigned to the height parameter. The function calculates and returns .
Questions students ask
Ask about this topic
Where this comes from: OpenStax Computer Science Principles · Khan Academy Intro to Computer Science
See also