[Tutor] Re: List Comprehensions again [an example with the interpreter]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 27 Jan 2002 20:35:20 -0800 (PST)


On Sun, 27 Jan 2002, Erik Price wrote:

> On Friday, January 25, 2002, at 10:19  PM, Danny Yoo wrote:
> 
> > ###
> > for w in words:
> >     if w[-1] == 's':
> >         print w
> > ###
> 
> Is using the three hashes a standard way of marking up example code in 
> Python?  I see it a lot on this list, and was wondering if it was 
> specific to the language or just a convention of this list.

It's a completely arbitrary convention.  The hash mark '#' is the comment
symbol in Python --- it comments the rest of the line.  I use it to mark
off code from the rest of an email message.

(When I'm quoting Scheme code, I'll often use the semicolon character ';'
for similar reasons.  *grin*)




> > ###
> > def endsWithS(word):
> >     return word[-1] == 's'
> >
> > for w in words:
> >     if endsWithS(w):
> >         print w
> > ###
> 
> This is something I haven't seen before -- using an expression as the
> return value of a function.  I take it that this means "return boolean
> value TRUE if the expression 'word[-1] == "s" ' ".  But I'm not sure. 


Let's say that we didn't know the answer to this, but we still wanted to
find out.  What's nice about Python is that it has an interactive
interpreter, and we can set up an experiment to see what happens:

###
>>> def endsWithS(word):
...     return word[-1] == 's'
... 
>>> endsWithS('the language instinct')
0
>>> endsWithS('soliloquies')
1
###

Yes, it returns a true value.  Oh, by the way, here are a list of values
that Python considers to be "false" values:

    ""
    []
    ()
    0
    {}

We can use the interpreter to play around with Python's idea of truth:

###
>>> def isTrue(x):
...     if x: print "true!"
...     else: print "false!"
... 
>>> isTrue("")
>>> isTrue("0")
true!
>>> isTrue(0)
false!
>>> isTrue([])
false!
>>> isTrue({})
false!
>>> isTrue(isTrue)
true!
###


Hope this helps!