The variable “difference” isn’t defined

thanks for your help. I’ve got the function working. I’ll continue to practice defining functions.

1 Like

Extra Study

Very soon, if it hasn’t already, the subject of protecting the global namespace will surface wherein is discussed the danger of having functions that access global variables, such as the one above.

Written as it is, it can only work with the two globals, square and cube which MUST be defined or the function will raise an error. This is referred to as dependency and makes the function non-reusable unless we update the globals.

We address this concern by giving arguments in our function calls and parameters in the definition signature line.

def difference_between(a, b):
    return b - a

The function has two positional parameters which will be matched by two positional arguments in the call…

square = num ** 2
cube = num ** 3
difference = difference_between(square, cube)
print (f"The difference between {cube} and {square} is {difference}")

There is not a lot of difference save that now the function can be given any two values to find the difference between them. The order of the arguments determines what values are taken by the parameters.

1 Like