defining functions

Antaeus Feldspar feldspar at ix.netcom.com
Mon Feb 11 01:44:06 EST 2002


Patio87 wrote:
> 
> I am pretty new to python, and I dont understand the parameters when defining
> functions. Whenever I see a function definition with a argument It seems like
> the argument already is a variable, but it goes threw the function and it makes
> no sense. I dont know if what I just said made any sence but if you can help me
> please reply
> 
> def factorial(n):
>     if n == 1:
>         return 1
>     else:
>         return n * factorial(n-1)
> What the hell does 'n' have assingned to it?

I think you must be very new to programming in general, not just to
Python, but that's quite all right.

A function definition tells you how to perform that function in the
abstract.  For instance, if I asked you, "How do you average two
numbers?" you would probably say something to me like the following: 
"Add the first number and the second number together.  Divide their sum
by 2.  There's your answer."  There you go, you've just defined the
averaging of two numbers -- without having to define the numbers
themselves.

If we turned your definition into Python code, it might look like this:

def average_two(first_num, second_num):
  sum = first_num + second_num
  average = sum / 2.0  # Dividing by 2 would abandon any remainder
  return average

There, you've just written a function that the interpreter can use any
time it wants to average *any* two numbers.  If you define average_two
in your interpreter in interactive mode, and then type in

>>> average_two(5, 7)

The interpreter will execute the function you wrote, with a value of 5
for "first_num" and a value of 7 for "second_num".

That's the point of functions:  you define some operation in the
abstract, with abstract inputs that you give variable names to.  Once
you do that, the interpreter then knows how to perform that operation in
the concrete, substituting the actual values.

	-jc



More information about the Python-list mailing list