Components of a Function
Functions are mainly composed of Parameters
, Arguments
, and Return Values
.
Parameters
Parameters are variables
used when defining a function to determine what kind of input the function will take.
For example, when defining a function that adds two numbers, the parameters are the two numbers to be added.
def add_numbers(a, b):
# Return the sum of a and b
result = a + b
# Return the result
return result
In the code above, the add_numbers
function takes two parameters, a
and b
, and returns the result of adding these two numbers.
Arguments
Arguments are the actual values that you pass to the function when calling it.
For example, when calling add_numbers(3, 5)
, the numbers 3
and 5
are the arguments.
These values are then used within the function as the parameters a
and b
.
def add_numbers(a, b):
result = a + b
return result
# Store the result of adding 3 and 5 in result
result = add_numbers(3, 5)
# Print 8
print(result)
Return Value
In the previous function example, the add_numbers
function returned the result of adding two numbers in the result
variable.
Here, the return keyword is used to return the final result of the function.
A function with a return value sends that value back to where the function was called.
For example, a function to convert a given temperature from Celsius (C) to Fahrenheit (F) can be defined as follows:
# Function to convert input Celsius temperature to Fahrenheit
def celsius_to_fahrenheit(celsius):
# Convert Celsius to Fahrenheit
fahrenheit = celsius * 9 / 5 + 32
# Return the Fahrenheit value
return fahrenheit
# Convert 30 degrees Celsius to Fahrenheit
result = celsius_to_fahrenheit(30)
# Print 86
print(result)
The celsius_to_fahrenheit
function takes the parameter celsius
, which is a Celsius temperature, and returns the converted Fahrenheit value.
When calling celsius_to_fahrenheit(30), the result is that 30 degrees Celsius is converted to 86 degrees Fahrenheit.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.