Beginning Question about Python functions, parameters...

Discussion in 'Python' started by astral orange, Nov 23, 2009.

  1. Hi, I am trying to teach myself Python and have a good book to help me
    but I am stuck on something and I would like for someone to explain
    the following piece of code for me and what it's actually doing.
    Certain parts are very clear but once it enters the "def store(data,
    full_name): ...." function and the "def lookup()..." function things
    get a little confusing for me. Specifically, lines 103-108 *and* Lines
    110-111.

    Lastly, I am not sure how to print the results I've put into this
    program either, the book I'm reading doesn't tell me. As you can tell,
    I am a beginner and I don't truly understand everything that is going
    on here...a lot, but not all....

    Here is the code:

    92 def init(data):
    93 data['first'] = {}
    94 data['middle'] = {}
    95 data['last'] = {}
    96
    97 def store(data, full_name):
    98 names = full_name.split()
    100 if len(names) == 2: names.insert(1, '')
    101 labels = 'first', 'middle', 'last'
    103 for label, name in zip(labels, names):
    104 people = lookup(data, label, name)
    105 if people:
    106 people.append(full_name)
    107 else:
    108 data[label][name] = [full_name]
    109
    110 def lookup(data, label, name):
    111 return data[label].get(name)
    112
    113
    114 MyNames = {}
    115 init(MyNames)
    116 store(MyNames, 'John Larry Smith')
    117 lookup(MyNames, 'middle', 'Smith')
     
    astral orange, Nov 23, 2009
    #1
    1. Advertising

  2. astral orange

    Neo Guest

    astral orange schrieb:
    > Hi, I am trying to teach myself Python and have a good book to help me
    > but I am stuck on something and I would like for someone to explain
    > the following piece of code for me and what it's actually doing.
    > Certain parts are very clear but once it enters the "def store(data,
    > full_name): ...." function and the "def lookup()..." function things
    > get a little confusing for me. Specifically, lines 103-108 *and* Lines
    > 110-111.
    >
    > Lastly, I am not sure how to print the results I've put into this
    > program either, the book I'm reading doesn't tell me. As you can tell,
    > I am a beginner and I don't truly understand everything that is going
    > on here...a lot, but not all....
    >
    > Here is the code:
    >
    > 92 def init(data):
    > 93 data['first'] = {}
    > 94 data['middle'] = {}
    > 95 data['last'] = {}
    > 96
    > 97 def store(data, full_name):
    > 98 names = full_name.split()
    > 100 if len(names) == 2: names.insert(1, '')
    > 101 labels = 'first', 'middle', 'last'
    > 103 for label, name in zip(labels, names):
    > 104 people = lookup(data, label, name)
    > 105 if people:
    > 106 people.append(full_name)
    > 107 else:
    > 108 data[label][name] = [full_name]
    > 109
    > 110 def lookup(data, label, name):
    > 111 return data[label].get(name)
    > 112
    > 113
    > 114 MyNames = {}
    > 115 init(MyNames)
    > 116 store(MyNames, 'John Larry Smith')
    > 117 lookup(MyNames, 'middle', 'Smith')


    If it tells you so I'm not really sure its a good book - partially for
    teaching you into the unpythonic way to do things (above stuff, if its
    not a counter example, should really go into a class)

    Have you tried the tutorial first? Its online and very easy to follow
    from the very beginning but you can also skip parts if you are sure you
    already understand it:

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

    HTH
    Tino
     
    Neo, Nov 23, 2009
    #2
    1. Advertising

  3. astral orange wrote:

    > Hi, I am trying to teach myself Python and have a good book to help me
    > but I am stuck on something and I would like for someone to explain
    > the following piece of code for me and what it's actually doing.
    > Certain parts are very clear but once it enters the "def store(data,
    > full_name): ...." function and the "def lookup()..." function things
    > get a little confusing for me. Specifically, lines 103-108 *and* Lines
    > 110-111.
    >
    > Lastly, I am not sure how to print the results I've put into this
    > program either, the book I'm reading doesn't tell me. As you can tell,
    > I am a beginner and I don't truly understand everything that is going
    > on here...a lot, but not all....
    >
    > Here is the code:
    >
    > 92 def init(data):
    > 93 data['first'] = {}
    > 94 data['middle'] = {}
    > 95 data['last'] = {}
    > 96
    > 97 def store(data, full_name):
    > 98 names = full_name.split()
    > 100 if len(names) == 2: names.insert(1, '')
    > 101 labels = 'first', 'middle', 'last'
    > 103 for label, name in zip(labels, names):


    The zip-function takes n iterables, and produces a list with n-tuples out of
    it. Type this into the python-prompt:

    >>> zip([1, 2, 3], ["a", "b", "c"])


    The other thing here is tuple-unpacking. If you know that something has a
    specific length, you can unpack it into distinct values like this:

    >>> a, b = (10, 20)
    >>> print a

    10
    >>> print b

    20

    Now

    for label, name in zip(labels, names):


    does

    - create a list of tuples, each tuple having two elements, the first being
    the label, the second a name
    - loops over this list
    - for each item in the list (remember, it's a 2-tuple!), unpack it into
    label and name




    > 104 people = lookup(data, label, name)
    > 105 if people:
    > 106 people.append(full_name)
    > 107 else:
    > 108 data[label][name] = [full_name]
    > 109
    > 110 def lookup(data, label, name):
    > 111 return data[label].get(name)


    Data here is expected to be a dictionary of dictionaries. The first level of
    keys are the labels. The second is the name. It is expected that labels
    always exist, but names might be empty, so instead of writing

    return data[label][name]

    it uses get(name) on a dict which will return the value for the key, or
    None:

    >>> {"foo" : "bar"}.get("foo")

    bar
    >>> {"foo" : "bar"}.get("baz")
    >>> # no output means None



    That being said, I agree with Neo that this introduction seems to be rather
    bad.

    Diez
     
    Diez B. Roggisch, Nov 23, 2009
    #3
  4. astral orange

    j Guest

    On Nov 23, 12:37 pm, Neo <> wrote:
    > astral orange schrieb:
    >
    >
    >
    > > Hi, I am trying to teach myself Python and have a good book to help me
    > > but I am stuck on something and I would like for someone to explain
    > > the following piece of code for me and what it's actually doing.
    > > Certain parts are very clear but once it enters the "def store(data,
    > > full_name): ...." function and the "def lookup()..." function things
    > > get a little confusing for me. Specifically, lines 103-108 *and* Lines
    > > 110-111.

    >
    > > Lastly, I am not sure how to print the results I've put into this
    > > program either, the book I'm reading doesn't tell me. As you can tell,
    > > I am a beginner and I don't truly understand everything that is going
    > > on here...a lot, but not all....

    >
    > > Here is the code:

    >
    > >  92 def init(data):
    > >  93     data['first'] = {}
    > >  94     data['middle'] = {}
    > >  95     data['last'] = {}
    > >  96
    > >  97 def store(data, full_name):
    > >  98     names = full_name.split()
    > > 100     if len(names) == 2: names.insert(1, '')
    > > 101     labels = 'first', 'middle', 'last'
    > > 103     for label, name in zip(labels, names):
    > > 104         people = lookup(data, label, name)
    > > 105     if people:
    > > 106         people.append(full_name)
    > > 107     else:
    > > 108         data[label][name] = [full_name]
    > > 109
    > > 110 def lookup(data, label, name):
    > > 111     return data[label].get(name)
    > > 112
    > > 113
    > > 114 MyNames = {}
    > > 115 init(MyNames)
    > > 116 store(MyNames, 'John Larry Smith')
    > > 117 lookup(MyNames, 'middle', 'Smith')

    >
    > If it tells you so I'm not really sure its a good book - partially for
    > teaching you into the unpythonic way to do things (above stuff, if its
    > not a counter example, should really go into a class)
    >
    > Have you tried the tutorial first? Its online and very easy to follow
    > from the very beginning but you can also skip parts if you are sure you
    > already understand it:
    >
    > http://docs.python.org/tutorial/
    >
    > HTH
    > Tino


    The book is "Apress Beginning Python 2nd Edition". I think what you
    are saying is if I don't understand all of the code I should go into a
    class? Unfortunately I don't have the money or time to enroll into a
    class and even if I did they wouldn't be teaching Python it would be
    Java instead...and I've already taken Java before...so that's not
    really an option...

    Regardless, I understand up to the part "for label, name in zip
    (labels, names):" which zips the two sequences 'names' and 'labels'
    into a list of tuples...

    What I am not totally sure about is when the store function callsthe
    lookup function and does "return data[label].get(name)", that line
    "trips" me up some....then the lookup function returns that back to
    the store function, assigns the data to the variable 'people', THEN
    does this, which also isn't that clear to me what it's all doing:

    if people:
    people.append(full_name)
    else:
    data[label][name] = [full_name]

    My main problem is finding out what's it's actually *doing*? I know
    and understand the terminologies (what 'append' does, what a
    'sequence' is, a 'list', a 'tuple', 'if'...'else'...etc...et....)

    Thanks for the reply back
     
    j, Nov 23, 2009
    #4
  5. astral orange

    david wright Guest

    ----- Original Message ----

    From: j <>
    To:
    Sent: Mon, November 23, 2009 10:26:42 AM
    Subject: Re: Beginning Question about Python functions, parameters...

    On Nov 23, 12:37 pm, Neo <> wrote:
    > astral orange schrieb:
    >
    >
    >
    > > Hi, I am trying to teach myself Python and have a good book to help me
    > > but I am stuck on something and I would like for someone to explain
    > > the following piece of code for me and what it's actually doing.
    > > Certain parts are very clear but once it enters the "def store(data,
    > > full_name): ...." function and the "def lookup()..." function things
    > > get a little confusing for me. Specifically, lines 103-108 *and* Lines
    > > 110-111.

    >
    > > Lastly, I am not sure how to print the results I've put into this
    > > program either, the book I'm reading doesn't tell me. As you can tell,
    > > I am a beginner and I don't truly understand everything that is going
    > > on here...a lot, but not all....

    >
    > > Here is the code:

    >
    > > 92 def init(data):
    > > 93 data['first'] = {}
    > > 94 data['middle'] = {}
    > > 95 data['last'] = {}
    > > 96
    > > 97 def store(data, full_name):
    > > 98 names = full_name.split()
    > > 100 if len(names) == 2: names.insert(1, '')
    > > 101 labels = 'first', 'middle', 'last'
    > > 103 for label, name in zip(labels, names):
    > > 104 people = lookup(data, label, name)
    > > 105 if people:
    > > 106 people.append(full_name)
    > > 107 else:
    > > 108 data[label][name] = [full_name]
    > > 109
    > > 110 def lookup(data, label, name):
    > > 111 return data[label].get(name)
    > > 112
    > > 113
    > > 114 MyNames = {}
    > > 115 init(MyNames)
    > > 116 store(MyNames, 'John Larry Smith')
    > > 117 lookup(MyNames, 'middle', 'Smith')

    >
    > If it tells you so I'm not really sure its a good book - partially for
    > teaching you into the unpythonic way to do things (above stuff, if its
    > not a counter example, should really go into a class)
    >
    > Have you tried the tutorial first? Its online and very easy to follow
    > from the very beginning but you can also skip parts if you are sure you
    > already understand it:
    >
    > http://docs.python.org/tutorial/
    >
    > HTH
    > Tino



    > > > My main problem is finding out what's it's actually *doing*?


    open it up in IDLE (or whatever development environment you use) and use the debugger to step through the code.

    the only way to learn stuff is to actually play with it.

    make a guess as to what will happen, run it, did that happen? what did happen? change something, what happens now? etc.
     
    david wright, Nov 23, 2009
    #5
  6. astral orange

    MRAB Guest

    j wrote:
    > On Nov 23, 12:37 pm, Neo <> wrote:
    >> astral orange schrieb:
    >>
    >>
    >>
    >>> Hi, I am trying to teach myself Python and have a good book to help me
    >>> but I am stuck on something and I would like for someone to explain
    >>> the following piece of code for me and what it's actually doing.
    >>> Certain parts are very clear but once it enters the "def store(data,
    >>> full_name): ...." function and the "def lookup()..." function things
    >>> get a little confusing for me. Specifically, lines 103-108 *and* Lines
    >>> 110-111.
    >>> Lastly, I am not sure how to print the results I've put into this
    >>> program either, the book I'm reading doesn't tell me. As you can tell,
    >>> I am a beginner and I don't truly understand everything that is going
    >>> on here...a lot, but not all....
    >>> Here is the code:
    >>> 92 def init(data):
    >>> 93 data['first'] = {}
    >>> 94 data['middle'] = {}
    >>> 95 data['last'] = {}
    >>> 96
    >>> 97 def store(data, full_name):
    >>> 98 names = full_name.split()
    >>> 100 if len(names) == 2: names.insert(1, '')
    >>> 101 labels = 'first', 'middle', 'last'
    >>> 103 for label, name in zip(labels, names):
    >>> 104 people = lookup(data, label, name)
    >>> 105 if people:
    >>> 106 people.append(full_name)
    >>> 107 else:
    >>> 108 data[label][name] = [full_name]
    >>> 109
    >>> 110 def lookup(data, label, name):
    >>> 111 return data[label].get(name)
    >>> 112
    >>> 113
    >>> 114 MyNames = {}
    >>> 115 init(MyNames)
    >>> 116 store(MyNames, 'John Larry Smith')
    >>> 117 lookup(MyNames, 'middle', 'Smith')

    >> If it tells you so I'm not really sure its a good book - partially for
    >> teaching you into the unpythonic way to do things (above stuff, if its
    >> not a counter example, should really go into a class)
    >>
    >> Have you tried the tutorial first? Its online and very easy to follow
    >> from the very beginning but you can also skip parts if you are sure you
    >> already understand it:
    >>
    >> http://docs.python.org/tutorial/
    >>
    >> HTH
    >> Tino

    >
    > The book is "Apress Beginning Python 2nd Edition". I think what you
    > are saying is if I don't understand all of the code I should go into a
    > class? Unfortunately I don't have the money or time to enroll into a
    > class and even if I did they wouldn't be teaching Python it would be
    > Java instead...and I've already taken Java before...so that's not
    > really an option...
    >

    [snip]
    No, he's saying that the _functions_ shown in the code should go into a
    class, but the main criticism is that judging by the code shown above it
    doesn't look like a good book, and you should look at the on-line
    tutorial first if you haven't already done so.
     
    MRAB, Nov 23, 2009
    #6
  7. On Nov 23, 1:17 pm, "Diez B. Roggisch" <> wrote:
    > astral orange wrote:
    > > Hi, I am trying to teach myself Python and have a good book to help me
    > > but I am stuck on something and I would like for someone to explain
    > > the following piece of code for me and what it's actually doing.
    > > Certain parts are very clear but once it enters the "def store(data,
    > > full_name): ...." function and the "def lookup()..." function things
    > > get a little confusing for me. Specifically, lines 103-108 *and* Lines
    > > 110-111.

    >
    > > Lastly, I am not sure how to print the results I've put into this
    > > program either, the book I'm reading doesn't tell me. As you can tell,
    > > I am a beginner and I don't truly understand everything that is going
    > > on here...a lot, but not all....

    >
    > > Here is the code:

    >
    > >  92 def init(data):
    > >  93     data['first'] = {}
    > >  94     data['middle'] = {}
    > >  95     data['last'] = {}
    > >  96
    > >  97 def store(data, full_name):
    > >  98     names = full_name.split()
    > > 100     if len(names) == 2: names.insert(1, '')
    > > 101     labels = 'first', 'middle', 'last'
    > > 103     for label, name in zip(labels, names):

    >
    > The zip-function takes n iterables, and produces a list with n-tuples out of
    > it. Type this into the python-prompt:
    >
    > >>> zip([1, 2, 3], ["a", "b", "c"])

    >
    > The other thing here is tuple-unpacking. If you know that something has a
    > specific length, you can unpack it into distinct values like this:
    >
    > >>> a, b = (10, 20)
    > >>> print a

    > 10
    > >>> print b

    >
    > 20
    >
    > Now
    >
    >  for label, name in zip(labels, names):
    >
    > does
    >
    >  - create a list of tuples, each tuple having two elements, the first being
    > the label, the second a name
    >  - loops over this list
    >  - for each item in the list (remember, it's a 2-tuple!), unpack it into
    > label and name
    >
    > > 104         people = lookup(data, label, name)
    > > 105     if people:
    > > 106         people.append(full_name)
    > > 107     else:
    > > 108         data[label][name] = [full_name]
    > > 109
    > > 110 def lookup(data, label, name):
    > > 111     return data[label].get(name)

    >
    > Data here is expected to be a dictionary of dictionaries. The first level of
    > keys are the labels. The second is the name. It is expected that labels
    > always exist, but names might be empty, so instead of writing
    >
    >   return data[label][name]
    >
    > it uses get(name) on a dict which will return the  value for the key, or
    > None:
    >
    >
    >
    > >>> {"foo" : "bar"}.get("foo")

    > bar
    > >>> {"foo" : "bar"}.get("baz")
    > >>> # no output means None

    >
    > That being said, I agree with Neo that this introduction seems to be rather
    > bad.
    >
    > Diez


    Thanks all for the replies back! I do appreciate it.

    Yes, lines 104-111 is really where my problem lies in understanding
    what is going on here.
    I am beginner so this stuff seems a little unwieldy at the moment. :)
    I *did* invest $40
    into this book so it' what I have to work with. By the way, the book
    is, "Apress Beginning Python 2nd Edition"....

    But back to the example, on line 104 I see there's a call to the
    lookup function, passing 3
    parameters ('data', which I think is a nested dictionary, label
    (first, middle, last) and name).
    But I am getting lost on line 111 after the parameters are passed in
    to the lookup function. I'm
    not exactly sure what it's returning and when it does return, is this
    assigned the the variable
    'people'? And if so, I'm not sure what 'append(full_name)' does here.
    The else statement which assigns
    '[full_name]' to 'data[label][name]' is somewhat confusing as I'm
    saying to myself where the heck did
    '[full_name]' come "into the picture".

    If I could understand what's going on with everything in this the rest
    of the chapter and the next
    should be fairly easy, but I really need to understand this before I
    move on. Thanks again for the
    replies back. I am looking over your comments right now.

    457r0
     
    astral orange, Nov 23, 2009
    #7
  8. astral orange

    Terry Reedy Guest

    astral orange wrote:

    > Yes, lines 104-111 is really where my problem lies in understanding
    > what is going on here.
    > I am beginner so this stuff seems a little unwieldy at the moment. :)
    > I *did* invest $40


    Water under the bridge. Focus on the future...

    > into this book so it' what I have to work with. By the way, the book
    > is, "Apress Beginning Python 2nd Edition"....


    The online tutorial is free. Read it along with the book. Two
    explanations of a particular point are often better than one, at least
    for me.

    Now, to where you seem to be stuck. Data is a dict of 3 dicts, one for
    each part of a full [Western] name. Each subdict maps pieces of
    fullnames to a list of fullnames that contain that piece in the
    appropriate position.

    This is something like a database of names with 3 fields and an index
    for each field pointing to records in the database, except that there is
    no database. This is why the structure strikes people as a bit strange.
    The records are still there, off in anonymous dataspace, but there is no
    way to access them except via the indexes. If init started with
    data['names'] = [] # empty list, not dict
    and the third line of store were
    data['names'].append(names)
    then there would be. You might try that as an exercise once you
    understand what is already there.

    Anyway, you should "print MyNames" (2.x) or "print(MyNames)" (3.x) after
    storing the first name so you can see the structure of MyNames. The
    tutorial, of course, tells you this. DO read it.

    Then add more data and print again to see what changes. For instance,

    store(MyNames, 'Susan Smith')
    print(MyNames)

    Then try several lookups.

    store() checks each of the pieces of a name to see whether or not it is
    already in the corresponding key dict. This is the "people =" line. The
    important point in lookup is that when dict d does not contain key k,
    d.get(k) returns None while the usual d[k]raises a KeyError. So lookup()
    always return something, even if just None. So 'people' is either None
    or an exiting list of names. In the latter case, the current full names
    is added to the list. In the former case, the name-piece is associated
    with a new list with one item.

    If this is still not clear, add print statements or print function
    statements at appropriate places inside the code for the store function.
    This is how many people clarify thier understanding of a function,
    including when debugging.

    Good luck.

    Terry Jan Reedy
     
    Terry Reedy, Nov 23, 2009
    #8
  9. On Nov 23, 4:35 pm, Terry Reedy <> wrote:
    > astral orange wrote:
    > > Yes, lines 104-111 is really where my problem lies in understanding
    > > what is going on here.
    > > I am beginner so this stuff seems a little unwieldy at the moment. :)
    > > I *did* invest $40

    >
    > Water under the bridge. Focus on the future...
    >
    > > into this book so it' what I have to work with. By the way, the book
    > > is, "Apress Beginning Python 2nd Edition"....

    >
    > The online tutorial is free. Read it along with the book. Two
    > explanations of a particular point are often better than one, at least
    > for me.
    >
    > Now, to where you seem to be stuck. Data is a dict of 3 dicts, one for
    > each part of a full [Western] name. Each subdict maps pieces of
    > fullnames to a list of fullnames that contain that piece in the
    > appropriate position.
    >
    > This is something like a database of names with 3 fields and an index
    > for each field pointing to records in the database, except that there is
    > no database. This is why the structure strikes people as a bit strange.
    > The records are still there, off in anonymous dataspace, but there is no
    > way to access them except via the indexes. If init started with
    >      data['names'] = [] # empty list, not dict
    > and the third line of store were
    >      data['names'].append(names)
    > then there would be. You might try that as an exercise once you
    > understand what is already there.
    >
    > Anyway, you should "print MyNames" (2.x) or "print(MyNames)" (3.x) after
    > storing the first name so you can see the structure of MyNames. The
    > tutorial, of course, tells you this. DO read it.
    >
    > Then add more data and print again to see what changes. For instance,
    >
    > store(MyNames, 'Susan Smith')
    > print(MyNames)
    >
    > Then try several lookups.
    >
    > store() checks each of the pieces of a name to see whether or not it is
    > already in the corresponding key dict. This is the "people =" line. The
    > important point in lookup is that when dict d does not contain key k,
    > d.get(k) returns None while the usual d[k]raises a KeyError. So lookup()
    > always return something, even if just None. So 'people' is either None
    > or an exiting list of names. In the latter case, the current full names
    > is added to the list. In the former case, the name-piece is associated
    > with a new list with one item.
    >
    > If this is still not clear, add print statements or print function
    > statements at appropriate places inside the code for the store function.
    > This is how many people clarify thier understanding of a function,
    > including when debugging.
    >
    > Good luck.
    >
    > Terry Jan Reedy


    Wow! First, thanks Terry for the detailed explanation. I'll spend
    the rest of the night trying to figure all of this out. :) Also,
    thanks to everyone
    else that responded as well. I do appreciate you all volunteering your
    time to help.
    I should of came here sooner.

    As far as the program. I did add print statements such as print
    (MyNames) and got back:

    {'middle': {}, 'last': {'Smith': ['John Larry Smith']}, 'first': {}}

    'Smith': ['John Larry Smith'] was in the last key so I will spend some
    time figuring
    out just why that is the case. I'll spend more time working with the
    functions and
    hopefully figure this out soon.

    Thanks again!

    Thanks again for the responses. I'll take all your advice.
     
    astral orange, Nov 23, 2009
    #9
  10. astral orange

    Terry Reedy Guest

    astral orange wrote:

    > As far as the program. I did add print statements such as print
    > (MyNames) and got back:
    >
    > {'middle': {}, 'last': {'Smith': ['John Larry Smith']}, 'first': {}}


    Hmmm, as I understood the code, either that should be ... 'last': {} ...
    before the first store(), as you seem to be thinking below, or after the
    first store(),

    {'middle': {'Larry': ['John Larry Smith'],
    'last': {'Smith': ['John Larry Smith'],
    'first': {'John' " ['John Larry Smith']}

    or the same with [['John','Larry','Smith']] for each entry (do not
    remember exactly what was stored. Maybe a typo.

    tjr
     
    Terry Reedy, Nov 24, 2009
    #10
  11. astral orange

    r Guest

    On Nov 23, 11:19 am, astral orange <> wrote:
    > Hi, I am trying to teach myself Python and have a good book to help me
    > but I am stuck on something and I would like for someone to explain
    > the following piece of code for me and what it's actually doing.
    > Certain parts are very clear but once it enters the "def store(data,
    > full_name): ...." function and the "def lookup()..." function things
    > get a little confusing for me. Specifically, lines 103-108 *and* Lines
    > 110-111.
    >
    > Lastly, I am not sure how to print the results I've put into this
    > program either, the book I'm reading doesn't tell me. As you can tell,
    > I am a beginner and I don't truly understand everything that is going
    > on here...a lot, but not all....
    >
    > Here is the code:
    >
    >  92 def init(data):
    >  93     data['first'] = {}
    >  94     data['middle'] = {}
    >  95     data['last'] = {}
    >  96
    >  97 def store(data, full_name):
    >  98     names = full_name.split()
    > 100     if len(names) == 2: names.insert(1, '')
    > 101     labels = 'first', 'middle', 'last'
    > 103     for label, name in zip(labels, names):
    > 104         people = lookup(data, label, name)
    > 105     if people:
    > 106         people.append(full_name)
    > 107     else:
    > 108         data[label][name] = [full_name]
    > 109
    > 110 def lookup(data, label, name):
    > 111     return data[label].get(name)
    > 112
    > 113
    > 114 MyNames = {}
    > 115 init(MyNames)
    > 116 store(MyNames, 'John Larry Smith')
    > 117 lookup(MyNames, 'middle', 'Smith')


    This is a horrible example to show noobs. I think the OP could better
    understand this as a class EVEN though the OP may or may not know what
    a class *is* yet.

    >>> class Name():

    def __init__(self, first, middle, last):
    self.first = first
    self.middle = middle
    self.last = last

    >>> name1 = Name('Guido', 'van', 'Rossum')
    >>> name1.first

    'Guido'
    >>> name1.middle

    'van'
    >>> name1.last

    'Rossum'
    >>> print name1

    <__main__.Name instance at 0x029BFD78>


    This time we add a __str__ method, the result will speak louder than
    words!!

    >>> class Name():

    def __init__(self, first, middle, last):
    self.first = first
    self.middle = middle
    self.last = last
    def __str__(self):
    return '%s %s %s' %(self.first, self.middle, self.last)

    >>> name2 = Name('Terry', 'J', 'Reedy')
    >>> name2.first

    'Terry'
    >>> name2.middle

    'J'
    >>> name2.last

    'Reedy'
    >>> print name2

    Terry J Reedy

    See the difference in the print statements. Now lets have some real
    fun and access each sub name by index haha!


    >>> class Name():

    def __init__(self, first, middle, last):
    self.first = first
    self.middle = middle
    self.last = last
    def __str__(self):
    return '%s %s %s' %(self.first, self.middle, self.last)
    def __len__(self):
    return 3
    def __getitem__(self, item):
    if item == 0:
    return self.first
    elif item == 1:
    return self.middle
    elif item == 2:
    return self.last
    else:
    raise IndexError("Index must be in range 0, 2")


    >>> name = Name('Joe', 'blow', 'scripter')
    >>> name[0]

    'Joe'
    >>> name[1]

    'blow'
    >>> name[2]

    'scripter'
    >>> len(name)

    3

    WOW, thats more info in a few lines than any tut i ever seen! I wish i
    could have seen that in my initial days, could have save some
    countless hours of confusion!!! Maybe i am in the wrong line of work?

    Should i keep going...?
     
    r, Nov 24, 2009
    #11
  12. astral orange

    Peter Otten Guest

    Terry Reedy wrote:

    > astral orange wrote:
    >
    >> As far as the program. I did add print statements such as print
    >> (MyNames) and got back:
    >>
    >> {'middle': {}, 'last': {'Smith': ['John Larry Smith']}, 'first': {}}

    >
    > Hmmm, as I understood the code, either that should be ... 'last': {} ...
    > before the first store(), as you seem to be thinking below, or after the
    > first store(),
    >
    > {'middle': {'Larry': ['John Larry Smith'],
    > 'last': {'Smith': ['John Larry Smith'],
    > 'first': {'John' " ['John Larry Smith']}
    >
    > or the same with [['John','Larry','Smith']] for each entry (do not
    > remember exactly what was stored. Maybe a typo.


    That's a bug in the store() function

    # as posted
    def store(data, full_name):
    names = full_name.split()
    if len(names) == 2: names.insert(1, '')
    labels = 'first', 'middle', 'last'
    for label, name in zip(labels, names):
    people = lookup(data, label, name)
    if people:
    people.append(full_name)
    else:
    data[label][name] = [full_name]

    # what was probably intended
    def store(data, full_name):
    names = full_name.split()
    if len(names) == 2: names.insert(1, '')
    labels = 'first', 'middle', 'last'
    for label, name in zip(labels, names):
    people = lookup(data, label, name)
    if people:
    people.append(full_name)
    else:
    data[label][name] = [full_name]


    Peter
     
    Peter Otten, Nov 24, 2009
    #12
  13. On Nov 23, 10:37 pm, r <> wrote:
    > On Nov 23, 11:19 am, astral orange <> wrote:
    >
    >
    >
    > > Hi, I am trying to teach myself Python and have a good book to help me
    > > but I am stuck on something and I would like for someone to explain
    > > the following piece of code for me and what it's actually doing.
    > > Certain parts are very clear but once it enters the "def store(data,
    > > full_name): ...." function and the "def lookup()..." function things
    > > get a little confusing for me. Specifically, lines 103-108 *and* Lines
    > > 110-111.

    >
    > > Lastly, I am not sure how to print the results I've put into this
    > > program either, the book I'm reading doesn't tell me. As you can tell,
    > > I am a beginner and I don't truly understand everything that is going
    > > on here...a lot, but not all....

    >
    > > Here is the code:

    >
    > >  92 def init(data):
    > >  93     data['first'] = {}
    > >  94     data['middle'] = {}
    > >  95     data['last'] = {}
    > >  96
    > >  97 def store(data, full_name):
    > >  98     names = full_name.split()
    > > 100     if len(names) == 2: names.insert(1, '')
    > > 101     labels = 'first', 'middle', 'last'
    > > 103     for label, name in zip(labels, names):
    > > 104         people = lookup(data, label, name)
    > > 105     if people:
    > > 106         people.append(full_name)
    > > 107     else:
    > > 108         data[label][name] = [full_name]
    > > 109
    > > 110 def lookup(data, label, name):
    > > 111     return data[label].get(name)
    > > 112
    > > 113
    > > 114 MyNames = {}
    > > 115 init(MyNames)
    > > 116 store(MyNames, 'John Larry Smith')
    > > 117 lookup(MyNames, 'middle', 'Smith')

    >
    > This is a horrible example to show noobs. I think the OP could better
    > understand this as a class EVEN though the OP may or may not know what
    > a class *is* yet.
    >
    > >>> class Name():

    >
    >         def __init__(self, first, middle, last):
    >                 self.first = first
    >                 self.middle = middle
    >                 self.last = last
    >
    > >>> name1 = Name('Guido', 'van', 'Rossum')
    > >>> name1.first

    > 'Guido'
    > >>> name1.middle

    > 'van'
    > >>> name1.last

    > 'Rossum'
    > >>> print name1

    >
    > <__main__.Name instance at 0x029BFD78>
    >
    > This time we add a __str__ method, the result will speak louder than
    > words!!
    >
    > >>> class Name():

    >
    >         def __init__(self, first, middle, last):
    >                 self.first = first
    >                 self.middle = middle
    >                 self.last = last
    >         def __str__(self):
    >                 return '%s %s %s' %(self.first, self.middle, self.last)
    >
    > >>> name2 = Name('Terry', 'J', 'Reedy')
    > >>> name2.first

    > 'Terry'
    > >>> name2.middle

    > 'J'
    > >>> name2.last

    > 'Reedy'
    > >>> print name2

    >
    > Terry J Reedy
    >
    > See the difference in the print statements. Now lets have some real
    > fun and access each sub name by index haha!
    >
    > >>> class Name():

    >
    >         def __init__(self, first, middle, last):
    >                 self.first = first
    >                 self.middle = middle
    >                 self.last = last
    >         def __str__(self):
    >                 return '%s %s %s' %(self.first, self.middle, self.last)
    >         def __len__(self):
    >                 return 3
    >         def __getitem__(self, item):
    >                 if item == 0:
    >                         return self.first
    >                 elif item == 1:
    >                         return self.middle
    >                 elif item == 2:
    >                         return self.last
    >                 else:
    >                         raise IndexError("Index must be in range 0, 2")
    >
    > >>> name = Name('Joe', 'blow', 'scripter')
    > >>> name[0]

    > 'Joe'
    > >>> name[1]

    > 'blow'
    > >>> name[2]

    > 'scripter'
    > >>> len(name)

    >
    > 3
    >
    > WOW, thats more info in a few lines than any tut i ever seen! I wish i
    > could have seen that in my initial days, could have save some
    > countless hours of confusion!!! Maybe i am in the wrong line of work?
    >
    > Should i keep going...?


    Yeah, I don't think the example in the book is the best for someone
    starting out. I still
    am "not getting" certain parts of the program so I think I'll move on
    in hopes that it will
    *not* came back to haunt me and the book (along with the online
    tutorial) will help me grab
    more of the basics of Python programming.

    As for the "class Name():" example above? Even though I haven't seen
    exactly what purpose 'self' serves
    yet I can follow and understand what is going on very easily, that
    helps out tremendously.
    Very clearly written...Thank you!

    And thanks again to everyone...
     
    astral orange, Nov 24, 2009
    #13
  14. astral orange

    Terry Reedy Guest

    Peter Otten wrote:
    > Terry Reedy wrote:


    >> remember exactly what was stored. Maybe a typo.

    >
    > That's a bug in the store() function
    >
    > # as posted
    > def store(data, full_name):
    > names = full_name.split()
    > if len(names) == 2: names.insert(1, '')
    > labels = 'first', 'middle', 'last'
    > for label, name in zip(labels, names):
    > people = lookup(data, label, name)
    > if people:
    > people.append(full_name)
    > else:
    > data[label][name] = [full_name]
    >
    > # what was probably intended
    > def store(data, full_name):
    > names = full_name.split()
    > if len(names) == 2: names.insert(1, '')
    > labels = 'first', 'middle', 'last'
    > for label, name in zip(labels, names):
    > people = lookup(data, label, name)
    > if people:
    > people.append(full_name)
    > else:
    > data[label][name] = [full_name]


    (Note indent error, which I overlooked)
    It is a nuisance when people post untested code, without identifying it
    as such. Publishing untested but trivial-to-test code like this (one
    print statement needed), especially in a book for learners, is really bad.

    (I am trying to do better in the book I am working on.)

    tjr
     
    Terry Reedy, Nov 24, 2009
    #14
  15. astral orange

    r Guest

    On Nov 24, 9:45 am, astral orange <> wrote:
    >
    > As for the "class Name():" example above? Even though I haven't seen
    > exactly what purpose 'self' serves
    > yet I can follow and understand what is going on very easily, that
    > helps out tremendously.
    > Very clearly written...Thank you!


    Yes and this is the stumbling block that almost every tutorial writer
    puts before the uninitiated! Simple, Simple examples are the key. The
    subject matter of the example should never outshine the subject that
    is being taught. Everybody understand what a first, middle, and last
    name is! What really ticks me off is when some show-off tut writer
    goes off using an internet protocol or mp3 tags example to explain
    classes or functions... WHAT!-O

    Pssst...tut writers remember this! While you may be an emacs "zen
    master" playing key chords that would make most piano virtuosos
    jealous, your tutorials are meant for inexperience users. Yes,
    exposing your "huge intelligence" to the world may give you warm
    fuzzies, but the "shock-and-awe-freak-show" will only be to the
    detriment of the very ideas you are attempting to transform into these
    minds.
     
    r, Nov 25, 2009
    #15
  16. astral orange a écrit :
    > On Nov 23, 10:37 pm, r <> wrote:

    (snip)
    >> This is a horrible example to show noobs. I think the OP could better
    >> understand this as a class EVEN though the OP may or may not know what
    >> a class *is* yet.
    >>
    >>>>> class Name():

    >> def __init__(self, first, middle, last):
    >> self.first = first
    >> self.middle = middle
    >> self.last = last
    >>

    (snip)

    > As for the "class Name():" example above? Even though I haven't seen
    > exactly what purpose 'self' serves


    It's a reference to the current Name instance. But while technically
    correct, I'm sure such this kind of explanation really helps :-/
     
    Bruno Desthuilliers, Nov 25, 2009
    #16
  17. astral orange

    Lie Ryan Guest

    astral orange wrote:
    >
    > As for the "class Name():" example above? Even though I haven't seen
    > exactly what purpose 'self' serves


    In many other programming language, self (or this, or Me) refers the the
    current class instance. In some languages, you can refer to an instance
    attribute without an explicit self, this, or Me; the name resolver will
    search in the local namespace (method-level), instance namespace
    (instance-level), class namespace (class-level), perhaps module level
    namespace (file-level), and finally global (application level).

    Python interpreter is simple and stupid. It doesn't have many smarts;
    instead of having such a sophisticated name resolver, the compiler
    passes an argument to the function, making `self` a local variable that
    refers to the current instance.

    Python programmers accesses instance and class namespace by explicitly
    referring to `self`; the name resolver only have two places to lookup
    names: local namespace (method level) and global namespace (module-level
    [!] not application level in python).

    This choice of design simplifies the name resolver, simplifies
    method/function object design (since it does not need any code to handle
    an otherwise implicit self), and completely eliminates ambiguity (to the
    programmer) when having a local variable with the same name as an
    instance variable. Among many other advantages.

    The side-effect of this design choice is self must be explicitly
    referenced to access class/instance attributes; unlike in some other
    language where self/this/Me may be omitted when it doesn't clash with
    other variable in local namespace.
     
    Lie Ryan, Nov 25, 2009
    #17
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xiangliang Meng
    Replies:
    1
    Views:
    1,665
    Victor Bazarov
    Jun 21, 2004
  2. Magnus Lie Hetland

    ANN: Beginning Python (Practical Python 2.0)

    Magnus Lie Hetland, Oct 19, 2005, in forum: Python
    Replies:
    6
    Views:
    347
    Dennis Lee Bieber
    Oct 21, 2005
  3. Franz Mueller
    Replies:
    6
    Views:
    549
    Anders Eriksson
    Nov 29, 2005
  4. Kriv
    Replies:
    8
    Views:
    1,322
    bruno at modulix
    May 30, 2006
  5. Jesse B.
    Replies:
    9
    Views:
    261
    Jesse B.
    Mar 27, 2010
Loading...

Share This Page