Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

Beginning Question about Python functions, parameters...

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


457r0.jp at gmail

Nov 23, 2009, 9:19 AM

Post #1 of 19 (388 views)
Permalink
Beginning Question about Python functions, parameters...

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')
--
http://mail.python.org/mailman/listinfo/python-list


neo at picture-art

Nov 23, 2009, 9:37 AM

Post #2 of 19 (387 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

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
--
http://mail.python.org/mailman/listinfo/python-list


deets at nospam

Nov 23, 2009, 10:17 AM

Post #3 of 19 (377 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

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
--
http://mail.python.org/mailman/listinfo/python-list


jimmy.casey.3 at gmail

Nov 23, 2009, 10:26 AM

Post #4 of 19 (376 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Nov 23, 12:37 pm, Neo <n...@picture-art.eu> 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
--
http://mail.python.org/mailman/listinfo/python-list


david_v_wright at yahoo

Nov 23, 2009, 11:05 AM

Post #5 of 19 (376 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

----- Original Message ----

From: j <jimmy.casey.3 [at] gmail>
To: python-list [at] python
Sent: Mon, November 23, 2009 10:26:42 AM
Subject: Re: Beginning Question about Python functions, parameters...

On Nov 23, 12:37 pm, Neo <n...@picture-art.eu> 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.
--
http://mail.python.org/mailman/listinfo/python-list


python at mrabarnett

Nov 23, 2009, 11:12 AM

Post #6 of 19 (377 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

j wrote:
> On Nov 23, 12:37 pm, Neo <n...@picture-art.eu> 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.

--
http://mail.python.org/mailman/listinfo/python-list


457r0.jp at gmail

Nov 23, 2009, 11:14 AM

Post #7 of 19 (376 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Nov 23, 1:17 pm, "Diez B. Roggisch" <de...@nospam.web.de> 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
--
http://mail.python.org/mailman/listinfo/python-list


apt.shansen at gmail

Nov 23, 2009, 11:33 AM

Post #8 of 19 (377 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Mon, Nov 23, 2009 at 10:26 AM, j <jimmy.casey.3 [at] gmail> wrote:

> 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:
>
>
It does it right when it hits it in the code; basically, the for loop runs
over the list of items from the zip.

In each one, it calls the lookup function. Execution then jumps over to
lookup. Once the lookup function is done ('returns' or hits its it),
execution jumps right back with a result, and that result is stored int he
'people' variable.

Then the next item in the for loop is processed; again, when the function()
is called, execution jumps over to that again, and so on.

Only when all the things are done in the for loop, does execution move on
to...


> if people:
> people.append(full_name)
> else:
> data[label][name] = [full_name]
>
>
Basically, "lookup" will return one of two things.

If someone with the given part of a name already has been stored, it'll
return a list containing the people with that name.

Otherwise, it will return None.

The if/else above will operate on those two conditions: if 'lookup' returned
a list of people, its going to add this person to that list. If it doesn't
return a list of people, it's going to add this persons name to the data
dictionary as a new list. So anyone in the future who has that name will
find them on lookup.

The thing is, I think lines 105-108 should be indented deeper one level to
be 'inside' the for loop; and thus called with each execution, and not only
after the for is all done with. As it is, it seems like a bug. Or I don't
get at all what the point of the code is :)



> 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....)
>

I concur with the other people who say this is bad code to learn from; the
book could be a LOT clearer. I'd try another resource.. the online Python
tutorial is a good place to start. A different book may be in order :)


--S


apt.shansen at gmail

Nov 23, 2009, 11:40 AM

Post #9 of 19 (377 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Mon, Nov 23, 2009 at 11:14 AM, astral orange <457r0.jp [at] gmail> wrote:

> 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


The 'get' method of dictionaries returns either the value if it exists, or
None.

So lookup is returning either a the value from that nested dictionary (the
value which will be a list of names), or None.


> and when it does return, is this
> assigned the the variable
> 'people'?


Yes.


> 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".
>
>
Look up at line 97.

The "purpose" of this code seems-- on a cursory glance-- to be to categorize
peoples names into lists where their names are common.

The data dictionary contains three dictionaries; one for first names, one
for middle names, one for last names.

Each dictionary would, over time, contain the name-part as a key and then a
list of full names...

So, I'd be:

data['first']['Stephen'] = ['Stephen Hansen']
data['last']['Hansen'] = ['Stephen Hansen']

Then if Bob Hansen was run through the code, it'd end up as:

data['last']['Hansen'] = ['Stephen Hansen', 'Bob Hansen']

At least I think that's what the code is doing. Based upon just a stare. :)
(And if that's what its doing, I think it has a bug as I mentioned in a
previous email; I think lines 105-108 need to be indented one level more)

So, what all this code is doing is breaking apart someoen's full_name which
was passed into the function originally, and seeing where to put it. That's
what the for loop and lookup function calls are doing... seeing if we need a
new list , or if there's an existing one to add the name to... When it
decides where it goes, it puts the full_name in.


--S


tjreedy at udel

Nov 23, 2009, 1:35 PM

Post #10 of 19 (369 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

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

--
http://mail.python.org/mailman/listinfo/python-list


457r0.jp at gmail

Nov 23, 2009, 3:13 PM

Post #11 of 19 (367 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Nov 23, 4:35 pm, Terry Reedy <tjre...@udel.edu> 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.
--
http://mail.python.org/mailman/listinfo/python-list


tjreedy at udel

Nov 23, 2009, 5:05 PM

Post #12 of 19 (367 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

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


--
http://mail.python.org/mailman/listinfo/python-list


rt8396 at gmail

Nov 23, 2009, 7:37 PM

Post #13 of 19 (364 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Nov 23, 11:19 am, astral orange <457r0...@gmail.com> 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...?
--
http://mail.python.org/mailman/listinfo/python-list


__peter__ at web

Nov 24, 2009, 5:11 AM

Post #14 of 19 (344 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

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

--
http://mail.python.org/mailman/listinfo/python-list


457r0.jp at gmail

Nov 24, 2009, 7:45 AM

Post #15 of 19 (344 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Nov 23, 10:37 pm, r <rt8...@gmail.com> wrote:
> On Nov 23, 11:19 am, astral orange <457r0...@gmail.com> 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...
--
http://mail.python.org/mailman/listinfo/python-list


tjreedy at udel

Nov 24, 2009, 2:29 PM

Post #16 of 19 (334 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

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

--
http://mail.python.org/mailman/listinfo/python-list


rt8396 at gmail

Nov 24, 2009, 5:53 PM

Post #17 of 19 (332 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

On Nov 24, 9:45 am, astral orange <457r0...@gmail.com> 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.



--
http://mail.python.org/mailman/listinfo/python-list


bruno.42.desthuilliers at websiteburo

Nov 25, 2009, 12:24 AM

Post #18 of 19 (327 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

astral orange a écrit :
> On Nov 23, 10:37 pm, r <rt8...@gmail.com> 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 :-/

--
http://mail.python.org/mailman/listinfo/python-list


lie.1296 at gmail

Nov 25, 2009, 7:08 AM

Post #19 of 19 (326 views)
Permalink
Re: Beginning Question about Python functions, parameters... [In reply to]

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.
--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.