Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formal and actual parameters in a function in python [duplicate]

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?

like image 444
Czar Luc Avatar asked Dec 05 '25 08:12

Czar Luc


2 Answers

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.

like image 186
juanpa.arrivillaga Avatar answered Dec 07 '25 00:12

juanpa.arrivillaga


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.

like image 28
chepner Avatar answered Dec 07 '25 00:12

chepner