Re: [Tutor] Dictionaries

2006-01-26 Thread Alan Gauld
> Is there anyway to print informtation from dictionaries better than this?:

For formatted printing look at the print format operator '%'

You can specify field sizes, justification etc

thus : 

>>> pairs = {"Jon Moore": "Tony Moore",
 "Simon Nightingale": "John Nightingale",
 "David Willett": "Bernard Willet",
 "John Jackson": "Stuart Jackson",
 "James Southey": "Richard Southey",
 "William Forsythe": "Shaun Forsythe"}
>>> print pairs.keys()
['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', 'James
Southey', 'William Forsythe']

>>> for father,son in pairs.items:
...   print "%20s\t%20s" % (father,son)

Which will print father and son each in a field 20 characters wide 
with a tab between them.

The docs on the format operator are here:

http://docs.python.org/lib/typesseq-strings.html

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries

2006-01-26 Thread Jon Moore
KentThanks! I have not come accross string formatting yet, but I can see how the for statement works.How would I modify this to just print either the values or keys?Jon
On 26/01/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Jon Moore wrote:> Hi>> Is there anyway to print informtation from dictionaries better than this?:>>  >>> pairs = {"Jon Moore": "Tony Moore",>  "Simon Nightingale": "John Nightingale",
>  "David Willett": "Bernard Willet",>  "John Jackson": "Stuart Jackson",>  "James Southey": "Richard Southey",>  "William Forsythe": "Shaun Forsythe"}
>  >>> print pairs.keys()> ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale',> 'James Southey', 'William Forsythe']>  > Is there no way to make it a nice list as I want to print the keys and
> values next to each other in a list such as:Of course there is :-)  >>> for father, son in pairs.iteritems():  ...   print '%-20s %s' % (father, son)  ...David WillettBernard Willet
Jon MooreTony MooreJohn Jackson Stuart JacksonSimon NightingaleJohn NightingaleJames SoutheyRichard SoutheyWilliam Forsythe Shaun Forsythepairs.iteritems() iterates over key, value pairs. The string formatting
operations are very handy for formatted output.http://docs.python.org/lib/typesseq-strings.htmlKent>> Jon Moore  Tony Moore
> Simon Nightingale   John Nightingale> David Willett   Bernard Willet> John Jackson Stuart Jackson> James Southey  Richard Southey> William ForsytheShaun Forsythe
>> For anyone who is wondering, it is to show father/son pairs. Next is to> add grandfathers *eek*.> --> Best Regards>> Jon Moore>>> 
>> ___> Tutor maillist  -  Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Adding items to dictionaries

2006-01-26 Thread Jon Moore
Hi,I have the following dictionary:pairs = {"Jon Moore": ["Tony Moore", "Stanley Moore"], "Simon Nightingale": ["John Nightingale", "Alan Nightingale"],
 "David Willett": ["Bernard Willet", "Robert Willet"], "John Jackson": ["John Jackson", "Peter Jackson"], "James Southey": ["Richard Southey", "Paul Southey"],
 "Shaun Forsythe": ["William Forsythe", "Angus Forsythe"], "Daniel Geach": ["Mike Geach", "Andy Geach"]}Where the names represent a son, father and grandfather.
I am trying to add a new term and related definitions to the dictionary, but my code does not seem to work:    son = raw_input("Please enter the name of the Son: ")    if son not in pairs:
    father = raw_input("Who is the Father?: ")    grandfather = raw_input("What is the Grand Father?: ")    pairs[son][0] = father    pairs[son][1] = grandfather
    print "\n", son, ",", father, "and" ,grandfather, "have been added."    else:    print "\nThat Son already exists!"The error I get is:
Please enter the name of the Son: Steven BatesWho is the Father?: Alan BatesWhat is the Grand Father?: Master BatesTraceback (most recent call last):  File "C:\Documents and Settings\Administrator\Desktop\FOO\transfer\whos_your_daddy_and_grandaddy.py", line 65, in ?
    pairs[son][0] = fatherKeyError: 'Steven Bates'>>> Where am I going wrong?-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries

2006-01-26 Thread Kent Johnson
Jon Moore wrote:
> Kent
> 
> Thanks! I have not come accross string formatting yet, but I can see how 
> the for statement works.
> 
> How would I modify this to just print either the values or keys?

Use
   for key in pairs.iterkeys():
or
   for value in pairs.itervalues():
and change the print statement appropriately.

This page shows the operations available on a dict:
http://docs.python.org/lib/typesmapping.html

Kent

> 
> Jon
> 
> On 26/01/06, *Kent Johnson* <[EMAIL PROTECTED] > 
> wrote:
> 
> Jon Moore wrote:
>  > Hi
>  >
>  > Is there anyway to print informtation from dictionaries better
> than this?:
>  >
>  >  >>> pairs = {"Jon Moore": "Tony Moore",
>  >  "Simon Nightingale": "John Nightingale",
>  >  "David Willett": "Bernard Willet",
>  >  "John Jackson": "Stuart Jackson",
>  >  "James Southey": "Richard Southey",
>  >  "William Forsythe": "Shaun Forsythe"}
>  >  >>> print pairs.keys()
>  > ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale',
>  > 'James Southey', 'William Forsythe']
>  >  >>>
>  >
>  > Is there no way to make it a nice list as I want to print the
> keys and
>  > values next to each other in a list such as:
> 
> Of course there is :-)
>   >>> for father, son in pairs.iteritems():
>   ...   print '%-20s %s' % (father, son)
>   ...
> David WillettBernard Willet
> Jon MooreTony Moore
> John Jackson Stuart Jackson
> Simon NightingaleJohn Nightingale
> James SoutheyRichard Southey
> William Forsythe Shaun Forsythe
> 
> pairs.iteritems() iterates over key, value pairs. The string formatting
> operations are very handy for formatted output.
> http://docs.python.org/lib/typesseq-strings.html
> 
> Kent
> 
>  >
>  > Jon Moore  Tony Moore
>  > Simon Nightingale   John Nightingale
>  > David Willett   Bernard Willet
>  > John Jackson Stuart Jackson
>  > James Southey  Richard Southey
>  > William ForsytheShaun Forsythe
>  >
>  > For anyone who is wondering, it is to show father/son pairs. Next
> is to
>  > add grandfathers *eek*.
>  > --
>  > Best Regards
>  >
>  > Jon Moore
>  >
>  >
>  >
> 
> 
>  >
>  > ___
>  > Tutor maillist  -  Tutor@python.org 
>  > http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org 
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> 
> -- 
> Best Regards
> 
> Jon Moore


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mod_python and other web frameworks

2006-01-26 Thread wkranec
There seems to be a discussion about this sort of thing every other
week or so, and I'm always surprised that no one mentions Cheetah
Templates (www.cheetahtemplate.org).  It's useful for both web and
non-Web applications, and has a straightforward syntax that pretty
much *is* Python.  For web programming, it can be used for straight up
CGI, or in a mod_python type setup.  I have used it several times and
really enjoyed it.

There's alot of work being done right now in preparation for a 2.0
release, so the web site should be very up to date, as well as the
tutorial / user's guide.  Check it out!

Bill

On 1/25/06, Ben Vinger <[EMAIL PROTECTED]> wrote:
>
> --- Intercodes <[EMAIL PROTECTED]> wrote:
>
> > List: I am still open to suggestions.
>
> Being also keen to write better web apps in Python,
> I've spent a considerable amount of time reading about
> this (and it is indeed confusing), I've opted to try
> out something like Pylons or Turbogears.
> One thing I will say though, is that most of the
> frameworks you've read about can be run on top of
> mod_python.  So mod_python is not one of the lot - it
> is essential on Apache unless you opt to use CGI or
> FCGI. But as I understand it, you would always opt for
> mod_python over CGI or FCGI on a high-traffic website,
> though CGI or FCGI is of course fine for smaller
> things.
> But mod_python is not so easy to work with and it will
> only work on Apache.  So it seems best to choose
> something else and run that through mod_python when
> you're on Apache.
>
>
>
>
>
>
> ___
> Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with 
> voicemail http://uk.messenger.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding items to dictionaries

2006-01-26 Thread Kent Johnson
Jon Moore wrote:
> Hi,
> 
> I have the following dictionary:
> 
> pairs = {"Jon Moore": ["Tony Moore", "Stanley Moore"],
>  "Simon Nightingale": ["John Nightingale", "Alan Nightingale"],
>  "David Willett": ["Bernard Willet", "Robert Willet"],
>  "John Jackson": ["John Jackson", "Peter Jackson"],
>  "James Southey": ["Richard Southey", "Paul Southey"],
>  "Shaun Forsythe": ["William Forsythe", "Angus Forsythe"],
>  "Daniel Geach": ["Mike Geach", "Andy Geach"]}
> 
> Where the names represent a son, father and grandfather.
> 
> I am trying to add a new term and related definitions to the dictionary, 
> but my code does not seem to work:
> 
> son = raw_input("Please enter the name of the Son: ")
> if son not in pairs:
> father = raw_input("Who is the Father?: ")
> grandfather = raw_input("What is the Grand Father?: ")
> pairs[son][0] = father
> pairs[son][1] = grandfather
> print "\n", son, ",", father, "and" ,grandfather, "have been 
> added."
> else:
> print "\nThat Son already exists!"
> 
> The error I get is:
> 
> pairs[son][0] = father
> KeyError: 'Steven Bates'
>  >>>
> 
> Where am I going wrong?

The problem is, when you say
   pairs[son][0] = father

pairs[son] does not yet exist. This is on the left side of an 
assignment, but it is really an access to pair[son]. It is as if you had 
written
   temp = pairs[son]
   temp[0] = father

You get a KeyError accessing pairs[son].

The solution is to create a new list for the (father, grandfather) pair, 
and assign that to pairs[son]:

ancestors = [father, grandfather]
pairs[son] = ancestors

You might want to rethink how you are storing the data. (father, 
grandfather) is actually a (son, father) pair so you might want to store 
them as another entry in the dictionary. Also two sons could have the 
same father and grandfather; with your scheme you will store the 
(father, grandfather) pair twice. In general this kind of duplication of 
data is better avoided.

You might also want to Google 'python genealogy'.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] smarter way of looping

2006-01-26 Thread Elderely Geek
Hi,
I`m a python newbie and could use some help.
 
I often do a loop over arbitrary number of sequences. I do it like this:
 
for elem1 in seq1:
    for elem2 in seq2:
    do whatever seq1,seq2
 
this isn`t nice I think. Is there some way I can say myiterator=geniousfunction(seq1,seq2,seq3)
 
and then myiterator.next()  and have it return the corresponding elemnts from all sequences like if
 
seq1 = ['a','b']
seq2 = [1,2]
 
I could get
 
a 1
a 2
b 1
b 2
 
also, how do you loop over all the elements that can be returned by myiterator?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries

2006-01-26 Thread Alan Gauld
 for father,son in pairs.items:
> ...   print "%20s\t%20s" % (father,son)

Oops! Should have been 

for father,son in pairs.items():

Sorry,

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries

2006-01-26 Thread Alan Gauld
> How would I modify this to just print either the values or keys?

Just ask for the values or the keys!

for value in pairs.values()
 print value

for key in pairs.keys()
 print key

for key,value in pairs.items()
print key
print value

Dictionaries are extremely powerful data containers.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smarter way of looping

2006-01-26 Thread Kent Johnson
Elderely Geek wrote:
> Hi,
> I`m a python newbie and could use some help.
>  
> I often do a loop over arbitrary number of sequences. I do it like this:
>  
> for elem1 in seq1:
> for elem2 in seq2:
> do whatever seq1,seq2
>  
> this isn`t nice I think. Is there some way I can say 
> myiterator=geniousfunction(seq1,seq2,seq3)
>  
> and then myiterator.next()  and have it return the corresponding elemnts 
> from all sequences like if
>  
> seq1 = ['a','b']
> seq2 = [1,2]
>  
> I could get
>  
> a 1
> a 2
> b 1
> b 2

This is a perennial topic on comp.lang.python and there are many clever 
ways to do it. The most straightforward way is to use a recursive 
generator. The idea is, at each step, combine each element of the first 
sequence with each sequence generated from the remaining sequences. Here 
is one way to do it:

def combine(*seqs):
   if not seqs:
 yield []
   else:
 for item in seqs[0]:
   for subitem in combine(*seqs[1:]):
 yield [item] + subitem

seq1 = ['a','b']
seq2 = [1,2]

for seq in combine(seq1, seq2):
   print seq

print list(combine(seq1, seq2))

This uses some fairly advanced bits of Python:
arbitrary argument lists (I can't find a good doc for this)
generators: http://www.python.org/doc/2.3.5/whatsnew/section-generators.html
and recursion.

>  
> also, how do you loop over all the elements that can be returned by 
> myiterator?

As in the example above, you can iterate it with a for loop, or convert 
to a list.

Kent
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mod_python and other web frameworks

2006-01-26 Thread Christian Wyglendowski
Some others have already mentioned TurboGears, but since it sounds like
you want more control perhaps, I would recommend going with CherryPy
(http://www.cherrypy.org).  You basically write python code and then
expose it to the web (or intranet or whatever).

# simple example
import cherrypy
import time

class MySection(object):
@cherrypy.expose
def index(self):
yield "Hello, world!"
yield "Check the time"
# if you are using Python 2.3, you do the following to expose a method
#   index.exposed = True

@cherrypy.expose
def time(self):
return "The current time is %s" % self.get_time()

# this method is not exposed and thus not accessible from the web
def get_time(self):
return time.ctime()

# mount the class at the server root
cherrypy.root = MySection()

cherrypy.server.start()
# end of example

You can then run that script and visit http://localhost:8080/.  That
will call the "index" method of the MySection object mounted at the
server root.  You can also visit http://localhost:8080/time.  However,
http://localhost:8080/get_time is _not_ available to the web, because it
is not "exposed".

Anyhow, CherryPy is very pythonic and flexible.  Use whatever DB you
want (or flat files or ...).  Use whatever templating language you want
(or just return html from your methods.

Anyhow, that's probably more info than you wanted.  Good luck!

Christian
http://www.dowski.com

ps And "as a beginner", I would _not_ start with something like
mod_python ;-)


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Intercodes
Sent: Wednesday, January 25, 2006 12:59 PM
To: tutor@python.org
Subject: [Tutor] mod_python and other web frameworks

Hello everyone,

Disclaimer:  Beginner.

I have an idea of coding a web application and decided to do it entirely
with python (reddit style). I started looking for web programming in
python and somehow I saw mod_python first. Iam perusing the help
document now. 

Few minutes of browsing confused my mind entirely , since it seems there
are about 20 different web frameworks available for python. I am left
clueless as to pick which one. I have an soft side towards the one I
picked first. 

Considering yourself as a beginner to python  ,do you prefer mod_python
over all other framework?. Say if you want to create a blog , will
mod_python suffice? And is mod_python and cgi (the python lib)
different?


--
Intercodes


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding items to dictionaries

2006-01-26 Thread Jon Moore
KentThanks again. I have a question (see below).On 26/01/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Jon Moore wrote:> Hi,>> I have the following dictionary:>> pairs = {"Jon Moore": ["Tony Moore", "Stanley Moore"],
>  "Simon Nightingale": ["John Nightingale", "Alan Nightingale"],>  "David Willett": ["Bernard Willet", "Robert Willet"],>  "John Jackson": ["John Jackson", "Peter Jackson"],
>  "James Southey": ["Richard Southey", "Paul Southey"],>  "Shaun Forsythe": ["William Forsythe", "Angus Forsythe"],>  "Daniel Geach": ["Mike Geach", "Andy Geach"]}
>> Where the names represent a son, father and grandfather.>> I am trying to add a new term and related definitions to the dictionary,> but my code does not seem to work:>> son = raw_input("Please enter the name of the Son: ")
> if son not in pairs:> father = raw_input("Who is the Father?: ")> grandfather = raw_input("What is the Grand Father?: ")> pairs[son][0] = father
> pairs[son][1] = grandfather> print "\n", son, ",", father, "and" ,grandfather, "have been> added."> else:> print "\nThat Son already exists!"
>> The error I get is:>> pairs[son][0] = father> KeyError: 'Steven Bates'>  > Where am I going wrong?The problem is, when you say   pairs[son][0] = father
pairs[son] does not yet exist. This is on the left side of anassignment, but it is really an access to pair[son]. It is as if you hadwritten   temp = pairs[son]   temp[0] = fatherYou get a KeyError accessing pairs[son].
The solution is to create a new list for the (father, grandfather) pair,and assign that to pairs[son]:ancestors = [father, grandfather]pairs[son] = ancestorsYou might want to rethink how you are storing the data. (father,
grandfather) is actually a (son, father) pair so you might want to storethem as another entry in the dictionary. Also two sons could have thesame father and grandfather; with your scheme you will store the
(father, grandfather) pair twice. In general this kind of duplication ofdata is better avoided.Good point, but I have no idea how to do this! Could you show me? 
You might also want to Google 'python genealogy'.Kent___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mod_python and other web frameworks

2006-01-26 Thread Intercodes
 Christian,You are certainly right. I couldn't get anything apart from "Hello world" coding in mod_python. The mod_python manual is also bit vague, not for beginners. I wonder why there aren't any good tutorials on mod_python.
I am having a look at quixote as a developer in this list suggested. I would take a look at cherrypy if quixote is too deep for me.Thanks for your time and the example. I believe your website is written completely in cherrypy. Working on so many projects ,nice work.
Intercodes# simple exampleimport cherrypyimport time
class MySection(object):@cherrypy.exposedef index(self):yield "Hello, world!"yield "Check the time"# if you are using Python 
2.3, you do the following to expose a method#   index.exposed = True@cherrypy.exposedef time(self):return "The current time is %s" % self.get_time()
# this method is not exposed and thus not accessible from the webdef get_time(self):return time.ctime()# mount the class at the server rootcherrypy.root = MySection()cherrypy.server.start
()# end of exampleYou can then run that script and visit http://localhost:8080/.  Thatwill call the "index" method of the MySection object mounted at theserver root.  You can also visit 
http://localhost:8080/time.  However,http://localhost:8080/get_time is _not_ available to the web, because itis not "exposed".
Anyhow, CherryPy is very pythonic and flexible.  Use whatever DB youwant (or flat files or ...).  Use whatever templating language you want(or just return html from your methods.Anyhow, that's probably more info than you wanted.  Good luck!
Christianhttp://www.dowski.comps And "as a beginner", I would _not_ start with something likemod_python ;-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding items to dictionaries

2006-01-26 Thread Alan Gauld
> pairs[son][0] = father
> KeyError: 'Steven Bates'

> Where am I going wrong?

A KeyError means you are trying to access an object that does not exist
in the dictionary. And this is true, you haven't added anything for Steven 
Bates
yet, but you are trying to access his parents list.
You need to create an associated list which you can then edit.

pairs[son] = [0,0]  # need to put dummy data in
pairs[son][0] = father
pairs[son][1] = grandfather

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smarter way of looping

2006-01-26 Thread Alan Gauld
> I often do a loop over arbitrary number of sequences. I do it like this:
>
>for elem1 in seq1:
>for elem2 in seq2:
>do whatever seq1,seq2
>
> this isn`t nice I think.

Actually its pretty common and not that ugly.
But...

> myiterator=geniousfunction(seq1,seq2,seq3)
>
> and then myiterator.next()  and have it return the corresponding elemnts
> from all sequences

The problem is that there are so many different ways you can do that.
Python offers several options but none of them solve all the cases.

Look at the documentation for

List Comprehensions
zip()
map()
filter()
reduce()

> seq1 = ['a','b']
> seq2 = [1,2]
> a 1
> a 2
> b 1
> b 2

[a,b for a in seq1 for b in seq2]

> how do you loop over all the elements that can be returned by
> myiterator?

return the options as a list of tuples and then use the usual list iteration 
techniques.

for elem in [a,b for a in seq1 for b in seq2]:
# use elem here

HTH

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smarter way of looping

2006-01-26 Thread Elderly Geek
On 1/26/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > I often do a loop over arbitrary number of sequences. I do it like this:
> >
> >for elem1 in seq1:
> >for elem2 in seq2:
> >do whatever seq1,seq2
> > this isn`t nice I think.
>
> Actually its pretty common and not that ugly.
> But...

Ok, I see. I was trying to show that I`m (was) unable to pass in an
arbitrary number of secuences, but the generator in one of the other
posts in thread solves this, right? quite impressive that one I think

> > myiterator=geniousfunction(seq1,seq2,seq3)
> >
> > and then myiterator.next()  and have it return the corresponding elemnts
> > from all sequences
>
> The problem is that there are so many different ways you can do that.
> Python offers several options but none of them solve all the cases.
>
> Look at the documentation for
>
> List Comprehensions
> zip()
> map()
> filter()
> reduce()

I will. Thanks.

>
> > seq1 = ['a','b']
> > seq2 = [1,2]
> > a 1
> > a 2
> > b 1
> > b 2
>
> [a,b for a in seq1 for b in seq2]
>
> > how do you loop over all the elements that can be returned by
> > myiterator?
>
> return the options as a list of tuples and then use the usual list iteration
> techniques.
>
> for elem in [a,b for a in seq1 for b in seq2]:
># use elem here
>

that`s nice. Thanks for the replies
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Controling my loops and redundant code?!?

2006-01-26 Thread Bob Gailer
At 08:44 AM 1/25/2006, Jon Moore wrote:

Hi,
I have written the program below as an exercise from a book I am working my way through.
Objective from book:Write
a character creator program for a role-playing-game. The player should
be given a pool of 30 points to spend on four attributes: strength,
health, wisdom and dexterity. The player should be able to spend points
from the pool on any attribute and should be also be able to take
points from an attribute and put them back in the pool. 
Although the program meets the aim of the exercise set out in the book , there are a couple of things I am not happy with!
1. I am sure I have written far more code than required. Where could I have made some shorcuts? 
2. Should the user enter a value greater than what is available, the
program kicks the user all the way back to the main menu. How could I
tidy this up to just loop round to ask the user to try a new value?
choice = None
# Set max number of available points
POINTS_POOL = 30
# store attribute values
attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], ["Dexterity", 0]] 


Some ideas to chew on as you develop skills and understanding of programming.

Separate the "essential data" from the code. The essential data are attributes, associated points and max_points. So


attributes = ["Strength", "Health", "Wisdom", "Dexterity"] 

points = [0, 0, 0, 0]

MAX_POINTS = 30

In this model the relationship between attributes and points is by
position. Later you will study and use classes; then the points list
will be replaced by a list of class instances, one per attribute.

Develop code that operates on these lists to accomplish the various
objectives. The code itself will never refer to any attribute by name! 

 

For example - to list the attributes with their points:


for x in range(len(attributes)):

  print "\t",attributes[x], points[x]

To assign values. Note I separated getting input from converting it to
integer so we can see if the user's entry is convertible.:


available_points = MAX_POINTS - sum(points)

print "You have " + available_points + " available."

for x in range(len(attributes)):

 cvalue = raw_input("How much would you like to assign to " + attributes[x] + " ?: "))

  if cvalue.isdigit():

    value = int(cvalue)

  else:

    print "Number expected"

[snip]-- Bob Gailer510-978-4454
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Controling my loops and redundant code?!?

2006-01-26 Thread Paul Kraus
What book are you working through? That is a pretty interesting exercise.

Paul
On Thursday 26 January 2006 12:52 pm, Bob Gailer wrote:
> At 08:44 AM 1/25/2006, Jon Moore wrote:
>
> Hi,
>
> I have written the program below as an exercise from a book I am working my
> way through.
>
> Objective from book:
> Write a character creator program for a role-playing-game. The player
> should be given a pool of 30 points to spend on four attributes: strength,
> health, wisdom and dexterity. The player should be able to spend points
> from the pool on any attribute and should be also be able to take points
> from an attribute and put them back in the pool.
>
> Although the program meets the aim of the exercise set out in the book ,
> there are a couple of things I am not happy with!
>
> 1. I am sure I have written far more code than required. Where could I have
> made some shorcuts?
>
> 2. Should the user enter a value greater than what is available, the
> program kicks the user all the way back to the main menu. How could I tidy
> this up to just loop round to ask the user to try a new value?
>
> choice = None
>
> # Set max number of available points
> POINTS_POOL = 30
>
> # store attribute values
> attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], ["Dexterity",
> 0]]
>
>
> Some ideas to chew on as you develop skills and understanding of
> programming.
> Separate the "essential data" from the code. The essential data are
> attributes, associated points and max_points. So
>
> attributes = ["Strength", "Health", "Wisdom", "Dexterity"]
> points = [0, 0, 0, 0]
> MAX_POINTS = 30
>
> In this model the relationship between attributes and points is by
> position. Later you will study and use classes; then the points list will
> be replaced by a list of class instances, one per attribute.
>
> Develop code that operates on these lists to accomplish the various
> objectives. The code itself will never refer to any attribute by name!
>
> For example - to list the attributes with their points:
>
> for x in range(len(attributes)):
>   print "\t",attributes[x], points[x]
>
> To assign values. Note I separated getting input from converting it to
> integer so we can see if the user's entry is convertible.:
>
> available_points = MAX_POINTS - sum(points)
> print "You have " + available_points + " available."
> for x in range(len(attributes)):
>  cvalue = raw_input("How much would you like to assign to " + attributes[x]
> + " ?: "))
>   if cvalue.isdigit():
> value = int(cvalue)
>   else:
> print "Number expected"
>
> [snip]
> --
> Bob Gailer
> 510-978-4454

-- 
Paul Kraus
=-=-=-=-=-=-=-=-=-=-=
PEL Supply Company
Network Administrator
216.267.5775 Voice
216.267.6176 Fax
www.pelsupply.com
=-=-=-=-=-=-=-=-=-=-=
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] First steps with Tkinter

2006-01-26 Thread etrade . griffiths
Hi!

Just started trying to get to grips with Python and Tkinter.  Have Frederick 
Lundh's tutorial and am on program hello2.py which looks like this

# File: hello2.py

from Tkinter import *

class App:

def __init__(self, master):

frame = Frame(master)
frame.pack()

self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)

self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)

def say_hi(self):
print "hi there, everyone!"

root = Tk()

app = App(root)

root.mainloop()

I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run 
hello2.py it freezes when I press "QUIT".  The only way to kill it is through 
Alt-Ctrl-Del but this crashes Pythonwin.  Any workaround for this so that I 
can use Tkinter from inside the IDE?  BTW the same thing happend with IDLE

Thanks in advance

Alun Griffiths
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First steps with Tkinter

2006-01-26 Thread Michael Lange
On Thu, 26 Jan 2006 18:20:48 +
[EMAIL PROTECTED] wrote:


> 
> root.mainloop()
> 
> I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run 
> hello2.py it freezes when I press "QUIT".  The only way to kill it is through 
> Alt-Ctrl-Del but this crashes Pythonwin.  Any workaround for this so that I 
> can use Tkinter from inside the IDE?  BTW the same thing happend with IDLE
> 

Hi,

when running Tkinter apps from IDLE or Pythonwin, you need to comment out the 
call to mainloop() .
This is because the IDE itself runs a Tkinter mainloop() and two of these 
cannot coexist in one process.

I hope this helps

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Controling my loops and redundant code?!?

2006-01-26 Thread Bob Gailer
At 08:44 AM 1/25/2006, Jon Moore wrote:
> Hi,
>
> I have written the program below as an exercise from a book I am 
> working my way through.
>
> Objective from book:
> Write a character creator program for a role-playing-game. The player 
> should be given a pool of 30 points to spend on four attributes: 
> strength, health, wisdom and dexterity. The player should be able to 
> spend points from the pool on any attribute and should be also be able 
> to take points from an attribute and put them back in the pool.
>
> Although the program meets the aim of the exercise set out in the book 
> , there are a couple of things I am not happy with!
>
> 1. I am sure I have written far more code than required. Where could I 
> have made some shorcuts?
>
> 2. Should the user enter a value greater than what is available, the 
> program kicks the user all the way back to the main menu. How could I 
> tidy this up to just loop round to ask the user to try a new value?
>
> choice = None
>
> # Set max number of available points
> POINTS_POOL = 30
>
> # store attribute values
> attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], 
> ["Dexterity", 0]] 

Some ideas to chew on as you develop skills and understanding of 
programming.
Separate the "essential data" from the code. The essential data are 
attributes, associated points and max_points. So

attributes = ["Strength", "Health", "Wisdom", "Dexterity"]
points = [0, 0, 0, 0]
MAX_POINTS = 30

In this model the relationship between attributes and points is by 
position. Later you will study and use classes; then the points list 
will be replaced by a list of class instances, one per attribute.

Develop code that operates on these lists to accomplish the various 
objectives. The code itself will never refer to any attribute by name!
 
For example - to list the attributes with their points:

for x in range(len(attributes)):
  print "\t",attributes[x], points[x]

To assign values. Note I separated getting input from converting it to 
integer so we can see if the user's entry is convertible.:

available_points = MAX_POINTS - sum(points)
print "You have " + available_points + " available."
for x in range(len(attributes)):
 cvalue = raw_input("How much would you like to assign to " + 
attributes[x] + " ?: "))
  if cvalue.isdigit():
value = int(cvalue)
  else:
print "Number expected"

[snip]
-- 
Bob Gailer
510-978-4454
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-26 Thread Orri Ganel




Rinzwind wrote:
In basic I can use SGN to get back -1, 0,  +1 if a number
is <0, 0, >0.
I searched on  the web for a bit but sgn and sign give me way too many
discussions about Decimals. python.org
with numbers/digits doesn't tell about a function.
  
Maybe Python uses a different name for it so I am not looking for the
correct wording :( Sucks not knowing syntax from my memory and having
to look them up alot).
  
  
Wim
  
  
  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  


Well, the cmp() function does this if you compare the number
to 0:

>>> cmp(-34,0)
-1
>>> cmp(0,0)
0
>>> cmp(23,0)
1

Of course, that's not all cmp() is good for, but it
would work in this case.

HTH,
Orri
-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-26 Thread Rinzwind
Thank you!*opens manual again*WimOn 1/26/06, Orri Ganel <[EMAIL PROTECTED]> wrote:



  


Rinzwind wrote:
In basic I can use SGN to get back -1, 0,  +1 if a number
is <0, 0, >0.
I searched on  the web for a bit but sgn and sign give me way too many
discussions about Decimals. python.org
with numbers/digits doesn't tell about a function.
  
Maybe Python uses a different name for it so I am not looking for the
correct wording :( Sucks not knowing syntax from my memory and having
to look them up alot).
  
  
Wim
  
  
  
___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  


Well, the cmp() function does this if you compare the number
to 0:

>>> cmp(-34,0)
-1
>>> cmp(0,0)
0
>>> cmp(23,0)
1

Of course, that's not all cmp() is good for, but it
would work in this case.

HTH,
Orri
-- Email: singingxduck AT gmail DOT comAIM: singingxduckProgramming Python for the fun of it.




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-26 Thread Rinzwind
In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.I searched on  the web for a bit but sgn and sign give me way too many discussions about Decimals. python.org
 with numbers/digits doesn't tell about a function.Maybe Python uses a different name for it so I am not looking for the correct wording :( Sucks not knowing syntax from my memory and having to look them up alot).
Wim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-26 Thread Orri Ganel




No problem.  As for the main use of  cmp(), btw, afaik, it's
used to define custom sorting, as in the following:

>>> import random
>>> temp = []
>>> for i in range(10):
   
temp.append((random.randint(0,100),random.randint(0,100),random.randint(0,100)))

    
>>> temp
[(16, 70, 87), (57, 80, 33), (14, 22, 2), (21, 92, 69), (40, 18, 90),
(60, 78, 35), (3, 98, 7), (32, 21, 39), (15, 67, 15), (70, 95, 39)]
>>> temp.sort(cmp=lambda x, y: cmp(x[0],y[0]))
>>> temp
[(3, 98, 7), (14, 22, 2), (15, 67, 15), (16, 70, 87), (21, 92, 69),
(32, 21, 39), (40, 18, 90), (57, 80, 33), (60, 78, 35), (70, 95, 39)]
>>> temp.sort(cmp=lambda x, y: cmp(x[1],y[1]))
>>> temp
[(40, 18, 90), (32, 21, 39), (14, 22, 2), (15, 67, 15), (16, 70, 87),
(60, 78, 35), (57, 80, 33), (21, 92, 69), (70, 95, 39), (3, 98, 7)]
>>> temp.sort(cmp=lambda x, y: cmp(x[2],y[2]))
>>> temp
[(14, 22, 2), (3, 98, 7), (15, 67, 15), (57, 80, 33), (60, 78, 35),
(32, 21, 39), (70, 95, 39), (21, 92, 69), (16, 70, 87), (40, 18, 90)]

or, without lambdas:

>>> def sort(x,y):
    return cmp(x[0],y[0])

>>> def sort1(x,y):
    return cmp(x[1],y[1])

>>> def sort2(x,y):
    return cmp(x[2],y[2])

>>> temp.sort(cmp=sort)
>>> temp
[(3, 98, 7), (14, 22, 2), (15, 67, 15), (16, 70, 87), (21, 92, 69),
(32, 21, 39), (40, 18, 90), (57, 80, 33), (60, 78, 35), (70, 95, 39)]
>>> temp.sort(cmp=sort1)
>>> temp
[(40, 18, 90), (32, 21, 39), (14, 22, 2), (15, 67, 15), (16, 70, 87),
(60, 78, 35), (57, 80, 33), (21, 92, 69), (70, 95, 39), (3, 98, 7)]
>>> temp.sort(cmp=sort2)
>>> temp
[(14, 22, 2), (3, 98, 7), (15, 67, 15), (57, 80, 33), (60, 78, 35),
(32, 21, 39), (70, 95, 39), (21, 92, 69), (16, 70, 87), (40, 18, 90)]

Rinzwind wrote:
Thank you!
*opens manual again*
  
Wim
  
  On 1/26/06, Orri Ganel <[EMAIL PROTECTED]>
wrote:
  Well,
the cmp() function does this if you compare the number
to 0:

>>> cmp(-34,0)
-1
>>> cmp(0,0)
0
>>> cmp(23,0)
1

Of course, that's not all cmp() is good for, but it
would work in this case.

HTH,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

  
  
  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  



-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list.__init__()

2006-01-26 Thread Christopher Spears
What purpose does list.__init__() play in the piece of
code below?

class Mylist(list):
def __init__(self, value = []):
list.__init__([])
self.concat(value)
def concat(self, value):
for x in value:
if not x in self:
self.append(x)

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-26 Thread Kent Johnson
Orri Ganel wrote:
> Rinzwind wrote:
> 
>> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> Well, the cmp() function does this if you compare the number to 0:
> 
>  >>> cmp(-34,0)
> -1
>  >>> cmp(0,0)
> 0
>  >>> cmp(23,0)

One caution: this behaviour doesn't seem to be required, the docs allow 
any positive or negative integer:
cmp(x, y)
 Compare the two objects x and y and return an integer according to 
the outcome. The return value is negative if x < y, zero if x == y and 
strictly positive if x > y.

So this behaviour might differ between Python versions.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list.__init__()

2006-01-26 Thread Kent Johnson
Christopher Spears wrote:
> What purpose does list.__init__() play in the piece of
> code below?

It's an incorrect call to the base class __init__() function. This does 
base class initialization on the current list. The correct call is
   list.__init__(self)

By the way this list seems to be doing the work of a set. Since Python 
2.3 set types have been standard in Python (in module sets in 2.3 and 
the builtin type set in 2.4). Before 2.3 a dict is a better choice for 
rolling your own because it supports fast lookup.

Kent
> 
> class Mylist(list):
>   def __init__(self, value = []):
>   list.__init__([])
>   self.concat(value)
>   def concat(self, value):
>   for x in value:
>   if not x in self:
>   self.append(x)
>   
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] designing a class

2006-01-26 Thread Christopher Spears
Here is an exercise out of Learning Python:

Write a class called Mylist that shadows ("wraps") a
Python list: it should overload most list operators
and operations including +, indexing, iteration,
slicing, and list methods such as append and sort. 
See the Python reference manual for a list of possible
methods to support.  Also, provide a constructor for
your class that takes an existing list (or a Mylist
instance) and copies it components inro an instance
member.

When I read this, I feel like a deer caught in the
headlights.  Where should I begin?  How do I go about
designing a new class?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [newbie alert] why can't I find a function that givesme the sign of an integer?

2006-01-26 Thread Alan Gauld
>> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> Well, the cmp() function does this if you compare the number to 0:

Neat trick Orri, I'd never have thought of that one :-)

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is this overkill?

2006-01-26 Thread catherine curley
Bradly
 
I'm new to python also.  Have you come across any good exercises that a beginner try.
 
I've spend some time going throught the many available turorials, but find it hard to get good exercises to try out what you learn.
 
Catherine 
On 1/21/06, Bradly McConnell <[EMAIL PROTECTED]> wrote:
Greetings all:I'm new to Python, and have come across and exercise that basicallycounts to 100.  The idea is to accept user input for an initial
number, and then let the user add additional numbers.  I wanted togive feedback if a number selected would bring the total above 100, sothe user would select a lower number.  It looks like I have itworking, but it doesn't seem very efficient.  I would like any hints,
help, or comments that you can provide.  Below is what I have so far.number = input("Please enter a number: ")while number != 100:   additional_number = input("Please enter an additional number: ")
   if additional_number + number > 100:   lower_number = input("please enter a lower number: ")   if lower_number + number > 100:   lower_number = input("Lower!")
   else:   number = lower_number + number   elif additional_number + number < 100:   number = additional_number + number   else:   continueprint "Done", number
Brad___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First steps with Tkinter

2006-01-26 Thread catherine curley
Alan
 
As a matter of interest, did you have much knowledge of Python before you tried TKinter?  I'm only a python beginner at present.
 
Catherine 
On 1/26/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:
Hi!Just started trying to get to grips with Python and Tkinter.  Have FrederickLundh's tutorial and am on program 
hello2.py which looks like this# File: hello2.pyfrom Tkinter import *class App:   def __init__(self, master):   frame = Frame(master)   frame.pack()   self.button
 = Button(frame, text="QUIT", fg="red", command=frame.quit)   self.button.pack(side=LEFT)   self.hi_there = Button(frame, text="Hello", command=self.say_hi)   self.hi_there.pack
(side=LEFT)   def say_hi(self):   print "hi there, everyone!"root = Tk()app = App(root)root.mainloop()I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run
hello2.py it freezes when I press "QUIT".  The only way to kill it is throughAlt-Ctrl-Del but this crashes Pythonwin.  Any workaround for this so that Ican use Tkinter from inside the IDE?  BTW the same thing happend with IDLE
Thanks in advanceAlun Griffiths___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] designing a class

2006-01-26 Thread Terry Carroll
On Thu, 26 Jan 2006, Christopher Spears wrote:

> Here is an exercise out of Learning Python:

Which edition?  If I recall, the second edition covers through a release
of Python (2.2?) that permits direct subclassing of lists; while the
earlier one came out prior to Python 2.2, and would expect you to fake it
out a bit by subclassing USerList.
 
> Write a class called Mylist that shadows ("wraps") a
> Python list: 

Okay; what this means is that you're defining a class by subclassing the 
list type (or UserList type, for pre-2.2).

> it should overload most list operators
> and operations including...

This meens you need to write a bunch of methods name __x__ where "x" is 
some specific name that is related to the task listed in the problem.

You'll find most of these, I think, in section 3.3 of the reference
Manual; see http://docs.python.org/ref/specialnames.html and the pages
that follow.

For some examples,

> +, 

That would be __add__ ; see http://docs.python.org/ref/numeric-types.html

> indexing, iteration,
> slicing, and list methods such as append and sort.

Most of these are discussed at 
http://docs.python.org/ref/sequence-methods.html  There seem to be quite a 
lot of them!  I'm wondering if you can skip most of them; one advantage of 
subclassing is to be able to rely on the superclasses implementations.

> Also, provide a constructor for
> your class that takes an existing list (or a Mylist
> instance) and copies it components inro an instance
> member.

That's __init__.

> 
> When I read this, I feel like a deer caught in the
> headlights.  Where should I begin?  How do I go about
> designing a new class?

I would suggest you first just successfully subclass the list builtin.  
(Even if you're using the First Edition of LP, I'd go with subclassing 
list directly, rather than using UserList.  If you're on a sufficiently 
old version of Python that you can't do that, enough has changed that it's 
worth upgrading.)

Play with that, adding and printing list members.

Once you have that down, add your __init__ to support initialization by 
making a copy.

Then add the other pieces.

Small steps, get some confidence, then work forwards.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] AttributeError - ChatServer

2006-01-26 Thread Bob Hinkle
While following a tutorial on how to create a simple chat server I stumbled upon this problem: 
AttributeError: ChatServer instance has no attribute 'decriptors'

here is my code:
#...
import socket
import select

class ChatServer:

    def __init__(self,port):
    self.port = port;

    self.srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.srvsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.srvsock.bind(("", port))
    self.srvsock.listen(5)

    self.descriptors = [self.srvsock]
    print 'Chat Server started on port %s' % port

    def run ( self ):

    while 1:

    #Await even on a readable socket descriptor
   
(sread, swrite, sexc) = select.select(self.descriptors, [], [])

    #Iterate through the tagged read descriptors
    for sock in sread:

   
#check if received a connect to the server
    if sock == self.srvsock:
   
self.accept_new_connection()
    else:

   
# received something on a client socket
   
str = sock.recv(100)

   
# check and see if the peer closed socket
    if str == '':
   
host,port = sock.getpeername()
   
str = 'Client left %s:%s\r\n' % (host, port)
   
self.broadcast_string(str,sock)
   
sock.close
   
self.descriptors.remose(sock)
    else:
   
host,port = sock.getpeername()
   
newstr = '[%s:%s] %s' % (host, port, str)
   
self.broadcast_string(newstr,sock)

    def broadcast_string(self, str, omit_sock):

    for sock in self.decriptors:
    if sock != self.srvsock and sock != omit_sock:
    sock.send(str)

    print str,


    def accept_new_connection( self ):

    newsock, (remhost, remport) = self.srvsock.accept()
    self.descriptors.append( newsock )

    newsock.send("You're connected to Chat Server!\r\n")
    str = "Client joined %s:%s\r\n" % (remhost, remport)
    self.broadcast_string( str, newsock )

myserver = ChatServer( 23000 )
myserver.run()
#...

It starts fine but when someone connects, I get the error.
[saiph]$ python telnetserver2.py
Chat Server started on port 23000
Traceback (most recent call last):
  File "telnetserver2.py", line 74, in ?
    myserver.run()
  File "telnetserver2.py", line 32, in run
    self.accept_new_connection()
  File "telnetserver2.py", line 69, in accept_new_connection
    self.broadcast_string( str, newsock )
  File "telnetserver2.py", line 53, in broadcast_string
    for sock in self.decriptors:
AttributeError: ChatServer instance has no attribute 'decriptors'

Any help would be appreciated! TIA
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] AttributeError - ChatServer

2006-01-26 Thread John Fouhy
On 27/01/06, Bob Hinkle <[EMAIL PROTECTED]> wrote:
> While following a tutorial on how to create a simple chat server I stumbled
> upon this problem:
>  AttributeError: ChatServer instance has no attribute 'decriptors'

Hi Bob,

Attributes are things like methods or variables that are "attached" to
a class instance.  For example, instances of your CharServer class
have attributes like .port or .srvsock.

When you get an AttributeError, it means that you tried to access an
attribute and python couldn't find the attribute you wanted.  In this
particular case, the error message says that on line 53, you tried to
access "self.decriptors", and "self" (which is your ChatServer) didn't
have a "decriptors" attribute.

Looking through your code, I can see that you assign to
"self.descriptors" in your __init__ method.  So I guess this is just a
typo --- if you change "self.decriptors" to "self.descriptors", you
might have more luck :-)

--
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trying to enter text from a file to a Dictionary

2006-01-26 Thread Ben Markwell
Being new to programming, I made a text file that  contains terms with their definitions that I have come across in my  studying. As an exercise, I thought  I would make a glossary using  a dictionary so I can look up words, add new words, view all entries,  etc.   I want to enter the words and definitions from the  text file into the dict. The way the text file is set up is that one  line is the word and the next line is the definition. For example:  Word      Definition of the word.  Second Word      Definition of the second word.  EtcI thought this would be rather simple (maybe it really is), but I'm  stuck.  I can't figure out how to tell Python to read the line  with the word, add the word to the Key of the dict, then read the next  line and add that line to the Value of the dict, then do it all again  'til the end of the file.I tried using a!
  for loop
 like thisf = open('glossary.txt','r')  gloss = {}for line in f:      gloss[line] = lineWhen I tried to print this, a huge list of key/values printed out. With  many copies of the same key/value pair.   And the key and the  value were the same. (not word followed by definition) , which  afterword made sense, because, I told it that   gloss[line] = lineI tried :for line in f:      gloss[line] = f.readline()That got me nowhere. Sorry for being so dense. I understand what needs to happen, but am having trouble implementing it. Thanks for your help and understanding.  
		Bring words and photos together (easily) with 
PhotoMail  - it's free and works with Yahoo! Mail.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-26 Thread Danny Yoo
>   I tried :
>
>   for line in f:
>   gloss[line] = f.readline()
>

This should have worked, but there's one problem.  Whenever we're doing
something like:

for line in f:
...

there can be some interference between the iteration and any readline()
in the body of the loop.  For efficiency reasons, the iterator's allowed
to march through the file ahead several lines at with an internal buffer.
This means our position in the file might be further along than we might
realize, and that means that readline() will give nonsensical results.

So we're getting caught by a low-level detail.  We should try to avoid
using both the for loop and readline() on the same file. Here's one way we
can avoid the problem:

while True:
word = f.readline()
defn = f.readline()
if not word or not defn:
   break
...

Does this make sense?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why can't I find a function that givesme the sign of an integer?

2006-01-26 Thread Rinzwind
> On 1/26/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> >> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> > Well, the cmp() function does this if you compare the number to 0:
>
> Neat trick Orri, I'd never have thought of that one :-)
>
> Alan G.

Glad I could help :=)


On 1/26/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Orri Ganel wrote:
> > Rinzwind wrote:
> >
> >> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> > Well, the cmp() function does this if you compare the number to 0:
> >
> >  >>> cmp(-34,0)
> > -1
> >  >>> cmp(0,0)
> > 0
> >  >>> cmp(23,0)
>
> One caution: this behaviour doesn't seem to be required, the docs allow
> any positive or negative integer:
> cmp(  x, y)
>  Compare the two objects x and y and return an integer according to
> the outcome. The return value is negative if x < y, zero if x == y and
> strictly positive if x > y.
>
> So this behaviour might differ between Python versions.
>
> Kent

Now you lost me.
Eh you mean to say that in next Python versions someone could decide
to change cmp(x,0) to another meaning? I bet my countryman (I'm from
Holland too ;-) ) will veto that! Or else I'll pay him a visit :D
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] designing a class

2006-01-26 Thread Runsun Pan
On 1/26/06, Christopher Spears <[EMAIL PROTECTED]> wrote:

> headlights.  Where should I begin?  How do I go about
> designing a new class?

Some starter 101:

First, recognize that a class is a compound type that is not only a type
but binds other variables and methods with it.

#--- class definition
class People(object):
 lastname = 'Spears'
 firstname = Chris

object is the parent of People from where People inherits all of its
definitions and behavior (functions). It's also called "subclassing" --
subclassing object to get People.

#--- instantiation
p = People( )

p is called "an instance of class People"

>>> p.lastname
Spears
>>> p.firstname
Chris
>>> p.firstname = 'runsun'
>>> p.firstname
runsun


~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
Runsun Pan, PhD
[EMAIL PROTECTED]
Nat'l Center for Macromolecular Imaging
http://ncmi.bcm.tmc.edu/ncmi/
~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] designing a class

2006-01-26 Thread Runsun Pan
# initialization of class

If you want to be able to give initial values to the class when it
is instantialized, you do it in the __init__ function that Terry
mentioned:

class People(object):
def __init__(self, firstname='Chris', lastname='Spears'):
 self.firstname = firstname
 self.lastname = lastname

That is, instead of putting

lastname = 'Spears'
firstname = Chris

right under "class People(object)", you put them inside the __init__.

This will allow some user values be entered during the instantiation:

p = People( firstname = 'Christopher')



On 1/27/06, Runsun Pan <[EMAIL PROTECTED]> wrote:
> On 1/26/06, Christopher Spears <[EMAIL PROTECTED]> wrote:
>
> > headlights.  Where should I begin?  How do I go about
> > designing a new class?
>
> Some starter 101:
>
> First, recognize that a class is a compound type that is not only a type
> but binds other variables and methods with it.
>
> #--- class definition
> class People(object):
> lastname = 'Spears'
> firstname = Chris
>
> object is the parent of People from where People inherits all of its
> definitions and behavior (functions). It's also called "subclassing" --
> subclassing object to get People.
>
> #--- instantiation
> p = People( )
>
> p is called "an instance of class People"
>
> >>> p.lastname
> Spears
> >>> p.firstname
> Chris
> >>> p.firstname = 'runsun'
> >>> p.firstname
> runsun
>
>
> ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
> Runsun Pan, PhD
> [EMAIL PROTECTED]
> Nat'l Center for Macromolecular Imaging
> http://ncmi.bcm.tmc.edu/ncmi/
> ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
>


--
~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
Runsun Pan, PhD
[EMAIL PROTECTED]
Nat'l Center for Macromolecular Imaging
http://ncmi.bcm.tmc.edu/ncmi/
~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor