Jump to content

3.4.2 Parameters and Return Values

From Computer Science Knowledge Base

3.4.2 Parameters and Return Values

Imagine you have a robot that can make smoothies. To make a smoothie, the robot needs to know what ingredients to use (like bananas, strawberries, milk). After it makes the smoothie, it gives you the finished drink.

In programming, functions often need information to do their job, and they can also give back a result after they're done.

  • Parameters (Inputs):
    • Parameters (sometimes called arguments) are the pieces of information that you pass into a function when you call it. They are like the ingredients you give to the smoothie robot.
    • They allow functions to be flexible and work with different data each time they are used.
    • When you define a function, you list the parameters it expects inside the parentheses ().

Example: A function to add two numbers would need two parameters:

function add(number1, number2):

   result = number1 + number2

   return result

  • When you call it: add(5, 3) (here, 5 and 3 are the arguments passed to the parameters number1 and number2).
  • Return Values (Outputs):
    • A return value is the result that a function sends back after it has finished its task. It's like the finished smoothie the robot gives you.
    • Not all functions have a return value. Some functions just do something (like printing a message) and don't need to give back a specific result. These are often called void functions in some languages.
    • If a function has a return value, you specify the type of data it will return when you define the function (e.g., int if it returns a whole number, String if it returns text).
    • The return keyword is used inside the function to send the value back.

Example:

function calculateArea(length, width):

   area = length * width

   return area // This function returns the calculated area

When you call it:

my_room_area = calculateArea(10, 5) // my_room_area will now be 50

Parameters make functions useful for different situations, and return values allow functions to give back results that other parts of your program can use.

Bibliography: