Functions Returning Values
Functions in Python can not only perform actions but also return values back to the place where they were called. This is very useful when we want to process or use the result of some operation. To return a value from a function, we use the return
keyword. For example:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Outputs: 7
This add
function has two arguments, which it adds together and returns using the return
keyword. We then assign this returned value to the variable result
, which we subsequently print. It is also important to note that returning a value ends the execution of the function. For example:
def rectangle_area(a, b):
if a < 0 or b < 0:
return "Side lengths cannot be negative!"
return a * b
result = add(3, 4)
print(result) # Outputs: 12
result = add(-3, 4)
print(result) # Outputs: Side lengths cannot be negative!
This rectangle_area
function takes two arguments (side lengths of a rectangle) a
and b
and returns the text "Side lengths cannot be negative!"
if any side length is negative. If this occurs, the value is returned and the rest of the function is not executed (return a * b
is not executed). If no side length is negative, the function returns the area of the rectangle using return a * b
. We assign the returned value to the variable result
, which we subsequently print.
Instructions
Complete the subtract
function to return the difference (a-b).
Start programming for free
6/7