Formal and actual parameters in a function in pyth

2020-07-31 08:40发布

问题:

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?

回答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.



回答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.



回答3:

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.



回答4:

In Python you defined a function as follow:

  • You start the function blocks with the keyword def 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



回答5:

when a function is defined, it may have some parameters. These parameters are useful to receive values from outside of the function. They are called 'formal arguments'. When we call the function, we should pass data or values to the function. These values are called 'actual arguments'. In the following code, 'a' and 'b' are formal arguments and 'x' and 'y' are actual arguments.

def sum(a, b): #a, b are formal arguments
    c = a+b 
    print(c)

#call the function 
x = 10; y = 15
sum(x, y) #x, y are actual arguments