Chapter 6.ABSTRACTION. from 'Beginning Python From Novice to Professional' by Magnus Lie Hetland

fibs = [0, 1]
for i in range(8):
   fibs.append(fibs[-2] + fibs[-1])

>>> fibs
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
__________________________

To print fibs for numbers set by user

fibs = [0, 1]
num = input('How many numbers do you want? ')
for i in range(num-2):
    fibs.append(fibs[-2] + fibs[-1])
    print fibs
______________________________________
Making your own function

 def hello(name):
    return 'Hello, '+ name +'!'
>>> print hello('John')
Hello, John!
_______________________________________
def fibs(num):
    result = [0, 1]
    for i in range(num-2):
        result.append(result[-2] + result[-1])
    return result
>>> fibs(8)
[0, 1, 1, 2, 3, 5, 8, 13]
_______________________________________

    'Calculates the square of number x'
    return x*x
>>> square(2)
4
>>> square.__doc__
'Calculates the square of number x'
>>> help(square)
Help on function square in module __main__:

square(x)
    Calculates the square of number x
________________________________________
Parameters

>>> def change(n):
n[0]='Mr.Gumby'


>>> names = ['Mrs.Entity','Mr.Ben']
>>> change(names)
>>> names

['Mr.Gumby', 'Mr.Ben']
def square(x):
______________________________
OR

>>> names = ['Mrs.Entity','Mr.Ben']
>>> n = names
>>> n[0] = 'Mr.Gumby'
>>> names
['Mr.Gumby', 'Mr.Ben']
_______________________________
>>> names = ['Mrs.Entity','Mr.Ben']
>>> n = names[:]
>>> names
['Mrs.Entity', 'Mr.Ben']
>>> n
['Mrs.Entity', 'Mr.Ben']
>>>
>>> n is names
False
>>> n == names
True
_______________________________
>>> n[0] = 'Mr.Gumby'
>>> names
['Mrs.Entity', 'Mr.Ben']
>>> n
['Mr.Gumby', 'Mr.Ben']
_______________________________
USING A FUNCTION

a program that stores
names and that allows you to look up people by their first, middle, or last names. 

storage = {}
storage['first'] = {}
storage['middle'] = {}

storage['last'] = {}

>>> me = 'Magnus Lie Hetland'
>>> storage['first']['Magnus'] = [me]
>>> storage['middle']['Lie'] = [me]
>>> storage['last']['Hetland'] = [me]

>>> storage['middle']['Lie']
['Magnus Lie Hetland']

def init(data):
  data['first'] = {}
  data['middle'] = {}
  data['last'] = {}

>>> storage = {}
>>> init(storage)
>>> storage
{'middle': {}, 'last': {}, 'first': {}}

def lookup(data, label, name):
  return data[label].get(name)

>>> lookup(storage, 'middle', 'Lie')
['Magnus Lie Hetland']

>>> my_sister = 'Anne Lie Hetland'
>>> storage['first'].setdefault('Anne', []).append(my_sister)
>>> storage['middle'].setdefault('Lie', []).append(my_sister)
>>> storage['last'].setdefault('Hetland', []).append(my_sister)
>>> storage['first']['Anne']
['Anne Lie Hetland']

>>> storage['middle']['Lie']
['Magnus Lie Hetland', 'Anne Lie Hetland']
>>> lookup(storage,'last','Hetland')
['Magnus Lie Hetland', 'Anne Lie Hetland']
___________________________________________________________

Immutable parameters. (f.e. integers). Solution

>>> def inc(x): return x+1

>>> foo = 1
>>> foo = inc(foo)
>>> foo
2
___________________________________________________________
If you really wanted to modify your parameter, you could use a trick such as wrapping your
value in a list, like this:
>>> def inc(x): x[0] = x[0] + 1
...
>>> foo = [10]
>>> inc(foo)
>>> foo
[11]
__________________________________________________________
Keyword Parameters and Defaults

positional parameters because their

positions are important—more important than their names, in fact

def hello(greeting,name):

    return '%s, %s!' % ('Hello','world')
>>> hello ('greeting = hello','name = world')

'Hello, world!'

def hello(name,greeting):

    return '%s, %s!' % ('Hello','world')
>>> hello ('greeting = hello','name = world')

'Hello, world!'
_________________________________________

It's possible to supply function with default values

def hello(greeting = 'Hello',name = 'world'):
    return '%s, %s!' % (greeting,name)

>>> hello()
'Hello, world!'
>>> hello('Hi','Iurii')
'Hi, Iurii!'
>>> hello('Buenos Dias')
'Buenos Dias, world!'
>>> hello(name = 'Dude')
'Hello, Dude!'
__________________________________________
def hello_1(name,greeting = 'Hello',punctuation = '!'):
    return '%s, %s%s' % (greeting,name,punctuation)

>>> hello_1('Bob')
'Hello, Bob!'
>>> hello_1('Bob','Hey')
'Hey, Bob!'
>>> hello_1('Bob','No','...')
'No, Bob...'
>>> hello_1('Bob',punctuation='.')
'Hello, Bob.'
>>> hello_1('Mohito',greeting = 'Idiot')
'Idiot, Mohito!'
>>>
____________________________________________

Collecting Parameters

def print_params (*params):
    print params

>>> print_params('window')
('window',)
>>> print_params(1)
(1,)
>>> print_params(1,2,3)
(1, 2, 3)
_______________________________
def print_params (title,*params):
    print title
    print params
>>> print_params('Params:',1,2,3)
Params:
(1, 2, 3)
>>> print_params('Nothing:')
Nothing:
()
_______________________________

** - makes dictionary

 def print_params(**params):
    print params
>>> print_params(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
_______________________________

def print_params(x,y,z=3,*pospar,**keypar):
    print x,y,z
    print pospar
    print keypar

>>> print_params(1,2,3,4,5,6,foo=3,bar=5)
1 2 3
(4, 5, 6)
{'foo': 3, 'bar': 5}
>>> print_params(1,2,7,4,5,6,8,foo=3,bar=5)
1 2 7
(4, 5, 6, 8)
{'foo': 3, 'bar': 5}
_____________________________________

Reversing the process

def add(x,y):
    return x+y

>>> params = (1,2)
>>> add(*params)
3
______________________________________

def hello(name = 'Hello',greeting = 'world'):
    print '%s, %s!' % (greeting,name)

>>> arg = {'name':'Mr.Gumby','greeting':'Hello'}
>>> hello(**arg)
Hello, Mr.Gumby!
>>> hello(*arg)
greeting, name!
>>> arg = ('Grey','Bill')
>>> hello(*arg)
Bill, Grey!
________________________________________
In the next two functions result is the same, so stars are really useful only if you use them either when defining a function (to allow a varying
number of arguments) or when calling a function (to “splice in” a dictionary or a sequence
>>> def with_stars(**kwds):
print kwds['name'],'is',kwds['age'],'years old'
>>> args = {'name':'Gumby','age':42}
>>> with_stars(**args)
Gumby is 42 years old
_________________________________________

>>> def without_stars(kwds):
print kwds['name'],'is',kwds['age'],'years old'
>>> args = {'name':'Gumby','age':42}
>>> without_stars(args)
Gumby is 42 years old
____________________________________________

def story(**kwds):
    return 'Once upon a time,' \
           'a %(who)s was %(what)s' % kwds

>>> print story(who='king',what='killed')
Once upon a time,a king was killed
>>> params = {'job': 'language', 'name': 'Python'}
>>> print story(**params)
Once upon a time, there was a language called Python.
>>> del params['job']
>>> print story(job='stroke of genius', **params)
Once upon a time, there was a stroke of genius called Python.
____________________________________________
def power(x,y,*others):
    if others:
        print 'Received redundant params: ', others
    return pow(x,y)
>>> power(2,3)
8
>>> power(2,5,'glory')
Received redundant params:  ('glory',)
32
>>> power(x=4,y=5)
1024
>>> params = (5,)*2
>>> print params
(5, 5)
>>> power(*params)
3125
____________________________________________

Popular posts from this blog

Ketamine: The Past, Present, and Potential Future of an Anesthetic Drug

Fast track anesthesia approaches