First script, please comment and advise

bruno at modulix onurb at xiludom.gro
Fri Mar 10 03:45:39 EST 2006


Pedro Graca wrote:
> bearophileHUGS at lycos.com wrote:
> 
>>My version is similar to Just one:
>>
>>from random import shuffle
>>
>>def scramble_text(text):
>>    """Return the words in input text string scrambled
>>    except for the first and last letter."""
>>    def scramble_word(word):
> 
> 
> Nice. You can have functions inside functions.
> However I think scramble_word() deserves being a callable function by
> itself.
> 
> Can a "sub-function" be called directly from outside the defining
> function?
> 

"directly", no, but since Python's functions are objects, you can return
a function from another function. The nice thing is that the inner
function will carry it's environnement along (it's called a "closure").


def make_adder(add_val=1):
  def adder(num):
    return num + add_val
  return adder

add1 = make_adder()
add1(42)

add42 = make_adder(42)
add42(3)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list