Formal and actual parameters in a function in python
Solution 1
A formal parameter, i.e. a parameter, is in the function definition. An actual parameter, i.e. an argument, is in a function call.
So n
here:
def factorial(n):
Is a formal parameter.
And n - 1
(or rather, the value it evaluates to) here:
return n * factorial(n-1)
Is an "actual parameter", i.e. an argument.
Solution 2
The formal parameter is the name you use to refer to the actual parameter (aka argument) to the function. In your definition of factorial
, n
is the formal parameter. In the call to factorial
, the value of the expression n - 1
serves as the actual parameter which inside the recursive call is bound to (again) the formal parameter n
.
Solution 3
In Python you defined a function as follow:
You start the
function
blocks with the keyworddef
followed by the function name and parentheses()
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
In the code you provided. the function factorial
takes a parameter n
. So for example when I call the function factorial(1+2+3)
the expression 1+2+3
get interpreted and becomes 6
and passed in as the function argument to fit parameter n
.
So in your function factorial
where you called factorial(n+1)
you are passing in whatever value generate by n+1
in to factorial
as the parameter n
Solution 4
The n
in the factorial(n)
definition is the formal parameter, as it is the parameter with which the function is being defined. The n-1
in the factorial(n-1)
call is an actual parameter, as that is the parameter which the function is being called with.
Related videos on Youtube
Czar Luc
Updated on June 07, 2021Comments
-
Czar Luc almost 3 years
I'm kind of confused on how to identify the formal and actual parameters in a recursive function. For example in this block of code for getting the factorial of a number:
def factorial(n): if n == 1: return 1 else: return n * factorial(n-1)
Is "factorial(n-1)" the formal parameter since it is inside the function itself? Or is it the actual parameter because it assigned a value for the function. Also, is the "factorial(n)" the formal parameter as well?