[Tutor] I'm trying to wrap my head around defs

Dave Angel d at davea.name
Tue Dec 4 23:37:00 CET 2012


On 12/04/2012 04:51 PM, frank ernest wrote:
> Opensuse 12.2 python3.2
>  I'm having trouble understanding them.
>  Python is my first language... excluding English.
>  I've already read ALL OF THE PYTHON Language Referance and I still don't "get it."

You usually should start with a tutorial, not with a reference.  A
reference assumes some working knowledge, either from previously doing a
tutorial, or from many other languages where you're really just looking
for differences.

You also need to make sure that the version of both tutorial and
reference matches your version.  Otherwise you'll needlessly confuse
yourself with differences.  This is especially true between Python 2.x
and 3.x.

http://docs.python.org/3.2/tutorial/

>  What do they do?
>  How do they work?

A function definition defines a section of the code that can be called
from multiple places.  Each time it's called, control transfers to the
function's first line, and continues till the function returns.  Then
control continues on the line that contained that function call,
possibly returning a value to be used in that expression.

>  How do you define self?
>  Is self an object, a variable, or what?

'self' is a common convention for the first formal parameter to an
ordinary class method.  But since 'class' is an advanced topic, you'd do
far better to defer thinking about it.

>  How about some over commented examples?
Using the first example of section 4.6 ("Defining Functions") from that
tutorial I gave you a link for.

def fib(n):    # write Fibonacci series up to n
     """Print a Fibonacci series up to n."""
     a, b = 0, 1     #build a tuple of (0,1).  Unpack it to the names a
and b, respectively
                            #equiv. to  a=0;  b=1
     while a < n:    #starts a loop, which will repeat until a >= n
         print(a, end=' ')     #print current value of n, but without a
newline
         a, b = b, a+b        #build a tuple (b, a+b), and then unpack
it to a and b
     print()            #print a newline



>  The if statement is a statement of comparison. what is a def and more specifically a class?
>

The 'if' statement has nothing to do with comparison.  It simply
arranges conditional change in the order of execution, based on the
"truthness" of an expression.  In other words, instead of proceeding in
sequential order, the interpreter skips over either the then-portion or
the else-portion, depending on how the expression evaluates.

The most common USE of an 'if' statement will be of some form like:
    if x<10:

But understand that 'if' doesn't care, as long as the expression can
produce a boolean.




-- 

DaveA



More information about the Tutor mailing list