From cheshire_cat_sf@yahoo.com  Mon Apr  1 00:46:44 2002
From: cheshire_cat_sf@yahoo.com (Britt Green)
Date: Sun, 31 Mar 2002 16:46:44 -0800 (PST)
Subject: [Tutor] Instantiating classes
In-Reply-To: <E16rocG-0005KD-00@mail.python.org>
Message-ID: <20020401004644.31899.qmail@web14102.mail.yahoo.com>

Suppose I have a simple class called BankAccount that contains three
variables: a name, an account number and a balance. When I run my
program, it asks the bank teller if a new account would like to be
created. Should the teller say yes, the program would create a new
instance to the BankAccount class.

My question is this: what's the easiest way to create this new instance
to the BankAccount class in Python? Obviously the teller can't go into
the sourcecode everytime she needs to create a new account, but that's
the only way that I've done it so far.

Many thanks,

Britt

=====
"The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman."

__________________________________________________
Do You Yahoo!?
Yahoo! Greetings - send holiday greetings for Easter, Passover
http://greetings.yahoo.com/



From urnerk@qwest.net  Mon Apr  1 02:05:23 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 31 Mar 2002 18:05:23 -0800
Subject: [Tutor] Instantiating classes
In-Reply-To: <20020401004644.31899.qmail@web14102.mail.yahoo.com>
References: <E16rocG-0005KD-00@mail.python.org>
Message-ID: <4.2.0.58.20020331175158.00d29650@pop3.norton.antivirus>

Hi Britt --

This is similar to the Stock class example we were doing
just a few posts ago.  There's also the question of how
to have persistence in your bank accounts between program
sessions, i.e. if you don't output something to a file,
everything goes away.

The shelve module has an interface similar to a dictionary,
meaning you can store objects with names.  You might use
the account number as the dictionary key and shelve your
BankAccount instances by account number when exiting the
program.  Upon starting a new session, these saved
BankAccount instances would be retrievable by the same
key -- convenient for tellers.

However, this is not a super realistic example as in a
real bank you'd want multiple tellers all pulling up and
saving info at the same time, and shelve does not support
concurrent access by multiple users.  So the example here
is more for learning purposes than for actually running
a bank.  A real bank would more likely use a big iron
relational database like Oracle -- so a next step towards
realism in a sandbox would be to use MySQL or something
similar (Python quite capable of serving as a front end).

Anyway, if your teller says 'yes' to add a new account,
you can have something like:

  def addaccount()
       """
       Function for adding new account, called
       from mainmenu()
       """
       accountno   = raw_input("Enter new account number: ")
       accountname = raw_input("Name of account holder  : ")
       balance     = raw_input("Opening balance         : ")

       allaccounts[accountno] = \
          BankAccount(accountno,accountname,balance)

For more details, see (a thread):
http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1093972

And:
http://www.inetarena.com/~pdx4d/ocn/python/stocks.py


Kirby

At 04:46 PM 3/31/2002 -0800, Britt Green wrote:
>Suppose I have a simple class called BankAccount that contains three
>variables: a name, an account number and a balance. When I run my
>program, it asks the bank teller if a new account would like to be
>created. Should the teller say yes, the program would create a new
>instance to the BankAccount class.
>
>My question is this: what's the easiest way to create this new instance
>to the BankAccount class in Python? Obviously the teller can't go into
>the sourcecode everytime she needs to create a new account, but that's
>the only way that I've done it so far.
>
>Many thanks,
>
>Britt




From erikprice@mac.com  Mon Apr  1 02:25:22 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 31 Mar 2002 21:25:22 -0500
Subject: [Tutor] hacking 101
In-Reply-To: <20020331235620.A10302@pino.selwerd.nl>
Message-ID: <B80A6F79-4517-11D6-9170-00039351FE6A@mac.com>

On Sunday, March 31, 2002, at 04:56  PM, Remco Gerlich wrote:

> At every place where you get user input, *in any form*, try to think of 
> the
> weirdest form it could take, the syntax you don't expect. Question your
> assumptions - if it's user input, they're not held to your assumptions.
>
> Input length is part of the input (but not as critical in Python as it 
> often
> is in C). Input timing is part of the input. Etc.
>
> Get into the mindset of someone who sees a set of rules for a game, and
> tries to figure out how to cheat at it.
>
> Focus at user input. Everything that comes from outside is suspect. 
> Trace
> the path of this data through your code.

I haven't yet had a chance to use Python for web stuff (I'm still 
learning the basics), but Remco sums up the attitude I take when 
programming app stuff in PHP -- for security, you need to have a robust 
server like apache that is configured such that it cannot be easily 
taken advantage of -- this is really beyond the topic of programming and 
more the domain of system administration -- and for the code itself, you 
write what I call "error-checking" functions to ensure that user input 
conforms to certain criteria or that your program knows what to do if it 
doesn't.  For instance, in the content mgmt site i'm developing for my 
employer, every single user input is checked via regexes to make sure 
that it's appropriate.  The app won't accept letters or punctuation when 
it's expecting an integer.  If the user enters this, I except an error 
message and re-display the user's values.  Really, my security is 
designed to protect the user from making a mistake than from an 
intruder, but it serves the same purpose.  I check for as many 
possibilities as I can possibly think of.  And while it would be nice to 
be able to accept "two-thousand-two" OR "2002" as input, it's really 
outside the scope of the app I am making to be this flexible.  I try to 
make sure that my forms use as many non-textual inputs as possible, 
limiting the user to making choices rather than producing their own 
input.

Of course, on this last note, be very careful -- just because the form 
only displays three choices doesn't mean that those are the only choices 
that the user has!  For instance, perhaps the user isn't even using a 
web browser to communicate with the script!  Perhaps they've telnetted 
in and are submitting some POST data that I wasn't prepared for.  If 
this is the case, then I am in trouble if I expected that the user would 
enter nothing but 1, 2, or 3 for instance.  Remember that all HTTP data 
is plaintext unless you've encrypted it, so even a password form is 
pretty much wide open to the internet if you're not using SSL.  Make 
sure that once your data has successfully and safely made the trip from 
the client to the server that the data is still secure -- FreeBSD seems 
like a reasonably secure box but still needs to be maintained -- shut 
down unnecessary services, make sure you have a firewall, don't give any 
access to any parts of the box that aren't needed, if your database is 
shared then use md5() to encrypt passwords etc etc etc.

There's quite a bit to learn in this topic, and I'm sorry I don't have 
any python-specific advice.  But I'm sure there are python equivalents 
to anything that can be done in PHP, like session management and the 
htmlentities() function (translates all user data into entity form so 
that they can't 'escape' the input with quotes or &gt; etc).  Really, 
I've never seen a hard-and-fast list of what to watch for.  Just get 
into web development and learn as you go.  Everyone makes mistakes with 
this, and I'm no exception.


Erik




From erikprice@mac.com  Mon Apr  1 02:26:56 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 31 Mar 2002 21:26:56 -0500
Subject: [Tutor] simple problem
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4CD@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <F0239420-4517-11D6-9170-00039351FE6A@mac.com>

On Sunday, March 31, 2002, at 05:08  PM, alan.gauld@bt.com wrote:

>> for on mac os 10, and i am using it through terminal
>
> MacOS X is catching on...

I see Python mentioned on the Fink mailing list at least every other 
day -- lots of people are picking up Python via their Mac OS X boxes.


Erik




From erikprice@mac.com  Mon Apr  1 02:38:30 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 31 Mar 2002 21:38:30 -0500
Subject: [Tutor] Instantiating classes
In-Reply-To: <4.2.0.58.20020331175158.00d29650@pop3.norton.antivirus>
Message-ID: <8D412732-4519-11D6-9170-00039351FE6A@mac.com>

On Sunday, March 31, 2002, at 09:05  PM, Kirby Urner wrote:

> so a next step towards
> realism in a sandbox would be to use MySQL or something
> similar (Python quite capable of serving as a front end)

Two things:

(1) Use PostgreSQL instead of MySQL if you're working with financial 
data, since it contains support for transactions and I think triggers -- 
stuff I haven't experience with  yet

(2) I use and love MySQL (perfect for just about anything else, and I 
think transaction support is coming soon) -- what's the Python module 
that will provide me with functions to access it?

Thanks

Erik




From erikprice@mac.com  Mon Apr  1 02:42:03 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 31 Mar 2002 21:42:03 -0500
Subject: [Tutor] command line
In-Reply-To: <20020331214509.GA30387@dman.ddts.net>
Message-ID: <0C4A626C-451A-11D6-9170-00039351FE6A@mac.com>

On Sunday, March 31, 2002, at 04:45  PM, dman wrote:

> I see you're using "Apple Mail".  Are you on OSX?  If so fire up a
> shell and try
>     ldd `which python`

Hmm... no go; a search shows that 'ldd' isn't installed on my system.  
I've actually never heard of that command.

> and see if "libreadline" is mentioned anywhere in the output.  My
> guess is that it won't be.  GNU readline is a library (made by the GNU
> folks) for reading a lines of input from a terminal.  bash uses it and
> python _can_ use it if it was compiled with it.  This is what gives
> command history and line editing with emacs or vi style keybindings.
> The default for readline is 'emacs' style.

Hm... oh well, I'm positive that I didn't specify emacs as a ./configure 
parameter when I compiled Python.  I'll have to recompile.  No big deal, 
I just need some time to do it.  Thanks for the tip dman.


Erik




From dyoo@hkn.eecs.berkeley.edu  Mon Apr  1 03:56:43 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 31 Mar 2002 19:56:43 -0800 (PST)
Subject: [Tutor] Instantiating classes
In-Reply-To: <8D412732-4519-11D6-9170-00039351FE6A@mac.com>
Message-ID: <Pine.LNX.4.44.0203311947240.26978-100000@hkn.eecs.berkeley.edu>

> On Sunday, March 31, 2002, at 09:05  PM, Kirby Urner wrote:
>
> > so a next step towards
> > realism in a sandbox would be to use MySQL or something
> > similar (Python quite capable of serving as a front end)
>
> Two things:
>
> (1) Use PostgreSQL instead of MySQL if you're working with financial
> data, since it contains support for transactions and I think triggers --
> stuff I haven't experience with  yet

I'm learning how to use PostgreSQL right now, so perhaps we can share our
experiences with it sometime.  *grin*



> (2) I use and love MySQL (perfect for just about anything else, and I
> think transaction support is coming soon)

Transactions have been in MySQL for a while now via the 'InnoDB' table
type.  See:

http://mysql.com/documentation/mysql/bychapter/manual_Table_types.html#InnoDB

for more details on transaction support in MySQL.



> what's the Python module that will provide me with functions to access
> it?

The 'MySQLdb' module is pretty good, and also supports transactions:

    http://sourceforge.net/projects/mysql-python



(Now if only adustman would respond to my bug fix...

http://sourceforge.net/tracker/index.php?func=detail&aid=536624&group_id=22307&atid=374932

*grin*)


Talk to you later!




From vcardon@siue.edu  Mon Apr  1 06:19:24 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Mon, 1 Apr 2002 00:19:24 -0600
Subject: [Tutor] Getting exit code in Windows
Message-ID: <20020401001924.A25655@client156-52.ll.siue.edu>

--pf9I7BMVVzbSWLtt
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Hi everyone,

I am writing a simple shell in python as a small demonstration project.
I have figured out how to get the exit code for a process on UNIX using
the waitpid function in the os module. Unfortunately, this function does
not seem to exist on Windows. Is there a portable way of getting that
kind of information? I know I could use the win32all extensions, but I
wanted to make sure there was not a better way.

Thanks,
Victor
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--pf9I7BMVVzbSWLtt
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8p/vsZU/bSegbOhwRAu/XAJ94Y3FDvZWnFouCp3BV34XY5wiIFACfSaXu
lwFO6u9eN5g3UdGCwratskg=
=FfO6
-----END PGP SIGNATURE-----

--pf9I7BMVVzbSWLtt--



From sheila@thinkspot.net  Mon Apr  1 05:24:31 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sun, 31 Mar 2002 21:24:31 -0800
Subject: [Tutor] Getting exit code in Windows
In-Reply-To: <20020401001924.A25655@client156-52.ll.siue.edu>
Message-ID: <3747D445D0F@kserver.org>

On Mon, 1 Apr 2002 00:19:24 -0600, Victor R. Cardona wrote:
> Hi everyone,
>
> I am writing a simple shell in python as a small demonstration
> project.
> I have figured out how to get the exit code for a process on UNIX
> using the waitpid function in the os module. Unfortunately, this
> function does not seem to exist on Windows. Is there a portable way
> of getting that kind of information? I know I could use the
> win32all extensions, but I wanted to make sure there was not a
> better way.
>
>
> Thanks, Victor

I've written portable scripts that I run on both Unix and Windows, 
that return the exit code with the following command:

sys.exit(int)

You must import the sys module and pass an integer as the parameter.


-- 
Sheila King
http://www.thinkspot.net/sheila/






From sheila@thinkspot.net  Mon Apr  1 05:34:03 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sun, 31 Mar 2002 21:34:03 -0800
Subject: [Tutor] Getting exit code in Windows
In-Reply-To: <3747D445D0F@kserver.org>
Message-ID: <37D3A9910D1@kserver.org>

On Sun, 31 Mar 2002 21:24:31 -0800, Sheila King wrote:
> On Mon, 1 Apr 2002 00:19:24 -0600, Victor R. Cardona wrote:
> > Hi everyone,
> >
> > I am writing a simple shell in python as a small demonstration
> > project.
> > I have figured out how to get the exit code for a process on UNIX
> > using the waitpid function in the os module. Unfortunately, this
> > function does not seem to exist on Windows. Is there a portable
> > way of getting that kind of information? I know I could use the
> > win32all extensions, but I wanted to make sure there was not a
> > better way.

>
> I've written portable scripts that I run on both Unix and Windows,
> that return the exit code with the following command:
>
> sys.exit(int)
>
>
> You must import the sys module and pass an integer as the
> parameter.

After reading your post again, I must apologize. I have not addressed 
your question at all. I told how to set an exit code, which is 
apparently not what you want to do. You want to retrieve the exit 
code of a different process.

Sorry for the confusion.


-- 
Sheila King
http://www.thinkspot.net/sheila/





From tutor@python.org  Mon Apr  1 06:19:47 2002
From: tutor@python.org (Tim Peters)
Date: Mon, 01 Apr 2002 01:19:47 -0500
Subject: [Tutor] Getting exit code in Windows
In-Reply-To: <20020401001924.A25655@client156-52.ll.siue.edu>
Message-ID: <LNBBLJKPBEHFEDALKOLCKEIPOJAA.tim.one@comcast.net>

[Victor R. Cardona]
> I am writing a simple shell in python as a small demonstration project.
> I have figured out how to get the exit code for a process on UNIX using
> the waitpid function in the os module. Unfortunately, this function does
> not seem to exist on Windows.

os.waitpid() works under Windows in Python 2.3, but we're a long way from
releasing that.

> Is there a portable way of getting that kind of information? I know I
> could use the win32all extensions, but I wanted to make sure there was
> not a better way.

I'm afraid there really isn't.  os.system('command string') runs a shell
command and returns its exit code, so you'd *think* that would be portable
(at least among systems that *have* "a shell"; for example, Mac Classic does
not).  But it turns out that the way Microsoft implemented the Win9x shell
(command.com), os.system() *always* returns 0 on Win9x.  command.com doesn't
pass along the exit code of the command it ran, it unaccountably and
uselessly returns its own "hey, I ran a command!  that's a success!" 0 exit
code.

So you're stuck.

computers-are-great-ly y'rs  - tim




From dman@dman.ddts.net  Mon Apr  1 06:49:04 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 1 Apr 2002 00:49:04 -0600
Subject: [Tutor] command line
In-Reply-To: <4.2.0.58.20020331151629.019d2860@pop3.norton.antivirus>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D2@mbtlipnt02.btlabs.bt.co.uk> <4.2.0.58.20020331151629.019d2860@pop3.norton.antivirus>
Message-ID: <20020401064904.GD32641@dman.ddts.net>

All of this is FYI (with a question at the end).

On Sun, Mar 31, 2002 at 03:44:39PM -0800, Kirby Urner wrote:
| At 11:46 PM 3/31/2002 +0100, alan.gauld@bt.com wrote:
| 
| >> | In my experience, pro programmers appreciate time-saving
| >> | and productivity-enhancing features,
| >
| >Not in my experience, most long term pros stick by the tools
| >they know really well, editor and debugger mainly and just
| >carve out the code. They know the language etc so well they
| >hardly ever use the "toys". There's nothing so productive
| >as just typing the code in and it works first time! Many
| >experienced pros reach that level of quality after 10 years
| >or so...
| 
| Depends what you include in the "toy" category.
| 
| I like project management utilities that keep classes,
| forms, reports, data tables in order, and compile only
| changes (ala make).  Templates and dialog box driven
| builders of various types also save time.

Personally I hate "wizards".

| Helpful and useful:  a visual class browser,

yes

| code rollups,

This is called "folding" in vim (version >=6).

| and, of course, a way to develop GUI forms by simply
| dragging and dropping widgets from a palette ala VB
| (an IDE I've never used).  WYSIWYG interface design saves
| hours, can't be sidelined as "just a Windows thing".

Use glade for the gui part, and then the 'libglade' library in your
code.  Once again it's not an all-in-one solution.  Use the right tool
for each job :-).

| I appreciate that the high-powered *nix editors (emacs
| and vi/vim) are so code-aware that a lot of the IDE perks
| we're talking about are simply folded into the program
| editor (color coding, auto-completion, call tips).  Vim
| not only knows about HTML, but DTML (Zope) and just about
| every other language under the sun.

Have you found a way to mix dtml and sql?  I prefer using vim and cvs
rather than the web-based Z Management interface.  I'd like my Z SQL
Method objects to have both highlightings, but my attempt at a syntax
file has failed.

-D

-- 

If your company is not involved in something called "ISO 9000" you
probably have no idea what it is.  If your company _is_ involved in ISO
9000 then you definitely have no idea what it is.
                                (Scott Adams - The Dilbert principle)




From vcardon@siue.edu  Mon Apr  1 08:26:51 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Mon, 1 Apr 2002 02:26:51 -0600
Subject: [Tutor] Getting exit code in Windows
In-Reply-To: <LNBBLJKPBEHFEDALKOLCKEIPOJAA.tim.one@comcast.net>; from tim.one@comcast.net on Mon, Apr 01, 2002 at 01:19:47AM -0500
References: <20020401001924.A25655@client156-52.ll.siue.edu> <LNBBLJKPBEHFEDALKOLCKEIPOJAA.tim.one@comcast.net>
Message-ID: <20020401022651.A26442@client156-52.ll.siue.edu>

--PEIAKu/WMn1b1Hv9
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Apr 01, 2002 at 01:19:47AM -0500, Tim Peters wrote:
> [Victor R. Cardona]
> > I am writing a simple shell in python as a small demonstration project.
> > I have figured out how to get the exit code for a process on UNIX using
> > the waitpid function in the os module. Unfortunately, this function does
> > not seem to exist on Windows.
>=20
> os.waitpid() works under Windows in Python 2.3, but we're a long way from
> releasing that.

Yeah!

> > Is there a portable way of getting that kind of information? I know I
> > could use the win32all extensions, but I wanted to make sure there was
> > not a better way.
>=20
> I'm afraid there really isn't.  os.system('command string') runs a shell
> command and returns its exit code, so you'd *think* that would be portable
> (at least among systems that *have* "a shell"; for example, Mac Classic d=
oes
> not).  But it turns out that the way Microsoft implemented the Win9x shell
> (command.com), os.system() *always* returns 0 on Win9x.  command.com does=
n't
> pass along the exit code of the command it ran, it unaccountably and
> uselessly returns its own "hey, I ran a command!  that's a success!" 0 ex=
it
> code.

Oh my...

> So you're stuck.

Thanks. I was afraid of that.

-v
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--PEIAKu/WMn1b1Hv9
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8qBnLZU/bSegbOhwRAoelAJ4ngeI24ZanjIVI0PR6meOc1wRE6wCePiKK
oTkgL/U99vG8BRtP6AfpkgM=
=0Beu
-----END PGP SIGNATURE-----

--PEIAKu/WMn1b1Hv9--



From dyoo@hkn.eecs.berkeley.edu  Mon Apr  1 07:26:50 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 31 Mar 2002 23:26:50 -0800 (PST)
Subject: [Tutor] Any interest in a tutorial for writing a Python C extension?
Message-ID: <Pine.LNX.4.44.0203312305430.30142-100000@hkn.eecs.berkeley.edu>

[Note: skip this message if you haven't fiddled around with C extensions
yet.]


Hi everyone,

Out of curiosity, is anyone interested in helping to edit a tutorial for
writing a Python extension?


I'm thinking of writing one for a module I'm starting to write called
"FileString"; it tries to make a file-like object look almost like a
string.  The book "Object Oriented Perl", by Damian Conway, has an example
of a module called "Genome::Array" that caught my eye.  Such a module
might be useful for people dealing with huge sequences, and I think it
might be nice to have an equivalent class in Python.


Also, there was discussion a while back about why re.search() would give
an odd message about a "read-only string or buffer".  What distinction
does the term "buffer"  mean, if the only object that implements it is the
string type?  *grin* So I'm hoping I can have FileString implement the
"buffer" interface so that it becomes fairly easy to do regular
expressions on very large files.


My plan is to write an introductory tutorial for people who are reading
the "Extending and Embedding" document on python.org:

    http://python.org/doc/current/ext/ext.html

as an extended case study.  But to tell the truth, I haven't really
written a serious C extension before, so that's why I'll like some
collaborators to share the blame.  *grin*


If anyone's interested, please feel free to email me.  Talk to you later!




From vcardon@siue.edu  Mon Apr  1 08:30:03 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Mon, 1 Apr 2002 02:30:03 -0600
Subject: [Tutor] Determining the OS a program runs on
Message-ID: <20020401023003.B26442@client156-52.ll.siue.edu>

--FkmkrVfFsRoUs1wW
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

How should I detrmine what operating system a program is running on?
Should I use sys.platform or os.name?

Thanks,
-v
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--FkmkrVfFsRoUs1wW
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8qBqKZU/bSegbOhwRAtWgAKCW5hUdANFsxp/2RmvSOb+ml/FAlwCgmkZi
RznjRPsyieoB8ESBqacfPl4=
=WVh/
-----END PGP SIGNATURE-----

--FkmkrVfFsRoUs1wW--



From seedseven@home.nl  Mon Apr  1 08:48:18 2002
From: seedseven@home.nl (ingo)
Date: Mon, 01 Apr 2002 10:48:18 +0200
Subject: [Tutor] regular expression
In-Reply-To: <001101c1d8ef$ad11e8e0$ec61accf@othello>
References: <200203311740240328.01E5AFD0@mail>
 <001101c1d8ef$ad11e8e0$ec61accf@othello>
Message-ID: <200204011048180390.0066C4A7@mail>

On 2002/03/31 at 15:07 Raymond Hettinger wrote:

>>>> re.sub( r'(<[^>]+)( class[^>]+)(>)' , r'\1\3', t
>'<table><tr><td> class="Three" </td>'
>
>The strategy is find three consequetive groups and keep on the first
and
>third.

Thanks, exactly what I was looking for. Now I also understand what is
going on in the documentation of re.sub

>Grasshopper:  'I have a problem I want to solve with regular
expressions'
>Master: 'Now you have two problems'

Grasshopper:  'Master, I am puzzled.'
Master: 'That is the beginning of wisdom.'

Ingo




From yduppen@xs4all.nl  Mon Apr  1 09:48:58 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Mon, 1 Apr 2002 11:48:58 +0200
Subject: [Tutor] hacking 101
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D3@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D3@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <200204010948.g319mwCc052193@smtpzilla1.xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> There are some sites around covering secure code techniques
> but many are biased to C/C++ in my experience. Things like
> buffer overruns etc are not such an issue in Python because
> we can't read a string into a fixed length byte array etc.

Well, the Perl documentation has some good information on this in the section 
about 'tainted variables'; while the code examples are typically Perl (i.e. 
unreadable), the basics are pretty much the same -- both python & perl are 
interpreted languages with much automatic boundary checking. 

If you happen to have perl (w. documentation) installed on your system, 
'perldoc perlsec' will give you this page; It's also online at 
http://www.perldoc.com/perl5.6.1/pod/perlsec.html

YDD

(what have i done? my first post at Tutor is about perl. aaarghl.)
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8qC0KLsKMuCf5EdwRAhF1AJ9bLc6HcU00hdjZs0ZSHqMzZaeFewCfZESF
2ARMMhFvgKbmqkJCdXld8ZI=
=TIKc
-----END PGP SIGNATURE-----



From erikprice@mac.com  Mon Apr  1 11:57:12 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 1 Apr 2002 06:57:12 -0500
Subject: [Tutor] Instantiating classes
In-Reply-To: <Pine.LNX.4.44.0203311947240.26978-100000@hkn.eecs.berkeley.edu>
Message-ID: <99FA61D2-4567-11D6-A9FE-00039351FE6A@mac.com>

On Sunday, March 31, 2002, at 10:56  PM, Danny Yoo wrote:

> I'm learning how to use PostgreSQL right now, so perhaps we can share 
> our
> experiences with it sometime.  *grin*

'mos def.  I haven't started playing with it yet (I use MySQL with 
MyISAM table type at work) but when I finally get my home server set up, 
I was thinking of using PostgreSQL so that I could learn some of the 
more advanced features, like transactions...

>> (2) I use and love MySQL (perfect for just about anything else, and I
>> think transaction support is coming soon)
>
> Transactions have been in MySQL for a while now via the 'InnoDB' table
> type.

...which I must have misunderstood, since I thought that InnoDB, while a 
feature of MySQL, was a completely different technology from the 
standard MySQL.

>> what's the Python module that will provide me with functions to access
>> it?
>
> The 'MySQLdb' module is pretty good, and also supports transactions:
>
>     http://sourceforge.net/projects/mysql-python

I see, so modules can be open source projects too (separate from the 
main Python distribution) -- this is an instance of a "library" that I 
asked about a week or two ago?   I honestly had no idea that SF projects 
were so varied, I thought that they were for the most part self-standing 
applications and programs.

> (Now if only adustman would respond to my bug fix...
>
> http://sourceforge.net/tracker/index.php?func=detail&aid=536624&group_id=
> 22307&atid=374932

No offense, but the way SF renders your example code, it looks like 
perl.  :P  (:))


Erik




From pythontutor@venix.com  Mon Apr  1 12:59:03 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 01 Apr 2002 07:59:03 -0500
Subject: [Tutor] Instantiating classes
References: <99FA61D2-4567-11D6-A9FE-00039351FE6A@mac.com>
Message-ID: <3CA85997.80706@venix.com>

 >> http://sourceforge.net/tracker/index.php?func=detail&aid=536624&group_id=22307&atid=374932
 >
 >
 > No offense, but the way SF renders your example code, it looks like
 > perl.  :P  (:))

Actually it is C.  MySQLdb must be a Python module implemented in C.
(I assume Danny is sleeping now...)

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From marsha_sheridan@agilent.com  Mon Apr  1 13:54:24 2002
From: marsha_sheridan@agilent.com (marsha_sheridan@agilent.com)
Date: Mon, 1 Apr 2002 06:54:24 -0700
Subject: [Tutor] RE: Tutor digest, Vol 1 #1532 - 13 msgs
Message-ID: <E3CC9150F0CAD4118E160090278CA71C04E2328F@axcs17.cos.agilent.com>

Teach Yourself Python in 24 Hours Website

To access the downloadable examples for each chapter you need to go to the
following site:
 http://www.pauahtun.org/TYPython/

The files are under Chapter Links.



-----Original Message-----
From: tutor-request@python.org [mailto:tutor-request@python.org]
Sent: Sunday, March 31, 2002 4:20 PM
To: tutor@python.org
Subject: Tutor digest, Vol 1 #1532 - 13 msgs


Send Tutor mailing list submissions to
	tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
	http://mail.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. Teach Yourself Python in 24 Hours Website (Brian W. Carver)
   2. RE: simple problem (alan.gauld@bt.com)
   3. RE: importing a subprocess in dos (alan.gauld@bt.com)
   4. Re: hacking 101 (Paul Sidorsky)
   5. Re: Teach Yourself Python in 24 Hours Website (Brian W. Carver)
   6. RE: command line (alan.gauld@bt.com)
   7. RE: command line (alan.gauld@bt.com)
   8. RE: command line (alan.gauld@bt.com)
   9. Re: hacking 101 (Blake Winton)
  10. Re: command line (Blake Winton)
  11. RE: command line (alan.gauld@bt.com)
  12. RE: hacking 101 (alan.gauld@bt.com)
  13. RE: idle - namespaces (was idle) (alan.gauld@bt.com)

--__--__--

Message: 1
Date: Sun, 31 Mar 2002 14:05:19 -0800
From: "Brian W. Carver" <bwcarver@earthlink.net>
To: tutor@python.org
Subject: [Tutor] Teach Yourself Python in 24 Hours Website

Hi,

I recently bought Ivan Van Laningham's book: Teach Yourself Python in 24
Hours.
Throughout the book he makes reference to a website for the book that
includes
files to download.  When I go to the website indicated (
http://www.pauahtun.org
) I find his personal pages but nothing related to the book, and very little
related to Python.  Anyone else used this book, had this problem, and
eventually
found the files?  If so, can you point me in the right direction?  I've sent
a
similar e-mail to what appears to be the author's address, but didn't know
whether I'd get a response.  Thanks for any help.

Brian W. Carver




--__--__--

Message: 2
From: alan.gauld@bt.com
To: hysterix240@yahoo.com, tutor@python.org
Subject: RE: [Tutor] simple problem
Date: Sun, 31 Mar 2002 23:08:06 +0100

> for on mac os 10, and i am using it through terminal

MacOS X is catching on...

> i try to put a line of code and and then try to put
> another underneath it, i have to hit return, and
> python runs through the code, so what happens if i
> want to put more than 1 line of code 

You can put your code in a file. Use textedit to create 
a file with a .py extension(by convention). Then in terminal type:

$ python foo.py

where $ is the unix prompt
python is the interpreter
foo.py is the file you created.

Yu can also use vi or emacs within terminal which is how real 
unix heads do it, but textedit will suffice - just make 
sure you save as plain text.

> python GUI, or the IDLE, 

I'm sure someone will have pointed you to Danny's IDLE tutor 
by now. Just remember you need to run an Xserver like XonX 
to use IDLE on MacOS X.

Alan g



--__--__--

Message: 3
From: alan.gauld@bt.com
To: bwgolling@attbi.com, tutor@python.org
Subject: RE: [Tutor] importing a subprocess in dos
Date: Sun, 31 Mar 2002 23:12:04 +0100

> do I run a process in dos (btw my os is win98) and import the 
> result to my python interpreter?

Use popen() or one of its variants - look min os module.

BUT it used to be on DOS that you had to use the one 
from the winall package(or ActiveState's python).
Does anyone know if this is still true in V2.xx?

Alan G



--__--__--

Message: 4
Date: Sun, 31 Mar 2002 15:14:03 -0700
From: Paul Sidorsky <paulsid@shaw.ca>
Subject: Re: [Tutor] hacking 101
To: tutor <tutor@python.org>

Remco Gerlich wrote:

> At every place where you get user input, *in any form*, try to think of
the
> weirdest form it could take, the syntax you don't expect. Question your
> assumptions - if it's user input, they're not held to your assumptions.

Better yet, have somebody else do the questioning.  I never had the
cracker mentality but I knew a guy who did and the holes he found in my
software were rather remarkable to me.  I just never would have thought
to do the things he did.  Most of the time they weren't even
unconscionable or devious things, they were just fairly routine things
that ordinary programmers wouldn't think anybody would do.

--
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



--__--__--

Message: 5
Date: Sun, 31 Mar 2002 14:16:09 -0800
From: "Brian W. Carver" <bwcarver@earthlink.net>
To: tutor@python.org
Subject: [Tutor] Re: Teach Yourself Python in 24 Hours Website

I thought I'd answer my own question, since the author responded with
lightning
speed.

The files are at: http://www.pauahtun.org/TYPython/

Sorry for the wasted bandwidth.  Next time I write, I'll have a good Python
question for the group.

Brian W. Carver

> Hi,
>
> I recently bought Ivan Van Laningham's book: Teach Yourself Python in 24
Hours.
> Throughout the book he makes reference to a website for the book that
includes
> files to download.  When I go to the website indicated (
http://www.pauahtun.org
> ) I find his personal pages but nothing related to the book, and very
little
> related to Python.  Anyone else used this book, had this problem, and
eventually
> found the files?  If so, can you point me in the right direction?  I've
sent a
> similar e-mail to what appears to be the author's address, but didn't know
> whether I'd get a response.  Thanks for any help.
>
> Brian W. Carver
>




--__--__--

Message: 6
From: alan.gauld@bt.com
To: wolf_binary@hotmail.com, tutor@python.org
Subject: RE: [Tutor] command line
Date: Sun, 31 Mar 2002 23:21:20 +0100

------_=_NextPart_001_01C1D902.62330F80
Content-type: text/plain; charset="iso-8859-1"

 >  Why would you use the command line Python instead of the IDLE? 
 
1) It uses less machine resources
 
2) It starts faster
 
3) My text editor is better than IDLE's so edit run 
   is better than edit, switch program, run
 
 4) IDLE sets up its own environment python at 
    the command prompt python executes like the 
    production environment so less spurious errors
 
5) Tkinter does strange things in IDLE, not at the 
   python prompt.
 
Some of that relates to using the interpreter from the 
OS prompt, some to the cython interpreter prompt. 
The latter assumes as a minimum NT level editing 
functions and getline by preference.
 
Alan G

------_=_NextPart_001_01C1D902.62330F80
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.50.4807.2300" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=#ffffff>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff>&nbsp;&gt; &nbsp;</FONT></SPAN>Why would
you 
use the command line Python instead of the IDLE?<SPAN 
class=830241622-31032002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=830241622-31032002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff>1) It uses less machine 
resources</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff>2) It starts 
faster</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff></FONT></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff>3) My text editor is better than IDLE's so
edit 
run </FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff>&nbsp;&nbsp; is better than edit, switch 
program, run</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=830241622-31032002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN
class=830241622-31032002>&nbsp;<FONT 
face="Courier New" color=#0000ff>4) IDLE sets up its own environment python
at 
</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff>&nbsp;&nbsp;&nbsp; the command prompt
python 
executes like the </FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=830241622-31032002><FONT 
face="Courier New" color=#0000ff>&nbsp;&nbsp;&nbsp; production environment
so 
less spurious errors</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002>5) Tkinter does strange things in IDLE, not at the 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002>&nbsp;&nbsp; python
prompt.</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002>Some of that relates to using the interpreter from
the 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002>OS prompt, some to the cython interpreter prompt. 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002>The latter assumes as a minimum NT level editing 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002>functions and getline by 
preference.</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=830241622-31032002>Alan G</SPAN></FONT></FONT></DIV></BODY></HTML>

------_=_NextPart_001_01C1D902.62330F80--



--__--__--

Message: 7
From: alan.gauld@bt.com
To: dman@dman.ddts.net, tutor@python.org
Subject: RE: [Tutor] command line
Date: Sun, 31 Mar 2002 23:26:58 +0100

Wayyyy off topic but...

> After you install Microsoft Windows XP, you have the option to create
> user accounts.  If you create user accounts, by default, they 
> will have an account type of administrator with no password.

<RANT>
True on XP Home and a really terrible decision by MS.
Why not a single administrator and new users either 
Poweruser or restricted user? The latter is too restricted 
for most users but admin is simply insane! Bang goes much
of XPs security protection! I am seriously considering 
upgrading from Home to Pro just because of this issue.
</RANT>

Otherwise its not bad....

Alan G.



--__--__--

Message: 8
From: alan.gauld@bt.com
To: urnerk@qwest.net, dman@dman.ddts.net
Cc: tutor@python.org
Subject: RE: [Tutor] command line
Date: Sun, 31 Mar 2002 23:32:23 +0100

> environment.  Maybe it's different in Win2k, where uparrow
> history is somehow available.

Yes, you get the minimal up arrow functions in Win2000 and XP

But a better option is to install cygwin which provides 
full getline() functionality.

IDLE still has advantages and if I'm doing a big session 
I use it:

function hints as mentioned, 
color coding(!)
Save a session

But for quick tests and all Tkinter work I use the command 
line version

Alan g.



--__--__--

Message: 9
Date: Sun, 31 Mar 2002 17:29:16 -0500
From: Blake Winton <bwinton@tor.dhs.org>
To: tutor <tutor@python.org>
Subject: Re: [Tutor] hacking 101

* Remco Gerlich <scarblac@pino.selwerd.nl> [020331 16:54]:
> At every place where you get user input, *in any form*, try to think of
the
> weirdest form it could take, the syntax you don't expect. Question your
> assumptions - if it's user input, they're not held to your assumptions.
> 
> Focus at user input. Everything that comes from outside is suspect. Trace
> the path of this data through your code.

For web-based applications, change your username to "<!--" and see if
the rest of the page gets displayed correctly.  If you suspect it's
using a SQL backend, change your name to "name' OR name='aaa" and see if
that breaks anything.  On most of the projects I work on, I test for
stuff like that, and even though it's a PITA to handle it, you've got
to, cause people will mess you up (not even on purpose) if they can.
Heck, that isn't even hacking or cracking, it's just good testing.

Try subscribing to a mailing list as "foo@bar.com\nyahoo@bad.com" (even
better would be if the \n was the actual new-line character, perhaps
copied into the clipboard and pasted into the app).  Or maybe make your
name "test@bad.com;print 'This isnt good!!!'"  Stuff like that.  You
know better than the rest of us what you do with your input, so take
that knowledge, and see if you can create input that breaks your code.

(And email me a link to the code, and I'll look it over, and see what I
can come up with.  *grin*  ;)

Later,
Blake.
-- 
  5:28pm  up 18 days, 21:17,  2 users,  load average: 0.00, 0.01, 0.04



--__--__--

Message: 10
Date: Sun, 31 Mar 2002 17:34:48 -0500
From: Blake Winton <bwinton@tor.dhs.org>
To: alan.gauld@bt.com
Cc: wolf_binary@hotmail.com, tutor@python.org
Subject: Re: [Tutor] command line

* alan.gauld@bt.com <alan.gauld@bt.com> [020331 17:23]:
>  >  Why would you use the command line Python instead of the IDLE? 
> 1)
[...]  
> 5) 

6)

[~ bwinton] /opt/python/src/Tools/idle/idle.py
Traceback (most recent call last):
  File "/opt/python/src/Tools/idle/idle.py", line 4, in ?
    PyShell.main()
  File "/opt/python/src/Tools/idle/PyShell.py", line 747, in main
    root = Tk(className="Idle")
  File "/opt/python/lib/python2.2/lib-tk/Tkinter.py", line 1480, in
__init__
    self.tk = _tkinter.create(screenName, baseName, className)
TclError: no display name and no $DISPLAY environment variable


[~ bwinton] /opt/python/bin/python
Python 2.2a3 (#1, Sep 16 2001, 12:18:17)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

(I can't run idle, but the command line works just fine...
 I don't run X by default.  Just cause.)

Later,
Blake.
-- 
9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07



--__--__--

Message: 11
From: alan.gauld@bt.com
To: dman@dman.ddts.net, tutor@python.org
Subject: RE: [Tutor] command line
Date: Sun, 31 Mar 2002 23:46:00 +0100

> Do you know of any non-windows IDEs that have these features?  

Depending on the language there are lot of them in Unix 
but they tend to cost megeabucks. (HP SoftBench, 
Sun WorkBench, ObjectCenter, Sniff++ etc etc)

There are some new ones coming along for Linux etc 
too Kdevelop, Blackadder, and some others(Activestates tool?)

> New converts to *nix often ask (in deb-user at least) where the IDEs
> usual answer is "unix _is_ an IDE -- 

And that is the correct answer. Most of our windows programmers 
do their development on Unix and then move the code to Windows 
(VC++ or JBuilder) for final build & test. but the tools on 
Unix surpass any of the Windows tools commercial or otherwise.
(trace, gdb, tcov, [g]prof, ctags, xref, gplot, cflow, etc etc)

> | In my experience, pro programmers appreciate time-saving
> | and productivity-enhancing features,

Not in my experience, most long term pros stick by the tools 
they know really well, editor and debugger mainly and just 
carve out the code. They know the language etc so well they 
hardly ever use the "toys". There's nothing so productive 
as just typing the code in and it works first time! Many 
experienced pros reach that level of quality after 10 years 
or so...

> | >The important lesson to walk away with is this: if you are not
> | >using an interactive python interpreter while coding and
> | >experimenting you are missing out on one of the key benefits
> | >python offers.

This is true and is where Python development differs from 
traditional style coding.

Alan G



--__--__--

Message: 12
From: alan.gauld@bt.com
To: i812@iname.com, tutor@python.org
Subject: RE: [Tutor] hacking 101
Date: Mon, 1 Apr 2002 00:03:28 +0100 

Rob,

> On Sun, Mar 31, 2002 at 04:03:08PM -0500, kirk Bailey wrote:
> > FreeBSD
> 
> Oh, that's probably a pretty good choice. I'm sure they have 
> a security mailing list which you could join 

I think the thing Kirk is interested in is how to make the 
mailing list registration form he has written in Python 
secure, not how to make his BSD box secure. That's why he 
needs to know how crackers operate so he can guard against 
it in his code.

Kirk,

There are some sites around covering secure code techniques 
but many are biased to C/C++ in my experience. Things like 
buffer overruns etc are not such an issue in Python because 
we can't read a string into a fixed length byte array etc.

But there are plenty other things to look out for I'm sure, 
and I'd be interested if you do find a good source of info.

Alan g.



--__--__--

Message: 13
From: alan.gauld@bt.com
To: glingl@aon.at, apython101@yahoo.com, tutor@python.org
Subject: RE: [Tutor] idle - namespaces (was idle)
Date: Mon, 1 Apr 2002 00:16:39 +0100 

------_=_NextPart_001_01C1D90A.1CCDBC30
Content-type: text/plain; charset="iso-8859-1"

I may have missed the answer to this but here goes anyway...
 
>  away code. However I just noticed something, when I delete all the code  
>  to write some more throw away code the variables and I think also other  
>  things do not get deleted. How do I delete them?  
 
With great difficulty.
 
When you import names from a module they get stored 
in a dictionary. When you reload a module it simply 
adds the names - which is why reload doesn't work 
for the "from f import x" form.
 
The only reliable way to do this is to exit and restart
(Cameron another reason I use the OS command line...)
 
Of course avoiding the from f inmoprt x style helps a lot.
 

>>> dir()
['__builtins__', '__doc__', '__name__']
 

dir() returns a list but its built up from the underlying 
dictionary. deleting from the list doesn't affect the 
dictionary underneath.
 

>>> del a


This deletes the name from the underlying dictionary...

 >>> dir()
['__builtins__', '__doc__', '__name__', 'foo']

 so its gone from dir() too... 


But if you try to delete several items from a list, this doesn't work,
because of the difference between the string 'a' and the name a, I think:
 
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'foo']
>>> dir()[3:]  
['a', 'foo']
>>> for name in dir()[3:]:
     del name 
 

This deletes the string that was in the list (I think, 
I admit I'm getting more shaky here...)

>>> for name in dir()[3:]:
    del eval(name) 

This uses the string to eval which returns the alue of 
the variable named by the string - ie 3 in this case.
 
 >  So how do I get acces to the Variable a via dir() ? 
 
I don't think you can. You have to go to the Builtins 
dictionary and grub about in the innards - not recommended! 
 
Alan G.
 

------_=_NextPart_001_01C1D90A.1CCDBC30
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.50.4807.2300" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=#ffffff>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>I may have missed the answer to this but here goes 
anyway...</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002></SPAN><SPAN
class=050230623-31032002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>away code. However I just noticed something,

when I delete all the code&nbsp;<SPAN class=050230623-31032002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>to write some more throw away code the
variables 
and I think also other&nbsp;<SPAN class=050230623-31032002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>things do not get deleted. How do I delete 
them?&nbsp;<SPAN class=050230623-31032002><FONT face="Courier New"
color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002></SPAN>&nbsp;</DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>With great difficulty.</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002></SPAN>&nbsp;</DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>When you import names from a module they get stored
</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>in a dictionary. When you reload a module it simply
</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>adds the names - which is why reload doesn't work
</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>for the "from f import x" form.</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>The only reliable way to do this is to exit and 
restart</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>(Cameron another reason I use the OS command
line...)</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2>Of course avoiding the from f inmoprt x style helps a 
lot.</FONT></SPAN></DIV>
<DIV><SPAN class=050230623-31032002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<BLOCKQUOTE dir=ltr 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid;
MARGIN-RIGHT: 0px">
  <DIV><FONT face="Courier New" size=2>&gt;&gt;&gt;
dir()<BR>['__builtins__', 
  '__doc__', '__name__']<BR><SPAN class=050230623-31032002><FONT 
  color=#0000ff>&nbsp;</FONT></SPAN></FONT></DIV></BLOCKQUOTE>
<DIV dir=ltr><FONT face="Courier New" size=2><SPAN 
class=050230623-31032002>dir() returns a list but its built up from the 
underlying </SPAN></FONT></DIV>
<DIV dir=ltr><FONT face="Courier New" size=2><SPAN 
class=050230623-31032002>dictionary. deleting from the list doesn't affect
the 
</SPAN></FONT></DIV>
<DIV dir=ltr><FONT face="Courier New" size=2><SPAN 
class=050230623-31032002>dictionary underneath.</SPAN></FONT></DIV>
<DIV dir=ltr><FONT face="Courier New" size=2><SPAN 
class=050230623-31032002></SPAN></FONT>&nbsp;</DIV>
<BLOCKQUOTE dir=ltr 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid;
MARGIN-RIGHT: 0px">
  <DIV><FONT face=Arial><FONT face="Courier New" size=2>&gt;&gt;&gt; del 
  a<BR><SPAN class=050230623-31032002><FONT 
  color=#0000ff></FONT></SPAN></FONT></FONT></DIV></BLOCKQUOTE>
<DIV dir=ltr><FONT face=Arial><FONT face="Courier New" size=2><SPAN 
class=050230623-31032002><FONT color=#0000ff>This deletes the name from the 
underlying dictionary...</FONT></SPAN></FONT></FONT></DIV>
<BLOCKQUOTE dir=ltr 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid;
MARGIN-RIGHT: 0px">
  <DIV><FONT face=Arial><FONT face="Courier New"><FONT size=2><SPAN 
  class=050230623-31032002>&nbsp;</SPAN>&gt;&gt;&gt;
dir()<BR>['__builtins__', 
  '__doc__', '__name__', 'foo']</FONT></FONT></FONT></DIV></BLOCKQUOTE>
<DIV dir=ltr><FONT face=Arial><FONT face="Courier New"><FONT size=2><SPAN 
class=050230623-31032002>&nbsp;</SPAN><SPAN class=050230623-31032002><FONT 
color=#0000ff>so its&nbsp;gone from dir() 
too...&nbsp;</FONT></SPAN></FONT><BR></DIV><FONT size=2></FONT></FONT>
<BLOCKQUOTE dir=ltr 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid;
MARGIN-RIGHT: 0px"></FONT>
  <DIV><FONT size=2>But if you try to delete several items from a list, this

  doesn't work,</FONT></DIV>
  <DIV><FONT size=2>because of the difference between the&nbsp;string 'a'
and 
  the name a, I think:</FONT></DIV>
  <DIV><FONT size=2></FONT>&nbsp;</DIV>
  <DIV><FONT size=2>&gt;&gt;&gt; dir()<BR>['__builtins__', '__doc__', 
  '__name__', 'a', 'foo']<BR>&gt;&gt;&gt; dir()[3:]<SPAN 
  class=050230623-31032002><FONT face="Courier New" 
  color=#0000ff>&nbsp;</FONT></SPAN><SPAN 
  class=050230623-31032002>&nbsp;</SPAN><BR>['a', 'foo']<BR>&gt;&gt;&gt; for

  name in dir()[3:]:<BR>&nbsp;&nbsp;&nbsp;&nbsp; del name<SPAN 
  class=050230623-31032002><FONT face="Courier New" 
  color=#0000ff>&nbsp;</FONT></SPAN></FONT></DIV>
  <DIV><FONT size=2><SPAN 
class=050230623-31032002>&nbsp;</SPAN></FONT></DIV></BLOCKQUOTE>
<DIV dir=ltr><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=050230623-31032002>This deletes the string that was in the list (I
think, 
</SPAN></FONT></DIV>
<DIV dir=ltr><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=050230623-31032002>I admit I'm getting more shaky 
here...)</SPAN></FONT></DIV>
<BLOCKQUOTE dir=ltr 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid;
MARGIN-RIGHT: 0px">
  <DIV><FONT size=2>&gt;&gt;&gt; for name in
dir()[3:]:<BR>&nbsp;&nbsp;&nbsp; 
  del eval(name)<SPAN class=050230623-31032002><FONT face="Courier New" 
  color=#0000ff>&nbsp;</FONT></SPAN></FONT></DIV></BLOCKQUOTE>
<DIV dir=ltr><FONT size=2><SPAN class=050230623-31032002><FONT 
face="Courier New" color=#0000ff>This uses the string to eval which returns
the 
alue of </FONT></SPAN></FONT></DIV>
<DIV dir=ltr><FONT size=2><SPAN class=050230623-31032002><FONT 
face="Courier New" color=#0000ff>the variable named by the string - ie 3 in
this 
case.</FONT></SPAN></FONT></DIV>
<DIV dir=ltr><FONT size=2><SPAN
class=050230623-31032002>&nbsp;</SPAN><BR><SPAN 
class=050230623-31032002><FONT face="Courier New" color=#0000ff>&nbsp;<FONT 
face="Times New Roman" color=#000000>&gt; </FONT>&nbsp;</FONT></SPAN>So how
do I 
get acces to the Variable a via dir() ?<SPAN class=050230623-31032002><FONT 
face="Courier New" color=#0000ff>&nbsp;</FONT></SPAN></FONT></DIV>
<DIV dir=ltr><FONT size=2><SPAN 
class=050230623-31032002></SPAN></FONT>&nbsp;</DIV>
<DIV dir=ltr><FONT size=2><SPAN class=050230623-31032002><FONT 
face="Courier New" color=#0000ff>I don't think you can. You have to go to
the 
Builtins </FONT></SPAN></FONT></DIV>
<DIV dir=ltr><FONT size=2><SPAN class=050230623-31032002><FONT 
face="Courier New" color=#0000ff>dictionary and grub about in the innards -
not 
recommended!</FONT>&nbsp;</SPAN></FONT></DIV>
<DIV dir=ltr><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=050230623-31032002></SPAN></FONT>&nbsp;</DIV>
<DIV dir=ltr><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=050230623-31032002>Alan G.</SPAN></FONT></DIV>
<DIV dir=ltr><FONT size=2><SPAN 
class=050230623-31032002></SPAN></FONT>&nbsp;</DIV></BODY></HTML>

------_=_NextPart_001_01C1D90A.1CCDBC30--




--__--__--

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


End of Tutor Digest



From ak@silmarill.org  Mon Apr  1 14:38:18 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Mon, 1 Apr 2002 09:38:18 -0500
Subject: [Tutor] hacking 101
In-Reply-To: <3CA663F7.9D143E1B@netzero.net>
References: <3CA663F7.9D143E1B@netzero.net>
Message-ID: <20020401143818.GA20420@ak.silmarill.org>

On Sat, Mar 30, 2002 at 08:18:47PM -0500, kirk Bailey wrote:
> OK, comes now before you an unuual question.
> 
> I want to learn about hacking a computer.
> 
> See, I Want to complete the program for creating a list using a web
> form. BUT I kow that it is possible to insert escape codes and such to
> take over control and do unintended things, but I know nothing of how
> this is done. I WANT TO UNDERSTAND IT SO I CAN WATCH FOR SUCH ATTEMPTS
> AND ABORT THE PROCESS if they are detected. To PREVENT hcking, one
> must UNDERSTAND hacking. Any takers? Feel free to reply to me off list
> if you preferr.
> 
> 
> -- 
>  
> end
> 	    Respectfully,
> 			 Kirk D Bailey
>
Well, when I made an irc bot (that prints output of "fortune" command
and that sort of thing), I ran into a few exploits.. well actually kind
people of #python ran into a few exploits, but more to the point: I was
parsing variables and passing them to os.system() call and the problem
was that I only checked for ';' character there, thinking that the only
thing they could abuse was command of form fortune pattern; rm -rf /.
Evidently there's also stuff like $(rm -rf /.), and others I forget
about. Firstly, try not to use anything you got from user in an
os.system call. Secondly, if you do, only allow things that they
absolutely need, for instance only string.letters. If you need @ there,
add @. Be paranoid - instead of excluding dangerous stuff only include
safe things.

> 
> 
> +---------------------"Thou Art Free." -Eris----------------------+
> | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net |
> | http://www.tinylist.org  +--------+  mailto:grumpy@tinylist.org |
> +------------------Thinking| NORMAL |Thinking---------------------+
>                            +--------+
> 
> NOTE: By sending SPAM to this address you agree to pay me a service
> fee of $100 for the service of receiving,  storing,  examining, and
> deleting your piece of SPAM. I am a postmaster, and take a dim view
> of such.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From wolf_binary@hotmail.com  Mon Apr  1 15:55:08 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Mon, 01 Apr 2002 09:55:08 -0600
Subject: [Tutor] enumeration in C++
Message-ID: <F44mQaqQhCnIruMJ4yS0000d124@hotmail.com>

Hi all,

Currently in college right now, I have come across enumeration in C++ and 
wanted to know if Python can do the same thing and how?

thanks,
Cameron Stoner


_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.




From dyoo@hkn.eecs.berkeley.edu  Mon Apr  1 16:05:52 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 1 Apr 2002 08:05:52 -0800 (PST)
Subject: [Tutor] enumeration in C++
In-Reply-To: <F44mQaqQhCnIruMJ4yS0000d124@hotmail.com>
Message-ID: <Pine.LNX.4.44.0204010759000.4803-100000@hkn.eecs.berkeley.edu>


On Mon, 1 Apr 2002, Cameron Stoner wrote:

> Currently in college right now, I have come across enumeration in C++
> and wanted to know if Python can do the same thing and how?

Almost.  In C++, we can create an enumeration with the following:

///
enum {red, white, blue} color;
color c = red;
///


One way of doing something like this might be:

###
RED, WHITE, BLUE = range(3)
c = RED
###


Also, I remember seeing that someone had implemented an enum class in the
'metaclasses' tutorial:

    http://www.python.org/doc/essays/metaclasses/Enum.py

So we can extend Python to have enumerations.


Good luck to you!  If you have more questions, please feel free to ask
them.




From paulsid@shaw.ca  Mon Apr  1 06:24:51 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sun, 31 Mar 2002 23:24:51 -0700
Subject: [Tutor] Getting exit code in Windows
References: <20020401001924.A25655@client156-52.ll.siue.edu>
Message-ID: <3CA7FD33.CB62C7FE@shaw.ca>

"Victor R. Cardona" wrote:

> I am writing a simple shell in python as a small demonstration project.
> I have figured out how to get the exit code for a process on UNIX using
> the waitpid function in the os module. Unfortunately, this function does
> not seem to exist on Windows. Is there a portable way of getting that
> kind of information? I know I could use the win32all extensions, but I
> wanted to make sure there was not a better way.

If I remember the Win32 documentation correctly, the exit code is not
even used by Windows, thus I doubt that there's any easy way to get at
it.  If indeed you can do it with win32all, that's probably the best (if
not the only) way to go.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From nicole.seitz@urz.uni-hd.de  Mon Apr  1 19:04:08 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Mon, 1 Apr 2002 21:04:08 +0200
Subject: [Tutor] A nicer output...
Message-ID: <02033121373001.00705@utopia>

Hi !




>Yes, pprint is just a quick way to display the content of a dictionary or 
>list. For a nicer output, you need to write some more code.

Ok, I wrote some code , but the result is still not satisfactory:


WORD:                   IN LINE(S):
===================================================
MarkUp                  [338]
SoftQuad                        [335]
AnyPoint                        [479, 478, 477]
AccelGalaxy                   [510]
CompuServe                   [103, 105]
SenseWeb                      [483, 485]
MacWeek                       [88]
TopWare                        [535]
AltaVista                        [403, 402, 400]
LonWorks                       [247]
AppleShare                    [259]
InterBus                         [234, 110]
JavaScript                      [81, 485]
StarOffice                       [263, 265]
McKinsey                       [463, 462]
TeleTrust                        [447, 445]
StarDivision                    [267, 265]
MediaOne                      [495, 497]
SysOps                  [105]
NetBooting                      [557]
NeuroVisionen                 [186, 173]



Is there a better way to get a nicely formatted output?(I 'm sure there is 
one..) 
Oh, almost forgot to add my code:


 print "WORD:\t\t\tIN LINE(S): "
    print "==================================================="

    for key in wordDict.keys():
        
        print key,"\t\t\t",uniq(wordDict[key])




>>How come that the words in the output are alphabetically ordered?


>I was surprised too. The pprint function (prettyprint) seems to sort the 
>output by default. 

Well, if I don't want to use pprint, how can I then sort my dictionary 
(alphabetically)? I read somewhere about sorting dictionaries, but can't find 
it right now.Hope you can help!


Many greetings


Nicole






From nicole.seitz@urz.uni-hd.de  Mon Apr  1 19:05:58 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Mon, 1 Apr 2002 20:05:58 +0100
Subject: [Tutor] German Umlaut
In-Reply-To: <4.3.2.7.2.20020326163412.00e8ccf0@pop3.norton.antivirus>
References: <4.3.2.7.2.20020325192321.00b9a810@pop3.norton.antivirus> <4.3.2.7.2.20020326163412.00e8ccf0@pop3.norton.antivirus>
Message-ID: <02033018535600.00703@utopia>

Am Dienstag, 26. M=E4rz 2002 17:06 schrieben Sie:

> It will match extended characters (eg. French accents, German Umlaut
> letters, etc.). Here is a longer explanation:
>
> \w
> When the LOCALE and UNICODE flags are not specified, matches any
> alphanumeric character; this is equivalent to the set [a-zA-Z0-9_]. Wit=
h
> LOCALE, it will match the set [0-9_] plus whatever characters are defin=
ed
> as letters for the current locale. If UNICODE is set, this will match t=
he
> characters [0-9_] plus whatever is classified as alphanumeric in the
> Unicode character properties database.
> Source: http://www.python.org/doc/current/lib/re-syntax.html

This reminds me of another problem I'm trying to deal with:

I'd like to extract from a text nouns that are coordinated with the word=20
"und". I wrote a little regex that seemed to work well at first sight.But=
=20
then I realized that it didn't match nouns with umlauts.
This was my first try:

reg =3D re.compile(r"\b[A-Z][a-z]+-? und [A-Z][a-z]+\b")

Output:

Arm und Reich
Sinn und Unsinn
Schule und Universit
Rock- und Popgr=20

The last to matches should be:

Schule und Universit=E4t  (aumlaut)
Rock- und Popgr=F6=DFen (oumlaut, )

Reading your email I changed my regex to:

reg =3D re.compile(r"\b[A-Z]\w+-? und [A-Z]\w+\b",re.UNICODE)

But this still doesn't match nouns like "=DCbung", i.d. the capitel lette=
r is=20
an umlaut.How can I deal with that??

Thanx and Happy Easter! (Wrote this email 2 days ago.Guess I'm now a bit=20
late.)

Nicole












From joorce@hotmail.com  Mon Apr  1 20:17:38 2002
From: joorce@hotmail.com (Jose Ortega)
Date: Mon, 1 Apr 2002 22:17:38 +0200
Subject: [Tutor] Executing programs from python
Message-ID: <OE19Ov0hv2RJHzkvd1G00008840@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0014_01C1D9CB.0821B5E0
Content-Type: text/plain;
	charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable

Hello
I'm new here. I want to ask you somthing.
I'm trying to do a kind of Renderman editor. For the ones that not know =
is what people from Pixar use to make Monsters, Inc, Toy storie and so =
on.=20
Anyway, so far I have a barely working text editor in Tkinter. What I =
want now is to fire rendrib.exe(BMRT's version of renderman) from my =
editor for render the file I'm working on.
I use=20
import os
os.system("c:/BMRT/bin/rendrib.exe x.rib")

And I got a warning saying that this program is configured to run in =
MS-DOS mode only but is not true because I can exec it from a DOS window =
without any problem.

So, wthat's the problem?. Is it the right way to do it (I guess not)?

Any help will be apreciated,TIA=20

------=_NextPart_000_0014_01C1D9CB.0821B5E0
Content-Type: text/html;
	charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Dwindows-1252">
<META content=3D"MSHTML 5.50.4522.1800" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hello</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I'm new here. I want to ask you=20
somthing.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I'm trying to do a kind of Renderman =
editor. For=20
the ones that not know is what people from Pixar use to make Monsters, =
Inc, Toy=20
storie and so on. </FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Anyway, so far I have a&nbsp;barely =
working text=20
editor in Tkinter. What I want now is to fire&nbsp;rendrib.exe(BMRT's =
version of=20
renderman)&nbsp;from my editor for render the file I'm working =
on.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>I use </FONT></DIV>
<DIV>import os</DIV>
<DIV>os.system("c:/BMRT/bin/rendrib.exe x.rib")</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>And I got a warning saying that this =
program is=20
configured to run in MS-DOS mode only but is not true because I can exec =
it from=20
a DOS window without any problem.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>So, wthat's the problem?. Is it the =
right way to do=20
it (I guess not)?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Any help will be=20
apreciated,TIA&nbsp;</FONT></DIV></BODY></HTML>

------=_NextPart_000_0014_01C1D9CB.0821B5E0--



From dyoo@hkn.eecs.berkeley.edu  Mon Apr  1 20:29:18 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 1 Apr 2002 12:29:18 -0800 (PST)
Subject: [Tutor] German Umlaut
In-Reply-To: <02033018535600.00703@utopia>
Message-ID: <Pine.LNX.4.44.0204011214080.10268-100000@hkn.eecs.berkeley.edu>

> Reading your email I changed my regex to:
>
> reg =3D re.compile(r"\b[A-Z]\w+-? und [A-Z]\w+\b",re.UNICODE)
>
> But this still doesn't match nouns like "=DCbung", i.d. the capitel lette=
r
> is an umlaut.How can I deal with that??


Hmmm... Is it possible to relax the regular expression a little?  Instead
of forcing a "capitalized" word, would this be feasible:

###
reg =3D re.compile(r"\b\w+-? und \w+\b",re.UNICODE)
###



Otherwise, we can stuff in 'string.uppercase' in the regular expression.
Here's one way to do it with some string formatting:

###
reg =3D re.compile(r"\b[%s]\w+-? und [%s]\w+\b"
                  % (string.uppercase, string.uppercase), re.UNICODE)
###


This is probably what you want, since:

###
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ\xc0\xc1\xc2\xc3\xc4\xc5\xc6
\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8
\xd9\xda\xdb\xdc\xdd\xde'
###

appears to contain all those characters.


Good luck!  I hope this helps.




From jeff@ccvcorp.com  Mon Apr  1 20:42:53 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 01 Apr 2002 12:42:53 -0800
Subject: [Tutor] Win XP (was command line)
References: <E16rocG-0005KD-00@mail.python.org>
Message-ID: <3CA8C64C.68E4467C@ccvcorp.com>

> alan.gauld@bt.com wrote:
>
> Wayyyy off topic but...

(and getting further off....  ;) )


> > After you install Microsoft Windows XP, you have the option to create
> > user accounts.  If you create user accounts, by default, they
> > will have an account type of administrator with no password.
>
> <RANT>
> True on XP Home and a really terrible decision by MS.
> Why not a single administrator and new users either
> Poweruser or restricted user? The latter is too restricted
> for most users but admin is simply insane! Bang goes much
> of XPs security protection! I am seriously considering
> upgrading from Home to Pro just because of this issue.
> </RANT>

Well, this is true of Win XP Pro, too (I've got that on one of my boxes at home).  Of course, it gives you
the *option* to set the privelidges and password to whatever you like -- but if you don't deliberately set
them differently, then you get Admin/None.

Keep in mind that the WinXP target market is people who are upgrading from 98/ME, to whom the concept of
user privelidges is new.  They want to be able to just install software and have it work.  Trying to
explain to them that they need to log in under a different account to install software just leaves them
baffled.  (Trust me on this one. ;) )  Of course, it *would* be reasonable to force a password, and given
that XP has so many features that assume a constant network connection, it's really horrifying that it
*doesn't* require a password, but...  >shrug<

Jeff Shannon
Technician/Programmer
Credit International





From wolf_binary@hotmail.com  Mon Apr  1 22:16:17 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Mon, 01 Apr 2002 16:16:17 -0600
Subject: [Tutor] install on zip disk
Message-ID: <F162kzTWeDSeqCmx66b000056f8@hotmail.com>

Hi all,

Yes I have another question. :-)

In order to make Python portable between computers that wouldn't necessarily 
have it loaded on, do you think you could install it on a zip disk and still 
be able to run it from another computer that has never had it installed on 
it?  I am going to try, but I don't think it will work, because of possible 
registry entries.  What do you guys think about it.  I want to be able to 
take it to the college lab and be able to work on Python from any computer 
with a zip drive.

Cameron Stoner

_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From cheshire_cat_sf@yahoo.com  Mon Apr  1 22:21:45 2002
From: cheshire_cat_sf@yahoo.com (Britt Green)
Date: Mon, 1 Apr 2002 14:21:45 -0800 (PST)
Subject: [Tutor] SQL databases
In-Reply-To: <E16s5B7-0004lG-00@mail.python.org>
Message-ID: <20020401222145.13151.qmail@web14105.mail.yahoo.com>

I know this is quite offtopic, but I'm hoping someone can point me in
the right direction. Basically, what are the differences between the
various databases that run under Linux? I'm starting a small website
and would like to use a DB to keep track of various things, and
integrate it with Python.

So as a complete newbie to databases, could someone give me some hints?

Britt

=====
"The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman."

__________________________________________________
Do You Yahoo!?
Yahoo! Greetings - send holiday greetings for Easter, Passover
http://greetings.yahoo.com/



From wolf_binary@hotmail.com  Mon Apr  1 22:28:22 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Mon, 01 Apr 2002 16:28:22 -0600
Subject: [Tutor] install on zip disk
Message-ID: <F722gH0JteseQfScft20000397c@hotmail.com>


Sratch that, it doesn't work, not that I really thought it would, but I 
still would like an idea to make it portable though.  If you have any other 
suggestions tell me please?

Cameron Stoner


_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From alan.gauld@bt.com  Mon Apr  1 22:32:45 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Apr 2002 23:32:45 +0100
Subject: [Tutor] command line
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D6@mbtlipnt02.btlabs.bt.co.uk>

> >hardly ever use the "toys". There's nothing so productive
> >as just typing the code in and it works first time! Many
> >experienced pros reach that level of quality after 10 years
> >or so...
> 
> Depends what you include in the "toy" category.

Granted, I really mean things like parameter displays, 
class browsers (for the core libraries, they are useful 
for user defined classes), graphical debuggers - "a sop 
to those who don't understand their own code" - to quote 
one seasoned hack...

> changes (ala make).  

make is most definitely not one of the "toys" but GUI 
project builders could be... depeding on their power. 
Some of these are now getting to the stage of being useful.

> Templates and dialog box driven
> builders of various types also save time.

Depends, If the GUI desitgners are non programmers and 
design the GUI in Visio (quite common) then the coders 
will often just hack together a resource file. The 
biggest Unix project I ever worked on the GUI team 
all used VT200 terminals and shared a single X display 
for testing! I definitely wouldn't recommend that!

> Helpful and useful:  a visual class browser, 

Hmm, sometimes yes. Mostly I find them overrated if 
you know the library well.

> code rollups,

??? whats one of them? Do you mean folding?
If so yes I agree that's useful, but with ctags still 
very much a luxury.

> and, of course, a way to develop GUI forms by simply
> dragging and dropping widgets from a palette ala VB

But that implies you are designing 'on the fly'. Fine 
for small projects with maybe a dozen forms but once 
you get into big projects(Photoshop say) then the design 
will tend to be on paper or in visio etc. Or maybe 
in VB as a demonstrator but be recoded by hand 
elsewhere...

> want to go back to the text-only tools of my past.  But I
> can understand sticking with what you know best.

On mainframes text only is all you get very often but 
I agree GUI tools have their place. However on Unix most
of the traditionally GUI tools are available as text 
and thats what gets used. I stress I'm talking about 
hard core coders here. I certainly am not in that 
category and I've been programming on and off for 25 
years. I mean the contractors who specialise in maybe 
3 or 4 languages on 2 or 3 OS's. They are paid to 
produce large volumes of code to a predetermined design. 
They have no need for design as you go type tools - they 
just sit down and churn out a thousand lines of 
working C/Java/COBOL per day.

> The idea that a *nix environment is itself an IDE makes
> plenty of sense 

Yes, Its the biggest thing about Unix, its a software 
engineering foundry that just happens to double as 
a decent OS :-)

> I also appreciate that *nix gives you more high powered
> tools at an affordable price 

Its not just the freeness of Linux etc. I was using 
Solaris(SunOS) long before Linux etc existed - I even 
tried Minix for a while! But its the integration and breadth 
of the tools. PC IDEs have only recently started shipping 
with profilers, they still don't do test coverage. You 
can buy the addons but often they don't integrate with 
each other - you can debug this build but not profile it...

> But it's also true that the *nix OS is a platform for
> expensive, proprietary, closed source software development
> IDEs and applications.  

Sure is. The IDEs I mentioned earlier all cost >$1000 per seat.
The test tool we use costs over $5000 per seat and the CASE 
tool is higher still. But these are production strength 
tools for serious use. When a projects development budget 
exceeds 10 million dollars (say) the tool costs become a 
minor issue! An hours downtime of the server will likely 
cost more!

> is, of course, not true.  Yet it seems some evangelists
> want us to believe that only Windows users ever run closed
> source, expensive stuff.

And that is certainly a myth. Unix has lots of closed source 
software, mostly good quality but there are some stinkers 
in there too.

> What I really like about Python, on all the platforms it
> supports, is that batteries are included.  

Absolutely. It is a great prototyping language, great 
for experimenting and great for scripting. For occasional 
users like me (I only program for a few hours each week) 
its perfect. If you want to take an idea to production 
level you can do that too. It only runs out of steam on 
the very biggest of projects or on the highest performance 
cases - Once you know you need that performance thens a 
good time to wheel in the hard core C++ gyys to rewrite 
the critical bits - and python is the pseudo code :-)

>  > This is true and is where Python development differs from
>  > traditional style coding.
> 
> Some languages have a builtin shell mode, and take advantage
> of it, whereas others don't.  APL, Logo, Scheme, many Lisps,
> Xbase, MATLAB, Mathematica, ISETL and Python are very shell-

Yeah but only LISP and Python out of that list are things 
I'd consider writing a big application in. And even Lisp 
has some problems in that area.

Smalltalk is the other one. The Smalltalk transcript window 
and class browser IDE are very similar in feel to a python 
prompt/editor environment IMHO.

Alan G



From alan.gauld@bt.com  Mon Apr  1 22:47:13 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Apr 2002 23:47:13 +0100
Subject: [Tutor] enumeration in C++
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D7@mbtlipnt02.btlabs.bt.co.uk>

> Currently in college right now, I have come across 
> enumeration in C++ and wanted to know if Python can 
> do the same thing and how?

Depends on which bit of C++ enums you want to use, 
its a flexible beast and gets used for all sorts 
of tricks.

If you just want a finite set of values then you 
can use a tuple. 

If you want to set a range of non contiguous values to 
a collection of names then I think you need a 
dictionary - but then it becomes mutable! Of course 
you could use a tuple of single element dicionaries, 
but thats not bombproof either!

If you need an autoincrementing list of consts 
(eg error codes) then I think you might be beat 
- ie I can't think of a pythonic equivalent! :-)

For most enum things in C++ there is a different 
idiom in Python - what aspect took your fancy?

Alan G



From alan.gauld@bt.com  Mon Apr  1 22:51:27 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 1 Apr 2002 23:51:27 +0100
Subject: [Tutor] FW: [Message Blocked] -
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D8@mbtlipnt02.btlabs.bt.co.uk>

I got this from my company email gatekeeper. I can't 
think what kind of attachment admin might be sending 
me... Can anyone give me a clue?

Alan G


> -----Original Message-----
> From: BT Alerts T 
> Sent: 01 April 2002 00:28
> To: Gauld,AJ,Alan,YEE11 GAULDAJ R
> Subject: [Message Blocked] - 
> 
> 
> An email addressed to you has been blocked at the Interchange 
> email gateway from the Internet.
> 
> The subject of the email was '' and was received by 
> Interchange on 01/04/02 00:28:11
> 
> The email was blocked as it contained an attachment that was 
> of a potentially dangerous type and may have contained a virus.
> 
> The original email was sent to you by mailto:tutor-admin@python.org
> 
> For more information on Interchange Virus and attachment 
> blocking see 

Alan g



From lkvam@venix.com  Mon Apr  1 22:29:37 2002
From: lkvam@venix.com (Lloyd Kvam)
Date: Mon, 01 Apr 2002 17:29:37 -0500
Subject: [Tutor] debugging classes with a __setattr__ method
Message-ID: <3CA8DF51.2010706@venix.com>

I have a class for processing DataBase records that keeps a dictionary of the
actual field values from the database in a separate dictionary from the
Class's __dict__ dictionary.  When I try to step through the program using the
debugger,  I can no longer step into the called methods.  Deleting the
__setattr__ method restores normal debugging capabilities.

Is this a normal side effect on the debugger?  Very little of the code depends
on the __setattr__ method, so I can remove it, debug and then put it back.
However, there may be a better way.  Any suggestions?

class Record:
	def __getattr__(self, key):
		""" This is called if the object lacks the attribute.
			If the key is not found, it raises an error in the
			same way that the attribute access would were no
			__getattr__ method present.
		"""
		try:
			return self._record[key]
		except:
			raise AttributeError, "%s not in _record dictionary" % (key)

	def __setattr__(self, key, value):
		if hasattr(self, "_record") and self._record.has_key(key):
			self._record[key] = value
		else:
			self.__dict__[key] = value

	def __delattr__(self, key):
		if hasattr(self, "_record") and self._record.has_key(key):
			raise AttributeError, "Must not delete record attributes.  %s in _record." % (key)
		elif self.__dict__.has_key(key):
			del self.__dict__[key]
		else:
			raise AttributeError, "delete non-existing instance attribute: %s" % (key)


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From iamgod@cc.jyu.fi  Tue Apr  2 00:13:26 2002
From: iamgod@cc.jyu.fi (Risto Peranen)
Date: Tue, 2 Apr 2002 03:13:26 +0300 (EEST)
Subject: [Tutor] Wolf scripting language
In-Reply-To: <E16s5B7-0004lM-00@mail.python.org>
Message-ID: <Pine.LNX.4.44.0204020253280.9058-100000@itu.st.jyu.fi>

I have read some source codes for python and it looks quite good. However,
I'm going to make a scripting language which is more event based and has 
single heritance and some other restrictions.

However, Python has extreme nice bundle of libtaries and huge amount of 
users so I'm not sure am I doing a smart thing or not.

I guess I will copy-paste some of python features to wolf but we'll see 
about that. (Licence for python is just perfect for my purposes)

My point for this silly mail is that if someone can explain how 
python compiles source to bytecode (just before executing) I would be 
gratefull for advices. 



P.S. I hope this mail won't set any flame-wars. Python is great language 
for most of the tasks but it's too slow for game- and AI-scripting. I 
personally have make my firewall setting quite easy with python. Python is 
also great tool for teaching programming. Personally I don't understand 
why most universities teach C++ as first-time-language.

P.P.S:
One thing where python sucks just a little bit is extenting. One cannot 
mix C/C++ and python so easily as could be done. My language will have 
strong typing so it's _much_ easier for me. (Wolf is not designed to be a 
good first-time-language so typing is not so bad thing to do). I don't 
know yet but it should be possible to add overloading even for return type.

 
----------
Risto Peranen ( Risto Per&auml;nen with proper lang setting )
mailto iamgod@jyu.fi 
In the world of freedom who needs Gates?








From dman@dman.ddts.net  Tue Apr  2 00:26:03 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 1 Apr 2002 18:26:03 -0600
Subject: [Tutor] Determining the OS a program runs on
In-Reply-To: <20020401023003.B26442@client156-52.ll.siue.edu>
References: <20020401023003.B26442@client156-52.ll.siue.edu>
Message-ID: <20020402002603.GA7195@dman.ddts.net>

On Mon, Apr 01, 2002 at 02:30:03AM -0600, Victor R. Cardona wrote:
| How should I detrmine what operating system a program is running on?
| Should I use sys.platform or os.name?

I didn't RTFM, but it looks like it depends what you're looking for.

For me :
    sys.platform    == linux2
    os.name         ==  posix

-D

-- 

In my Father's house are many rooms; if it were not so, I would have
told you.  I am going there to prepare a place for you.  And if I go and
prepare a place for you, I will come and take you to be with me that you
also may be where I am.
        John 14:2-3 




From dman@dman.ddts.net  Tue Apr  2 00:28:44 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 1 Apr 2002 18:28:44 -0600
Subject: [Tutor] enumeration in C++
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D7@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D7@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020402002844.GB7195@dman.ddts.net>

On Mon, Apr 01, 2002 at 11:47:13PM +0100, alan.gauld@bt.com wrote:
| > Currently in college right now, I have come across 
| > enumeration in C++ and wanted to know if Python can 
| > do the same thing and how?
| 
| Depends on which bit of C++ enums you want to use, 
| its a flexible beast and gets used for all sorts 
| of tricks.
 
| If you need an autoincrementing list of consts 
| (eg error codes) then I think you might be beat 
| - ie I can't think of a pythonic equivalent! :-)

The value of a label in an enum is undefined (at least in C).  The
compiler _probably_ just starts at 0 and works its way up except for
the cases where you've specified the value, but it isn't guaranteed to
be that way.  In python you can use range() to assign increasing ints
to a set of names, but like most things pythonic you must be
disciplined enough not to reassign them later.

HTH,
-D

-- 

Consider what God has done:
    Who can straighten what He has made crooked?
        Ecclesiastes 7:13




From dman@dman.ddts.net  Tue Apr  2 00:31:01 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 1 Apr 2002 18:31:01 -0600
Subject: [Tutor] install on zip disk
In-Reply-To: <F722gH0JteseQfScft20000397c@hotmail.com>
References: <F722gH0JteseQfScft20000397c@hotmail.com>
Message-ID: <20020402003101.GC7195@dman.ddts.net>

On Mon, Apr 01, 2002 at 04:28:22PM -0600, Cameron Stoner wrote:
 
| Sratch that, it doesn't work, not that I really thought it would, but I 
| still would like an idea to make it portable though.  If you have any other 
| suggestions tell me please?

Some builds (Activestate? Pythonwin? definitely cygwin's) don't touch
the registry (that nasty horrible beast that prevents program
portability!).  Cygwin's build presents a new set of dependencies,
though.  Maybe you can get cygwin installed on a zip disk and just
fudge the mount table for each new machine you move to (IIRC that's
the only thing cygwin sticks in the registry, and that's just a
convenience thing.  bash will still work even if the registry is
wiped clean.).

HTH,
-D

-- 

Your beauty should not come from outward adornment, such as braided hair
and the wearing of gold jewelry and fine clothes.  Instead, it should be
that of your inner self, the unfading beauty of a gentle and quiet
spirit, which is of GREAT WORTH in God's sight.  For this is the way the
holy women of the past used to make themselves beautiful.
        I Peter 3:3-5




From dman@dman.ddts.net  Tue Apr  2 00:32:58 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 1 Apr 2002 18:32:58 -0600
Subject: [Tutor] SQL databases
In-Reply-To: <20020401222145.13151.qmail@web14105.mail.yahoo.com>
References: <E16s5B7-0004lG-00@mail.python.org> <20020401222145.13151.qmail@web14105.mail.yahoo.com>
Message-ID: <20020402003258.GD7195@dman.ddts.net>

On Mon, Apr 01, 2002 at 02:21:45PM -0800, Britt Green wrote:
| I know this is quite offtopic, but I'm hoping someone can point me in
| the right direction. Basically, what are the differences between the
| various databases that run under Linux? I'm starting a small website
| and would like to use a DB to keep track of various things, and
| integrate it with Python.
| 
| So as a complete newbie to databases, could someone give me some hints?

    http://www.phpbuilder.com/columns/tim20000705.php3
    http://www.phpbuilder.com/columns/tim20001112.php3

In addition to traditional SQL RDBMSes there's ZODB, DB3 (aka Berkely
DB, aka DBM), and plain old pickle, depending on your needs.

What do you need to do with your db?

-D

-- 

If we confess our sins, He is faithful and just and will forgive us our
sins and purify us from all unrighteousness.
        I John 1:9




From shalehperry@attbi.com  Tue Apr  2 00:34:51 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 01 Apr 2002 16:34:51 -0800 (PST)
Subject: [Tutor] Wolf scripting language
In-Reply-To: <Pine.LNX.4.44.0204020253280.9058-100000@itu.st.jyu.fi>
Message-ID: <XFMail.20020401163451.shalehperry@attbi.com>

> 
> My point for this silly mail is that if someone can explain how 
> python compiles source to bytecode (just before executing) I would be 
> gratefull for advices. 
> 

Suggestion, ask this again on the main list.  tutor is meant for those new to
the language seeking gentle guidance.  Deep answers are best sought from the
masters on the python list.

The obvious answer is read the python source.  It is all there in fairly clean
and clear code.

I would also suggest you leave off why you want to know.  No sense diluting the
issue.



From shalehperry@attbi.com  Tue Apr  2 00:36:24 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 01 Apr 2002 16:36:24 -0800 (PST)
Subject: [Tutor] Wolf scripting language
In-Reply-To: <Pine.LNX.4.44.0204020253280.9058-100000@itu.st.jyu.fi>
Message-ID: <XFMail.20020401163624.shalehperry@attbi.com>

One more thought.

The worst part about a new language is having to write all of the support
libraries again.  You have to implement all of the nifty things in python's
standard lib plus work on bindings for existing C/whatever language libraries
like SSL and GUI's.



From jeff@ccvcorp.com  Tue Apr  2 02:26:53 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 01 Apr 2002 18:26:53 -0800
Subject: [Tutor] install on zip disk
References: <E16sBdf-0006FZ-00@mail.python.org>
Message-ID: <3CA916ED.669CBE31@ccvcorp.com>

> "Cameron Stoner" <wolf_binary@hotmail.com> wrote:
>
> In order to make Python portable between computers that wouldn't necessarily
> have it loaded on, do you think you could install it on a zip disk and still
> be able to run it from another computer that has never had it installed on
> it?  I am going to try, but I don't think it will work, because of possible
> registry entries.  What do you guys think about it.  I want to be able to
> take it to the college lab and be able to work on Python from any computer
> with a zip drive.

This should work, provided that you take care with all your file paths.  Paths and file associations are
really the only thing that Python requires the registry for, and paths can always be explicitly specified.
You might also want to look at Secret Labs' distribution of Python (www.pythonware.com), which specifically
avoids using the registry at all.

Note, however, that the win32all package *does* use the registry, and specifically anything COM related *must*
use the registry.

Jeff Shannon
Technician/Programmer
Credit International





From dman@dman.ddts.net  Tue Apr  2 02:38:26 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 1 Apr 2002 20:38:26 -0600
Subject: FW: RE: [Tutor] enumeration in C++
Message-ID: <20020402023826.GB8058@dman.ddts.net>

Tim says I'm wrong.  I think he's right.

-D

----- Forwarded message from Tim Peters <tim.one@comcast.net> -----

From: Tim Peters <tim.one@comcast.net>
To: dman <dman@dman.ddts.net>
Subject: RE: [Tutor] enumeration in C++
Date: Mon, 01 Apr 2002 20:04:01 -0500

[dman]
> The value of a label in an enum is undefined (at least in C).  The
> compiler _probably_ just starts at 0 and works its way up except for
> the cases where you've specified the value, but it isn't guaranteed to
> be that way.

    An enumerator with = defines its enumeration constant as the value of
    the constant expression.  If the first enumerator has no =, the
    value of its enumeration constant is 0.  Each subsequent enumerator
    with no = defines its enumeration constant as the value of the
    constant expression obtained by adding 1 to the value of the previous
    enumeration constant. (The use of enumerators with = may produce
    enumeration constants with values that duplicate other values in the
    same enumeration.)

That's pulled from the current C standard -- you may want to have a talk
with your compiler vendor <wink>.

> In python you can use range() to assign increasing ints
> to a set of names, but like most things pythonic you must be
> disciplined enough not to reassign them later.

Yup.  This is easy if you use the common ALLCAPS convention for conceptual
constants.

RED, WHITE, PURPLE = range(3)

----- End forwarded message -----

-- 

Microsoft: "Windows NT 4.0 now has the same user-interface as Windows 95"
    Windows 95: "Press CTRL-ALT-DEL to reboot"
Windows NT 4.0: "Press CTRL-ALT-DEL to login"




From dman@dman.ddts.net  Tue Apr  2 02:42:30 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 1 Apr 2002 20:42:30 -0600
Subject: [Tutor] command line
In-Reply-To: <0C4A626C-451A-11D6-9170-00039351FE6A@mac.com>
References: <20020331214509.GA30387@dman.ddts.net> <0C4A626C-451A-11D6-9170-00039351FE6A@mac.com>
Message-ID: <20020402024230.GA8094@dman.ddts.net>

On Sun, Mar 31, 2002 at 09:42:03PM -0500, Erik Price wrote:
| 
| On Sunday, March 31, 2002, at 04:45  PM, dman wrote:
| 
| >I see you're using "Apple Mail".  Are you on OSX?  If so fire up a
| >shell and try
| >    ldd `which python`
| 
| Hmm... no go; a search shows that 'ldd' isn't installed on my system.  
| I've actually never heard of that command.
 
[from the manpage]
DESCRIPTION
   ldd prints the shared libraries required by each program or shared
   library specified on the command line.

On my debian system it is part of the 'libc6' package.  Just for your
edification, here's what it outputs on my system.

$ ldd /usr/bin/python2.
    libpython2.2.so.0.0 => /usr/lib/libpython2.2.so.0.0 (0x40020000)
    libdl.so.2 => /lib/libdl.so.2 (0x400ed000)
    libpthread.so.0 => /lib/libpthread.so.0 (0x400f1000)
    libutil.so.1 => /lib/libutil.so.1 (0x40107000)
    libm.so.6 => /lib/libm.so.6 (0x4010a000)
    libc.so.6 => /lib/libc.so.6 (0x4012c000)
    /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

Must be dynamically loaded via dlopen().  ldd isn't going to help you
with this one.

| >and see if "libreadline" is mentioned anywhere in the output.  My
| >guess is that it won't be.  GNU readline is a library (made by the GNU
| >folks) for reading a lines of input from a terminal.  bash uses it and
| >python _can_ use it if it was compiled with it.  This is what gives
| >command history and line editing with emacs or vi style keybindings.
| >The default for readline is 'emacs' style.
| 
| Hm... oh well, I'm positive that I didn't specify emacs as a ./configure 
| parameter when I compiled Python.

Two things :
    you specify inclusion of the readline module (not emacs)
    python doesn't use autoconf (./configure), instead you need to
        uncomment the proper line in Modules/Setup (I think is the
        filename)

| I'll have to recompile.  No big deal, I just need some time to do
| it.  Thanks for the tip dman.

You're welcome.

-D

-- 

Better a little with righteousness
than much gain with injustice.
        Proverbs 16:8




From erikprice@mac.com  Tue Apr  2 02:47:23 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 1 Apr 2002 21:47:23 -0500
Subject: [Tutor] question about where to import
Message-ID: <F5CC0322-45E3-11D6-9AD0-00039351FE6A@mac.com>

I have a quick question about where import statements should go.  Most 
scripts feature them at the top of the script, or module, or whatever 
code container is calling the import statement.  Between the Stocks 
class we discussed earlier this weekend and another tutorial I found, 
I'm finally starting to "get" the idea behind OO -- it's not that hard 
to understand, but my impression is that it can be very tricky to 
efficiently come up with a flexible and reuseable class, and that it is 
in the "planning" stage that all the hard work takes place.

But I have a question.  Appended to this email is a code snippet, a 
class actually.  I didn't write it, it's from a tutorial.  In the class, 
the "time" module and the "gmtime" module are both imported for use.  
But the point at which they are imported intrigues me -- they are not 
imported at the top of the module, nor at the top of the class 
definition, but rather at the top of one of the class method 
definitions.  Is there some reason that the author would choose to put 
their import statement in a method definition?  I am probably wrong, but 
doesn't that mean that these modules are imported every time the method 
is called?  and if this is true, then doesn't this get expensive if you 
are creating many instances of the class?

If this is not just some laziness on the part of the tutorial-writer 
(and I'm not saying it is!), then can someone just explain why you would 
do it this way and not just import once at the top of the script -- if I 
am not mistaken, these functions should be available to any instance of 
the class if it is done this way too.

TIA,

-- Erik





# each Clock object is initialized with offsets
# indicating the difference between GMT and local time

class Clock:

   # constructor
   def __init__(self, offsetSign, offsetH, offsetM, city):
     # set variables to store timezone offset
     # from GMT, in hours and minutes, and city name
     self.offsetSign = offsetSign
     self.offsetH = offsetH
     self.offsetM = offsetM
     self.city = city

     # print message
     print 'Clock created'

     # method to display current time, given offsets
     def display(self):

       # use the gmtime() function to convert local to GMT
       # returns an array
       from time import time, gmtime

       self.GMTTime = gmtime(time())

       self.seconds = self.GMTTime[5]
       self.minutes = self.GMTTime[4]
       self.hours = self.GMTTime[3]

       # calculate time
       if (self.offsetsign == '+'):
         # city time is ahead of GMT
         self.minutes = self.minutes + self.offsetM

         if (self.minutes > 60):
           self.minutes = self.minutes - 60
           self.hours = self.hours + 1

         self.hours = self.hours + self.offsetH

         if (self.hours >= 24):
           self.hours = self.hours - 24

       else:
         # city time is behind GMT
         self.seconds = 60 - self.seconds
         self.minutes = self.minutes - self.offsetM

         if (self.minutes < 0):
           self.minutes = self.minutes + 60
           self.hours = self.hours -1

         self.hours = self.hours - self.offsetH

         if (self.hours < 0):
           self.hours = 24 + self.hours

       # make it look pretty and display it
       self.localTime = str(self.hours) + ":" + str(self.minutes) + ":" + 
str(self.seconds)
       print "Local time in " + self.city + " is " + self.localTime




From evan_jm@hotmail.com  Tue Apr  2 03:16:02 2002
From: evan_jm@hotmail.com (Evan Mahaiacheq)
Date: Mon, 01 Apr 2002 19:16:02 -0800
Subject: [Tutor] *Newbie who needs help*
Message-ID: <F168Ko9XsNktXPBODST00003b9f@hotmail.com>

Okay, I've written a program in the python interpreter, but how do i run the 
script in a new window, so i can try the program out?
I'm on Windows 98 so that doesn't help...

                                    Thanks for your help,
                                             ¤EVAN¤

_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From shalehperry@attbi.com  Tue Apr  2 03:33:42 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Mon, 01 Apr 2002 19:33:42 -0800 (PST)
Subject: [Tutor] question about where to import
In-Reply-To: <F5CC0322-45E3-11D6-9AD0-00039351FE6A@mac.com>
Message-ID: <XFMail.20020401193342.shalehperry@attbi.com>

> 
> If this is not just some laziness on the part of the tutorial-writer 
> (and I'm not saying it is!), then can someone just explain why you would 
> do it this way and not just import once at the top of the script -- if I 
> am not mistaken, these functions should be available to any instance of 
> the class if it is done this way too.
> 

as always a test script helps:

foo.py:

#!/usr/bin/python

class Foo:
  def __init__(self):
    print "Foo being constructed"

  def do_it(self):
    import bar
    b = bar.Bar()
    print b

for i in range(1, 5):
  f = Foo()
  print f

for i in range(1, 5):
  f = Foo()
  f.do_it()

bar.py:

class Bar:
  def __init__(self):
    print "Bar being constructed"

print "bar being imported"

when I run it:

./foo.py 
Foo being constructed
<__main__.Foo instance at 0x8057b7c>
Foo being constructed
<__main__.Foo instance at 0x808a6c4>
Foo being constructed
<__main__.Foo instance at 0x8057b7c>
Foo being constructed
<__main__.Foo instance at 0x808a5ec>
Foo being constructed
bar being imported
Bar being constructed
<bar.Bar instance at 0x805862c>
Foo being constructed
Bar being constructed
<bar.Bar instance at 0x80595bc>
Foo being constructed
Bar being constructed
<bar.Bar instance at 0x808a6cc>
Foo being constructed
Bar being constructed
<bar.Bar instance at 0x80595bc>

note the import only happens the first time the method is called.  If the
method is never called, the import never happens.  If the method is called
many, many times it is only imported once.





From erikprice@mac.com  Tue Apr  2 03:43:16 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 1 Apr 2002 22:43:16 -0500
Subject: [Tutor] command line
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D6@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <C429B86B-45EB-11D6-9AD0-00039351FE6A@mac.com>

On Monday, April 1, 2002, at 05:32  PM, alan.gauld@bt.com wrote:

> Absolutely. It is a great prototyping language, great
> for experimenting and great for scripting. For occasional
> users like me (I only program for a few hours each week)
> its perfect. If you want to take an idea to production
> level you can do that too. It only runs out of steam on
> the very biggest of projects or on the highest performance
> cases - Once you know you need that performance thens a
> good time to wheel in the hard core C++ gyys to rewrite
> the critical bits - and python is the pseudo code :-)

Really?  I mean, it's obviously more complicated than that, but can you 
for the most part map C++ to Python codeblock-for-codeblock?

I'm liking Python more and more the more I learn about it.  I was sold 
on the interpreter (nothing like an interpreter to help you see what's 
going on in your programs!), but now I'm learning about classes and it 
seems to be a pretty neat feature that PHP doesn't really have (it 
imitates classes somehow but they are limited).


Erik




From erikprice@mac.com  Tue Apr  2 03:55:28 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 1 Apr 2002 22:55:28 -0500
Subject: [Tutor] question about where to import
In-Reply-To: <XFMail.20020401193342.shalehperry@attbi.com>
Message-ID: <78445927-45ED-11D6-9AD0-00039351FE6A@mac.com>

On Monday, April 1, 2002, at 10:33  PM, Sean 'Shaleh' Perry wrote:

> note the import only happens the first time the method is called.  If 
> the
> method is never called, the import never happens.  If the method is 
> called
> many, many times it is only imported once.

I think I understand.  It's a way of avoiding the import if you don't 
really need it -- you only call it if it's needed (by the method that 
calls it), but if it gets called more than once then no big deal because 
Python won't import it again.

Neat!

Similar to PHP's require_once() function.  I had often wondered why you 
would ever really need this, as opposed to require().  Now I see that it 
lets you use it in some flow control block that may get executed more 
than once, to avoid having to call it additional times (in fact this is 
very bad in PHP depending on the contents of the 'required' file).  and 
rather than just automatically require() the external file all the time, 
you can require() it only if you need it by putting it in the flow 
control block.

thanks for clearing that one up for me!


Erik




From vcardon@siue.edu  Tue Apr  2 06:45:09 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Tue, 2 Apr 2002 00:45:09 -0600
Subject: [Tutor] Determining the OS a program runs on
In-Reply-To: <20020402002603.GA7195@dman.ddts.net>; from dman@dman.ddts.net on Mon, Apr 01, 2002 at 06:26:03PM -0600
References: <20020401023003.B26442@client156-52.ll.siue.edu> <20020402002603.GA7195@dman.ddts.net>
Message-ID: <20020402004509.A31118@client156-52.ll.siue.edu>

--xHFwDpU9dbj6ez1V
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Apr 01, 2002 at 06:26:03PM -0600, dman wrote:
> On Mon, Apr 01, 2002 at 02:30:03AM -0600, Victor R. Cardona wrote:
> | How should I detrmine what operating system a program is running on?
> | Should I use sys.platform or os.name?
>=20
> I didn't RTFM, but it looks like it depends what you're looking for.
>=20
> For me :
>     sys.platform    =3D=3D linux2
>     os.name         =3D=3D  posix

Thanks. I think sys.platform is the way to go in this case.

-v
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--xHFwDpU9dbj6ez1V
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8qVN0ZU/bSegbOhwRAt6IAJ4hspuIppm+jr8qBKoWLalEzUTC2gCfRsjk
nZSYEvDtyKqkwrSctafUhUw=
=fsC+
-----END PGP SIGNATURE-----

--xHFwDpU9dbj6ez1V--



From alex@gabuzomeu.net  Tue Apr  2 08:44:01 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Tue, 02 Apr 2002 10:44:01 +0200
Subject: [Tutor] Re: Tutor] A nicer output...
In-Reply-To: <E16sBde-0006FP-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020402100309.00d153e0@pop3.norton.antivirus>

Hi Nicole,


At 18:55 01/04/2002 -0500, you wrote:
>From: Nicole Seitz <nicole.seitz@urz.uni-hd.de>
>Date: Mon, 1 Apr 2002 21:04:08 +0200
>Subject: [Tutor] A nicer output...

> >Yes, pprint is just a quick way to display the content of a dictionary or
> >list. For a nicer output, you need to write some more code.
>
>Ok, I wrote some code , but the result is still not satisfactory:
>
>WORD:                   IN LINE(S):
>===================================================
>MarkUp                  [338]
>SoftQuad                        [335]
>AnyPoint                        [479, 478, 477]

>Is there a better way to get a nicely formatted output?(I 'm sure there is
>one..)

How do you want to format the list? For instance, you may want to separate 
the line numbers with commas. Take a look at the join() method of strings.

 >>> toto = [1, 2, 3, 4]

# First, let's convert the list content from integers to strings. Here we 
use a
# feature called list comprehension (new in Python 2), but you can do that
# with a 'for' loop (left as an exercice :-)
 >>> titi = [str(x) for x in toto]
 >>> print titi
['1', '2', '3', '4']

# Now, let's join the list with a comma and a space
 >>> print ", ".join(titi)

1, 2, 3, 4

>Oh, almost forgot to add my code:
>
>  print "WORD:\t\t\tIN LINE(S): "
>     print "==================================================="
>
>     for key in wordDict.keys():
>
>         print key,"\t\t\t",uniq(wordDict[key])

To output values, you can also use the "%" idiom:

 >>> titi = 1
 >>> toto = "truc"
 >>> outputTemplate = "First value: %i - Second value: %s"
 >>> print outputTemplate % (titi, toto)
First value: 1 - Second value: truc

This is useful to format output strings in a complex way. As you guess, %i 
is the placeholder for an integer and %s is a placeholder for a string. 
There are codes for other data types.

> >>How come that the words in the output are alphabetically ordered?
>
> >I was surprised too. The pprint function (prettyprint) seems to sort the
> >output by default.
>
>Well, if I don't want to use pprint, how can I then sort my dictionary
>(alphabetically)? I read somewhere about sorting dictionaries, but can't find
>it right now.Hope you can help!

You can copy the keys to a list, sort the list and use it to iterate on the 
dictionary content.

Eg. :

keyList = wordDict.keys()
keyList.sort()
for key in keyList:
         print key, wordDict[key]


Cheers.

Alexandre




From alan.gauld@bt.com  Tue Apr  2 09:39:44 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Apr 2002 10:39:44 +0100
Subject: [Tutor] command line
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4DA@mbtlipnt02.btlabs.bt.co.uk>

> > Absolutely. It is a great prototyping language, ...
> > cases - Once you know you need that performance thens a
> > good time to wheel in the hard core C++ gyys to rewrite
> > the critical bits - and python is the pseudo code :-)
> 
> Really?  I mean, it's obviously more complicated than that, 
> but can you for the most part map C++ to Python 
> codeblock-for-codeblock?

Yes, unless you use a lot of the dynamic OO stuff 
- class introspection, adding attributes on the fly etc.

But mostly Python code can be translated to C++ pretty 
easily, although the C++ will be 2 to 3 times as long...
and run 5-10 times faster...

Trivial example:

#### Python ########
class Foo:
  def __init__(self, bar): self.bar = bar
  def say(self): print self.bar

class Baz(Foo):
  def __init__(self): Foo.__init__(self,42)
  def say(self): print "We defaulted to: ", self.bar

/***** untested C++ *****/
class Foo{
protected:
   int myBar;
public:
   Foo(int bar){myBar = bar;};
   virtual void say(){ cout << bar;};
};

class Baz: public Foo{
public:
   Baz():Foo(42){}; // could use direct assignment too...
   virtual void say(){cout << "We defaulted to ", myBar;};
};

HTH,

Alan G



From alan.gauld@bt.com  Tue Apr  2 09:46:46 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Apr 2002 10:46:46 +0100
Subject: [Tutor] Linux databases
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4DB@mbtlipnt02.btlabs.bt.co.uk>

Britt,

This is not a popular answer in Linux circles since 
it isn't Open Source but I highly recommend Borland's 
Interbase. It's small, very full featured, very scaleable 
and theres at least some documentation available both 
in help files and in books.


Alan Gauld
Solutions Designer
BT computing partners
Tel : 0141 220 8795
Fax : 0141 248 1284 
Mob : 0771 249 2129



From mennosimons@gmx.net  Tue Apr  2 10:58:52 2002
From: mennosimons@gmx.net (Huuuuuu)
Date: Tue, 2 Apr 2002 12:58:52 +0200
Subject: [Tutor] style ok?
Message-ID: <20020402105858Z43473-16458+445@mail.uni-paderborn.de>

Hi,

this is a tiny script that puts the cvs-keywords $Id$ and $Log$ at the 
beginning and end of the specified files. It works as it is put below, but I 
assume there are ways to do it more compact/beautiful.

Any comments?

Thanks,
willi

----------------- logidfiles.py ----------------------------
#!/usr/bin/python
import sys, string

files = sys.argv[1:]
print "logid. v1.0 \nFiles to logid: ",files

id = """/*
 * $Id$
 */

 """

log = """
/*
 * $Log$
 */

 """
def listify(l):
    l = string.split(l, sep="\n")
    l = [w+"\n" for w in l]
    return l

id = listify(id)
log = listify(log)

for name in files:
    f = open(name, "r+")
    content = f.readlines()
    
    content[0:0] = id
    content[-1:] = log
    f.seek(0)
    f.writelines(content)
    print name,"bearbeitet."



From alan.gauld@bt.com  Tue Apr  2 12:44:28 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Apr 2002 13:44:28 +0100
Subject: [Tutor] enumeration in C++
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4DC@mbtlipnt02.btlabs.bt.co.uk>

> | Depends on which bit of C++ enums you want to use, 
>  
> | If you need an autoincrementing list of consts 
> 
> The value of a label in an enum is undefined (at least in C).  

Original K&R C didn't have enums at all.
In ANSI C they exist but values are implicit.

But not in C++....

You can do:

enum foo = {alpha=5,		// = 5
            beta,			// = 6
		gamma = 12,		// = 12
            delta,		// = 13
		epsilon,		// = 14
		omega};		// = 15

And the standard says the default first value is zero.

Alan g.



From alan.gauld@bt.com  Tue Apr  2 14:06:12 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 2 Apr 2002 15:06:12 +0100
Subject: [Tutor] *Newbie who needs help*
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4DD@mbtlipnt02.btlabs.bt.co.uk>

> Okay, I've written a program in the python interpreter, but 
> how do i run the script in a new window, so i can try the 
> program out?

If you are using IDLE then create a new window(File|New) and
type the code into the empty window that appears. Save the 
file with an extension of .py (lets say you chose spam.py)

Now you have a choice:
1) either open a DOS box and at the DOS prompt type

C:\> python spam.py

And the program will run

2) In IDLE use Edit|Run (Ctrl-F5) to run the program with 
   output appearing in the IDLE shell window.

3) Use explorer to double click on spam.py
This will run your program in a DOS box then close the 
DOS Box. If you need to see the output then add a line like:

raw_input("Hit ENTER to close...")

at the end of the file. The program will run then display 
the prompt until you hit ENTER.

HTH,

Alan G.

PS If using ActiveState Python with Pythonwin then there 
are very similar menu items to IDLE there too.




From ak@silmarill.org  Tue Apr  2 15:13:07 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Tue, 2 Apr 2002 10:13:07 -0500
Subject: [Tutor] style ok?
In-Reply-To: <20020402105858Z43473-16458+445@mail.uni-paderborn.de>
References: <20020402105858Z43473-16458+445@mail.uni-paderborn.de>
Message-ID: <20020402151306.GA28810@ak.silmarill.org>

On Tue, Apr 02, 2002 at 12:58:52PM +0200, Huuuuuu wrote:
> Hi,
> 
> this is a tiny script that puts the cvs-keywords $Id$ and $Log$ at the 
> beginning and end of the specified files. It works as it is put below, but I 
> assume there are ways to do it more compact/beautiful.
> 
> Any comments?
> 
> Thanks,
> willi
> 
> ----------------- logidfiles.py ----------------------------
> #!/usr/bin/python
> import sys, string
> 
> files = sys.argv[1:]
> print "logid. v1.0 \nFiles to logid: ",files
>
I usually put lines that execute in if __name__ == "__main__" block at
the end of file.

> 
> id = """/*
>  * $Id$
>  */
> 
>  """
> 
> log = """
> /*
>  * $Log$
>  */
> 
>  """
> def listify(l):
>     l = string.split(l, sep="\n")
>     l = [w+"\n" for w in l]
>     return l
> 
> id = listify(id)
> log = listify(log)
> 
> for name in files:
>     f = open(name, "r+")
>     content = f.readlines()
>     
>     content[0:0] = id
>     content[-1:] = log
>
I could be wrong, but I think you could have just inserted unlistified
id and log here.

>     f.seek(0)
>     f.writelines(content)
>     print name,"bearbeitet."
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From mennosimons@gmx.net  Tue Apr  2 15:14:34 2002
From: mennosimons@gmx.net (Menno Simons)
Date: Tue, 2 Apr 2002 17:14:34 +0200
Subject: [Tutor] style ok?
In-Reply-To: <20020402151306.GA28810@ak.silmarill.org>
References: <20020402105858Z43473-16458+445@mail.uni-paderborn.de> <20020402151306.GA28810@ak.silmarill.org>
Message-ID: <200204021514.g32FEZ911309@mailserver.c-lab.de>

Ups, I have just seen a bug there...

for name in files:
     f = open(name, "r+")
     content = f.readlines()

     content[0:0] = id
     content[-1:] = log

has to be

for name in files:
     f = open(name, "r+")
     content = f.readlines()

     content[0:0] = id
     content.append(log)

else the last original line will be deleted.

willi



From nicole.seitz@urz.uni-hd.de  Tue Apr  2 15:17:16 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Tue, 2 Apr 2002 17:17:16 +0200
Subject: [Tutor] enumeration in C++
In-Reply-To: <Pine.LNX.4.44.0204010759000.4803-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0204010759000.4803-100000@hkn.eecs.berkeley.edu>
Message-ID: <02040217171600.00705@utopia>

Am Montag,  1. April 2002 18:05 schrieben Sie:
> On Mon, 1 Apr 2002, Cameron Stoner wrote:
> > Currently in college right now, I have come across enumeration in C++
> > and wanted to know if Python can do the same thing and how?
>
> Almost.  In C++, we can create an enumeration with the following:
>
> ///
> enum {red, white, blue} color;
> color c = red;
> ///
>
>
> One way of doing something like this might be:
>
> ###
> RED, WHITE, BLUE = range(3)
> c = RED
> ###

What's enumeration  good for? Can someone give me a few examples when I would 
use enumeration?Years ago, when I was TRYING to learn C, I came across enum, 
but never found out its purpose.


Nicole




From jeff@ccvcorp.com  Tue Apr  2 17:43:07 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 02 Apr 2002 09:43:07 -0800
Subject: [Tutor] A nicer output...
References: <E16sRej-0002hR-00@mail.python.org>
Message-ID: <3CA9EDAB.CD40F917@ccvcorp.com>

>
> To output values, you can also use the "%" idiom:
>
>  >>> titi = 1
>  >>> toto = "truc"
>  >>> outputTemplate = "First value: %i - Second value: %s"
>  >>> print outputTemplate % (titi, toto)
> First value: 1 - Second value: truc
>
> This is useful to format output strings in a complex way. As you guess, %i
> is the placeholder for an integer and %s is a placeholder for a string.
> There are codes for other data types.

If you want your information in neat columns, you can modify this slightly.  Each
of those placeholders can take an optional numeric qualifier, and the formatting
will pad the string out to at least that many characters.

>>> breakfast = ['spam', 'eggs', 'bacon', 'baked beans']
>>> for food in breakfast:
...  print 'Eating %8s now' % food
...
Eating     spam now
Eating     eggs now
Eating    bacon now
Eating baked beans now
>>>

Note that extra space is added at the front of each food, so that %8s is printed
as *at least* eight characters.  But when there's more than 8 characters, it
doesn't truncate, just prints the whole thing as is.  If you wanted to have the
space added *after* each food, you can just make the number a negative, like so:

>>> for food in breakfast:
...  print 'Eating %-8s now' % food
...
Eating spam     now
Eating eggs     now
Eating bacon    now
Eating baked beans now
>>>

Now all the words are left-aligned instead of right-aligned.

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International





From deirdre@deirdre.net  Tue Apr  2 17:46:15 2002
From: deirdre@deirdre.net (Deirdre Saoirse)
Date: Tue, 2 Apr 2002 09:46:15 -0800 (PST)
Subject: [Tutor] Linux databases
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4DB@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.31.0204020942190.19775-100000@emperor.deirdre.org>

On Tue, 2 Apr 2002 alan.gauld@bt.com wrote:

> This is not a popular answer in Linux circles since it isn't Open
> Source but I highly recommend Borland's Interbase. It's small, very
> full featured, very scaleable and theres at least some documentation
> available both in help files and in books.

When recommending databases, please specify whether or not they are:

1) relational (in the true Codd & Date sense)
2) what part(s) of the ANSI SQL standard it conforms to. For example,
MySQL doesn't provide transactions or subqueries (though there is some
movement on at least the former).

This will help those who need databases evaluate them without having to
sort through a bunch of marketing hype.

After all, there's people who think Access is a database.

Open source databases:

MySQL, Postgres

Proprietary relational databases for Linux include:

Oracle, Sybase, Informix, DB2, Solid

--
_Deirdre                                              http://deirdre.net
"I love deadlines. I like the whooshing sound they make as they fly by."
                                                         - Douglas Adams




From jeff@ccvcorp.com  Tue Apr  2 18:05:18 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue, 02 Apr 2002 10:05:18 -0800
Subject: [Tutor] enumeration in C++
References: <E16sRej-0002hR-00@mail.python.org>
Message-ID: <3CA9F2DE.4C19E5B@ccvcorp.com>

> Nicole Seitz <nicole.seitz@urz.uni-hd.de> wrote:
>
> > On Mon, 1 Apr 2002, Cameron Stoner wrote:
> > > Currently in college right now, I have come across enumeration in C++
> > > and wanted to know if Python can do the same thing and how?
>
> What's enumeration  good for? Can someone give me a few examples when I would
> use enumeration?Years ago, when I was TRYING to learn C, I came across enum,
> but never found out its purpose.

Enumerations are good for two things -- associating a specific set of numbers with
symbolic names, and having a limited set of things to choose from.  For instance,
suppose I'm writing a program dealing with various weekdays.  I want to be able to
determine what weekday is two days ahead of the current day.  It might be
complicated to figure out that "Sunday" + 2 is "Tuesday", but if I create an
enumeration, like this:

>>> sunday, monday, tuesday, wednesday, thursday, friday, saturday = range(7)
>>> sunday + 2 == tuesday
1
>>>

Now, in C++, if you declare a variable to be of a specific enum type, and you try
to assign a value to it that is *not* a member of that enum, then you'll get a
compiler error.  This would prevent someone from using that variable for anything
*other* than a day of the week.  Of course, since Python doesn't use static
typing, that doesn't work in Python.  Personally, in Python, I would use a list
for this purpose.

>>> weekdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'saturday']
>>> len(weekdays)
7
>>> weekdays[4]
'thursday'
>>> weekdays.index('tuesday')
2
>>> weekdays[ weekdays.index('tuesday') + 3 ]
'friday'
>>>

As you can see, this lets us get the weeday corresponding to a specific number, or
the number for a particular weekday name, and it lets us do a certain amount of
arithmetic with weekdays (if we're careful).  One caution with the arithmetic --
we *do* want to be sure that the result of all of our arithmetic is within the
range of the length of our list (0-6).  We can use the modulus operator ( % ) to
do this:

>>> weekdays[ weekdays.index('friday') + 5 ]
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
IndexError: list index out of range
>>> weekdays[ (weekdays.index('friday') + 5) % len(weekdays) ]
'wednesday'
>>> weekdays.index('friday') + 5
10
>>> (weekdays.index('friday') + 5) % len(weekdays)
3
>>>

Hope this makes some sense to you.  :)

Jeff Shannon
Technician/Programmer
Credit International





From wolf_binary@hotmail.com  Tue Apr  2 18:11:53 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Tue, 02 Apr 2002 12:11:53 -0600
Subject: [Tutor] command line
Message-ID: <F891eHLRLm3IXJrongw0000a2d9@hotmail.com>



>From: alan.gauld@bt.com
>To: erikprice@mac.com, alan.gauld@bt.com
>CC: urnerk@qwest.net, tutor@python.org
>Subject: RE: [Tutor] command line
>Date: Tue, 2 Apr 2002 10:39:44 +0100
>
> > > Absolutely. It is a great prototyping language, ...
> > > cases - Once you know you need that performance thens a
> > > good time to wheel in the hard core C++ gyys to rewrite
> > > the critical bits - and python is the pseudo code :-)
> >
> > Really?  I mean, it's obviously more complicated than that,
> > but can you for the most part map C++ to Python
> > codeblock-for-codeblock?
>
>Yes, unless you use a lot of the dynamic OO stuff
>- class introspection, adding attributes on the fly etc.
>
>But mostly Python code can be translated to C++ pretty
>easily, although the C++ will be 2 to 3 times as long...
>and run 5-10 times faster...
>
>Trivial example:
>
>#### Python ########
>class Foo:
>   def __init__(self, bar): self.bar = bar
>   def say(self): print self.bar
>
>class Baz(Foo):
>   def __init__(self): Foo.__init__(self,42)
>   def say(self): print "We defaulted to: ", self.bar
>
>/***** untested C++ *****/
>class Foo{
>protected:
>    int myBar;
>public:
>    Foo(int bar){myBar = bar;};
>    virtual void say(){ cout << bar;};
>};
>
>class Baz: public Foo{
>public:
>    Baz():Foo(42){}; // could use direct assignment too...
>    virtual void say(){cout << "We defaulted to ", myBar;};
>};
>
>HTH,
>
>Alan G


This is exactly what I wanted to do with Python and C++, later.  I need to 
get my knowlege of both to equal one another.  This is why you will probably 
here a lot of comparisons from me from C++ to Python.  I want to build 
programs using Python as some of it an C++ for the engine of it.

Cameron Stoner

P.S.  I would apreciated any info on embedding the two languages together in 
either direction.

Thanks,
Cameron Stoner

_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.




From wolf_binary@hotmail.com  Tue Apr  2 18:16:48 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Tue, 02 Apr 2002 12:16:48 -0600
Subject: [Tutor] OOP purpose
Message-ID: <F49Tzof3kckIRyy4bJN0000ede5@hotmail.com>

Hi all,

What is the purpose of OOP?  Why  would you use it instead of just modular 
design?  I am having trouble finding the need to use it in my projects.

Thanks,

Cameron Stoner

_________________________________________________________________
MSN Photos is the easiest way to share and print your photos: 
http://photos.msn.com/support/worldwide.aspx




From hall@nhn.ou.edu  Tue Apr  2 18:16:28 2002
From: hall@nhn.ou.edu (Isaac Hall)
Date: Tue, 2 Apr 2002 12:16:28 -0600
Subject: [Tutor] passing objects
Message-ID: <02040212194300.31379@ouhep1>

I was wondering something about passing objects to class methods or functions.
when you pass an object (lets just say its really large, so this kind of
matters) to a function or class method, is the entire object copied again in
memory, or is it referenced.  and if it is copied, is there a way to only pass
a reference to the original object?

thanks 
Ike



From paulsid@shaw.ca  Tue Apr  2 18:00:06 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Tue, 02 Apr 2002 11:00:06 -0700
Subject: [Tutor] enumeration in C++
References: <Pine.LNX.4.44.0204010759000.4803-100000@hkn.eecs.berkeley.edu>
 <02040217171600.00705@utopia>
Message-ID: <3CA9F1A6.E231D629@shaw.ca>

Nicole Seitz wrote:

> What's enumeration  good for? Can someone give me a few examples when I would
> use enumeration?Years ago, when I was TRYING to learn C, I came across enum,
> but never found out its purpose.

Enumeration is very handy for things like mode or state constants, for
example:

typedef enum
{
    StBeginning, StMiddle, StMiddle2, StEnd, NUMSTATES
} states;

or

typedef enum
{
    ModeIcon, ModeSmallIcon, ModeList, ModeDetails, NUMMODES
} modes;

I always like to include the total in there since then if I insert new
modes/states it gets updated automatically.

In C++ (if I remember correctly) you also get type protection if a
variable is defined to be an enum, for example:

modes currentmode;
...
currentmode = ModeSmallIcon; // OK
...
currentmode = 2; // Illegal, even though 2==ModeList

Interestingly enough, despite having grown up with C for over a decade,
I haven't missed enumerations in Python.  But they can be rather handy
sometimes.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From brad.reisfeld@colostate.edu  Tue Apr  2 18:33:37 2002
From: brad.reisfeld@colostate.edu (Brad Reisfeld)
Date: Tue, 2 Apr 2002 11:33:37 -0700
Subject: [Tutor] creating objects in a loop
Message-ID: <NGEALAODAKLOJADDLGPACEDNCBAA.brad.reisfeld@colostate.edu>

Hi,
I was wondering if there is an efficient way to create objects based on
looping through members of a list or dictionary.

For instance, suppose I have

>>> class Pets:
...   def __init__(self, name):
...     self.name = name

>>> petlist = [('cat','fluffy'),('dog','fido'),('gorilla','spike')]

and I want to do the following:

>>> cat = Pets('fluffy')
>>> dog = Pets('fido')
>>> gorilla = Pets('spike')

Right now, I can use

>>> for species,name in petlist:
...   exec("%s = Pets('%s')" % (species, name))


This seems to do the right thing, but the use of the 'exec' kludge seems
really ugly and inefficient.

What is the proper way to do this? My lists and/or dictionaries in my actual
application may be quite large.

Thanks.

-Brad






From shalehperry@attbi.com  Tue Apr  2 18:33:46 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 02 Apr 2002 10:33:46 -0800 (PST)
Subject: [Tutor] OOP purpose
In-Reply-To: <F49Tzof3kckIRyy4bJN0000ede5@hotmail.com>
Message-ID: <XFMail.20020402103346.shalehperry@attbi.com>

On 02-Apr-2002 Cameron Stoner wrote:
> Hi all,
> 
> What is the purpose of OOP?  Why  would you use it instead of just modular 
> design?  I am having trouble finding the need to use it in my projects.
> 

OOP is just another way to think about programming.  It gives us humans a way
to think about the abstract nature of our code.

In some places it makes a whole lot of sense.  For instance GUI coding. 
Windows, buttons, titlebars, the mouse.  These are all real objects.  It
follows then to treat them as such.

Think about a file? It is a thing, you can describe it.

OOP in part is about letting the objects contain the smarts.  file.readlines().
 The file object knows how to retrieve its contents and give you a list of
them.  It does not matter if file is really a rfc822 message, a text file, or a
parsed XML object.  You think "I want the lines in the file".  In procedural
coding, you would need:

read_xml_lines()
read_database_lines()
read_rfc822_lines()

etc.  So you have separated the data from its controller.

Modular programming is part of OOP.  In a way, the modules in strict modular
programming are simple objects.



From gayers7@cogeco.ca  Tue Apr  2 19:50:26 2002
From: gayers7@cogeco.ca (Gordon W. Ayers)
Date: Tue, 02 Apr 2002 13:50:26 -0600
Subject: [Tutor] help: funny numbers
Message-ID: <3CAA0B82.96FB2017@cogeco.ca>

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [66.6, 333, 333, 1, 1234.5]
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.599999999999994, 333, -1, 333, 1, 1234.5, 333]
>>>

In the above list what happened to 66.6 when I redisplayed the list?

                                            Gord






From vcardon@siue.edu  Tue Apr  2 20:20:49 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Tue, 2 Apr 2002 14:20:49 -0600
Subject: [Tutor] passing objects
In-Reply-To: <02040212194300.31379@ouhep1>; from hall@nhn.ou.edu on Tue, Apr 02, 2002 at 12:16:28PM -0600
References: <02040212194300.31379@ouhep1>
Message-ID: <20020402142049.A1278@client156-52.ll.siue.edu>

--u3/rZRmxL6MmkK24
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Apr 02, 2002 at 12:16:28PM -0600, Isaac Hall wrote:
> I was wondering something about passing objects to class methods or funct=
ions.
> when you pass an object (lets just say its really large, so this kind of
> matters) to a function or class method, is the entire object copied again=
 in
> memory, or is it referenced.  and if it is copied, is there a way to only=
 pass
> a reference to the original object?

Objects are always passed by reference, but if the object is immutable,
then 'call by value' behavior emulated.

-v
--=20
Victor R. Cardona
Powered by SuSE Linux 7.1 (i386) Professional
GPG key ID E81B3A1C
Key fingerprint =3D 0147 A234 99C3 F4C5 BC64  F501 654F DB49 E81B 3A1C

--u3/rZRmxL6MmkK24
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8qhKgZU/bSegbOhwRAk61AKCTUDgNZnVnUeOCS/5eB1If/oPG6wCgq1hi
U8DIXF5+DenL6sktCpCef5Y=
=AVDq
-----END PGP SIGNATURE-----

--u3/rZRmxL6MmkK24--



From urnerk@qwest.net  Tue Apr  2 19:51:56 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 02 Apr 2002 11:51:56 -0800
Subject: [Tutor] OOP purpose
In-Reply-To: <F49Tzof3kckIRyy4bJN0000ede5@hotmail.com>
Message-ID: <4.2.0.58.20020402114425.00d32ef0@pop3.norton.antivirus>

At 12:16 PM 4/2/2002 -0600, you wrote:
>Hi all,
>
>What is the purpose of OOP?  Why  would you use it instead of
>just modular design?  I am having trouble finding the need
>to use it in my projects.
>
>Thanks,
>
>Cameron Stoner

I have this module called povray.py that outputs text in a
form suitable for rendering by Povray, a ray tracer.  The
core functionality is written as a class definition.

Now, if I have a specialized need to do something fancier
with Povray than my original class allows, I can just
subclass it.  This is good because sometimes the additional
functionality is very specialized (like I'm making the
cylinders and spheres look a certain way for a client,
maybe plastic and metalic respectively, plus I'm adding
cones), and because another project will require a
different kind of enchancement -- so I create a sibling
descendent, another subclass.

Were I not using the class/inheritance approach, my
inclination would be either to (a) continue complicating
the povray module with all kinds of bells and whistles,
mixing together features from multiple projects or (b)
always cutting and pasting a new copy of the original
module, and then expanding it in various ways.  Neither
(a) nor (b) would be as convenient.  With inheritance,
if I think of a way to enhance core functionality, I do
it once in the super class, and all subclasses benefit.
If I'd cloned the original code, I'd have to update each
clone.  And (a) would just make my code too complicated
and therefore difficult to maintain.

Kirby




From richert@upb.de  Tue Apr  2 09:03:43 2002
From: richert@upb.de (Willi Richert)
Date: Tue, 2 Apr 2002 11:03:43 +0200
Subject: [Tutor] style ok?
Message-ID: <20020402100353Z43236-16459+390@mail.uni-paderborn.de>

Hi,

this is a tiny script that puts the cvs-keywords $Id$ and $Log$ at the 
beginning and end of the specified files. It works as it is put below, but I 
assume there are ways to do it more compact/beautiful.

Any comments?

Thanks,
willi

----------------- logidfiles.py ----------------------------
#!/usr/bin/python
import sys, string

files = sys.argv[1:]
print "logid. v1.0 \nFiles to logid: ",files

id = """/*
 * $Id$
 */

 """

log = """
/*
 * $Log$
 */

 """
def listify(l):
    l = string.split(l, sep="\n")
    l = [w+"\n" for w in l]
    return l

id = listify(id)
log = listify(log)

for name in files:
    f = open(name, "r+")
    content = f.readlines()
    
    content[0:0] = id
    content[-1:] = log
    f.seek(0)
    f.writelines(content)
    print name,"bearbeitet."



From jkring@calbay.com  Tue Apr  2 16:46:58 2002
From: jkring@calbay.com (Jim Kring)
Date: Tue, 2 Apr 2002 08:46:58 -0800
Subject: [Tutor] Shelve Help
Message-ID: <000001c1da66$01e2ba80$0601a8c0@calbay>

I moved a shelve file from Redhat 6.X to Redhat 7.X and now I can't open it.
Both are using python 1.5.2.

I get the following error:

>>> db = shelve.open('shelveFile')
Traceback (innermost last):
    File "<stdin>", line 1, in ?
    File "/usr/lib/python1.5/shelve.py", line 152, in open return
DbfilenameShelf(filename, flag)
    File "/usr/lib/python1.5/shelve.py", line 142, in __init__
Shelf.__init__(self, anydbm.open(filename, flag))
    File "/usr/lib/python1.5/anydbm.py", line 86, in open return
mod.open(file, flag, mode)
    File "/usr/lib/python1.5/dbhash.py", line 8, in open return
bsddb.hashopen(file, flag, mode) bsddb.error: (22, 'Invalid argument')
Thanks for your help,

Jim





From urnerk@qwest.net  Tue Apr  2 20:03:44 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 02 Apr 2002 12:03:44 -0800
Subject: [Tutor] help: funny numbers
In-Reply-To: <3CAA0B82.96FB2017@cogeco.ca>
Message-ID: <4.2.0.58.20020402115241.00d38a90@pop3.norton.antivirus>

>
>[66.599999999999994, 333, -1, 333, 1, 1234.5, 333]
> >>>
>
>In the above list what happened to 66.6 when I redisplayed
>the list?
>
>                                             Gord

This is the age-old problem with floating point numbers.

Internally, they're converted from decimal to base 2,
and what come off as terminating decimals often end up
being non-terminal/repeating in binary.  Some truncation
occurs, and you notice the effects upon converting back
to decimal.

You will recall, for example, that 1/3 in decimal is
.33333... whereas 1/8 is .125 exactly.  With 1/3, we
have only a finite amount of space for digits, and so
have to truncate or round at some point.  The stored
decimal is no longer precisely 1/3.  Likewise, with
binary numbers, 6.65 isn't exactly captured in the
space allotted, so you get stuff like:

  >>> a = 6.65
  >>> a
  6.6500000000000004

We're used to thinking of finite decimals as approximations
of fractions, it's just that we forget 665/100 (i.e. 6.65)
is, for the computer, a division problem in base 2, and so
we keep being surprised by "floating point noise" in our
calculations.

Kirby




From urnerk@qwest.net  Tue Apr  2 20:16:22 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 02 Apr 2002 12:16:22 -0800
Subject: [Tutor] creating objects in a loop
In-Reply-To: <NGEALAODAKLOJADDLGPACEDNCBAA.brad.reisfeld@colostate.edu>
Message-ID: <4.2.0.58.20020402120444.00d30900@pop3.norton.antivirus>

At 11:33 AM 4/2/2002 -0700, Brad Reisfeld wrote:
>Hi,
>I was wondering if there is an efficient way to create objects based on
>looping through members of a list or dictionary.
>
>For instance, suppose I have
>
> >>> class Pets:
>...   def __init__(self, name):
>...     self.name = name
>
> >>> petlist = [('cat','fluffy'),('dog','fido'),('gorilla','spike')]
>
>and I want to do the following:
>
> >>> cat = Pets('fluffy')
> >>> dog = Pets('fido')
> >>> gorilla = Pets('spike')
>
>Right now, I can use
>
> >>> for species,name in petlist:
>...   exec("%s = Pets('%s')" % (species, name))
>
>
>This seems to do the right thing, but the use of the 'exec' kludge seems
>really ugly and inefficient.
>
>What is the proper way to do this? My lists and/or dictionaries in my actual
>application may be quite large.
>
>Thanks.

You can use the species as a key to a dictionary,
i.e.

petsdict['gorilla'] = Pets('spike') # and...
petsdict['dog']     = Pets('fido')

In other words:

petsdict = {}
for species,name in petlist:
    petsdict[species] = Pets(name)

Filing your multiple objects in a dictionary or list
is usually better than creating a lot of top level
variables in the namespace.  If you want to temporarily
point to an object by variable name, do that inside
a function e.g.

   def changename(species,newname):
       pet = petsdict[species]
       pet.name = newname

If you insist on creating top-level variables within
the module, you can do it without exec as follows:

for species,name in petlist:
    globals()[species] = name

Kirby





From urnerk@qwest.net  Tue Apr  2 21:00:33 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 02 Apr 2002 13:00:33 -0800
Subject: [Tutor] creating objects in a loop
In-Reply-To: <4.2.0.58.20020402120444.00d30900@pop3.norton.antivirus>
References: <NGEALAODAKLOJADDLGPACEDNCBAA.brad.reisfeld@colostate.edu>
Message-ID: <4.2.0.58.20020402125907.00d33b20@pop3.norton.antivirus>

>
>If you insist on creating top-level variables within
>the module, you can do it without exec as follows:
>
>for species,name in petlist:
>    globals()[species] = name

Sorry, that should have been:

for species,name in petlist:
    globals()[species] = Pet(name)

-- anyway, you get the idea.  I recommend the
dictionary method over the gobs-o-globals
approach.

Kirby




From Doug.Shawhan@gecits.ge.com  Tue Apr  2 21:40:39 2002
From: Doug.Shawhan@gecits.ge.com (Doug.Shawhan@gecits.ge.com)
Date: Tue, 2 Apr 2002 16:40:39 -0500
Subject: [Tutor] Stupid Windows Tricks
Message-ID: <47B6167F8E69D31194BA0008C7918D4204E4BE40@msxcvg02itscge.gecits.ge.com>

Howdy all,

I have a need to get a text listing of the contents of a windows domain. Is
there a way to spider the names of the various objects on an SMB domain? I
don't need any access to the objects, just their names.

Thanks!

d



From alex@gabuzomeu.net  Tue Apr  2 22:10:35 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 03 Apr 2002 00:10:35 +0200
Subject: [Tutor] creating objects in a loop
In-Reply-To: <E16sUfL-0003kp-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020402235324.00b76d90@pop3.norton.antivirus>

Hello Brad,


At 15:14 02/04/2002 -0500, you wrote:
>From: "Brad Reisfeld" <brad.reisfeld@colostate.edu>
>Date: Tue, 2 Apr 2002 11:33:37 -0700
>Subject: [Tutor] creating objects in a loop

>I was wondering if there is an efficient way to create objects based on
>looping through members of a list or dictionary.
>
>For instance, suppose I have
>
> >>> class Pets:
>...   def __init__(self, name):
>...     self.name = name
>
> >>> petlist = [('cat','fluffy'),('dog','fido'),('gorilla','spike')]

This is a bit off-topic, but you might be interested in using functions as 
class factories:

class Pets:
     def __init__(self, name):
         self.name = name

def factory(theClass, *args):
     "theClass is a class object."
     return theClass(*args)

def factoryFromName(className, *args):
     "className is a string."
     return eval(className)(*args)

def petFactory(arg):
     # This could be extended to accept a list of args
     # and return a list of class instances
     return Pets(arg)

if __name__ == "__main__":
     cat = factory(Pets, "fluffy")
     print cat

     monkey = factoryFromName("Pets", "foo")
     print monkey

     pet = petFactory("bombix")
     print pet

<__main__.Pets instance at 00FBFA7C>
<__main__.Pets instance at 00FBEFDC>
<__main__.Pets instance at 00FBB90C>

Also, if you have a lot of pets to handle, you could use a collection class 
to manage them. Eg.:

class BunchOfPets:

     def __init__(self):
         self.petDict = {}

     def addPet(self, name):
         pet = Pets(name)
         self.petDict[name] = pet

     def getPet(self, name):
         if self.petDict.has_key(name):
             return self.petDict[name]
         else:
             return None

     def getPetCount(self):
         return len(self.petDict)

if __name__ == "__main__":

     bunch = BunchOfPets()
     bunch.addPet("snafu")
     print bunch.getPetCount()
     print bunch.getPet("snafu")

1
<__main__.Pets instance at 018592FC>


Cheers.

Alexandre




From urnerk@qwest.net  Tue Apr  2 04:23:22 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 1 Apr 2002 23:23:22 -0500
Subject: [Tutor] command line
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D6@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4D6@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <E16sYmo-0007hT-00@mail.python.org>

On Monday 01 April 2002 05:32 pm, alan.gauld@bt.com wrote:

> > Depends what you include in the "toy" category.
>
> Granted, I really mean things like parameter displays,
> class browsers (for the core libraries, they are useful
> for user defined classes), graphical debuggers - "a sop
> to those who don't understand their own code" - to quote
> one seasoned hack...
>

I think we're seeing more of an age-old pattern:  pioneers 
develop a rustic, effective lifestyle, close to the elements,
They're amazingly competent, with minimalist tools.  Later 
generations come along expecting indoor plumbing with hot 
and cold running water -- they expect, nay demand, what look 
to the pioneers like unnecessary luxuries (and yet they call
this progress!).

By the way, I've been meaning to promote what I consider an
excellent background essay on all this:  'In the Beginning Was
the Command Line' by Neal Stephenson, a good writer.  He 
covers a lot of recent history, and without obnoxiously 
getting on a narrow-perspective soap box.

Here it is on-line:
http://www.spack.org/words/commandline.html

Kirby



From rdzx@myrealbox.com  Wed Apr  3 02:17:31 2002
From: rdzx@myrealbox.com (Rohan Deshpande)
Date: Tue, 2 Apr 2002 21:17:31 -0500
Subject: [Tutor] Python + HTTP?
Message-ID: <20020403021731.GA4324@abyss>

Hi,

I've just read through the tutorial for Python on the www.python.org
website, and I was just wondering where one should go to learn more
about HTTP programming with python.  Basically, I want to be able to
post data using user input, and then get files from websites and parse
them.  Any tips?

Thanks so much!

-- 
Rohan Deshpande
rdzx@myrealbox.com



From erikprice@mac.com  Wed Apr  3 02:27:47 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 2 Apr 2002 21:27:47 -0500
Subject: [Tutor] modules == class instances?
Message-ID: <63156C79-46AA-11D6-ADAB-00039351FE6A@mac.com>

I have noticed something in the past day or so -- that the syntax for 
referring to a module's namespace is identical to the syntax used for 
referring to a class instance's methods -- you specify the name of the 
module or the class instance, then a dot, and then you specify the name 
of the function or property or method you wish to access.

When I import a module into a script, does the import process in fact 
create an object instance to represent the module, or is this just a 
coincidence?



Just curious.


Erik




From shalehperry@attbi.com  Wed Apr  3 02:39:05 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 02 Apr 2002 18:39:05 -0800 (PST)
Subject: [Tutor] Python + HTTP?
In-Reply-To: <20020403021731.GA4324@abyss>
Message-ID: <XFMail.20020402183905.shalehperry@attbi.com>

On 03-Apr-2002 Rohan Deshpande wrote:
> Hi,
> 
> I've just read through the tutorial for Python on the www.python.org
> website, and I was just wondering where one should go to learn more
> about HTTP programming with python.  Basically, I want to be able to
> post data using user input, and then get files from websites and parse
> them.  Any tips?
> 

the library docs for the http modules are pretty good actually.



From shalehperry@attbi.com  Wed Apr  3 02:41:05 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 02 Apr 2002 18:41:05 -0800 (PST)
Subject: [Tutor] modules == class instances?
In-Reply-To: <63156C79-46AA-11D6-ADAB-00039351FE6A@mac.com>
Message-ID: <XFMail.20020402184105.shalehperry@attbi.com>

On 03-Apr-2002 Erik Price wrote:
> I have noticed something in the past day or so -- that the syntax for 
> referring to a module's namespace is identical to the syntax used for 
> referring to a class instance's methods -- you specify the name of the 
> module or the class instance, then a dot, and then you specify the name 
> of the function or property or method you wish to access.
> 
> When I import a module into a script, does the import process in fact 
> create an object instance to represent the module, or is this just a 
> coincidence?
> 

modules certainly ACT like objects:

>>> import re
>>> type(re)
<type 'module'>
>>> print re
<module 're' from '/usr/lib/python2.1/re.pyc'>
>>> dir(re)
['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U',
'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__',
'__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'match',
'purge', 'search', 'split', 'sub', 'subn', 'template']

but I am unsure how python treats them internally.

If nothing else it makes sense to use modules as objects too, so it makes sense
to simplify the language a bit.



From Ares.liu@Clarent.com  Wed Apr  3 02:53:54 2002
From: Ares.liu@Clarent.com (Ares Liu)
Date: Wed, 3 Apr 2002 10:53:54 +0800
Subject: [Tutor] Why cannot open a file?
Message-ID: <001801c1daba$cb0725a0$34461e0a@gege>

This is a multi-part message in MIME format.

------=_NextPart_000_0015_01C1DAFD.D8F069E0
Content-Type: text/plain;
	charset="gb2312"
Content-Transfer-Encoding: quoted-printable

C:\tmp>python
Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> f =3D open('foo.foo','W')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 0] Error: 'foo.foo'
>>> f =3D open('C:\\tmp\\foo.foo','W')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 0] Error: 'C:\\tmp\\foo.foo'
>>>

how can I do it?
Regards
=20
Ares

------=_NextPart_000_0015_01C1DAFD.D8F069E0
Content-Type: text/html;
	charset="gb2312"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>

<META content=3D"MSHTML 6.00.2715.400" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>C:\tmp&gt;python<BR>Python 2.1.1 (#20, =
Jul 20 2001,=20
01:19:29) [MSC 32 bit (Intel)] on win32<BR>Type "copyright", "credits" =
or=20
"license" for more information.<BR>&gt;&gt;&gt; f =3D=20
open('foo.foo','W')<BR>Traceback (most recent call last):<BR>&nbsp; =
File=20
"&lt;stdin&gt;", line 1, in ?<BR>IOError: [Errno 0] Error:=20
'foo.foo'<BR>&gt;&gt;&gt; f =3D =
open('C:\\tmp\\foo.foo','W')<BR>Traceback (most=20
recent call last):<BR>&nbsp; File "&lt;stdin&gt;", line 1, in =
?<BR>IOError:=20
[Errno 0] Error: 'C:\\tmp\\foo.foo'<BR>&gt;&gt;&gt;<BR></FONT></DIV>
<DIV><FONT face=3DArial size=3D2>how can I do it?</DIV></FONT>
<DIV><FONT face=3DArial size=3D2>Regards</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Ares</FONT></DIV></BODY></HTML>

------=_NextPart_000_0015_01C1DAFD.D8F069E0--



From dyoo@hkn.eecs.berkeley.edu  Wed Apr  3 03:04:59 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Apr 2002 19:04:59 -0800 (PST)
Subject: [Tutor] Why cannot open a file?
In-Reply-To: <001801c1daba$cb0725a0$34461e0a@gege>
Message-ID: <Pine.LNX.4.44.0204021904040.20033-100000@hkn.eecs.berkeley.edu>


On Wed, 3 Apr 2002, Ares Liu wrote:

> C:\tmp>python
> Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> f = open('foo.foo','W')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> IOError: [Errno 0] Error: 'foo.foo'
> >>> f = open('C:\\tmp\\foo.foo','W')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> IOError: [Errno 0] Error: 'C:\\tmp\\foo.foo'

Hi Ares,

Try lowercase 'w' when you're opening the file in "write" mode.  I believe
that the open() function is case sensitive.  Something like:

    f = open('foo.foo', 'w')


Good luck!




From dyoo@hkn.eecs.berkeley.edu  Wed Apr  3 03:12:37 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Apr 2002 19:12:37 -0800 (PST)
Subject: [Tutor] modules == class instances?
In-Reply-To: <XFMail.20020402184105.shalehperry@attbi.com>
Message-ID: <Pine.LNX.4.44.0204021906230.20033-100000@hkn.eecs.berkeley.edu>

On Tue, 2 Apr 2002, Sean 'Shaleh' Perry wrote:

>
> On 03-Apr-2002 Erik Price wrote:
> > I have noticed something in the past day or so -- that the syntax for
> > referring to a module's namespace is identical to the syntax used for
> > referring to a class instance's methods -- you specify the name of the
> > module or the class instance, then a dot, and then you specify the name
> > of the function or property or method you wish to access.
> >
> > When I import a module into a script, does the import process in fact
> > create an object instance to represent the module, or is this just a
> > coincidence?
>
> modules certainly ACT like objects:
>
> >>> import re
> >>> type(re)
> <type 'module'>
> >>> print re
> <module 're' from '/usr/lib/python2.1/re.pyc'>
> >>> dir(re)
> ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U',
> 'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__',
> '__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'match',
> 'purge', 'search', 'split', 'sub', 'subn', 'template']
>
> but I am unsure how python treats them internally.

Yes, modules are also "objects" in Python.  They don't support too many
things besides allowing us to get and set attributes within them, but they
are objects that can be tossed around quite easily and uniformly.

###
>>> import re, string, urllib
>>> for module in [re, string, urllib]:
...     print "Hey, I have a module: ", module
...
Hey, I have a module:  <module 're' from
'/opt/Python-2.1.1/lib/python2.1/re.pyc'>
Hey, I have a module:  <module 'string' from
'/opt/Python-2.1.1/lib/python2.1/string.pyc'>
Hey, I have a module:  <module 'urllib' from
'/opt/Python-2.1.1/lib/python2.1/urllib.pyc'>
###


(If you're a C junkie, you can look at the Python source code, in the
"Objects/moduleobject.c" directory, and you'll see how they're
implemented as objects.)


Hope this helps!




From erikprice@mac.com  Wed Apr  3 03:31:28 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 2 Apr 2002 22:31:28 -0500
Subject: [Tutor] enumeration in C++
In-Reply-To: <3CA9F2DE.4C19E5B@ccvcorp.com>
Message-ID: <48D1928C-46B3-11D6-ADAB-00039351FE6A@mac.com>

On Tuesday, April 2, 2002, at 01:05  PM, Jeff Shannon wrote:

> As you can see, this lets us get the weeday corresponding to a specific 
> number, or
> the number for a particular weekday name, and it lets us do a certain 
> amount of
> arithmetic with weekdays (if we're careful).  One caution with the 
> arithmetic --
> we *do* want to be sure that the result of all of our arithmetic is 
> within the
> range of the length of our list (0-6).  We can use the modulus 
> operator ( % ) to
> do this:
>
>>>> weekdays[ weekdays.index('friday') + 5 ]
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> IndexError: list index out of range
>>>> weekdays[ (weekdays.index('friday') + 5) % len(weekdays) ]
> 'wednesday'
>>>> weekdays.index('friday') + 5
> 10
>>>> (weekdays.index('friday') + 5) % len(weekdays)
> 3
>>>>
>
> Hope this makes some sense to you.  :)

It made a lot of sense to me AND it showed me a good reason to use the 
modulus operator.  (I'm not saying good reasons don't exist, I just 
haven't seen many of them yet.)

Now I know what enumerations are used for, and why they don't exist in 
Python (and how to wing it if I really want to use them, though I would 
probably use a tuple since it seems that enumerations don't change*).


Erik

* ... but then, when I tried the code, it says that tuples don't have 
the attribute 'index' -- what gives? I thought that tuples and lists 
were pretty much the same, except for immutableness on the part of 
tuples.




From erikprice@mac.com  Wed Apr  3 03:36:11 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 2 Apr 2002 22:36:11 -0500
Subject: [Tutor] creating objects in a loop
In-Reply-To: <NGEALAODAKLOJADDLGPACEDNCBAA.brad.reisfeld@colostate.edu>
Message-ID: <F198523C-46B3-11D6-ADAB-00039351FE6A@mac.com>

On Tuesday, April 2, 2002, at 01:33  PM, Brad Reisfeld wrote:

> I was wondering if there is an efficient way to create objects based on
> looping through members of a list or dictionary.
>
> For instance, suppose I have
>
>>>> class Pets:
> ...   def __init__(self, name):
> ...     self.name = name
>
>>>> petlist = [('cat','fluffy'),('dog','fido'),('gorilla','spike')]
>
> and I want to do the following:
>
>>>> cat = Pets('fluffy')
>>>> dog = Pets('fido')
>>>> gorilla = Pets('spike')
>
> Right now, I can use
>
>>>> for species,name in petlist:
> ...   exec("%s = Pets('%s')" % (species, name))
>
>
> This seems to do the right thing, but the use of the 'exec' kludge seems
> really ugly and inefficient.

Two comments (but remember I'm a newbie to Python):

1.  I think that for your pet names, you should use a dictionary rather 
than a list -- it seems that the elements of each mini-list are not 
really equal, but rather one is a category and the other is a specific 
example of that category.  Such as "fluffy" being a specific example of 
a "cat".  So I would suggest that you use a dictionary to store these 
pairs.

2.  It's strange, but Spike just seems like a most appropriate name for 
a gorilla.


Erik




From erikprice@mac.com  Wed Apr  3 03:38:51 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 2 Apr 2002 22:38:51 -0500
Subject: [Tutor] help: funny numbers
In-Reply-To: <4.2.0.58.20020402115241.00d38a90@pop3.norton.antivirus>
Message-ID: <507D1068-46B4-11D6-ADAB-00039351FE6A@mac.com>

On Tuesday, April 2, 2002, at 03:03  PM, Kirby Urner wrote:

> We're used to thinking of finite decimals as approximations
> of fractions, it's just that we forget 665/100 (i.e. 6.65)
> is, for the computer, a division problem in base 2, and so
> we keep being surprised by "floating point noise" in our
> calculations.

So is there a function, method, or technique that can "clean up" the 
noise, and approximate the value that we really want?  Or do we code it 
ourselves?


Erik




From erikprice@mac.com  Wed Apr  3 03:41:11 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 2 Apr 2002 22:41:11 -0500
Subject: [Tutor] creating objects in a loop
In-Reply-To: <4.2.0.58.20020402120444.00d30900@pop3.norton.antivirus>
Message-ID: <A3DFF224-46B4-11D6-ADAB-00039351FE6A@mac.com>

On Tuesday, April 2, 2002, at 03:16  PM, Kirby Urner wrote:

> Filing your multiple objects in a dictionary or list
> is usually better than creating a lot of top level
> variables in the namespace.

Is this for tidiness reasons (to avoid cluttering the namespace with 
unnecessary names), or is this convention?


Thank you,

Erik




From erikprice@mac.com  Wed Apr  3 03:45:06 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 2 Apr 2002 22:45:06 -0500
Subject: [Tutor] creating objects in a loop
In-Reply-To: <4.3.2.7.2.20020402235324.00b76d90@pop3.norton.antivirus>
Message-ID: <304BF152-46B5-11D6-ADAB-00039351FE6A@mac.com>

On Tuesday, April 2, 2002, at 05:10  PM, Alexandre Ratti wrote:

> if __name__ == "__main__":
>     cat = factory(Pets, "fluffy")
>     print cat
>
>     monkey = factoryFromName("Pets", "foo")
>     print monkey
>
>     pet = petFactory("bombix")
>     print pet


The "if __name__ == '__main__':" test -- I have seen it several times 
now.  Why is this test performed?  Isn't it obvious that __name__ is 
__main__ ?  Or am I missing something....


Erik

PS:  I truly am sorry that I have so many questions, but the more I 
learn the more I realize I don't know a lot of things.




From virketis@fas.harvard.edu  Wed Apr  3 04:07:11 2002
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Tue, 2 Apr 2002 23:07:11 -0500
Subject: [Tutor] help: funny numbers
References: <507D1068-46B4-11D6-ADAB-00039351FE6A@mac.com>
Message-ID: <01ca01c1dac5$0791c250$18adf78c@virketis2>

Erik,

> So is there a function, method, or technique that can "clean up" the
> noise, and approximate the value that we really want?  Or do we code it
> ourselves?

It is hard to imagine a magic function that you could feed a fp number in
and get what you had intended to get out as output: how would it ever know
what is "noise" and what is "signal"? However, you can work around some of
the problems. For example, fp rounding is sometimes a problem in Boolean
conditions:

>>> def Boolean(x):
 if x == 1: print "match"

OK, now lets pass this function the rounded fp value of the kind you
encountered: 0.99999999999994.

>>> Boolean(0.99999999999994)
>>>

Hm ... So, our condition did not fire: this can be an annoying problem. In
this particular case, since we are expecting an integer, we could round the
fp number. But what if we were expecting 1.5555 and got 1.55599999999999994?
The solution is to pick some very small standard error range, which is
acceptable in our application, and set the condition to fire across all of
it. So:

>>> epsilon = 0.000000000005
>>> def Boolean_epsilon(x):
 if (1 - epsilon) <= x <= (1 + epsilon): print "match"

Let's try this:

>>> Boolean_epsilon(0.99999999999994)
match

Alright, so now the behaviour is more reasonable.

Hope this helps. Cheers,

Pijus




From sheila@thinkspot.net  Wed Apr  3 06:34:04 2002
From: sheila@thinkspot.net (Sheila King)
Date: Tue, 2 Apr 2002 22:34:04 -0800
Subject: [Tutor] Using popen
Message-ID: <66DEB847507@kserver.org>

Well, I hope someone can give me some advice here.

I'm writing a cgi script that needs to call a shell command and get 
the output. Retrieving the exit code of the command would be fine. 
The syntax of the statement is this:

(we're talking Linux...bash shell...)

vauthenticate ACCOUNTNAME

and after this, it reads a password from stdin and then determines if 
that is the correct password for the POP email account ACCOUNTNAME.

If it is correct, it returns some string data plus an exit code of 
zero.

If it is not correct, it returns an exit code of 1 and not data.

I tested it at the command line with the following results:
(first, a successful password request)

[username@servername:~ ]$ vauthenticate secret_test
secret
UID=41121
GID=41121
USER=xaccountname
HOME=/big/dom/xaccountname
MAILDIR=./vmspool/secret_test
VUSER=secret_test

[username@servername:~ ]$ echo $?
0


(and now with a bad password)

[thinker@FQ-Nine:~ ]$ vauthenticate secret_test
badpass

[thinker@FQ-Nine:~ ]$ echo $?
1

OK, so you can see the shell syntax.

I figured, I'd use popen, 
issue the command 'vauthenticate ACCOUNTNAME'
and then write the proposed password to the pipe.
Then, according to the documentation, when I close the pipe, it 
should return the exit code of the command. Unfortuntately I did not 
get the results I expected. Here is the session, using same good 
account and good password as above:


Python 2.2 (#1, Feb 21 2002, 02:25:03)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.
>>> import os
>>> p = os.popen('vauthenticate secret_test', 'w', 0)
>>> p.write('secret')
>>> p.close()
256
>>>

Now, I don't really understand these pipes and popen as well as I'd 
like, so I may well be doing something really stupid here. But, I 
certainly did not expect to get an exit code of 256 with this 
particular ACCOUNTNAME/password pair, as it returns an exit code of 
zero at the command line (and I know these are correct values for one 
of my POP accounts...).

Advice...? Please? I'd be most grateful.

Thanks,

Sheila King
http://www.thinkspot.net/sheila/








From shalehperry@attbi.com  Wed Apr  3 06:53:07 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 02 Apr 2002 22:53:07 -0800 (PST)
Subject: [Tutor] Using popen
In-Reply-To: <66DEB847507@kserver.org>
Message-ID: <XFMail.20020402225307.shalehperry@attbi.com>

> 
> 
> Python 2.2 (#1, Feb 21 2002, 02:25:03)
> [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
> Type "help", "copyright", "credits" or "license" for more 
> information.
>>>> import os
>>>> p = os.popen('vauthenticate secret_test', 'w', 0)
>>>> p.write('secret')
>>>> p.close()
> 256
>>>>
> 
> Now, I don't really understand these pipes and popen as well as I'd 
> like, so I may well be doing something really stupid here. But, I 
> certainly did not expect to get an exit code of 256 with this 
> particular ACCOUNTNAME/password pair, as it returns an exit code of 
> zero at the command line (and I know these are correct values for one 
> of my POP accounts...).
> 
> Advice...? Please? I'd be most grateful.
> 

the shell is nice and returns the real exit code to you with $?.

I copied your code into a python script and wrote the following sh script:

#!/bin/sh

read foo

exit 2

I added:

ret = p.close()
print "Return value:", ret

to your script.  Here is the output:

$ python retval.py 
Return value 512

hmm, let's try exit 1.

$ python retval.py 
Return value 256

ok, let's try exit 0.

$ python retval.py 
Return value None

ok, let's try exit 10.

$ python retval.py 
Return value 2560

and one more, exit 4.

$ python retval.py 
Return value 1024

see the pattern?  the return value is ret / 256.  If the return value was zero
then ret == None.

Hope that helps.



From urnerk@qwest.net  Wed Apr  3 04:08:51 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 2 Apr 2002 23:08:51 -0500
Subject: [Tutor] help: funny numbers
In-Reply-To: <507D1068-46B4-11D6-ADAB-00039351FE6A@mac.com>
References: <507D1068-46B4-11D6-ADAB-00039351FE6A@mac.com>
Message-ID: <E16sepQ-000872-00@mail.python.org>

> So is there a function, method, or technique that can "clean up" the
> noise, and approximate the value that we really want?  Or do we code it
> ourselves?
>
>
> Erik

Many techniques possible to get around floating point noise.
One is to code a rational number type (which some languages
include natively), which lets you work in entirely in integers 
(numerator and denominator remain separate).  Since Python 
has powerful integer capabilities, you can actually get quite 
far with this.

You can also find modules that do extended precision decimals.

However, the floating point values we talked about already 
*do* approximate the value you really want.  The difference 
is miniscule.  So for many if not all purposes, it suffices to 
do the actual computations in floating point, and then 
round/format the results to conform to two decimal digits 
or whatever it is that you want to see:

>>> a = 62.3
>>> a
62.299999999999997
>>> print '%f' % a
62.300000
>>> print '%d' % a
62

Kirby



From urnerk@qwest.net  Wed Apr  3 04:22:00 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 2 Apr 2002 23:22:00 -0500
Subject: [Tutor] creating objects in a loop
In-Reply-To: <304BF152-46B5-11D6-ADAB-00039351FE6A@mac.com>
References: <304BF152-46B5-11D6-ADAB-00039351FE6A@mac.com>
Message-ID: <E16sf29-0008W8-00@mail.python.org>

On Tuesday 02 April 2002 10:45 pm, you wrote:

> The "if __name__ == '__main__':" test -- I have seen it several times
> now.  Why is this test performed?  Isn't it obvious that __name__ is
> __main__ ?  Or am I missing something....
>
>
> Erik

The convention here is to write a module that functions as a script
if executed at the command line or clicked on, but does nothing
in particular (except maybe compile) if imported as a module -- 
until you tell it to.

For example, I might have a module which includes a function to 
draw a sine wave.  When I run it as a script, I maybe go:

>>> python sinewave.py 5 20 3

thereby passing arguments to some sine function.  The module will
be considered '__main__' (top level) when it's run in this way, so 
I'll use the code block following this condition to read the arguments 
following sinewave.py, and actually draw the corresponding sine 
wave.

But if I'm in the Python shell and go:

>>> import sinewave

or do that same import at the top of some *other* module, then 
the __name__ = '__main__' condition won't be true, and no code
will actually execute, which is good, because when I import this 
way, I'm not supplying arguments to any function and I don't want 
to actually generate a sinewave.  I'll maybe do that later, by invoking 
an internal function explicitly.

Like, when you 'import math' (import the math module) you don't 
actually want it to start spitting out math results in some out-of-control 
burst.  You just want it to sit there like an open book, offering methods 
to be triggered, if and when, e.g. at the program's disgression.

The __name__ = '__main__' code block is sometimes used to 
write tests of the module's main functions.  This is in cases where
the module is really designed to function as a module.  The only
reason you'd run it as a standalone script is precisely to invoke
these tests, which will confirm or disconfirm that everything is
working properly as far as this module is concerned.

Kirby



From Ares.liu@Clarent.com  Wed Apr  3 07:26:07 2002
From: Ares.liu@Clarent.com (Ares Liu)
Date: Wed, 3 Apr 2002 15:26:07 +0800
Subject: [Tutor] How can I convert hex string to binary string?
Message-ID: <002901c1dae0$d245be00$34461e0a@gege>

This is a multi-part message in MIME format.

------=_NextPart_000_0026_01C1DB23.E0476C40
Content-Type: text/plain;
	charset="gb2312"
Content-Transfer-Encoding: quoted-printable

such as '0A0B' to '0000101000001011' ?
is there any function or module?
=20
Regards
=20
Ares

------=_NextPart_000_0026_01C1DB23.E0476C40
Content-Type: text/html;
	charset="gb2312"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>

<META content=3D"MSHTML 6.00.2715.400" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>such as '0A0B' to '0000101000001011' =
?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>is there any function or =
module?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Regards</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Ares</FONT></DIV></BODY></HTML>

------=_NextPart_000_0026_01C1DB23.E0476C40--



From urnerk@qwest.net  Wed Apr  3 04:34:18 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 2 Apr 2002 23:34:18 -0500
Subject: [Tutor] creating objects in a loop
In-Reply-To: <A3DFF224-46B4-11D6-ADAB-00039351FE6A@mac.com>
References: <A3DFF224-46B4-11D6-ADAB-00039351FE6A@mac.com>
Message-ID: <E16sfE3-0000a8-00@mail.python.org>

On Tuesday 02 April 2002 10:41 pm, you wrote:
> On Tuesday, April 2, 2002, at 03:16  PM, Kirby Urner wrote:
> > Filing your multiple objects in a dictionary or list
> > is usually better than creating a lot of top level
> > variables in the namespace.
>
> Is this for tidiness reasons (to avoid cluttering the namespace with
> unnecessary names), or is this convention?
>
>
> Thank you,
>
> Erik

It gives you more control to store your objects in a dictionary.  
Then you can easily iterate through it, check the keys, pass 
the dictionary around among functions.  

If you stick everything in as a separately named global variable, 
then you're without the means to work with the pets as a group.
Sure, the globals are contained in a dictionary of their own, but 
the pets won't be distinguished from the globals.

At least one other respondant to this thread defined a new 
class to handle the pets, not just a dictionary.  This is certainly 
an option -- basically it depends on the application, and how 
much control you really need.

As per the Stocks example, which did the same thing as Pets, 
and BankAccounts (i.e. it stuffed individual stock instances 
into a dictionary), one advantage of having all these objects
grouped together is they're what you want to save to disk
at the end of the day -- so upon exiting, the dictionary passes 
all its contents off to shelve (a module), which updates a 
file, and everyone goes home happy.

Kirby



From urnerk@qwest.net  Wed Apr  3 04:36:51 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 2 Apr 2002 23:36:51 -0500
Subject: [Tutor] modules == class instances?
In-Reply-To: <Pine.LNX.4.44.0204021906230.20033-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0204021906230.20033-100000@hkn.eecs.berkeley.edu>
Message-ID: <E16sfGW-0000eg-00@mail.python.org>

On Tuesday 02 April 2002 10:12 pm, Danny wrote:

> Yes, modules are also "objects" in Python.  They don't support too many
> things besides allowing us to get and set attributes within them, but they
> are objects that can be tossed around quite easily and uniformly.
>

I heard a rumor that a future Python would allow us to subclass 
entire modules, as we do classes.  Was I dreaming.  I don't find
it in the list of active/open PEPs.

Kirby



From dyoo@hkn.eecs.berkeley.edu  Wed Apr  3 07:44:28 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 2 Apr 2002 23:44:28 -0800 (PST)
Subject: [Tutor] How can I convert hex string to binary string?
In-Reply-To: <002901c1dae0$d245be00$34461e0a@gege>
Message-ID: <Pine.LNX.4.44.0204022342030.26809-100000@hkn.eecs.berkeley.edu>


On Wed, 3 Apr 2002, Ares Liu wrote:

> such as '0A0B' to '0000101000001011' ?
> is there any function or module?

Not directly.  There is a function called int() that can convert something
like the string '0A0B' into an integer:

###
>>> int('0A0B', 16)
2571
###

So your problem can be simplified to figuring out how to convert a regular
integer into a binary string.


If you have more questions, please feel free to bring them up to Tutor.
Good luck!




From sheila@thinkspot.net  Wed Apr  3 07:56:21 2002
From: sheila@thinkspot.net (Sheila King)
Date: Tue, 2 Apr 2002 23:56:21 -0800
Subject: [Tutor] Using popen
In-Reply-To: <XFMail.20020402225307.shalehperry@attbi.com>
Message-ID: <3D07DE3389@kserver.org>

On Tue, 02 Apr 2002 22:53:07 -0800 (PST), Sean 'Shaleh' Perry wrote:

> > Python 2.2 (#1, Feb 21 2002, 02:25:03)
> > [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
> > Type "help", "copyright", "credits" or "license" for more
> > information.
> > > > > import os p = os.popen('vauthenticate secret_test', 'w', 0)
> > > > > p.write('secret')
> > > > > p.close()
> > 256
> >
> > Now, I don't really understand these pipes and popen as well as
> > I'd like, so I may well be doing something really stupid here.
> > But, I certainly did not expect to get an exit code of 256 with
> > this particular ACCOUNTNAME/password pair, as it returns an exit
> > code of zero at the command line (and I know these are correct
> > values for one of my POP accounts...).
> >
> > Advice...? Please? I'd be most grateful.

> the shell is nice and returns the real exit code to you with $?.
> I copied your code into a python script and wrote the following sh
> script:
>
> #!/bin/sh
> read foo
> exit 2
>
> I added:
>
> ret = p.close()
> print "Return value:", ret
>
> to your script.  Here is the output:
>
> $ python retval.py Return value 512
>
> hmm, let's try exit 1.
>
>
> $ python retval.py Return value 256
>
> ok, let's try exit 0.
>
>
> $ python retval.py Return value None
>
> ok, let's try exit 10.
>
>
> $ python retval.py Return value 2560
>
> and one more, exit 4.
>
>
> $ python retval.py Return value 1024
>
> see the pattern?  the return value is ret / 256.  If the return
> value was zero then ret == None.

That's helpful, Sean, yes. However, I still don't understand even in 
this case, why I got a return of 256. I should have gotten None. At 
least, that command in the shell returns an exit code of zero with 
the data I tested. Shouldn't it return the same result in Python with 
popen? (i.e. in case of exitcode = 0, popen.close() should return 
None.)

Still confused...

Sheila King
http://www.thinkspot.net/sheila/






From alex@gabuzomeu.net  Wed Apr  3 08:09:46 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 03 Apr 2002 10:09:46 +0200
Subject: [Tutor] creating objects in a loop
In-Reply-To: <304BF152-46B5-11D6-ADAB-00039351FE6A@mac.com>
References: <4.3.2.7.2.20020402235324.00b76d90@pop3.norton.antivirus>
Message-ID: <4.3.2.7.2.20020403100105.00b7c3e0@pop3.norton.antivirus>

Hi Erik,


At 22:45 02/04/2002 -0500, Erik Price wrote:
>>if __name__ == "__main__":
>>     cat = factory(Pets, "fluffy")
>>     print cat
>
>The "if __name__ == '__main__':" test -- I have seen it several times 
>now.  Why is this test performed?  Isn't it obvious that __name__ is 
>__main__ ?  Or am I missing something....

__name__ only has the value "__main__" when the code is run as a standalone 
module. This is handy for testing: you can add test code in this section 
and it only runs when you launch execution from *this* module. If you just 
import your classes or functions into another module, the test code does 
not run.

>Erik
>
>PS:  I truly am sorry that I have so many questions,

Don't be and ask away; this is what this list is meant for :-)

>but the more I learn the more I realize I don't know a lot of things.

Same here.


Cheers.

Alexandre





From Ares.liu@Clarent.com  Wed Apr  3 08:17:48 2002
From: Ares.liu@Clarent.com (Ares Liu)
Date: Wed, 3 Apr 2002 16:17:48 +0800
Subject: [Tutor] How can I convert hex string to binary string?
References: <Pine.LNX.4.44.0204022342030.26809-100000@hkn.eecs.berkeley.edu>
Message-ID: <003101c1dae8$0a815340$34461e0a@gege>

Thank you very much.

I've got it.
#
# hex2bin
#
def hex2bin(str):
   bin = ['0000','0001','0010','0011',
         '0100','0101','0110','0111',
         '1000','1001','1010','1011',
         '1100','1101','1110','1111']
   aa = ''
   for i in range(len(str)):
      aa += bin[atoi(str[i],base=16)]
   return aa
# End
>>>hex2bin('0a0b')
'0000101000001011'
#
Regards

Ares
----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Ares Liu" <Ares.liu@Clarent.com>
Cc: <tutor@python.org>
Sent: Wednesday, April 03, 2002 3:44 PM
Subject: Re: [Tutor] How can I convert hex string to binary string?


>
>
> On Wed, 3 Apr 2002, Ares Liu wrote:
>
> > such as '0A0B' to '0000101000001011' ?
> > is there any function or module?
>
> Not directly.  There is a function called int() that can convert something
> like the string '0A0B' into an integer:
>
> ###
> >>> int('0A0B', 16)
> 2571
> ###
>
> So your problem can be simplified to figuring out how to convert a regular
> integer into a binary string.
>
>
> If you have more questions, please feel free to bring them up to Tutor.
> Good luck!



From printers@sendme.cz  Wed Apr  3 08:33:31 2002
From: printers@sendme.cz (A)
Date: Wed, 3 Apr 2002 10:33:31 +0200
Subject: [Tutor] How to check whether email /domain exists
Message-ID: <3CAADA7B.25443.509AE1@localhost>

Hello,
What is the simplest way how to check 
 whether a given email address( or domain for this email) exists?
Thanks for help

Ladislav




From alex@gabuzomeu.net  Wed Apr  3 08:41:49 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 03 Apr 2002 10:41:49 +0200
Subject: [Tutor] Python + HTTP?
In-Reply-To: <E16sc50-00014N-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020403101911.00b7ab10@pop3.norton.antivirus>

Hi Rohan,


At 23:09 02/04/2002 -0500, you wrote:
>Date: Tue, 2 Apr 2002 21:17:31 -0500
>From: Rohan Deshpande <rdzx@myrealbox.com>
>Subject: [Tutor] Python + HTTP?

>I've just read through the tutorial for Python on the www.python.org
>website, and I was just wondering where one should go to learn more
>about HTTP programming with python.  Basically, I want to be able to
>post data using user input, and then get files from websites and parse
>them.  Any tips?

Take a look at this doc:

"Writing Web Client-Side Applications in Python", Moshe Zadka

http://www.python9.org/p9-zadka.ppt

I remember I found interesting hints and code examples in this presentation.


Cheers.

Alexandre




From urnerk@qwest.net  Wed Apr  3 05:46:14 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 3 Apr 2002 00:46:14 -0500
Subject: [Tutor] How can I convert hex string to binary string?
In-Reply-To: <003101c1dae8$0a815340$34461e0a@gege>
References: <Pine.LNX.4.44.0204022342030.26809-100000@hkn.eecs.berkeley.edu> <003101c1dae8$0a815340$34461e0a@gege>
Message-ID: <E16sgLf-000496-00@mail.python.org>

On Wednesday 03 April 2002 03:17 am, Ares Liu wrote:
> def hex2bin(str):
>    bin = ['0000','0001','0010','0011',
>          '0100','0101','0110','0111',
>          '1000','1001','1010','1011',
>          '1100','1101','1110','1111']
>    aa = ''
>    for i in range(len(str)):
>       aa += bin[atoi(str[i],base=16)]
>    return aa

Good one.  Use of list index to access pre-computed strings, vs.
actually computing base 2 values over and over, seems a good
idea.

Slightly simpler (style point: best to not use str as a variable name,
as it's also a built-in function):

#
# hex2bin
#
def hex2bin(hexno):
   bin = ['0000','0001','0010','0011',
         '0100','0101','0110','0111',
         '1000','1001','1010','1011',
         '1100','1101','1110','1111']
   base2 = ''
   for d in hexno:
      base2 += bin[int(d,base=16)]
   return base2

Kirby



From alex@gabuzomeu.net  Wed Apr  3 08:45:51 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 03 Apr 2002 10:45:51 +0200
Subject: [Tutor] creating objects in a loop
In-Reply-To: <E16sc50-00014N-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020403103037.00b79ba0@pop3.norton.antivirus>

At 23:09 02/04/2002 -0500, you wrote:
>Date: Tue, 2 Apr 2002 22:41:11 -0500
>Subject: Re: [Tutor] creating objects in a loop
>From: Erik Price <erikprice@mac.com>
>
>On Tuesday, April 2, 2002, at 03:16  PM, Kirby Urner wrote:
>
> > Filing your multiple objects in a dictionary or list
> > is usually better than creating a lot of top level
> > variables in the namespace.
>
>Is this for tidiness reasons (to avoid cluttering the namespace with
>unnecessary names), or is this convention?

In my understanding, this is for tidiness. It will help avoiding name 
clashes that might create bugs in your program. If several methods / 
functions modify a global variable, you may find it difficult to know what 
its current status is.

[Terminology note: is this what programmers call "side effects"?]


Cheers.

Alexandre




From shalehperry@attbi.com  Wed Apr  3 08:52:01 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 03 Apr 2002 00:52:01 -0800 (PST)
Subject: [Tutor] Using popen
In-Reply-To: <3D07DE3389@kserver.org>
Message-ID: <XFMail.20020403005201.shalehperry@attbi.com>

 
> That's helpful, Sean, yes. However, I still don't understand even in 
> this case, why I got a return of 256. I should have gotten None. At 
> least, that command in the shell returns an exit code of zero with 
> the data I tested. Shouldn't it return the same result in Python with 
> popen? (i.e. in case of exitcode = 0, popen.close() should return 
> None.)
> 
> Still confused...
> 

one can only assume that the authenticate script is unhappy for some reason. 
If you have the source, consider adding some print statements which get logged
to a file.  Look for any 'exit 1' type lines, and see why you would get there.



From alan.gauld@bt.com  Wed Apr  3 11:00:10 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 12:00:10 +0100
Subject: [Tutor] Linux databases
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4E9@mbtlipnt02.btlabs.bt.co.uk>

> > Source but I highly recommend Borland's Interbase. 
> 
> When recommending databases, please specify whether or not they are:
> 1) relational (in the true Codd & Date sense)

Yes, fully relational. Main cometitor has been Informix.

> 2) what part(s) of the ANSI SQL standard it conforms to. 

1992 standard with extensions for stored procedures 
and event handling.

> After all, there's people who think Access is a database.

:-)

> Oracle, Sybase, Informix, DB2, Solid

Its in this category. Interbase sells for several hundred 
dollars on NT, Solaris etc but is(was?) free(as in beer) 
on Linux. It's what they ship with Delpi, CBuilder etc.

I use version 5 on NT and 4 on Linux, I think there's a 
v6 too. They "support" Red Hat and Cobolt Servers but 
it does run on other distros. There's a very active 
discussion group on the Borland news site.

Product details:

http://www.borland.com/interbase/

In fact I just checked and v6.5 is now Open Source 
on sourceforge!

http://sourceforge.net/projects/interbase

Interbase is IMHO Borland's best kept secret.

Alan g.



From alan.gauld@bt.com  Wed Apr  3 11:02:19 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 12:02:19 +0100
Subject: [Tutor] command line
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4EA@mbtlipnt02.btlabs.bt.co.uk>

>  By the way, I've been meaning to promote what I consider an
> excellent background essay on all this:  'In the Beginning Was
> the Command Line' by Neal Stephenson, 
> Here it is on-line:
> http://www.spack.org/words/commandline.html

I'll back this recommendation, its a great read - but long....

Alan g.



From alan.gauld@bt.com  Wed Apr  3 11:18:58 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 12:18:58 +0100
Subject: [Tutor] command line
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4ED@mbtlipnt02.btlabs.bt.co.uk>

> > for user defined classes), graphical debuggers - "a sop
> > to those who don't understand their own code" - to quote
> > one seasoned hack...
> I think we're seeing more of an age-old pattern:  pioneers 
> develop a rustic, effective lifestyle, close to the elements,
> They're amazingly competent, with minimalist tools.

Theres almost certainly an element of that but its not 
the whole story.

> and cold running water -- they expect, nay demand, what look 
> to the pioneers like unnecessary luxuries 

But the "pioneers" in this case are soimply more productive 
with their primitive techniques. In fact they are far from 
primitive and most of them drive their editors(vim or emacs 
almost exclusively) to thev limit in search of efficiency 
- after all they get paid by results.

Certainly newer programmers using the modern GUI/IDE type tools 
are invariavbly slower and less productive.

I guess the real test will be in ten years time when the 
current generation have acquired the same length of 
experience, will they have increased to the same (or better?)
level of output as the by then retiring coders of today?

Alan g.



From phil@xfr.co.uk  Wed Apr  3 11:22:20 2002
From: phil@xfr.co.uk (Philip Kilner)
Date: Wed, 03 Apr 2002 12:22:20 +0100
Subject: [Tutor] Linux databases
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4E9@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4E9@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <VA.00000269.04367396@xfr.co.uk>

Hi Alan,

(And thanks for the book, BTW!)

In article 
<5104D4DBC598D211B5FE0000F8FE7EB20E66C4E9@mbtlipnt02.btlabs.bt.co.uk>,  
wrote:
> Product details:
> 
> http://www.borland.com/interbase/
> 
> In fact I just checked and v6.5 is now Open Source 
> on sourceforge!
> 
> http://sourceforge.net/projects/interbase
> 
> Interbase is IMHO Borland's best kept secret.
>

I can't let this go without pointing out Firebird - the other, arguably 
more-open-source, fork of InterBase development: -

   http://firebird.sourceforge.net/
   
   http://www.cvalde.com/
   
HTH!

Cheers,

PhilK





From alan.gauld@bt.com  Wed Apr  3 11:39:58 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 12:39:58 +0100
Subject: [Tutor] RE: OOP purpose
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4EF@mbtlipnt02.btlabs.bt.co.uk>

> What is the purpose of OOP?  

To make programnming of large projects easier, 
to make the building of reusable components easier,
to make comprehension of program design easier,
to make code more reliable(debateable!)

> Why  would you use it instead of just modular 
> design?  

Its more extensible via inheritance for a start.

> I am having trouble finding the need to use it in my 
> projects.

You never *need* to use OOP. Anything you can do in 
OOP can be done without it. OOP just makes many 
things easier. Compare using string methods in Python 
against importing the string module and using the 
string functions.

Most GUIs are implemented in OOP terms because GUI 
widgets have a natural conceptual linkage to being 
objects.

OOP does take some time to adjust to however - estimates 
vary from 6 months to 2 years for an experienced 
procedural programmer.

Beginners are supposed to pick it up faster because to 
them the concept of asking a table to move across a 
room is more obvious than the idea of moving a table 
data item by explicitly changing its X and Y coordinates...

Theres lots more to be said (and most of it has been already!)
and a browse of the cetus-links web site is a good place 
to start...

But don't get hung up on OOP, it's not the final word in 
programming nor is it even the best approach in every case.

Alan G.



From erikprice@mac.com  Wed Apr  3 12:23:11 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 3 Apr 2002 07:23:11 -0500
Subject: [Tutor] command line
In-Reply-To: <E16sYmo-0007hT-00@mail.python.org>
Message-ID: <904BD497-46FD-11D6-BA3D-00039351FE6A@mac.com>

On Monday, April 1, 2002, at 11:23  PM, Kirby Urner wrote:

> By the way, I've been meaning to promote what I consider an
> excellent background essay on all this:  'In the Beginning Was
> the Command Line' by Neal Stephenson, a good writer.  He
> covers a lot of recent history, and without obnoxiously
> getting on a narrow-perspective soap box.

Almost three years ago to the day, I first read this essay.  I was in my 
second-to-last year of my undergrad, with the grades and ambition to 
head off to graduate school to pursue my quest of being a professional 
student (cultural studies) for the rest of my life.  Although I had used 
computers all my life, I didn't really know anything about them.

Infectious, that essay took root in my mind and didn't let go -- because 
of that essay, I never ended up going to grad school, I started learning 
Linux, and decided I wanted to become a web developer.

There are few objects in our lives that we can point to and say "this 
had a profound and life-changing effect on me", but for me that essay is 
one of them.


Erik




From erikprice@mac.com  Wed Apr  3 12:32:35 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 3 Apr 2002 07:32:35 -0500
Subject: [Tutor] RE: OOP purpose
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4EF@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <E0715B48-46FE-11D6-BA3D-00039351FE6A@mac.com>

On Wednesday, April 3, 2002, at 06:39  AM, alan.gauld@bt.com wrote:

> OOP does take some time to adjust to however - estimates
> vary from 6 months to 2 years for an experienced
> procedural programmer.
>
> Beginners are supposed to pick it up faster because to
> them the concept of asking a table to move across a
> room is more obvious than the idea of moving a table
> data item by explicitly changing its X and Y coordinates...
>
> Theres lots more to be said (and most of it has been already!)
> and a browse of the cetus-links web site is a good place
> to start...
>
> But don't get hung up on OOP, it's not the final word in
> programming nor is it even the best approach in every case.

Wolf,

I found two extremely helpful resources in understanding OO a little bit 
better (but this was just the other day, I am no expert):

(1) Check the archives, this past weekend someone posted a question 
about how to use objects to keep track of stocks.  Kirby Urner posted a 
class that made total sense to me.  I saved a copy of it if you want I 
can post it again (I commented it, and Kirby gave me feedback on the 
comments, so it should be helpful).

(2) But the class itself doesn't really explain some of the 
fundamentals -- I found the following two-part tutorial to be helpful in 
explaining those:
well, DevShed's site is under severe load I guess so I can't get the 
exact link.  I got this one from Google, but check and make sure that it 
is the first of a two-part introduction to Object Oriented programming 
with Python:  
http://www.devshed.com/Server_Side/Python/OOPWithPython/OOPWithPython2

I recommend reading the introduction (takes about 20 minutes including 
the time it takes to do the exercise using clockclass.py) and then 
taking a look at the more advanced Stocks.py .   Note that these two 
resources really require some basic Python experience to make sense of 
(or at least, for me I wouldn't have "gotten it" if I didn't already 
know something about Python).


Good luck,

Erik




From erikprice@mac.com  Wed Apr  3 12:32:52 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 3 Apr 2002 07:32:52 -0500
Subject: [Tutor] creating objects in a loop
In-Reply-To: <200204030718.g337IHn7016602@smtpin02.mac.com>
Message-ID: <EAD42D40-46FE-11D6-BA3D-00039351FE6A@mac.com>

On Tuesday, April 2, 2002, at 11:22  PM, Kirby Urner wrote:

> or do that same import at the top of some *other* module, then
> the __name__ = '__main__' condition won't be true, and no code
> will actually execute, which is good, because when I import this
> way, I'm not supplying arguments to any function and I don't want
> to actually generate a sinewave.  I'll maybe do that later, by invoking
> an internal function explicitly.

I see.  It hadn't crossed my mind that you might have a script that is 
useful both as an executable and as a library of code.  So this test 
lets you put executable code into a "protected" area that only runs if 
the script is run as a script, and not imported (because an import will 
automatically execute all code that is -not- protected in this fashion, 
won't it).  I understand now.

> The __name__ = '__main__' code block is sometimes used to
> write tests of the module's main functions.  This is in cases where
> the module is really designed to function as a module.  The only
> reason you'd run it as a standalone script is precisely to invoke
> these tests, which will confirm or disconfirm that everything is
> working properly as far as this module is concerned.

I see -- another, different use for this test.  You put "echo value" or 
something in the if __name__ = "__main__" to make sure that the function 
is declared properly, or the value was indeed created.

Are tests like this native to Python?  I mean, I understand that these 
names may be unique to Python, but do people use similar techniques to 
this in Java and C?


Erik




From alan.gauld@bt.com  Wed Apr  3 12:42:30 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 13:42:30 +0100
Subject: [Tutor] enumeration in C++
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4F0@mbtlipnt02.btlabs.bt.co.uk>

> What's enumeration  good for? 

> but never found out its purpose.

One thing I use it for extensively is creating unique error codes:

enum errorcodes = {
	CriticalError = 1,
      LessCritical,
      Warning,
      BadInput,
      BadOutput,
      BadUser,
      BadDog,
      }

Now the codes are automatically given unique values starting at 1.
I could achieve the same with #defines:

#define	CriticalError 1
# define    LessCritical CriticalError + 1
etc....

#define	BadDog BadUser+1

But when the compiler tries to grok those it expands the 
values so that the last one actually looks like 1+1+1+1+1+1....+1
Hopefully the optimiser will do the arithmetic but its still ugly.
Also by using an enum we get typechecking and flagging of 
invalid names(spelling mistakes etc)

There are a bunch of other things too, but C/C++ enums are not
as well behaved as, say Pascal, where defining an enum limits 
the range. In C you can hard code an invalid value to a 
variable holding an enum because C treats it pretty much 
like any other int!

HTH,

Alan g.



From scot@possum.in-berlin.de  Wed Apr  3 11:22:09 2002
From: scot@possum.in-berlin.de (Scot Stevenson)
Date: Wed, 3 Apr 2002 13:22:09 +0200
Subject: [Tutor] How can I convert hex string to binary string?
In-Reply-To: <002901c1dae0$d245be00$34461e0a@gege>
References: <002901c1dae0$d245be00$34461e0a@gege>
Message-ID: <200204031129.g33BT7S27915@possum.cozen.org>

Hello Ares, 

> such as '0A0B' to '0000101000001011' ?
> is there any function or module?

If I remember my binary math, each hex numeral (0 to F, that is) has an 
equivalent four digit binary number (0000 to 1111), so that

Hex - Bin

0	0000
2	0010
3	0011
...
E	1110
F	1111

So all you should have to do is a) make a dictionary with something of the 
sort of

convert = {'0': '0000', '1': '0001', '2': '0010', ....}

and b) go thru all letters in the string and string their bin values 
together: 

This seems to work for me:

========================================

convert = {'0': '0000', '1': '0001', '2': '0010', '3': '0011',
           '4': '0100', '5': '0101', '6': '0110', '7': '0111',
           '8': '1000', '9': '1001', 'A': '1010', 'B': '1011',
           'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}

hexstring = '38CF'   # our example
binstring = ''

for hexletter in hexstring:
    binstring = binstring + convert[hexletter]

print binstring

==========================================

Y, Scot



From alan.gauld@bt.com  Wed Apr  3 12:53:58 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 13:53:58 +0100
Subject: [Tutor] creating objects in a loop
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4F1@mbtlipnt02.btlabs.bt.co.uk>

> and I want to do the following:
> 
> >>> cat = Pets('fluffy')
> >>> dog = Pets('fido')
> >>> gorilla = Pets('spike')
> 
> Right now, I can use
> 
> >>> for species,name in petlist:
> ...   exec("%s = Pets('%s')" % (species, name))

Try a dictionary:

pets = {}
for species,name in petlist:
   pets[species] = Pets(name)

Then access them like:

print pets['cat'].name

Alan G.



From ak@silmarill.org  Wed Apr  3 14:09:00 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Wed, 3 Apr 2002 09:09:00 -0500
Subject: [Tutor] OOP purpose
In-Reply-To: <F49Tzof3kckIRyy4bJN0000ede5@hotmail.com>
References: <F49Tzof3kckIRyy4bJN0000ede5@hotmail.com>
Message-ID: <20020403140900.GA5743@ak.silmarill.org>

On Tue, Apr 02, 2002 at 12:16:48PM -0600, Cameron Stoner wrote:
> Hi all,
> 
> What is the purpose of OOP?  Why  would you use it instead of just modular 
> design?  I am having trouble finding the need to use it in my projects.
>
To sum it up, OOP makes it easier to write and change programs in many
cases. Don't push it on yourself, though - I tried to do that when
I began learning python and I could never make sense of it but it sort
of came with practice a bit later.

Don't use it until you feel some particular task calls for OOP. Then
it'll fall into place. On the other hand, I hear some people code for
decades and still don't feel OOP is useful, so it may be a matter of
personal taste.
> 
> Thanks,
> 
> Cameron Stoner
> 
> _________________________________________________________________
> MSN Photos is the easiest way to share and print your photos: 
> http://photos.msn.com/support/worldwide.aspx
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From bwinton@tor.dhs.org  Wed Apr  3 14:45:04 2002
From: bwinton@tor.dhs.org (Blake Winton)
Date: Wed, 3 Apr 2002 09:45:04 -0500
Subject: [Tutor] creating objects in a loop
In-Reply-To: <EAD42D40-46FE-11D6-BA3D-00039351FE6A@mac.com>
References: <200204030718.g337IHn7016602@smtpin02.mac.com> <EAD42D40-46FE-11D6-BA3D-00039351FE6A@mac.com>
Message-ID: <20020403094504.A23465@tor.dhs.org>

* Erik Price <erikprice@mac.com> [020403 07:32]:
> I see -- another, different use for this test.  You put "echo value"
> or something in the if __name__ = "__main__" to make sure that the
> function is declared properly, or the value was indeed created.
> 
> Are tests like this native to Python?  I mean, I understand that
> these names may be unique to Python, but do people use similar
> techniques to this in Java and C?

In the olden days, I used to write a "main" method in all my
Java classes which would run some simple unit tests.  Then I found
JUnit (a unit testing framework for Java), and now I just write all my
unit tests in a separate class, and I don't have the main method
anymore.

So, for Java, yeah.  For C/C++, I haven't seen anything similar.

Later,
Blake.
-- 
9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07



From alan.gauld@bt.com  Wed Apr  3 15:59:05 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 16:59:05 +0100
Subject: [Tutor] help: funny numbers
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4F6@mbtlipnt02.btlabs.bt.co.uk>

> So is there a function, method, or technique that can "clean up" the 
> noise, and approximate the value that we really want?  Or do 
> we code it ourselves?

You have to separate Pythons internal representatoon 
- which aims for maximum accuracy and the display of
that value - which is for human consumption.

In the latter case format strings are your friend.
You can format a floating point value pretty much 
anyway you like using format string codes:

>>> i = 66.6
>>> i
66.599999999999994
>>> print "%e" % i
6.660000e+001
>>> print "%f" % i
66.600000
>>> print "%3.4f" % i
66.6000
>>> print "%g" % i
66.6

There are functions to do some rounding etc too but usually 
its the display you want to affect not the stored value...

Alan g.



From alan.gauld@bt.com  Wed Apr  3 16:01:27 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 17:01:27 +0100
Subject: [Tutor] creating objects in a loop
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4F7@mbtlipnt02.btlabs.bt.co.uk>

> Is this for tidiness reasons (to avoid cluttering the namespace with 
> unnecessary names), or is this convention?

Tidiness mainly but it also means you can pass the whole 
object list to another namespace if needed. eg a utility 
module function.

Creating the names at the global level can be limiting 
in terms of visibility despite the name global!

Alan G.



From alan.gauld@bt.com  Wed Apr  3 16:11:30 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 17:11:30 +0100
Subject: [Tutor] creating objects in a loop
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4F8@mbtlipnt02.btlabs.bt.co.uk>

> The "if __name__ == '__main__':" test -- I have seen it several times 
> now.  Why is this test performed?  Isn't it obvious that __name__ is 
> __main__ ?  Or am I missing something....

The name is only __main__ when its the top level script. 
If the file is being imported by anither file then it 
will have its name set to the module name.

ie If we have modules spam and eggs where spam imports eggs
spam  creates a function s() and eggs a function e().

#### eggs.py
def e(): print 'eggs'

if __name__ == "__main__": e()


#### spam.py
import eggs

def s(): 
	print spam
	print eggs.__name__

if __name__ == "__main__": s()

##############

Now if we run 
$ python spam.py

Its name will be __main__ but egg's name will be eggs.
We see:

spam
eggs

If we run 

$ python eggs.py

Now its name will be __main__ and we see:

eggs


Thus Python provides us with the means to use the 
same file as both a program that can be run or a 
module that can be imported with no bad effects.

Alan G.



From alan.gauld@bt.com  Wed Apr  3 16:19:26 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 17:19:26 +0100
Subject: [Tutor] How can I convert hex string to binary string?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4F9@mbtlipnt02.btlabs.bt.co.uk>

>    for i in range(len(str)):
>       aa += bin[atoi(str[i],base=16)]

Since strings are sequences you only need:

    for c in str:
       aa += bin[atoi(c,base=16)]


Alan G.



From alan.gauld@bt.com  Wed Apr  3 16:23:28 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 3 Apr 2002 17:23:28 +0100
Subject: [Tutor] creating objects in a loop
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C4FA@mbtlipnt02.btlabs.bt.co.uk>

> functions modify a global variable, you may find it difficult 
> to know what its current status is.
> 
> [Terminology note: is this what programmers call "side effects"?]

Pretty much. When a function does something unexpected 
to something outside the function and its arguments 
then its a side effect. Since the thing outside the 
function is most likely a global variable you are correct.

Alan g.



From alex@gabuzomeu.net  Wed Apr  3 18:39:36 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 03 Apr 2002 20:39:36 +0200
Subject: [Tutor] Strange namespace issue
Message-ID: <4.3.2.7.2.20020403195218.00b782a0@pop3.norton.antivirus>

Hello,


I ran into this strange issue a couple of days ago. I'd be grateful if 
someone could explain it. Sorry for this long, rambling account; I tried to 
make it as clear as possible.

I wanted to parse a string into a tree for later processing. I created this 
class (based on the Trees chapter of "How to think like a computer 
scientist"). It defines a "multiple" tree, eg. a tree whose nodes can have 
several subnodes.

Here is the 1st version:

class TreeNode:
     "Node to build multiple trees."

     def __init__(self, cargo = None, nodeList = []):
         self.cargo = cargo
         self.nodeList = nodeList

     def addNode(self, node):
         "Add a TreeNode instance to the child node list."
         if node:
             self.nodeList.append(node)

     def __getitem__(self, index):
         "Return a child node."
         return self.nodeList[index]
...

I used another class to recursively cut a text snippet into pieces and 
store them in tree nodes, thus building a tree. Here is a short except of 
the main parsing method. The point I want to make is that I invoked the 
class using "node = TreeNode(someCargoObject)"; eg. I did not pass a list 
argument when creating a node instance. Then I appended the new node to the 
current tree node.

     def doParse(self, patternList, tree, workText):
         "Recursively parse wiki formatting into a tree."
...
                     pattern = NullPattern(textBefore)
                     node = TreeNode(pattern)
                     tree.addNode(node)
                     self.doParse(patternList[:-1], node, textBefore)

When trying to print out the tree content, I ran into an endless loop. Here 
is the printing code (I eventually added a test to break out of the loop 
before I had to forcefully close PythonWin :-).

testDict = {}

def printTree(tree, level = 0):
     if not tree:
         return
     print "  " * level + "|_", [str(tree.cargo)]
     for node in tree:
         if testDict.has_key(id(node)):
             print id(node), str(node)
             raise "Duplicated Node Error"
         else:
             testDict[id(node)] = None
         printTree(node, level + 1)

The tree looked OK (eg. I printed out the id for every node and it looked 
sane). After a long fight, I realised that all nodes used a common nodeList 
instance (with the same id)...

When I rewrote the __init__ method, the problem went away:

     def __init__(self, cargo = None, nodeList = None):
         "Initialise the node instance."
         self.cargo = cargo
         if nodeList:
             self.nodeList = nodeList
         else:
             self.nodeList = []

And now I get to my query: when I wrote...

     def __init__(self, cargo = None, nodeList = []):
         self.cargo = cargo
         self.nodeList = nodeList

... I expected self.nodeList to be initialised to a new, empty list if the 
constructor was called without a nodeList argument. Somehow it failed. I 
had to use "nodeList = None" in the argument list and then to specify 
"self.nodeList = []" to initialise the list properly.

What did I miss? Is this the normal behaviour?

This happened on WinNT 4 with Python 2.1.2. I can upload the complete code 
somewhere if needed.


Many thanks.

Alexandre




From Ace2336@aol.com  Wed Apr  3 19:11:15 2002
From: Ace2336@aol.com (Ace2336@aol.com)
Date: Wed, 3 Apr 2002 14:11:15 EST
Subject: [Tutor] (no subject)
Message-ID: <f4.19566d23.29dcadd3@aol.com>

--part1_f4.19566d23.29dcadd3_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

Please stop sending me emails.  :(

--part1_f4.19566d23.29dcadd3_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

<HTML><FONT FACE=arial,helvetica><FONT  SIZE=2 FAMILY="SANSSERIF" FACE="Arial" LANG="0">Please stop sending me emails.&nbsp; :(</FONT></HTML>

--part1_f4.19566d23.29dcadd3_boundary--



From scarblac@pino.selwerd.nl  Wed Apr  3 19:15:29 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Wed, 3 Apr 2002 21:15:29 +0200
Subject: [Tutor] Strange namespace issue
In-Reply-To: <4.3.2.7.2.20020403195218.00b782a0@pop3.norton.antivirus>; from alex@gabuzomeu.net on Wed, Apr 03, 2002 at 08:39:36PM +0200
References: <4.3.2.7.2.20020403195218.00b782a0@pop3.norton.antivirus>
Message-ID: <20020403211529.A29521@pino.selwerd.nl>

On  0, Alexandre Ratti <alex@gabuzomeu.net> wrote:

(snipped a lot)

> class TreeNode:
>      "Node to build multiple trees."
> 
>      def __init__(self, cargo = None, nodeList = []):
>          self.cargo = cargo
>          self.nodeList = nodeList

(mutables as default argument are a problem)

> When I rewrote the __init__ method, the problem went away:
> 
>      def __init__(self, cargo = None, nodeList = None):
>          "Initialise the node instance."
>          self.cargo = cargo
>          if nodeList:
>              self.nodeList = nodeList
>          else:
>              self.nodeList = []

This is the standard solution, more generically spelled:

def __init__(self, cargo=None, nodeList=None):
   "Initialise the node instance"
   if nodeList is None: nodeList = []
   
   self.cargo=cargo
   self.nodeList=nodeList

> ... I expected self.nodeList to be initialised to a new, empty list if the 
> constructor was called without a nodeList argument. Somehow it failed. I 
> had to use "nodeList = None" in the argument list and then to specify 
> "self.nodeList = []" to initialise the list properly.
> 
> What did I miss? Is this the normal behaviour?

Yes, it is normal. The default argument is evaluated at the moment that the
function is defined. So at the moment you define the class, with the
function definition in it, the expression "[]" is evaluated, and it returns
a list. This list is then used as the default for the function argument.

That list! It will always be the same object.

The FAQ explains this in different words,
http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.025.htp

This bites you once and then you remember it. Don't use mutable default
arguments. Use None, and a test for "if argument is None: argument=[]" at
the top of a function.

-- 
Remco Gerlich



From scarblac@pino.selwerd.nl  Wed Apr  3 19:26:55 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Wed, 3 Apr 2002 21:26:55 +0200
Subject: In reply to Ace2336@aol.com Re: [Tutor] (no subject)
In-Reply-To: <f4.19566d23.29dcadd3@aol.com>; from Ace2336@aol.com on Wed, Apr 03, 2002 at 02:11:15PM -0500
References: <f4.19566d23.29dcadd3@aol.com>
Message-ID: <20020403212655.A29598@pino.selwerd.nl>

On  0, Ace2336@aol.com wrote:
> Please stop sending me emails.  :(

You must unsubscribe yourself, we can't do that for you.

Go to http://mail.python.org/mailman/options/tutor/ace2336--at--aol.com and
unsubscribe.


-- 
Remco Gerlich



From dyoo@hkn.eecs.berkeley.edu  Wed Apr  3 20:25:28 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 3 Apr 2002 12:25:28 -0800 (PST)
Subject: [Tutor] Using popen
In-Reply-To: <3D07DE3389@kserver.org>
Message-ID: <Pine.LNX.4.44.0204031206570.7983-100000@hkn.eecs.berkeley.edu>

On Tue, 2 Apr 2002, Sheila King wrote:

> On Tue, 02 Apr 2002 22:53:07 -0800 (PST), Sean 'Shaleh' Perry wrote:
>
> > > Python 2.2 (#1, Feb 21 2002, 02:25:03)
> > > [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
> > > Type "help", "copyright", "credits" or "license" for more
> > > information.
> > > > > > import os p = os.popen('vauthenticate secret_test', 'w', 0)
> > > > > > p.write('secret')
> > > > > > p.close()
> > > 256
> > >
> > > Now, I don't really understand these pipes and popen as well as
> > > I'd like, so I may well be doing something really stupid here.
> > > But, I certainly did not expect to get an exit code of 256 with
> > > this particular ACCOUNTNAME/password pair, as it returns an exit
> > > code of zero at the command line (and I know these are correct

The reason for the wackiness is because the return value of os.popen()
actually contains more than the "errorcode" of the executed program.
os.popen() packs _two_ values into one integer, so here's a case where we
actually need to do some bit manipulation!


This bit packing is what the documentation is trying vaguely to imply when
they say something about "The exit status of the command (encoded in the
format specified for wait())".


Let's take a look at the wait() documentation:

"""
wait ()
Wait for completion of a child process, and return a tuple containing its
pid and exit status indication: a 16-bit number, whose low byte is the
signal number that killed the process, and whose high byte is the exit
status (if the signal number is zero); the high bit of the low byte is set
if a core file was produced. (Not on MS-DOS.)
"""



So the value that the close() returns is actually a combination of the
"exit status" that we're looking for, along with a "signal" number.  And
to get the true exit status, we'll want to grab the high byte.  One way to
do this is to just push the signal number part right off by using bitwise
right shifting:

###
>>> 256 >> 8
1
###

That is, just shift the number by 8 bits.  What's left is the return value
that we're looking for.  (By the way, this bit shift is equivalent to what
Sean was doing with the modulo 255 arithmetic.)


You're actually getting an exit code of 1, so your program may be
signalling an error of some sort.

Hope this helps!





From dyoo@hkn.eecs.berkeley.edu  Wed Apr  3 20:26:14 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 3 Apr 2002 12:26:14 -0800 (PST)
Subject: [Tutor] modules == class instances?
In-Reply-To: <E16sfGW-0000eg-00@mail.python.org>
Message-ID: <Pine.LNX.4.44.0204031201010.7983-100000@hkn.eecs.berkeley.edu>


On Tue, 2 Apr 2002, Kirby Urner wrote:

> On Tuesday 02 April 2002 10:12 pm, Danny wrote:
>
> > Yes, modules are also "objects" in Python.  They don't support too many
> > things besides allowing us to get and set attributes within them, but they
> > are objects that can be tossed around quite easily and uniformly.
> >
>
> I heard a rumor that a future Python would allow us to subclass entire
> modules, as we do classes.  Was I dreaming.  I don't find it in the list
> of active/open PEPs.

Hmmm... I have no idea on this one!  I can't get my head around
subclassing modules though: it's just too radical for me.  *grin* I'm
getting old.




From dyoo@hkn.eecs.berkeley.edu  Wed Apr  3 20:28:43 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 3 Apr 2002 12:28:43 -0800 (PST)
Subject: [Tutor] question about where to import  [import caches modules]
In-Reply-To: <F5CC0322-45E3-11D6-9AD0-00039351FE6A@mac.com>
Message-ID: <Pine.LNX.4.44.0204011916370.20166-100000@hkn.eecs.berkeley.edu>


On Mon, 1 Apr 2002, Erik Price wrote:

> I have a quick question about where import statements should go.  Most
> scripts feature them at the top of the script, or module, or whatever

I usually look for import statements near the top of my source files.



> definitions.  Is there some reason that the author would choose to put
> their import statement in a method definition?  I am probably wrong, but
> doesn't that mean that these modules are imported every time the method
> is called?

Thankfully, no.  Python keeps a cached list of loaded modules in memory,
so that the next time a module is 'import'ed, it ends up being a "no-op",
that is, it becomes an operation that Python just ignores.

By the way, this caching behavior is the reason why we have the reload()
function, to convince Python to toss out the cached module and really try
importing a module from scratch.




From dyoo@hkn.eecs.berkeley.edu  Wed Apr  3 20:29:25 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 3 Apr 2002 12:29:25 -0800 (PST)
Subject: [Tutor] Determining the OS a program runs on
In-Reply-To: <20020401023003.B26442@client156-52.ll.siue.edu>
Message-ID: <Pine.LNX.4.44.0204010938440.6079-100000@hkn.eecs.berkeley.edu>


On Mon, 1 Apr 2002, Victor R. Cardona wrote:

> How should I detrmine what operating system a program is running on?
> Should I use sys.platform or os.name?

sys.platform appears to be more specific than os.name, as the 'distutils'
module looks at sys.platform first to figure out how to deal with a
particular system.

Good luck!




From Gil Tucker [ateliermobile]" <gil@ateliermobile.de  Wed Apr  3 18:46:31 2002
From: Gil Tucker [ateliermobile]" <gil@ateliermobile.de (Gil Tucker [ateliermobile])
Date: Wed, 3 Apr 2002 20:46:31 +0200
Subject: [Tutor] routine command
Message-ID: <003501c1db5b$f3826340$6400a8c0@privat>



Greetings,
                     I am looking for a way to 
call programs or directories from the Python
GUI or otherwise. I am using WinME and
Win2000. Ideas anyone?
tanks gil





From urnerk@qwest.net  Wed Apr  3 23:21:30 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 03 Apr 2002 15:21:30 -0800
Subject: [Tutor] routine command
In-Reply-To: <003501c1db5b$f3826340$6400a8c0@privat>
Message-ID: <4.2.0.58.20020403151120.019a74d0@pop3.norton.antivirus>

At 08:46 PM 4/3/2002 +0200, you wrote:



>Greetings,
>                      I am looking for a way to
>call programs or directories from the Python
>GUI or otherwise. I am using WinME and
>Win2000. Ideas anyone?
>tanks gil
>

See os.system(command) or os.popen(command).

In theory, you can go os.system('notepad') in WinMe and
get notepad, but I always get a warning that this program
runs in real mode, which this version of windows doesn't
support.

But os.popen('notepad') works.  If you expect your command
to generate text in a shell, then you can write something
like:

def doscmd(cmd):
         f = popen(cmd)
         for i in f.readlines(): print i,
         f.close()

to echo it in Python. E.g.:

 >>> doscmd('dir')

  Volume in drive D is CAROL
  Volume Serial Number is 38D6-68D3
  Directory of D:\Program Files\Python22

.              <DIR>        07-22-01 10:40p .
..             <DIR>        07-22-01 10:40p ..
DLLS           <DIR>        07-22-01 10:40p DLLs
LIBS           <DIR>        07-22-01 10:40p libs
LIB            <DIR>        07-22-01 10:40p Lib
INCLUDE        <DIR>        07-22-01 10:40p include

etc. etc.

Or if you don't want to print it, but parse it, you
can return the lines in a list.

def doscmd(cmd):
         f = popen(cmd)
         output = f.readlines()
        f.close() # optional
         return output

Kirby




From slime@vsnl.net  Thu Apr  4 11:08:13 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Thu, 04 Apr 2002 06:08:13 -0500
Subject: [Tutor] Music player for various formats
Message-ID: <E16t56D-000586-00@mail.python.org>

Hi,

Just wrote a _very_ simple script to play sound files in various
formats. It currently supports wav, ogg, and a few others. I've put it
up here for your perusal :

    http://www.symonds.net/~prahladv/files/player.py

If you have the time, do take a look at it and send me feedback. As of
now, it just directly writes the raw data into a linuxaudiodev device.
So, it works only on Linux (I suppose). I would like to make it more
portable, but haven't found modules to do that :-(

Also, I haven't found a decent module to handle MP3 files, and I was
wondering if anyone here has seen/written something I could use.

The closest I got was a module to represent the tag of the MP3 file
alone, but nothing to handle the data.

Thanks !

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

My uncle was the town drunk -- and we lived in Chicago.
		-- George Gobel





From wilson@isis.visi.com  Thu Apr  4 13:03:09 2002
From: wilson@isis.visi.com (Tim Wilson)
Date: Thu, 4 Apr 2002 07:03:09 -0600 (CST)
Subject: [Tutor] Music player for various formats
In-Reply-To: <E16t56D-000586-00@mail.python.org>
Message-ID: <Pine.GSO.4.10.10204040702330.881-100000@isis.visi.com>

On Thu, 4 Apr 2002, Prahlad Vaidyanathan wrote:

> Also, I haven't found a decent module to handle MP3 files, and I was
> wondering if anyone here has seen/written something I could use.

Pygame can play MP3s. (http://www.pygame.org/) I've got a student
writing an MP3 player for his spring project.

-Tim

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




From csmith@blakeschool.org  Thu Apr  4 13:46:47 2002
From: csmith@blakeschool.org (Christopher Smith)
Date: Thu, 04 Apr 2002 07:46:47 -0600
Subject: [Tutor] len(l) as loop index
Message-ID: <fc.004c4b6b00930fc1004c4b6b00930fc1.930ffb@blakeschool.org>

Advice request:

Since the calculation of the list length is probably such a small part of
any task you are doing, is there any problem with using len(list) as a
loop index as opposed to calculating it once (e.g. n = len(list)) and then
using n as the loop index:

list=[1,2,3]
i=0
while i<len(list):
	print list[i]
	i=i+1

or should we not even be using the while loop this, using the following
instead:

for i in range(len(list)):
	print list[i]

or (if you don't need to know where you are):

for x in list:
	print x

The first method has been the method of choice for the How to Think text
on Python for beginners.

/c




From dman@dman.ddts.net  Thu Apr  4 14:29:23 2002
From: dman@dman.ddts.net (dman)
Date: Thu, 4 Apr 2002 08:29:23 -0600
Subject: [Tutor] How to check whether email /domain exists
In-Reply-To: <3CAADA7B.25443.509AE1@localhost>
References: <3CAADA7B.25443.509AE1@localhost>
Message-ID: <20020404142923.GA18719@dman.ddts.net>

On Wed, Apr 03, 2002 at 10:33:31AM +0200, A wrote:
| Hello,
| What is the simplest way how to check 
|  whether a given email address( or domain for this email) exists?
| Thanks for help

$ host -t mx <domain>
$ host -t a <domain>

You need to do a DNS lookup.  Sites SHOULD have a MX records that look
like :
    $ host -t mx dman.ddts.net
    dman.ddts.net       	MX	1 dman.ddts.net
    dman.ddts.net       	MX	10 dman2.ddts.net
The name on the left is the domain, the name on the right MUST point
to an A (or AAAA or A6 for IPv6) record, not a CNAME.  For example :
    $ host -t a dman.ddts.net
    dman.ddts.net       	A	65.107.69.216

I don't know what python modules/functions there are for performing
DNS queries.

You can _try_ to test for the existence of an email address by opening
an SMTP session with an MX for the domain and trying the "EXPN" or
"VRFY" commands, but many sites disable those because spammers can use
that to harvest valid addresses.

HTH,
-D

-- 

A)bort, R)etry, D)o it right this time




From urnerk@qwest.net  Thu Apr  4 15:26:06 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 04 Apr 2002 07:26:06 -0800
Subject: [Tutor] len(l) as loop index
In-Reply-To: <fc.004c4b6b00930fc1004c4b6b00930fc1.930ffb@blakeschool.org
 >
Message-ID: <4.2.0.58.20020404070525.019f1560@pop3.norton.antivirus>

At 07:46 AM 4/4/2002 -0600, Christopher Smith wrote:

>The first method has been the method of choice for the
>How to Think text on Python for beginners.
>
>/c

I'd say all of the above loop forms are fine.  The
"incremented index in order to access a list" approach
is very typical of many computer languages.

However, the 'for element in iter-sequence' construct
means that in Python we're less likely to compute an
incrementing index for the mere purpose of accessing
each element in turn, so it's important to show, and
use, this freedom.

Sometimes when I think I need an index, e.g. to access
both an element and the next element after, in the
same expression, I can actually do without.

For example,

 >>> def edges(face):
         lenface = len(face)
         edges = []
         for i in range(lenface):
            if i+1 < lenface:
               edges.append((face[i], face[i+1]))
            else:
               edges.append((face[i], face[0]))
        return edges

 >>> edges(['A','C','D','E'])
[('A', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'A')]

This program takes a polyhedron's face and figures
out what edges it implies, i.e. given face ACDE, you
must have edges AC CD DE and EA.  At first blush,
I need indexed access to the face in order to get
the pair (face[i],face[i+1]) -- except at the end
I have to "wrap around" to the beginning.

However, more recently, I've taken to writing this
function this way:

 >>> def edges(face):
         return zip(face,face[1:]+[face[0]])

 >>> edges(['A','C','D','E'])
[('A', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'A')]

except I really want sorted edges, i.e. ('A','E')
not ('E','A') -- because this makes it easier to
purge duplicates, I don't need to worry that
two edges might be the same except for the order
of the vertices, given I force the order.

So, final form:

def sort(thelist):  # called from various functions
         thelist.sort()
         return thelist

def edges(face):
         edges = []
         for i,j in zip(face,face[1:]+[face[0]]):
            edges.append(sort(list((i,j))))
         return edges

 >>> edges(['A','C','D','E'])
[['A', 'C'], ['C', 'D'], ['D', 'E'], ['A', 'E']]

There would be other forms of the above, but the main
point here is that I don't need to use indexing
syntax in the body of the loop -- just once in the
for statement to construct a "wrapped list" i.e.
['A','B','C','D'] becomes ['B','C','D','A'] and,
when zipped with the unwrapped list, you get the
edge pairs you need right off the bat.  All that
remains is to do the sort.

Kirby





From alan.gauld@bt.com  Thu Apr  4 15:34:49 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 4 Apr 2002 16:34:49 +0100
Subject: [Tutor] modules == class instances?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C505@mbtlipnt02.btlabs.bt.co.uk>

> > > Yes, modules are also "objects" in Python.  

> > I heard a rumor that a future Python would allow us to 
> subclass entire modules, as we do classes.  Was I dreaming.  

No, its in amongst the metaprogramming stuff.
You can subclass any builtin object in Python 
- int, float, string, list, function(!), and module...

It does get a bit wacky conceptually however but there 
is a paper on unifying the type and class models.

Alan g.



From alex@gabuzomeu.net  Thu Apr  4 16:05:59 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Thu, 04 Apr 2002 18:05:59 +0200
Subject: [Tutor] Strange namespace issue
In-Reply-To: <E16t95o-0008La-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020404174747.00ceadc0@pop3.norton.antivirus>

Hello,


At 10:23 04/04/2002 -0500, you wrote:
>Date: Wed, 3 Apr 2002 21:15:29 +0200
>From: Remco Gerlich <scarblac@pino.selwerd.nl>
>Subject: Re: [Tutor] Strange namespace issue

> > ... I expected self.nodeList to be initialised to a new, empty list if the
> > constructor was called without a nodeList argument. Somehow it failed. I
> > had to use "nodeList = None" in the argument list and then to specify
> > "self.nodeList = []" to initialise the list properly.
> >
> > What did I miss? Is this the normal behaviour?
>
>Yes, it is normal. The default argument is evaluated at the moment that 
>the function is defined. So at the moment you define the class, with the
>function definition in it, the expression "[]" is evaluated, and it returns
>a list. This list is then used as the default for the function argument.

Thanks Remco; this issue had been nibbling at me for a couple of days.

>That list! It will always be the same object.

Yes, that's a subtle trick it played on me.

>The FAQ explains this in different words,
>http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.025.htp
>
>This bites you once and then you remember it. Don't use mutable default
>arguments. Use None, and a test for "if argument is None: argument=[]" at 
>the top of a function.

I definitively will remember it :-)


Cheers.

Alexandre





From alan.gauld@bt.com  Thu Apr  4 16:04:18 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 4 Apr 2002 17:04:18 +0100
Subject: [Tutor] len(l) as loop index
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C506@mbtlipnt02.btlabs.bt.co.uk>

> Since the calculation of the list length is probably such a 
> small part of any task you are doing, is there any problem 
> with using len(list) as a loop index as opposed to 
> calculating it once 

That's a big assumption! A len() query basically has to 
run alomng the list counting members. If its a big list
that could take far more time than processing the loop body.

A quick test:
import time
L = range(100000000)  # 1 million ints

start = time.time()
l = len(L)
j = 0
while j < l:
   if L[j] % 10000000 == 0: # every 100K
      print j
   j += 1
stop = time.time
print stop-start

vv

import time
L = range(100000000)  # 100 million ints

start = time.time()
j = 0
while j < len(L):
   if L[j] % 10000000 == 0: # every 10 million
      print j
   j += 1
stop = time.time
print stop-start

Gives me times of 3.5 for the 1st and 5.8 for the second
- the first is about 60% faster

Obviously if you are doing a lot of processing in the 
loop body the difference becomes minimal. But the extra 
code is minimal why not just be as fast as you can be?

> for i in range(len(list)):
> 	print list[i]

This is a waste of space and time IMHO.
Using an index in a for loop is of little use 
since you can't modify the list without damage 
anyway

> for x in list:
> 	print x

This is shorter and faster.

(Using the above loop I get 2.75 for this one 
  - half of the longest value)

You only need the while loop if you intend to add/delete 
items and even then you need to be careful to maintain 
the index correctly - and in this case having len() 
inside the loop is probably the right way to go!.

Alan g.



From alex@gabuzomeu.net  Thu Apr  4 16:10:12 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Thu, 04 Apr 2002 18:10:12 +0200
Subject: [Tutor] Music player for various formats
In-Reply-To: <E16t95o-0008La-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020404175549.00cd99f0@pop3.norton.antivirus>

Hi Prahlad,


At 10:23 04/04/2002 -0500, you wrote:
>From: Prahlad Vaidyanathan <slime@vsnl.net>
>Date: Thu, 04 Apr 2002 06:08:13 -0500
>Subject: [Tutor] Music player for various formats
>
>Also, I haven't found a decent module to handle MP3 files, and I was
>wondering if anyone here has seen/written something I could use.
>
>The closest I got was a module to represent the tag of the MP3 file
>alone, but nothing to handle the data.

There is a code example in Dive into Python that might help you:

         http://diveintopython.org/fileinfo_divein.html


Cheers.

Alexandre




From e.kotyk@shaw.ca  Thu Apr  4 10:37:16 2002
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Thu, 04 Apr 2002 10:37:16 +0000
Subject: [Tutor] Working with files
Message-ID: <20020404103716.636afd48.e.kotyk@shaw.ca>

--=.WadRJoh?o1nEm0
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit

How do you open a file, read the file, remove an element in the file and
write it to a backup file.

I can do all of this from the following code from Alan's tutorial except
delete part of the file before rewriting it.

inp = open('menu.txt', 'r')
outp = open('menu.bak', 'w')
for line in inp.readlines():
	#here I would like to say that x = "spam'
	#if x is in inp.readlines del x
	#it seems to me that it doesn't act on the line, it just deletes x.  I
can't 	    #figure out any way to have it del x from line and then
write this line.	outp.write(line)
inp.close()
outp.close()

E


-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm

--=.WadRJoh?o1nEm0
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE8rCzfyxm8dPG0oMIRAtGgAJ0TrEgsZcwqyOTBbNVkyc3OvGo/2wCfSXWm
HcljW3NNEcXY/onh5aZEalQ=
=rfVY
-----END PGP SIGNATURE-----

--=.WadRJoh?o1nEm0--




From shalehperry@attbi.com  Thu Apr  4 17:09:01 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 04 Apr 2002 09:09:01 -0800 (PST)
Subject: [Tutor] Working with files
In-Reply-To: <20020404103716.636afd48.e.kotyk@shaw.ca>
Message-ID: <XFMail.20020404090901.shalehperry@attbi.com>

On 04-Apr-2002 Eve Kotyk wrote:
> How do you open a file, read the file, remove an element in the file and
> write it to a backup file.
> 
> I can do all of this from the following code from Alan's tutorial except
> delete part of the file before rewriting it.
> 
> inp = open('menu.txt', 'r')
> outp = open('menu.bak', 'w')
> for line in inp.readlines():
>       #here I would like to say that x = "spam'
>       #if x is in inp.readlines del x
>       #it seems to me that it doesn't act on the line, it just deletes x.  I
> can't             #figure out any way to have it del x from line and then
> write this line.      outp.write(line)
> inp.close()
> outp.close()
> 

import re

for line in inp.readlines():
  if re.search(r'Canada', line): continue # if line contains 'Canada'
  outp.write(line)



From alan.gauld@bt.com  Thu Apr  4 17:13:45 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 4 Apr 2002 18:13:45 +0100
Subject: [Tutor] Working with files
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C509@mbtlipnt02.btlabs.bt.co.uk>

> I can do all of this from the following code from Alan's 
> tutorial 

Oh well I'd better have a stab then ;-)

> for line in inp.readlines():
> 	#here I would like to say that x = "spam'
      x = "spam"  # that bit is easy!

> 	#if x is in inp.readlines del x

I think you really mean "if the word spam is 
within the line then delete the word spam from the line"?
If that's not right then please explain further.

If I'm right you need to use the string handling 
functions find() and replace() - take a look at 
the string module documentation.
      import string      
      if string.find(line, x):
         string.replace(line, '') # replace with nothing

Check the syntax (order of params etc) I haven't tested it!
Also you could use the new built in methods if using Python2.x

      if line.find(x): 
		line.replace(x,'')

> 	#it seems to me that it doesn't act on the line, it 
> just deletes x.  

That was what you asked it to do with del(x)! :-)

> outp.write(line)
> inp.close()
> outp.close()

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From wolf_binary@hotmail.com  Thu Apr  4 17:27:24 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Thu, 04 Apr 2002 11:27:24 -0600
Subject: [Tutor] directories
Message-ID: <F1662IfBvjTZUl3WCX500009f1b@hotmail.com>

Hi all,

I am making notes on Python and I want to specify a location of a file that 
is back one level from my source file.  Is there a way in HTML to specify 
the path of that file without having to give it the drive letter and all 
that?  I am writing my own sort of tutorial for me and my brother to use.  
Any help would be much apreciated.

Thanks,
Cameron Stoner

_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.




From shalehperry@attbi.com  Thu Apr  4 17:32:17 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 04 Apr 2002 09:32:17 -0800 (PST)
Subject: [Tutor] directories
In-Reply-To: <F1662IfBvjTZUl3WCX500009f1b@hotmail.com>
Message-ID: <XFMail.20020404093217.shalehperry@attbi.com>

On 04-Apr-2002 Cameron Stoner wrote:
> Hi all,
> 
> I am making notes on Python and I want to specify a location of a file that 
> is back one level from my source file.  Is there a way in HTML to specify 
> the path of that file without having to give it the drive letter and all 
> that?  I am writing my own sort of tutorial for me and my brother to use.  
> Any help would be much apreciated.
> 

typically this is referred to as '..' and the directory you are in is referred
to as '.'.



From e.kotyk@shaw.ca  Thu Apr  4 11:43:46 2002
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Thu, 04 Apr 2002 11:43:46 +0000
Subject: [Tutor] Working with files
In-Reply-To: <XFMail.20020404090901.shalehperry@attbi.com>
References: <20020404103716.636afd48.e.kotyk@shaw.ca>
 <XFMail.20020404090901.shalehperry@attbi.com>
Message-ID: <20020404114346.6088799d.e.kotyk@shaw.ca>

--=.O6PE'?icS+hp8:
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit


> import re
> 
> for line in inp.readlines():
>   if re.search(r'Canada', line): continue # if line contains 'Canada'
>   outp.write(line)

Thank you I will try this.

E

-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm

--=.O6PE'?icS+hp8:
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE8rDx2yxm8dPG0oMIRAs9lAKDIYfexJwxlBoUQJg5pgokuSFJQdwCfey3I
kxN/pUyp92jLJ8ozfyeU6QA=
=Ad6g
-----END PGP SIGNATURE-----

--=.O6PE'?icS+hp8:--




From jeff@ccvcorp.com  Thu Apr  4 18:11:38 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu, 04 Apr 2002 10:11:38 -0800
Subject: [Tutor] Working with files
References: <E16tAbe-0004so-00@mail.python.org>
Message-ID: <3CAC975A.C5354120@ccvcorp.com>


> Eve Kotyk <e.kotyk@shaw.ca> wrote:
>
> How do you open a file, read the file, remove an element in the file and
> write it to a backup file.
>
> I can do all of this from the following code from Alan's tutorial except
> delete part of the file before rewriting it.
>
> inp = open('menu.txt', 'r')
> outp = open('menu.bak', 'w')
> for line in inp.readlines():
>         # [...]
>         outp.write(line)
> inp.close()
> outp.close()

Well, this doesn't specifically have anything to do with files, actually -- you've
got the file-handling part right, you just need to modify the strings that you've
got while they're in memory, before you write them back out.  What you need is the
string's replace() method.

>>> lines = ['This is spam', 'This is not', 'Spam is good', 'Delicious spam']
>>> for line in lines:
...  print line.replace('spam', '')
...
This is
This is not
Spam is good
Delicious
>>>

Note that you can replace 'spam' with any string -- in this case, I've replaced it
with an empty string.  Note also that this is case sensitive -- 'spam' is replaced
but 'Spam' isn't.

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International






From nicole.seitz@urz.uni-hd.de  Thu Apr  4 17:56:16 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Thu, 4 Apr 2002 19:56:16 +0200
Subject: [Tutor] German Umlaut
In-Reply-To: <Pine.LNX.4.44.0204011214080.10268-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0204011214080.10268-100000@hkn.eecs.berkeley.edu>
Message-ID: <02040419561601.00710@utopia>

Am Montag,  1. April 2002 22:29 schrieben Sie:

> Hmmm... Is it possible to relax the regular expression a little?  Instead
> of forcing a "capitalized" word, would this be feasible:
>
> ###
> reg = re.compile(r"\b\w+-? und \w+\b",re.UNICODE)
> ###

As German nouns have to be "capitalized" words, I can't use this regex.

>
>
> Otherwise, we can stuff in 'string.uppercase' in the regular expression.
> Here's one way to do it with some string formatting:
>
> ###
> reg = re.compile(r"\b[%s]\w+-? und [%s]\w+\b"
>                   % (string.uppercase, string.uppercase), re.UNICODE)
> ###

That's better! Here's my latest regex:

reg = re.compile(r"\b[%s]\w+-?(?:,\s\b[%s]\w+)*\sund\s\b[%s]\w+"
                 
%(string.uppercase,string.uppercase,string.uppercase),re.UNICODE)


It works (matches also "Berlin, London,Wien  und Paris"),
but I don't like it because of  
%(string.uppercase,string.uppercase,string.uppercase).
The former version looks better:

reg3 = re.compile(r"(?:[%s\w-]+(?:,|\sund)?\s)+"
                  %(string.uppercase),
                  re.UNICODE)

Unfortunately, it finds pretty more things than I wanted it to find.


Many greetings,

Nicole




From charlie@begeistert.org  Thu Apr  4 18:38:46 2002
From: charlie@begeistert.org (Charlie Clark)
Date: Thu, 04 Apr 2002 20:38:46 +0200
Subject: [Tutor] Removing something from a file
In-Reply-To: <E16tAbd-0004sg-00@mail.python.org>
References: <E16tAbd-0004sg-00@mail.python.org>
Message-ID: <20020404205234.5420.8@gormenghast.1017865497.fake>

On 2002-04-04 at 19:00:09 [+0200], tutor-request@python.org wrote:
> How do you open a file, read the file, remove an element in the file and 
> write it to a backup file.
> 
> I can do all of this from the following code from Alan's tutorial except 
> delete part of the file before rewriting it.
> 

for line in inp.readlines():
if x is in inp.readlines del x
del removes an item from a sequence. This might work if a single line = x but not otherwise. Furthermore, you don't need to do this for every line. The syntax if wrong anyway.
if x in inp.readlines(): # this may return None as you are calling it again
    print x, "is in the file"
You can only use "in" to check for membership in a sequence.

If you want to remove entire lines 'spam' you could try this
for line in inp.readlines():
    if line != 'spam':
        outp.write(line)

if you just want to remove 'spam' from the file you don't even need to loop

content = inp.read()
content = content.replace('spam', '')
outp.write(content)

That any help?

Charlie




From nicole.seitz@urz.uni-hd.de  Thu Apr  4 18:01:45 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Thu, 4 Apr 2002 20:01:45 +0200
Subject: [Tutor] A nicer output...
In-Reply-To: <3CA9EDAB.CD40F917@ccvcorp.com>
References: <E16sRej-0002hR-00@mail.python.org> <3CA9EDAB.CD40F917@ccvcorp.com>
Message-ID: <02040420014502.00710@utopia>

Hi Jeff , hi Alexandre!

Thanks a lot! I've got now a satisfying output:


WORD:                     IN LINE(S):
===================================================
AccelGalaxy             510
AltaVista                   403,402,400
AnyPoint                   479,478,477
AppleShare               259
CompuServe             103,105
InterBus                    234,110
JavaScript                81,485
LonWorks                 247
MacWeek                 88
MarkUp                    338
McKinsey                 463,462
MediaOne                495,497
NetBooting               557
NeuroVisionen         186,173
SenseWeb               483,485
SoftQuad                 335
StarDivision             267,265
StarOffice                263,265
SysOps                   105
TeleTrust                 447,445
TopWare                 535

With your help, it was quite easy!



Many greetings,

Nicole



From nicole.seitz@urz.uni-hd.de  Thu Apr  4 18:28:10 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Thu, 4 Apr 2002 20:28:10 +0200
Subject: [Tutor] Counting words
Message-ID: <02040420281003.00710@utopia>

Hi there!


I would like to count words in a file, i.e. I want to know how often a word 
occurs.

In "GoTo Python" I found some help, so I could write:

_____________________________________________________

import re, string

reg = re.compile("[\W]")
file = open("someText","r")

text = file.read()


occurences = {}

for word in reg.split(text):
    
    occurences[word] = occurences.get(word,0)+1
    print occurences
    
for word in occurences.keys():
    print "word:",word,", occurences:",occurences[word]

_____________________________________________________

First question:  Can someone explain what's happening in the first for-loop?
                     I don't understand occurences.get(word,0)+1 .
                     I know it<#s counting there, but how?



(one possible output)

word: of , occurences: 1
word: Some , occurences: 1
word: are , occurences: 1
word: texts , occurences: 1
word: BORING , occurences: 1
word: some , occurences: 1
word: is , occurences: 2
word: boring , occurences: 1
word: This , occurences: 2
word: kind , occurences: 1
word: text , occurences: 1
word:  , occurences: 3

Second question:  
"Some" and "some" should be recognized as one word, the same is with "BORING" 
and "boring". I  thought of string.lowercase as a possible solution, but as 
it doesn't  work , I might be wrong. Any idea what to do?

Third question:

Last line of output:
Is  "\n" recognized as a word?? (My text  currently consists of three lines)


Thanx in advance.

Nicole







From shalehperry@attbi.com  Thu Apr  4 19:42:14 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 04 Apr 2002 11:42:14 -0800 (PST)
Subject: [Tutor] Counting words
In-Reply-To: <02040420281003.00710@utopia>
Message-ID: <XFMail.20020404114214.shalehperry@attbi.com>

> 
> import re, string
> 
> reg = re.compile("[\W]")
> file = open("someText","r")
> 
> text = file.read()
> 
> 
> occurences = {}
> 
> for word in reg.split(text):
>     
>     occurences[word] = occurences.get(word,0)+1
>     print occurences
>     
> for word in occurences.keys():
>     print "word:",word,", occurences:",occurences[word]
> 
> _____________________________________________________
> 
> First question:  Can someone explain what's happening in the first for-loop?
>                      I don't understand occurences.get(word,0)+1 .
>                      I know it<#s counting there, but how?
> 
> 

what is happening is the 'get' method of the dictionary is being called.  It is
looking for the key specified by word and if it is not found it returns 0.

This is equivalent to:

if occurences.has_key(word):
  occurences[word] = occurences[word] + 1
else:
  occurences[word] = 1

> 
> Second question:  
> "Some" and "some" should be recognized as one word, the same is with "BORING"
> and "boring". I  thought of string.lowercase as a possible solution, but as 
> it doesn't  work , I might be wrong. Any idea what to do?
> 

word = string.lower(word)

> Third question:
> 
> Last line of output:
> Is  "\n" recognized as a word?? (My text  currently consists of three lines)
> 

>>> s = 'A typical line\n'
>>> import re
>>> reg = re.compile("[\W]")
>>> reg.split(s)
['A', 'typical', 'line', '']

notice the empty last entry.  Have you loop skip empty words.



From csmith@blakeschool.org  Thu Apr  4 22:15:38 2002
From: csmith@blakeschool.org (Christopher Smith)
Date: Thu, 04 Apr 2002 16:15:38 -0600
Subject: [Tutor] len(l) as loop index
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C506@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C506@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <fc.004c4b6b009333313b9aca00a16cd0de.9333d8@blakeschool.org>

alan.gauld@bt.com writes:
>> Since the calculation of the list length is probably such a 
>> small part of any task you are doing, is there any problem 
>> with using len(list) as a loop index as opposed to 
>> calculating it once 
>
>That's a big assumption! A len() query basically has to 
>run alomng the list counting members. If its a big list
>that could take far more time than processing the loop body.

Are you sure?  That's what I thought but then I thought the length
parameter might actually be something that Python stores with its info
about the object so it might not actually take too long--it essentially
just finds out what the stored len parameter is for the object.  I tried
the following runs for which the first took 8 seconds and the second took
11 seconds.  So the index access time is about 50% longer but is a really
small time.

it=3000000
l=range(100000)
n=len(l)

import my
t=my.start()
i=0
while i<it:
	n
	i+=1
print my.stop(t)

t=my.start()
i=0
while i<it:
	len(l)
	i+=1
print my.stop(t)

/c




From glingl@aon.at  Thu Apr  4 22:26:03 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 5 Apr 2002 00:26:03 +0200
Subject: [Tutor] Counting words
References: <XFMail.20020404114214.shalehperry@attbi.com>
Message-ID: <001e01c1dc27$b49fc790$1664a8c0@mega>

> > Second question:
> > "Some" and "some" should be recognized as one word, the same is with
"BORING"
> > and "boring". I  thought of string.lowercase as a possible solution, but
as
> > it doesn't  work , I might be wrong. Any idea what to do?
> >
>
> word = string.lower(word)
>

In modern Pythons (with string-methods) you also may write:

word = word.lower()

> > Third question:
> >
> > Last line of output:
> > Is  "\n" recognized as a word?? (My text  currently consists of three
lines)
> >
>
> >>> s = 'A typical line\n'
> >>> import re
> >>> reg = re.compile("[\W]")
> >>> reg.split(s)
> ['A', 'typical', 'line', '']
>
> notice the empty last entry.  Have your loop skip empty words.
>

YES! Because even if there are no '\n's, empty entries may occur:

>>> s = 'A typical, yes, line!'
>>> import re
>>> reg = re.compile("[\W]")
>>> reg.split(s)
['A', 'typical', '', 'yes', '', 'line', '']
>>>

Gregor




From urnerk@qwest.net  Thu Apr  4 22:33:13 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 04 Apr 2002 14:33:13 -0800
Subject: [Tutor] len(l) as loop index
In-Reply-To: <4.2.0.58.20020404070525.019f1560@pop3.norton.antivirus>
References: <fc.004c4b6b00930fc1004c4b6b00930fc1.930ffb@blakeschool.org >
Message-ID: <4.2.0.58.20020404143143.019b5100@pop3.norton.antivirus>

At 07:26 AM 4/4/2002 -0800, I wrote:

>So, final form:
>
>def sort(thelist):  # called from various functions
>         thelist.sort()
>         return thelist
>
>def edges(face):
>         edges = []
>         for i,j in zip(face,face[1:]+[face[0]]):
>            edges.append(sort(list((i,j))))
>         return edges
>
> >>> edges(['A','C','D','E'])
>[['A', 'C'], ['C', 'D'], ['D', 'E'], ['A', 'E']]
>
>There would be other forms of the above

Such as:

    def edges(face):
         def sort(alist):
            alist = list(alist) # might have been a tuple
            alist.sort()
            return alist
         return [sort(alist) for alist \
                in zip(face,face[1:]+[face[0]])]

  >>> edges(['A','C','B','E'])
  [['A', 'C'], ['B', 'C'], ['B', 'E'], ['A', 'E']]

Kirby




From erikprice@mac.com  Thu Apr  4 23:27:26 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 4 Apr 2002 18:27:26 -0500
Subject: [Tutor] Working with files
In-Reply-To: <XFMail.20020404090901.shalehperry@attbi.com>
Message-ID: <85F8637F-4823-11D6-B534-00039351FE6A@mac.com>

On Thursday, April 4, 2002, at 12:09  PM, Sean 'Shaleh' Perry wrote:

> import re
>
> for line in inp.readlines():
>   if re.search(r'Canada', line): continue # if line contains 'Canada'
>   outp.write(line)

The only thing with this is that it wouldn't catch a phrase (or a word) 
that was split between two lines.

I can't think of a good solution that doesn't require the entire 
haystack string to be read into memory.  How does grep (and other 'find' 
utilities) do multi-line searches?


Erik




From erikprice@mac.com  Fri Apr  5 00:13:56 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 4 Apr 2002 19:13:56 -0500
Subject: [Tutor] impact of OO
Message-ID: <05196BDE-482A-11D6-B534-00039351FE6A@mac.com>

I have a general question about Object Oriented programming in general:  
why is it so lauded by... well, by everyone?

Granted, this is coming from Erik Newbie, and I only just figured out 
the basics of OO programming this week.  Obviously I haven't seen even 
close to the extent of what OO programming can do.  But that's why I'm 
asking this question.

It seems to make certain things easier -- for instance, in my 
application that I'm writing in PHP (whose OO facilities are no match 
for Python's, I've discovered :( ), I am now using objects to represent 
items which need to be inserted into the database, that I used to refer 
to with a group of variable names.  It's hard to describe, but this 
makes it much easier -- attributes/properties represent field names, and 
I can neatly group all of my error-checking functions (for user inputs) 
into the class, and the instance attribute doesn't even get assigned 
unless the error checking code returns true, for example.  As opposed to 
running each user input through a function and assigning it to a 
dynamically-generated variable name.  It's not really much different, 
but it is far more organized and cleaner.

But everywhere I used to read about programming would talk about how OO 
had revolutionized programming.  Now that I know what it is, although I 
really appreciate it and will use it whenever I can (it's so... clean 
compared to what I was doing before), but I still don't really see how 
it's that big a deal -- it's simply a different way of organizing code, 
as far as I can tell.

Please prove me wrong and help me see how OO "changed everything".

Erik





PS:  Also, I have heard someone say that "in Java everything is an 
object".  What does this mean?  I think I am interested in learning 
Java, especially since there are many employers in my area (Boston) 
advertising an interest in Java programmers (and I will be out of a job 
as soon as my project is finished).  Sadly, much more than Python or 
PHP.  But it seems like a big language to learn.




From dyoo@hkn.eecs.berkeley.edu  Thu Apr  4 22:38:31 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 4 Apr 2002 14:38:31 -0800 (PST)
Subject: [Tutor] Counting words   [reference documentation on dictionaries]
In-Reply-To: <02040420281003.00710@utopia>
Message-ID: <Pine.LNX.4.44.0204041432040.1185-100000@hkn.eecs.berkeley.edu>

>     occurences[word] = occurences.get(word,0)+1

Sean showed that this was equivalent to looking up the 'word' in
'occurences'.  If the 'word' actually isn't in there yet, it uses '0' as a
default value.

There's a little more detail about this here:

    http://www.python.org/doc/lib/typesmapping.html

though it is a bit sparse.  dict.get() is a pretty useful function, and is
there for our convenience.


Good luck to you!




From dyoo@hkn.eecs.berkeley.edu  Thu Apr  4 22:07:38 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 4 Apr 2002 14:07:38 -0800 (PST)
Subject: [Tutor] German Umlaut   [string formatting with dictionaries]
In-Reply-To: <02040419561601.00710@utopia>
Message-ID: <Pine.LNX.4.44.0204041349460.1185-100000@hkn.eecs.berkeley.edu>

> That's better! Here's my latest regex:
>
> reg = re.compile(r"\b[%s]\w+-?(?:,\s\b[%s]\w+)*\sund\s\b[%s]\w+"
>
> %(string.uppercase,string.uppercase,string.uppercase),re.UNICODE)
>
>
> It works (matches also "Berlin, London,Wien  und Paris"),
> but I don't like it because of
> %(string.uppercase,string.uppercase,string.uppercase).

The above using string formatting with tuples, and it is a bit wordy
because the tuples interpolate by their position --- the first '%s' gets
replaced by the first element in the tuple, the second '%s' with the
second element, and so on.


If we use a dictionary approach, we can make things look a little nicer:

###
reg = re.compile(r"""\b[%(CAPITALS)s]\w+           ## A capitalized word
                     -?                            ## followed by an

                                                   ## optional hyphen.
                     (?:,\s\b[%(CAPITALS)s]\w+     ## Don't make a group,
                                                   ## but match as many
                                                   ## capitalized words
                                                   ## separated by
                                                   ## commas,
                     )*

                     \s und \s                     ## followed by "und"

                     \b[%(CAPITALS)s]\w+"""        ## and the last
                                                   ## capitalized word
                     % { 'CAPITALS' : string.uppercase },
                 re.VERBOSE)
###

That is, every time Python sees '%(CAPITALS)s', it'll look within our
dictionary to substitute values.  This approach isn't positional, since
Python will actually look up the appropriate values in our dictioanry.
This approach allows us to avoid repeating 'string.uppercase' so many
times.


Also, I've broken the regular expression across several lines, and placed
comments to explain what the line noise means.  *grin* We can do this as
long as we tell the re.compile() function that we're being "verbose"
about this.  Verbose regular expressions allow us to put spaces and
comments for humans to read, and before the regular expression gets
processed, the system should strip out the spaces and comments.


Hope this helps!




From glidedon <glidedon@c-zone.net>  Thu Apr  4 17:58:03 2002
From: glidedon <glidedon@c-zone.net> (glidedon)
Date: Thu, 04 Apr 2002 17:58:03 +0000
Subject: [Tutor] Working with files, Truckers log
In-Reply-To: <85F8637F-4823-11D6-B534-00039351FE6A@mac.com>
References: <85F8637F-4823-11D6-B534-00039351FE6A@mac.com>
Message-ID: <00039dd057e8016b_mailit@mail.c-zone.net>

Hi All,

This is a timely subject for me :-). I want to save data that is in a list  
to a file , to be  used later to append the list.  The list contains decimal 
numbers.

Here is a sample list [ 8.5,8,9.5,10.75,6.25 ]

I think I know how to read and write to a file ,but how do I insert this data 
into the list in my program ?

I am working my way through Alan's book  (Wesley your book is next :-) )and 
its chapter on files uses text in its examples, how do I handle numerical 
data ?

Thanks in advance,

Don

Here is my learning program, submited for your critique.

#!  /boot/home/config/bin/python

# Logbook 8 or 7day recap

# this program will calculate hours on duty last 6 or7 days,
# hours avalible tomorrow(60 or 70 hours minus total  on dutydays ) ,hours on 
duty last 7 or 8 days
# for a truck drivers log book

###########################################################
import operator


history_list = [ ]   #create list for storing hours on duty record
last_days = 0     # variable to represent total of last 7 or 8 days on duty
max_hours = 0  # variable  to represent max allowable hours on duty ( 60 or 
70 )
recap_days = 0  # variable for indicating 7 or 8 day recap choice from user 
input
index_number = 0  # variable to indicate index value when extracting from 
history_list



def printSummary( ):
   print  ' \n', '='*20,'RECAP', '=' *33,' \n', '=' * 60
   print ' Total hours on duty last', recap_days -1 ,' days  : ',  last_days
   print ' Total hours available tomorrow    : ' , max_hours - last_days
   print ' Total hours on duty last', recap_days ,' days  : ' , last_days + 
history_list [ total_hours_index]
   print ' \n ' , ' You have entered ' , len(history_list), ' Days '
   print ' \n ' , history_list
   
###########################################################
   
#print welcome message ask for user input regarding 7 or 8 day recap choice

print ' \n '  *2 , ' Welcome to Don\'s Recap Calculator ! ', ' \n ' 
print ' I hope this makes recaping your log easier. ' , ' \n '

how_many_days = raw_input( ' Enter a "7" for 7 day Recap or "8" for 8 day 
Recap  : ' )
print '\n'

if    how_many_days == '7' :
   recap_days = 7
   index_number = -6
   max_hours = 60
   total_hours_index= -7
else :
   how_many_days = 8
   recap_days= 8
   index_number = -7
   max_hours = 70
   total_hours_index= -8
# populate history_list with first 7 or 8 days of recap and convert to float


for i in range( recap_days ):
    querry_string = " Enter total hours on duty on day%d   "  % ( i +1 )
    input = raw_input(querry_string)
    history_list.append( float( input ) )
last_days = reduce( operator.add,history_list[ index_number: ] )
printSummary( )

###########################################################
     
# ask for additional days input
# create loop to check if the answer is y or n, or some variation of
# assign value of the last 6 or  7 entries in history_list to the variable 
last_days
# output current recap status
# continue loop for more input

while  1:
    add_days = raw_input('\n' 'Do you want to add more days to recap ?  y/n   
: ' )
    
    if add_days in ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) : 
     next_day =raw_input('\n' ' Enter hours on duty next day : ')
     history_list.append( float (next_day ) ) 
     last_days = reduce( operator.add,history_list[ index_number: ] )
     printSummary( )
     
    elif add_days  in ( 'n', 'N', 'no', 'NO' ):
        print  ' \n' *2, '='*20,'EXIT', '=' *34,' \n', '=' * 60 
        print ' \n ' *2, 'Thanks for using Don\'s Recap calculator ! ', ' \n 
'*2, 'Have a safe trip :-) ',' \n' *3
        break 

    else:
        print '\n' ' Nice try good buddy, enter a y/n , ten-four ? '
      




From dyoo@hkn.eecs.berkeley.edu  Fri Apr  5 02:00:23 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 4 Apr 2002 18:00:23 -0800 (PST)
Subject: [Tutor] impact of OO
In-Reply-To: <05196BDE-482A-11D6-B534-00039351FE6A@mac.com>
Message-ID: <Pine.LNX.4.44.0204041733320.16153-100000@hkn.eecs.berkeley.edu>

> But everywhere I used to read about programming would talk about how OO
> had revolutionized programming.  Now that I know what it is, although I
> really appreciate it and will use it whenever I can (it's so... clean
> compared to what I was doing before), but I still don't really see how
> it's that big a deal -- it's simply a different way of organizing code,
> as far as I can tell.

Yes.  *grin*

Actually, it's not a unified opinion that OOP is the best thing since
sliced bread.  Paul Graham has some good reasons why it might not be
revolutionary on his web site:

    http://www.paulgraham.com/noop.html
    http://www.paulgraham.com/reesoo.html



> PS:  Also, I have heard someone say that "in Java everything is an
> object".  What does this mean?

They may be referring to the idea that all Java classes inherit from a
single base class called "Object".  Everything in Java (functions,
variables, etc.) needs to be in a class, and in that sense, Java's classes
act sorta like Python's modules... except Java classes are very strict.


I'm not sure it's perfectly true that everything is an Object in Java:
there are primitive values in Java, like 'int' or 'float', that just don't
like being treated as objects:

//////
ArrayList l = new ArrayList(); // An "ArrayList" in java is similar to
                               // Python's list.

v.add(42);                     // But this won't work.  42 is an integer,
                               // a primitive type, and primitive types
                               // aren't a subclass of Object.

v.add(new Integer(42));        // Java uses a class "wrapper" to get
                               // around this situation.
//////

So there's a great divide between primitive types and Objects in Java.


> I think I am interested in learning Java, especially since there are
> many employers in my area (Boston)  advertising an interest in Java
> programmers (and I will be out of a job as soon as my project is
> finished).  Sadly, much more than Python or PHP.  But it seems like a
> big language to learn.

You might be interested in the Jython project:

    http://jython.org/

You can leverage what you're learning in Python directly toward Java:
Jython allows you to write Java classes in Python.


Good luck!




From jeff@ccvcorp.com  Fri Apr  5 02:35:58 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu, 04 Apr 2002 18:35:58 -0800
Subject: [Tutor] Re: Tutor digest, Vol 1 #1546 - 16 msgs
References: <E16tHJo-00027J-00@mail.python.org>
Message-ID: <3CAD0D8D.4D53F9EF@ccvcorp.com>

> Message: 16
> Date: Thu, 4 Apr 2002 19:13:56 -0500
> From: Erik Price <erikprice@mac.com>
> To: tutor@python.org
> Subject: [Tutor] impact of OO
>
> I have a general question about Object Oriented programming in general:
> why is it so lauded by... well, by everyone?
> [...]
> But everywhere I used to read about programming would talk about how OO
> had revolutionized programming.  Now that I know what it is, although I
> really appreciate it and will use it whenever I can (it's so... clean
> compared to what I was doing before), but I still don't really see how
> it's that big a deal -- it's simply a different way of organizing code,
> as far as I can tell.

Actually, you're exactly right -- it really *is* just a different way to organize code.  But when the code that you have numbers not in hundreds of lines, but thousands of lines,
or *hundreds* of thousands of lines, then how you organize it becomes *very* important.  With well-written OO code, you know that you don't need to follow *every* aspect of a
program in order to understand a particular section -- you can focus on only one object, and the objects that it directly interacts with.  It lets you break the code down into
smaller sections that are almost totally self-contained, so that there's less to keep in your head at any one time.  Also, each of those sections is clearer and cleaner, as you've
noticed, so that less effort is required to understand a given amount of code.  And that means that, since you're spending less effort on remembering and understanding the code,
then you have *more* effort available to spend on *improving* the code.  You can also be a lot more confident that your improvements don't strangely affect some totally separate
part of the program, too.

All of these effects add up, and result in better, faster, more stable programs being completed in less time (and therefore lower cost).  Now, add a generous dash of marketing
hype to that, and you'll have the reason why OOP gets so much applause.  ;)

Jeff Shannon
Technician/Programmer
Credit International





From urnerk@qwest.net  Fri Apr  5 05:30:23 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 04 Apr 2002 21:30:23 -0800
Subject: [Tutor] impact of OO
In-Reply-To: <05196BDE-482A-11D6-B534-00039351FE6A@mac.com>
Message-ID: <4.2.0.58.20020404204915.00afe9b0@pop3.norton.antivirus>

At 07:13 PM 4/4/2002 -0500, Erik Price wrote:

>Please prove me wrong and help me see how OO "changed everything".
>
>Erik

Here's some more anti-OOP propaganda (to balance the pro-OOP
stuff), adding to Danny's links:

http://www.softpanorama.org/SE/anti_oo.shtml
http://www.geocities.com/SiliconValley/Lab/6888/meyer1.htm
http://www.geocities.com/SiliconValley/Lab/6888/oopbad.htm

and I'm sure you can find a lot more.

On the pro side, consider how you take advantage of OOP in
Python even *without* coding any classes yourself.  You
tend to look at lists, strings, dictionaries, as objects,
and you invoke their methods by using dot notation, e.g.
alist.append(this) or astring.split(that).

It's useful to think of a string object containing all
these powers, e.g. the power to output an uppercase
version of itself:

   >>> 'a'.upper()
   'A'

The feel here is of a string as a power tool, not as a
helpless sequence of bytes which has to operated on by
some external grab bag of functions.  No, a string or a
list comes with native powers (batteries included).
Data and powers to alter that data are all a part of
the same package.

What I'm suggesting is "dot notation", i.e. object.method()
or object.attribute syntax, has a positive organizing effect
on code even before we start thinking "gee, I wish I could
add to the functionality of this thing" (whence inheritance,
polymorphism, overriding).

You drag and drop some calendar object onto a form, and
start accessing its properties and methods using this
built-in API -- everything relating to this calendar is
prefixed with its name, immediately followed by one of
its methods or properties.  If you want another calendar,
create another instance and work with it the same way.
So simple.

The promise of OO was that it would promote reusability,
and I think it's helped do this.  Programmers now think
naturally along the lines made explicit by JavaBeans (you
have to hand it to Sun, they were very clever with the
whole coffee terminology, which has mnemonic and metaphoric
power -- a case study in good meme design (I'm sure some
find it all too sickly-cute and don't share my appreciative
attitude)).  More programmers now think in terms of writing
these nifty little utilities and packaging them as objects
designed to be accessed using dot notation in the context
of other peoples' programs.

Another thing about OO, which is partially true of Python as
well, and even more so of Java and Smalltalk, is the class
hierarchy is evolved upward from a primitive root system to
provide this large hierarchy of instantiable goodies, including
graphical widgets (Python gets these latter from outside, e.g.
from Tk, but mediated though an OO-style interface (Tkinter)).

Step 1 of learning these languages is to get comfortable with
basic syntax, but a lot of what comes next is growing familiar
with this large class hierarchy.  Now other languages, like
C/C++, offer huge, well-developed libraries.  But to embed
so much functionality into a class hierarchy provides more
of a systematic ordering scheme, a taxonomy, a structure, a
way of thinking about HTML parsers as sub-classes of SGML
parsers, or CGI-capable web servers as subclasses of more
primitive servers.

Python's standard library is far less tree-like than Java's
internal hierarchy, but it's module syntax follows the grain
of OO, i.e. modules are a lot like classes, as we were
discussing a bit earlier.  You import them, and then access
them using the very same dot notation, to get at their
variables and methods.

Anyway, I tend to agree with the criticism that OO is not
a panecea nor the "one correct paradigm" for doing all coding.
That's not so controversial a statement among Pythonistas
in any case, as the language doesn't enforce the OO
paradigm too harshly (in that way it's like Xbase, another
shell-accessible, interpretive language I use a lot, and
in which OO is definitely supported, but not rammed down
your throat).

Having a class facility and the ability to inherit, have
multiple instances of the same class, makes code a lot easier
to write and maintain in many cases (I do computational
geometry with Python a lot, and appreciate having Tetra-
hedron and Cube subclasses of a more generic Polyhedron
class -- fits the way I think).  And when you combine this
with operator overriding, you have the ability to be
creative with syntax as well, in ways which really fit
the problem.  E.g.

   icosa = Icosa()        # make an icosahedron object
   icosa *= 10            # make it 10 times bigger
   icosa.display(objfile) # write it out to a file object

In sum, OO has been, on balance, a very positive development
and influence in the programming world.  But as with any
such positive, some people go overboard and hype it to the
hilt, which overtaxes the tolerance of others, who feel
compelled to supply a skeptical dissenting voice.

These are all ancient patterns, in no way confined to
programming world.  My advice is to not get sucked in to
some partisan camp which wastes a lot of energy fighting
on either side in this debate, as OO is here to stay, and
not-OO is also here to stay.

Kirby




From urnerk@qwest.net  Fri Apr  5 05:47:24 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 04 Apr 2002 21:47:24 -0800
Subject: [Tutor] Working with files, Truckers log
In-Reply-To: <00039dd057e8016b_mailit@mail.c-zone.net>
References: <85F8637F-4823-11D6-B534-00039351FE6A@mac.com>
 <85F8637F-4823-11D6-B534-00039351FE6A@mac.com>
Message-ID: <4.2.0.58.20020404213325.0159acc0@pop3.norton.antivirus>

At 05:58 PM 4/4/2002 +0000, glidedon wrote:

>I think I know how to read and write to a file ,but how do I
>insert this data into the list in my program ?

Note that one solution to saving data is to write out
text which also happens to be executable Python code.
Save the file as a .py, and when you want your data
back, just import it.

For example, if my saved data file looks like this:

a = [1,2,3]
b = {'a':10,'b':30}

then in another program I can go:

from mydata import a,b

and I'll have those values available to me.

Just a thought.

Kirby






From glidedon <glidedon@c-zone.net>  Thu Apr  4 22:13:14 2002
From: glidedon <glidedon@c-zone.net> (glidedon)
Date: Thu, 04 Apr 2002 22:13:14 +0000
Subject: [Tutor] Working with files, Truckers log
In-Reply-To: <4.2.0.58.20020404213325.0159acc0@pop3.norton.antivirus>
References: <85F8637F-4823-11D6-B534-00039351FE6A@mac.com> <85F8637F-4823-11D6-B534-00039351FE6A@mac.com> <4.2.0.58.20020404213325.0159acc0@pop3.norton.antivirus>
Message-ID: <00039dd3e884a4cf_mailit@mail.c-zone.net>

>At 05:58 PM 4/4/2002 +0000, glidedon wrote:
>
>>I think I know how to read and write to a file ,but how do I
>>insert this data into the list in my program ?
>
>Note that one solution to saving data is to write out
>text which also happens to be executable Python code.
>Save the file as a .py, and when you want your data
>back, just import it.
>
>For example, if my saved data file looks like this:
>
>a = [1,2,3]
>b = {'a':10,'b':30}
>
>then in another program I can go:
>
>from mydata import a,b
>
>and I'll have those values available to me.
>
>Just a thought.
>
>Kirby
>
>
>
>

Thanks Kirby

That's a thought that would have never crossed my synapses , without me 
timing out :-)

Don




From charlie@begeistert.org  Fri Apr  5 07:02:30 2002
From: charlie@begeistert.org (Charlie Clark)
Date: Fri, 05 Apr 2002 09:02:30 +0200
Subject: [Tutor] Correcting myself
In-Reply-To: <E16tHJn-000278-00@mail.python.org>
References: <E16tHJn-000278-00@mail.python.org>
Message-ID: <20020405090601.7150.15@gormenghast.1017865497.fake>

On 2002-04-05 at 02:10:02 [+0200], tutor-request@python.org wrote:
> for line in inp.readlines():
> if x is in inp.readlines del x
> del removes an item from a sequence.
This is wrong, sorry! del removes something from the current namespace - it really deletes objects! List have the remove method. I don't use either very often which is probably why I find it easy to confuse them.
l = ['a', 'b', 'c']
l.remove('a')
l
>>> ['b', 'c']
del l
l
>>>NameError: name 'l' is not defined 

Charlie



From alex@gabuzomeu.net  Fri Apr  5 08:28:23 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 05 Apr 2002 10:28:23 +0200
Subject: [Tutor] Counting words
In-Reply-To: <E16tHJn-000278-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020405101412.00b7b980@pop3.norton.antivirus>

Hi Nicole,


At 19:10 04/04/2002 -0500, you wrote:
>From: Nicole Seitz <nicole.seitz@urz.uni-hd.de>
>Date: Thu, 4 Apr 2002 20:28:10 +0200
>Subject: [Tutor] Counting words

>I would like to count words in a file, i.e. I want to know how often a word
>occurs.

Based on the code example you provide, I think you're interested in 
computing the instance count for every unique word in a text snippet.

If you are interested in getting the instance count for a specific word, 
you can also try the count() method of string objects:

 >>> ch = "This is a test string. Yes, a test string."
 >>> ch.count("test")
2

This will be case-sensitive (you can lowercase the string before testing) 
and you may get spurious matches that are part of other words (to avoid 
this, you may need to turn back to regexps :-).


Cheers.

Alexandre




From lumbricus@gmx.net  Fri Apr  5 08:34:17 2002
From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=)
Date: Fri, 5 Apr 2002 10:34:17 +0200 (MEST)
Subject: [Tutor] impact of OO
References: <05196BDE-482A-11D6-B534-00039351FE6A@mac.com>
Message-ID: <6036.1017995657@www50.gmx.net>

> I have a general question about Object Oriented programming in general:  
> why is it so lauded by... well, by everyone?

Not me.I think it's evil.

[ snip ]

> Erik

SCNR J"o!

> object".  What does this mean?  I think I am interested in learning 
> Java, especially since there are many employers in my area (Boston) 
> advertising an interest in Java programmers (and I will be out of a job 
> as soon as my project is finished).  Sadly, much more than Python or 
> PHP.  But it seems like a big language to learn.

In Python everything is an Object, too. And it means exactly that ;-)
BTW: Java is evil.

-- 
sigfault

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net




From alex@gabuzomeu.net  Fri Apr  5 08:38:23 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 05 Apr 2002 10:38:23 +0200
Subject: [Tutor] Working with files
In-Reply-To: <E16tHJn-000278-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020405101906.00b6e570@pop3.norton.antivirus>

Hello,


At 19:10 04/04/2002 -0500, you wrote:
>Date: Thu, 4 Apr 2002 18:27:26 -0500
>Subject: Re: [Tutor] Working with files
>From: Erik Price <erikprice@mac.com>

> > import re
> >
> > for line in inp.readlines():
> >   if re.search(r'Canada', line): continue # if line contains 'Canada'
> >   outp.write(line)
>
>The only thing with this is that it wouldn't catch a phrase (or a word)
>that was split between two lines.
>
>I can't think of a good solution that doesn't require the entire
>haystack string to be read into memory.

You could try using 'read(aChunkSize)' instead of 'readlines()'.

Except from the library reference:

read([size])
Read at most size bytes from the file (less if the read hits EOF before 
obtaining size bytes). If the size argument is negative or omitted, read 
all data until EOF is reached. The bytes are returned as a string object. 
An empty string is returned when EOF is encountered immediately.

So I guess you could read and test chunks two by two. Sounds a bit more 
complex since you'd need to test a+b, b+c, etc. I suppose there is a 
standard solution (anyone ? :-)


Cheers.

Alexandre




From lumbricus@gmx.net  Fri Apr  5 09:00:26 2002
From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=)
Date: Fri, 5 Apr 2002 11:00:26 +0200 (MEST)
Subject: [Tutor] len(l) as loop index
References: <fc.004c4b6b00930fc1004c4b6b00930fc1.930ffb@blakeschool.org>
Message-ID: <32742.1017997226@www50.gmx.net>

> Advice request:
> 
> Since the calculation of the list length is probably such a small part of
> any task you are doing, is there any problem with using len(list) as a
> loop index as opposed to calculating it once (e.g. n = len(list)) and then
> using n as the loop index:

But in your examples len(list) is _not_ the
loop index. It is just the maximum value of
the index i (!). And it is only computed once
(I think). So it is OK.
 
> list=[1,2,3]
> i=0
> while i<len(list):
> 	print list[i]
> 	i=i+1
> 
> or should we not even be using the while loop this, using the following
> instead:
> 
> for i in range(len(list)):
> 	print list[i]
> 
> or (if you don't need to know where you are):
> 
> for x in list:
> 	print x
> 
> The first method has been the method of choice for the How to Think text
> on Python for beginners.
> 
> /c

HTH, HAND and
Greetings, J"o!

-- 
$ make LOVE
Make: Don't know how to make LOVE.  Stop.
$ 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net




From alan.gauld@bt.com  Fri Apr  5 09:56:35 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 5 Apr 2002 10:56:35 +0100
Subject: [Tutor] len(l) as loop index
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C50B@mbtlipnt02.btlabs.bt.co.uk>

> >That's a big assumption! A len() query basically has to 
> >run alomng the list counting members. 
> 
> Are you sure?  That's what I thought but then I thought the length
> parameter might actually be something that Python stores with its info

I guess a test will prove it...

#-------------
import time
#create lists outside loop to avoid slewing results
Lists = [range(10), range(10000), range(10000000)]

start = time.time()

for i in [0,1,2]:
    len(Lists[i]) # use different length lists

mid = time.time()

for i in [0,1,2]:
    len(Lists[0]) # use same length list each time

stop = time.time()
print mid-start
print stop-mid
#-----------------

Yields
0.05
0.0

So it looks from this test that len() is dependant 
to some degree on length of list.
But if thats true then by using Lists[2] in the 
second loop I should get the second figure being 
bigger, in fact I get:
0.05
0.0

Exactly the same! Oh well,  I guess we need to 
go read the source... ;-)

Anyone else checked the source while I've been wasting 
my time?

Alan g.



From alan.gauld@bt.com  Fri Apr  5 10:19:16 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 5 Apr 2002 11:19:16 +0100
Subject: [Tutor] impact of OO
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C50D@mbtlipnt02.btlabs.bt.co.uk>

> I have a general question about Object Oriented programming 
> in general:  why is it so lauded by... well, by everyone?

Its not. There are several minority groups who believe that 
OO is a retrograde step. Others believe that things like 
Functional Programming are more important etc etc. But 
the general opinion is that OO is a big improvement on 
traditional "Structured Methods"


There are lots of reasons, most only relevant to large 
projects so its hard for the newbie writing programs of 
only a few hundred lines to see the avantages. But one 
your prohgrams get into the tens of thousands of lines 
the benefits become far more obvious. However...

> to with a group of variable names.  It's hard to describe, but this 
> makes it much easier -- 

... even in smaller projects it can show benefits in ease 
of comprehension - as you've seen.

> but it is far more organized and cleaner.

We used to have one maintenance programmer looking after, 
on average 20,000 lines of code(in C) when we moved to 
OO designs we have one programmer looking after 100,000 
lines. A 5 to 1 improvement, mainly due to the better 
cohesion of the designs using OOP.

> ...but I still don't really see how 
> it's that big a deal -- it's simply a different way of 
> organizing code, as far as I can tell.

Which is the hardest aspect of industrial grade 
software engineering. Organizing code such that when one 
bit changes you don't need to change everything elsder 
with it has been the biggest headache in softwae since 
the start of commercial programming. OOP helps do just that.

> Please prove me wrong and help me see how OO "changed everything".

It doesn't change everything but it helps a lot.

There are other aspects to OOP too that we haven't 
touched on. The ease of extending existing code without 
changing it (and thus breaking existing code relying 
on the bit being extended) via inheritance. The way 
OOP eliminates long if/elif/else chains (or switch 
statements)via polymorphism (see the OOP page in my 
tutor for a discussion of polymorphism and inheritance)

The ability to build whoile abstract frameworks which 
act as application templates. These can quickly be 
added to to produce new apps - most GUI frameworks 
are done this way.


> PS:  Also, I have heard someone say that "in Java everything is an 
> object".  

Its a lie. In Java everything is in a class... 
only some things are objects. There is a big difference 
which the Java community seems to disregard. But claiming 
that everything is anobject is a big marketing coup!


> Java, especially since there are many employers 

This sadly is true. Mainly a result of the "emperors new clothes" syndrome
but none the less Java is taking over.


in my area (Boston) 
> advertising an interest in Java programmers (and I will be 
> out of a job 
> as soon as my project is finished).  Sadly, much more than Python or 
> PHP.  But it seems like a big language to learn.
> 
> 
> 
> 
> 
> 



From alan.gauld@bt.com  Fri Apr  5 10:32:05 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 5 Apr 2002 11:32:05 +0100
Subject: [Tutor] Working with files, Truckers log
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C50E@mbtlipnt02.btlabs.bt.co.uk>

> to a file , to be  used later to append the list.  The list 
> contains decimal numbers.
> 
> Here is a sample list [ 8.5,8,9.5,10.75,6.25 ]
> 
> I think I know how to read and write to a file ,but how do I 
> insert this data into the list in my program ?
> 
> I am working my way through Alan's book  (Wesley your book is 
> next :-) )and  its chapter on files uses text in its examples, 
> how do I handle numerical data ?

There are several options including writing data 
as raw binary (see the sidebar in the book) but personally 
I'd just go with converting the number to/from text.

Thus use format strings to write it to the file and when 
reading it back use the float() or int() convertion 
functions to read it back.

Alternatively, as Kirby suggested you can write it as a 
python data structure and use the eval() function to 
recreate it.

v1 = [2,3,4.5,'fred',42]
lineout = str(v1)  # convert to a string
outfile.write(lineout)
outfile.close()

infile = open(data,py)
line = infile.read()
values = eval(line)

values should now contain an identical copy of v1

Aan G.



From nicole.seitz@urz.uni-hd.de  Fri Apr  5 11:28:30 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Fri, 5 Apr 2002 13:28:30 +0200
Subject: [Tutor] Counting words
In-Reply-To: <XFMail.20020404114214.shalehperry@attbi.com>
References: <XFMail.20020404114214.shalehperry@attbi.com>
Message-ID: <02040510084400.00705@utopia>

Am Donnerstag,  4. April 2002 21:42 schrieben Sie:

> what is happening is the 'get' method of the dictionary is being called. 
> It is looking for the key specified by word and if it is not found it
> returns 0.
>
> This is equivalent to:
>
> if occurences.has_key(word):
>   occurences[word] = occurences[word] + 1
> else:
>   occurences[word] = 1


Now it's very clear, thanks!


>
> > Second question:
> > "Some" and "some" should be recognized as one word, the same is with
> > "BORING" and "boring". I  thought of string.lowercase as a possible
> > solution, but as it doesn't  work , I might be wrong. Any idea what to
> > do?
>
> word = string.lower(word)

I am so stupid! I do know this function from string module. I mixed up 
lower() and lowercase. I guess one should not program when he or she is 
totally overtired.It's much better when your brain's engaged:-)

> ['A', 'typical', 'line', '']
>
> notice the empty last entry.  Have you loop skip empty words.

Like this?

for word in reg.split(text):
    if word == "": continue
    word = string.lower(word)
    occurences[word] = occurences.get(word,0)+1




Many thanks.

Nicole





From erikprice@mac.com  Fri Apr  5 13:24:52 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 5 Apr 2002 08:24:52 -0500
Subject: [Tutor] Working with files
In-Reply-To: <4.3.2.7.2.20020405101906.00b6e570@pop3.norton.antivirus>
Message-ID: <83697490-4898-11D6-B633-00039351FE6A@mac.com>

On Friday, April 5, 2002, at 03:38  AM, Alexandre Ratti wrote:

>> > import re
>> >
>> > for line in inp.readlines():
>> >   if re.search(r'Canada', line): continue # if line contains 'Canada'
>> >   outp.write(line)
>>
>> The only thing with this is that it wouldn't catch a phrase (or a word)
>> that was split between two lines.
>>
>> I can't think of a good solution that doesn't require the entire
>> haystack string to be read into memory.
>
> You could try using 'read(aChunkSize)' instead of 'readlines()'.
>
> Except from the library reference:
>
> read([size])
> Read at most size bytes from the file (less if the read hits EOF before 
> obtaining size bytes). If the size argument is negative or omitted, 
> read all data until EOF is reached. The bytes are returned as a string 
> object. An empty string is returned when EOF is encountered immediately.
>
> So I guess you could read and test chunks two by two. Sounds a bit more 
> complex since you'd need to test a+b, b+c, etc. I suppose there is a 
> standard solution (anyone ? :-)

Ah, I hadn't thought of that.  All along I was wondering why one would 
ever want to read certain lengths rather than something convenient like 
lines or the length of the file.  (I mean, I knew the option to specify 
a length had a place for certain power coders or people with esoteric 
needs, but it didn't seem useful to me immediately.)

But you're right, one still needs to find a way to manage overlaps 
between chunksizes.  Perhaps something like this pseudocode:

# won't work; pseudocode
# needle = string to search for
chunk_size = len(needle)
if (!f = open('filename')):
   print 'Could not open ', haystack, ' for searching'
else:
   while 1:
     # pointer_multiplier is used to set read position in file
     pointer_multiplier = 1
     # read a section of the file twice the length of needle
     haystack = f.read(chunk_size * 2)
     # if needle is found, report it and stop
     if re.search(needle, haystack):
       print 'Found ', needle, '!'
       break
     else:
       # here's the pseudocode b/c I don't know how to write this yet
       # (and I'm late for work so I can't look it up)

       move internal file pointer (chunk_size * pointer_multiplier) bytes 
forward from start of file
       pointer_multiplier = pointer_multiplier + 1



Well, it's a try at least.  Maybe I've overlooked something.  But it 
lets you read discrete chunks instead of the entire file all at once, 
and as far as I can tell you would still be able to find a string if you 
accounted for newlines/end-of-line characters.

Of course, if needle is half the length of the file or more, you may as 
well just read the whole file into memory.

What do you think?


Erik




From roman@ga2.so-net.ne.jp  Fri Apr  5 13:50:44 2002
From: roman@ga2.so-net.ne.jp (Roman Suzuki)
Date: Fri, 5 Apr 2002 22:50:44 +0900
Subject: [Tutor] How to interrupt in IDLE
Message-ID: <002901c1dca8$e311de20$e3df84d2@thinkpad1200>

This is a multi-part message in MIME format.

------=_NextPart_000_0025_01C1DCF4.51E3D060
Content-Type: text/plain;
	charset="iso-2022-jp"
Content-Transfer-Encoding: 7bit

Hi, everyone

I'v just started learning Python language. and I am doing "Python Tutorial".
When I tried following example on  Section 4.5 "IDLE for Windows" freezed.
# example ----------
>>> while 1:
    pass
# example ----------

I had to push Ctrl+Alt+Del to kill IDLE.. If you know right way to interrupt
in IDLE, tell me that, please.

-------------------------------------------
Roman Suzuki
E-mail:
  roman@ga2.so-net.ne.jp
Homepage:
  http://romansuzuki@tripod.com

  10 Tajiri Miya-cho Gamagoori-shi
  Aichi 443-0021 JAPAN




------=_NextPart_000_0025_01C1DCF4.51E3D060
Content-Type: text/html;
	charset="iso-2022-jp"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-2022-jp">
<META content=3D"MSHTML 6.00.2715.400" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT size=3D2>Hi, everyone </FONT></DIV>
<DIV><FONT size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT size=3D2>I'v just started learning Python language. and =
</FONT><FONT=20
size=3D2>I am doing "Python Tutorial".&nbsp;</FONT></DIV>
<DIV><FONT size=3D2>When&nbsp;I tried following&nbsp;example =
on&nbsp;&nbsp;Section=20
4.5 <FONT size=3D2>"IDLE for Windows" freezed.</FONT></FONT></DIV>
<DIV><FONT size=3D2># example ----------</FONT></DIV>
<DIV><FONT size=3D2>&gt;&gt;&gt; while 1:</FONT></DIV>
<DIV><FONT size=3D2>&nbsp;&nbsp;&nbsp; pass</FONT></DIV>
<DIV><FONT size=3D2>
<DIV><FONT size=3D2># example ----------</FONT></DIV>
<DIV>&nbsp;</DIV></FONT></DIV>
<DIV><FONT size=3D2>I had to push Ctrl+Alt+Del to kill IDLE.. If you =
know right=20
way to interrupt in IDLE, tell me that, please.</FONT></DIV>
<DIV><FONT size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT =
size=3D2>-------------------------------------------</FONT></DIV>
<DIV><FONT size=3D2>Roman Suzuki <BR>E-mail:&nbsp; <BR>&nbsp; <A=20
href=3D"mailto:roman@ga2.so-net.ne.jp">roman@ga2.so-net.ne.jp</A><BR>Home=
page:<BR>&nbsp;=20
<A=20
href=3D"http://romansuzuki@tripod.com">http://romansuzuki@tripod.com</A><=
/FONT></DIV>
<DIV><FONT size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT size=3D2>&nbsp; 10 Tajiri Miya-cho Gamagoori-shi <BR>&nbsp; =
Aichi=20
443-0021 JAPAN<BR></FONT></DIV>
<DIV><FONT size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT size=3D2></FONT>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0025_01C1DCF4.51E3D060--




From alex@gabuzomeu.net  Fri Apr  5 14:30:05 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 05 Apr 2002 16:30:05 +0200
Subject: [Tutor] [OT] Terminogy: factored
Message-ID: <4.3.2.7.2.20020328183101.00b008a0@pop3.norton.antivirus>

Hello,


Here is a terminology query. This is a bit off topic for Python, but I 
guess it is relevant for our "programming culture" in a broader meaning :-)

I came across the word "factored" in a document. The examples they refer to 
are in C++ (AFAIK).

	The code samples used do not have exception handling, are not
	optimized, and are not *factored*. Thus, they are not intended for
	production systems.

And:

	In creating our example components, we will keep it as simple as
	possible to focus on the purpose of learning how and why to
	implement the interface methods. Hence, there will not be any
	complex error handling or reporting and the code will not be
	optimized and *factored*.

What does "factored" mean in this context? I know what "refactoring" legacy 
code means, is it related?


Thanks.

Alexandre




From urnerk@qwest.net  Fri Apr  5 15:31:26 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 05 Apr 2002 07:31:26 -0800
Subject: [Tutor] Working with files, Truckers log
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C50E@mbtlipnt02.btlabs
 .bt.co.uk>
Message-ID: <4.2.0.58.20020405071752.01a124a0@pop3.norton.antivirus>

>
>Alternatively, as Kirby suggested you can write it as a
>python data structure and use the eval() function to
>recreate it.

Actually, I wasn't suggesting using eval().  I was
suggesting saving the string

v1 = [2,3,4.5,'fred',42]

instead of just

[2,3,4.5,'fred',42]

in the data.py file, and then accessing v1 as a module
variable after importing it (not opening it).

E.g.

   outfile = open('data.py','w')
   lineout = 'v1 = ' + str([2,3,4.5,'fred',42])
   outfile.write(lineout)
   outfile.close()

then:

   from data import v1

Kirby




From alan.gauld@bt.com  Fri Apr  5 15:33:59 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 5 Apr 2002 16:33:59 +0100
Subject: [Tutor] Working with files, Truckers log
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C511@mbtlipnt02.btlabs.bt.co.uk>

> >Alternatively, as Kirby suggested you can write it as a
> >python data structure and use the eval() function to
> >recreate it.
> 
> Actually, I wasn't suggesting using eval().  I was
> suggesting saving the string

Yes, sorry I worded that badly. I should have said:

   "Alternatively, somewhat as Kirby suggested, you can write 
    it as a python data structure and use the eval() function 
    to recreate it."

The module/import approach would work too but eval() seems 
to be the idiomatic way that has been implemented in various 
well known projects. I was just trying to show an alternative.

The eval route has a couple of pro/con versus the import 
technique IMO.

Pro: It must be a single expression and so is less likely 
to be impregnated by viral code

Con: It can only be a single expression so tyou need to 
create a list of data structures or similar trick if you 
want to save lots of things.


Alan g.



From shalehperry@attbi.com  Fri Apr  5 15:59:10 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 05 Apr 2002 07:59:10 -0800 (PST)
Subject: [Tutor] Counting words
In-Reply-To: <02040510084400.00705@utopia>
Message-ID: <XFMail.20020405075910.shalehperry@attbi.com>

> Like this?
> 
> for word in reg.split(text):
>     if word == "": continue
>     word = string.lower(word)
>     occurences[word] = occurences.get(word,0)+1
> 

the python idiom is 'if not word: continue'.



From urnerk@qwest.net  Fri Apr  5 16:55:28 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 05 Apr 2002 08:55:28 -0800
Subject: [Tutor] Counting words
In-Reply-To: <XFMail.20020405075910.shalehperry@attbi.com>
References: <02040510084400.00705@utopia>
Message-ID: <4.2.0.58.20020405085310.01a11cb0@pop3.norton.antivirus>

Note:  in a recent Linux Journal, Alex Martelli gives a
very short program for indexing all the words in an
entire directory of .txt files, giving users the ability
to enter a word, and get back a listing of every file
and sentence wherein the word occurs.

Kirby




From brad.reisfeld@colostate.edu  Fri Apr  5 16:58:37 2002
From: brad.reisfeld@colostate.edu (Brad Reisfeld)
Date: Fri, 5 Apr 2002 09:58:37 -0700
Subject: [Tutor] combining tuples in a list
Message-ID: <NGEALAODAKLOJADDLGPAEEEHCBAA.brad.reisfeld@colostate.edu>

Hi,
I am faced with the problem of 'combining' tuples in a list in such a way
that any tuple whose last element matches the first element of another tuple
must be combined (eliminating the duplicate element). My aim is to end up
with a list of these resulting tuples.

In practice, I have a list containing a very large number of tuples (each of
which has three items). A short example illustrating this is

inlist =
[('c','p','l'),
('d','e','f'),
('c','h','i'),
('f','w','x'),
('a','b','c'),
('g','h','i'),
('r','z','d')]

For this case we see that the last element in the fifth tuple, 'c', matches
the first element in the third tuple. Combining these (and eliminating the
duplicate match) gives ('a','b','c') '+' ('c','h','i') =>
('a','b','c','h','i')

Following this procedure exhaustively on the list above would yield the
desired result (order of tuples in the final list doesn't matter):

outlist =
[('a','b','c','h','i'),
('r','z','d','e','f','w','x'),
('g','h','i'),
('a','b','c','p','l')]


Currently, I am carrying out this procedure in a seemingly very inefficient
way by going through the list of tuples multiple times for each tuple I am
building up. I'm sure there must be a better way.

Any suggestions are appreciated.

Thanks.

-Brad




From shalehperry@attbi.com  Fri Apr  5 17:16:18 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 05 Apr 2002 09:16:18 -0800 (PST)
Subject: [Tutor] combining tuples in a list
In-Reply-To: <NGEALAODAKLOJADDLGPAEEEHCBAA.brad.reisfeld@colostate.edu>
Message-ID: <XFMail.20020405091618.shalehperry@attbi.com>

> 
> Currently, I am carrying out this procedure in a seemingly very inefficient
> way by going through the list of tuples multiple times for each tuple I am
> building up. I'm sure there must be a better way.
> 
> Any suggestions are appreciated.
> 

The only thought coming to me (admittedly as I munch breakfast) is that if you
sort the list based on the last char of each tuple you can reduce the number of
elements you have to check.



From alex@gabuzomeu.net  Fri Apr  5 17:28:55 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 05 Apr 2002 19:28:55 +0200
Subject: [Tutor] Working with files, Truckers log
In-Reply-To: <E16tPFO-0006BZ-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020405114803.00b7bd60@pop3.norton.antivirus>

Hello,


At 03:38 05/04/2002 -0500, you wrote:
>Subject: Re: [Tutor] Working with files, Truckers log
>From: glidedon <glidedon@c-zone.net>
>Date: Thu, 04 Apr 2002 17:58:03 +0000

>This is a timely subject for me :-). I want to save data that is in a list
>to a file , to be  used later to append the list.  The list contains decimal
>numbers.
>
>Here is a sample list [ 8.5,8,9.5,10.75,6.25 ]
>
>I think I know how to read and write to a file ,but how do I insert this data
>into the list in my program ?

If you store your values in a text file, for instance one per line, it will 
be fairly simple to load them back and append them to a list. You can use 
eval() to transform a string value into a decimal value.

Note that eval() is often considered a security risk since it will happily 
execute any code. Is is advisable to test any input string before feeding 
it to eval() to make sure it only contains safe data.

Here is a function I used a couple of days ago:

import re

def isNumeric(inputString):
     "Returns TRUE is inputString only contains digits (or a dot)."
     expr = re.compile("^[\d\.]+$")
     return not(expr.search(inputString) == None)

Usage example:

if isNumeric(inputString):
     value = eval(inputString)
else:
     raise "Funny value error!"

(snip)

>while 1:
>     add_days = raw_input('\n' 'Do you want to add more days to recap 
> ?  y/n
>: ' )
>
>     if add_days in ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) :

You may want to lowercase the input string add_day before testing it so 
that you can support different answers more easily (you would not need to 
store both "y" and "Y" in the response list).


Cheers.

Alexandre




From urnerk@qwest.net  Fri Apr  5 18:27:30 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 05 Apr 2002 10:27:30 -0800
Subject: [Tutor] combining tuples in a list
In-Reply-To: <NGEALAODAKLOJADDLGPAEEEHCBAA.brad.reisfeld@colostate.edu>
Message-ID: <4.2.0.58.20020405102051.01a07c30@pop3.norton.antivirus>

At 09:58 AM 4/5/2002 -0700, Brad Reisfeld wrote:

>Currently, I am carrying out this procedure in a seemingly very
>inefficient way by going through the list of tuples multiple
>times for each tuple I am building up. I'm sure there must be
>a better way.
>
>Any suggestions are appreciated.
>
>Thanks.
>
>-Brad

Some use of the dictionary data structure, keying off
first and last letters of your tuples, would help you
find the splice points.

This would give you a quick way of looking up which
tuples start or end with a particular letter.

I'm wondering if the problem as presented is completely
defined though.  Suppose I have (a,b,a) and (a,c,a,b,a),
does this become:

    (a,b,a) + (a,c,a,b,a) = (a,b,a,c,a,b,a)

or

    (a,c,a,b,a) + (a,b,a) = (a,c,a,b,a,b,a)

Kirby




From lha2@columbia.edu  Fri Apr  5 18:22:11 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Fri, 05 Apr 2002 13:22:11 -0500
Subject: [Tutor] combining tuples in a list
References: <NGEALAODAKLOJADDLGPAEEEHCBAA.brad.reisfeld@colostate.edu>
Message-ID: <3CADEB53.533B6FA9@mail.verizon.net>

Brad Reisfeld wrote:
> 
> Hi,
> I am faced with the problem of 'combining' tuples in a list in such a way
> that any tuple whose last element matches the first element of another tuple
> must be combined (eliminating the duplicate element). My aim is to end up
> with a list of these resulting tuples.
> 
> In practice, I have a list containing a very large number of tuples (each of
> which has three items). A short example illustrating this is
> 
> inlist =
> [('c','p','l'),
> ('d','e','f'),
> ('c','h','i'),
> ('f','w','x'),
> ('a','b','c'),
> ('g','h','i'),
> ('r','z','d')]
> 
> For this case we see that the last element in the fifth tuple, 'c', matches
> the first element in the third tuple. Combining these (and eliminating the
> duplicate match) gives ('a','b','c') '+' ('c','h','i') =>
> ('a','b','c','h','i')
> 
> Following this procedure exhaustively on the list above would yield the
> desired result (order of tuples in the final list doesn't matter):
> 
> outlist =
> [('a','b','c','h','i'),
> ('r','z','d','e','f','w','x'),
> ('g','h','i'),
> ('a','b','c','p','l')]
> 
> Currently, I am carrying out this procedure in a seemingly very inefficient
> way by going through the list of tuples multiple times for each tuple I am
> building up. I'm sure there must be a better way.
> 
> Any suggestions are appreciated.
> 
> Thanks.
> 
> -Brad
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Here's an ugly way--the idea is that it runs through the list twice
(once forwards, then once through the output the other direction), and
hopefully gets everything that way. I'm uncomfortable with the repeated
output that is created from the (abc)(cpl)(chi), but that seems to be
what you want. The problem is that (aba)(aca) should, following these
rules, create an infinite loop (I'm assuming that an item should not
join to itself).

Because what we want the tuples to do to each other is extremely similar
to tuple concatenation, I thought it would be a good chance to use class
inheritance; __mul__ is overwritten instead of __add__ because the
procedure refers to the old __add__, if that makes any sense. That whole
"don't use the word in its own definition" (usually) thing.

###
class concatuple(tuple):
    def __mul__(self, other):
        """concatenates two tuples together, dropping the common
element.

        Ugly stuff happened when I tried to use __add__ to do this (inf
loop;
        sorry for the kludge)."""
#        print self
#        print other
        if self[-1] == other[0]:
            return self + other[1:]
        else:
            raise ValueError

def cyclelist(inlist):
    outlist = []
    while inlist:
        first = inlist[0]
    #    print first
        for second in inlist[1:]:
            if first[-1] == second[0]:
                inlist.append(first*second)
                try:
                    inlist.remove(first)
                except:
                    print "First arg tried to be removed twice"
                try:
                    inlist.remove(second)
                except:
                    print "Second arg tried to be removed twice"

        if first == inlist[0]:  #no matches found
            outlist.append(first)
            inlist.remove(first)
    return outlist

        
if __name__ == "__main__":
    inlist = map(concatuple, [('c','p','l'),
              ('d','e','f'),
              ('c','h','i'),
              ('f','w','x'),
              ('a','b','c'),
              ('g','h','i'),
              ('r','z','d')])
    newin = cyclelist(inlist)
#    print newin
    newin.reverse()
#    print newin
    outlist = cyclelist(newin)
    print outlist



From irishpnk@yahoo.com  Fri Apr  5 18:29:53 2002
From: irishpnk@yahoo.com (Brian Callahan)
Date: Fri, 5 Apr 2002 10:29:53 -0800 (PST)
Subject: [Tutor] Tkinter problem
Message-ID: <20020405182953.51352.qmail@web10707.mail.yahoo.com>

Hi everyone.  I'm trying to learn Tkinter right now
and I've run into a problem.  One of my examples is to
create a button widget.  I've entered the code and
when I try to run it, it tells me that I have a syntax
errors and points to the button event.  I've tripple
checked the code to make sure I didn't type anything
wrong.  Any other suggestions??? I'm including a copy
of the code. Thanx.
#!/usr/local/bin/python

import sys
from Tkinter import *

def die(event):
    sys.exit(0)

root = Tk()
 button = Button(root)
 button["text"] = "Ave atque vale!"
 button.bind("<Button-1>", die)
 button.pack()
 root.mainloop()



__________________________________________________
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
http://taxes.yahoo.com/



From brad.reisfeld@colostate.edu  Fri Apr  5 18:57:56 2002
From: brad.reisfeld@colostate.edu (Brad Reisfeld)
Date: Fri, 5 Apr 2002 11:57:56 -0700
Subject: [Tutor] combining tuples in a list
In-Reply-To: <3CADEB53.533B6FA9@mail.verizon.net>
Message-ID: <NGEALAODAKLOJADDLGPAKEEHCBAA.brad.reisfeld@colostate.edu>

Thank you for the response.

It looks like an interesting approach. What version of Python are you using?
I get a "TypeError: base is not a class object" error when I try to run the
script. Is it possible for a class to inherit from the tuple type in Python
2.1?

To answer the question both you and Kirby raised, the beginning and ending
members of a given tuple should never be the same, i.e. ('a','b','a') should
never happen in my problem.

-Brad

-----Original Message-----
From: Lloyd Hugh Allen [mailto:l.h.allen@verizon.net]
Sent: Friday, April 05, 2002 11:22 AM
To: Brad Reisfeld
Cc: tutor@python.org
Subject: Re: [Tutor] combining tuples in a list

Here's an ugly way--the idea is that it runs through the list twice
(once forwards, then once through the output the other direction), and
hopefully gets everything that way. I'm uncomfortable with the repeated
output that is created from the (abc)(cpl)(chi), but that seems to be
what you want. The problem is that (aba)(aca) should, following these
rules, create an infinite loop (I'm assuming that an item should not
join to itself).

Because what we want the tuples to do to each other is extremely similar
to tuple concatenation, I thought it would be a good chance to use class
inheritance; __mul__ is overwritten instead of __add__ because the
procedure refers to the old __add__, if that makes any sense. That whole
"don't use the word in its own definition" (usually) thing.

###
class concatuple(tuple):
    def __mul__(self, other):
        """concatenates two tuples together, dropping the common
element.

        Ugly stuff happened when I tried to use __add__ to do this (inf
loop;
        sorry for the kludge)."""
#        print self
#        print other
        if self[-1] == other[0]:
            return self + other[1:]
        else:
            raise ValueError

def cyclelist(inlist):
    outlist = []
    while inlist:
        first = inlist[0]
    #    print first
        for second in inlist[1:]:
            if first[-1] == second[0]:
                inlist.append(first*second)
                try:
                    inlist.remove(first)
                except:
                    print "First arg tried to be removed twice"
                try:
                    inlist.remove(second)
                except:
                    print "Second arg tried to be removed twice"

        if first == inlist[0]:  #no matches found
            outlist.append(first)
            inlist.remove(first)
    return outlist


if __name__ == "__main__":
    inlist = map(concatuple, [('c','p','l'),
              ('d','e','f'),
              ('c','h','i'),
              ('f','w','x'),
              ('a','b','c'),
              ('g','h','i'),
              ('r','z','d')])
    newin = cyclelist(inlist)
#    print newin
    newin.reverse()
#    print newin
    outlist = cyclelist(newin)
    print outlist




From max_ig@yahoo.com  Fri Apr  5 19:34:39 2002
From: max_ig@yahoo.com (Maximiliano Ichazo)
Date: Fri, 5 Apr 2002 11:34:39 -0800 (PST)
Subject: [Tutor] Tkinter problem
In-Reply-To: <20020405182953.51352.qmail@web10707.mail.yahoo.com>
Message-ID: <20020405193439.94606.qmail@web11307.mail.yahoo.com>

Brian,

Try this:

> 
> import sys
> from Tkinter import *
> 
> def die(event):
>     sys.exit(0)
> 
> root = Tk()

Dedent the following lines:

>  button = Button(root)
>  button["text"] = "Ave atque vale!"
>  button.bind("<Button-1>", die)
>  button.pack()
>  root.mainloop()

That's all.

Max

__________________________________________________
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
http://taxes.yahoo.com/



From lha2@columbia.edu  Fri Apr  5 19:52:51 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Fri, 05 Apr 2002 14:52:51 -0500
Subject: [Tutor] combining tuples in a list
References: <NGEALAODAKLOJADDLGPAKEEHCBAA.brad.reisfeld@colostate.edu>
Message-ID: <3CAE0093.A1855123@mail.verizon.net>

I use 2.2. Needed to have 2.2 to use Danny's "Permutations using
Generators" to answer a friend's problem.

Now that I look more closely at inheritance, I could have overwritten
the __add__ method, but then within it called tuple.__add__(self,
other[1:]) to make the code more transparent. Don't want to repost the
whole big thing though.

A complete solution, then, would also have to check and make sure that
you don't have (abc)(cda), which would yield an animal with its head at
its tail.

Brad Reisfeld wrote:
> 
> Thank you for the response.
> 
> It looks like an interesting approach. What version of Python are you using?
> I get a "TypeError: base is not a class object" error when I try to run the
> script. Is it possible for a class to inherit from the tuple type in Python
> 2.1?
> 
> To answer the question both you and Kirby raised, the beginning and ending
> members of a given tuple should never be the same, i.e. ('a','b','a') should
> never happen in my problem.
> 
> -Brad
>



From dyoo@hkn.eecs.berkeley.edu  Fri Apr  5 20:18:24 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 5 Apr 2002 12:18:24 -0800 (PST)
Subject: [Tutor] combining tuples in a list  [NP complete reduction]
In-Reply-To: <4.2.0.58.20020405102051.01a07c30@pop3.norton.antivirus>
Message-ID: <Pine.LNX.4.44.0204051157310.7010-100000@hkn.eecs.berkeley.edu>

On Fri, 5 Apr 2002, Kirby Urner wrote:

> At 09:58 AM 4/5/2002 -0700, Brad Reisfeld wrote:
>
> >Currently, I am carrying out this procedure in a seemingly very
> >inefficient way by going through the list of tuples multiple
> >times for each tuple I am building up. I'm sure there must be
> >a better way.
>
> Some use of the dictionary data structure, keying off
> first and last letters of your tuples, would help you
> find the splice points.


But his question is very very hard, deceptively so.  It's the traveling
salesman problem, a problem that haunts the dim nightmares of Computer
Science students everywhere.


The "traveling salesman problem" can be paraphrased as: given a list of
cities and a list of the roads between the cities, find the shortest route
along the roads that passes through all of the cities.


Imagine that we have a bunch of cities:

###
cities = ['c', 'l', 'd', 'f', 'i', 'x', 'a', 'g', 'r', 'd']
###

and a bunch of roads that can connect these cities together:

###
roads = [('c', 'l'),
         ('d', 'f'),
         ('c', 'i'),
	 ('f', 'x'),
         ('a', 'c'),
         ('g', 'i'),
         ('r', 'd')]
###


But suddenly, this traveling salesman instance looks suspiciously like
Brad's tuple-connected problem...

###
inlist = [('c','p','l'),
          ('d','e','f'),
          ('c','h','i'),
          ('f','w','x'),
          ('a','b','c'),
          ('g','h','i'),
          ('r','z','d')]
##

So any "fast" solution to the tuple-connecting problem will solve the
traveling salesman problem.




From nicole.seitz@urz.uni-hd.de  Fri Apr  5 20:42:58 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Fri, 5 Apr 2002 22:42:58 +0200
Subject: [Tutor] Cheating?No, not me:-)
In-Reply-To: <20020324220138.GA11090@dman.ddts.net>
References: <20020324210443.GC10420@dman.ddts.net> <Pine.LNX.4.44.0203241327110.27560-100000@hkn.eecs.berkeley.edu> <20020324220138.GA11090@dman.ddts.net>
Message-ID: <02040522425802.00703@utopia>

Am Sonntag, 24. M=E4rz 2002 23:01 schrieb dman:
>
>
> | For people who are interested: here's a similar problem: "Given a tex=
t
> | file and an integer K, you are to print the K most common words in th=
e
> | file (and the number of their occurences) in decreasing frequency."
>
> <cheater's hint>
> Search the tutor archives.  With only a couple minor modifications the
> answer is already there.
> </cheater's hint>
>

Some hint WHERE in the archives I could find the answer?Month?Year?

Thanx!

Nicole=20



From brad.reisfeld@colostate.edu  Fri Apr  5 20:43:45 2002
From: brad.reisfeld@colostate.edu (Brad Reisfeld)
Date: Fri, 5 Apr 2002 13:43:45 -0700
Subject: [Tutor] combining tuples in a list  [NP complete reduction]
In-Reply-To: <Pine.LNX.4.44.0204051157310.7010-100000@hkn.eecs.berkeley.edu>
Message-ID: <NGEALAODAKLOJADDLGPAMEEICBAA.brad.reisfeld@colostate.edu>

I agree that is seems like a hard problem (although this is probably because
my brain is a bit muddled), but I don't believe that this is a restatement
of the traveling salesman problem.

The problem seems to be one of enumeration (since the 'splicing' dictates
the paths), rather than one of optimization (to find the paths).

-Brad

-----Original Message-----
From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
Sent: Friday, April 05, 2002 1:18 PM
To: Kirby Urner
Cc: Brad Reisfeld; tutor@python.org
Subject: Re: [Tutor] combining tuples in a list [NP complete reduction]


On Fri, 5 Apr 2002, Kirby Urner wrote:

> At 09:58 AM 4/5/2002 -0700, Brad Reisfeld wrote:
>
> >Currently, I am carrying out this procedure in a seemingly very
> >inefficient way by going through the list of tuples multiple
> >times for each tuple I am building up. I'm sure there must be
> >a better way.
>
> Some use of the dictionary data structure, keying off
> first and last letters of your tuples, would help you
> find the splice points.


But his question is very very hard, deceptively so.  It's the traveling
salesman problem, a problem that haunts the dim nightmares of Computer
Science students everywhere.


The "traveling salesman problem" can be paraphrased as: given a list of
cities and a list of the roads between the cities, find the shortest route
along the roads that passes through all of the cities.


Imagine that we have a bunch of cities:

###
cities = ['c', 'l', 'd', 'f', 'i', 'x', 'a', 'g', 'r', 'd']
###

and a bunch of roads that can connect these cities together:

###
roads = [('c', 'l'),
         ('d', 'f'),
         ('c', 'i'),
	 ('f', 'x'),
         ('a', 'c'),
         ('g', 'i'),
         ('r', 'd')]
###


But suddenly, this traveling salesman instance looks suspiciously like
Brad's tuple-connected problem...

###
inlist = [('c','p','l'),
          ('d','e','f'),
          ('c','h','i'),
          ('f','w','x'),
          ('a','b','c'),
          ('g','h','i'),
          ('r','z','d')]
##

So any "fast" solution to the tuple-connecting problem will solve the
traveling salesman problem.




From dman@dman.ddts.net  Fri Apr  5 21:38:22 2002
From: dman@dman.ddts.net (dman)
Date: Fri, 5 Apr 2002 15:38:22 -0600
Subject: [Tutor] Cheating?No, not me:-)
In-Reply-To: <02040522425802.00703@utopia>
References: <20020324210443.GC10420@dman.ddts.net> <Pine.LNX.4.44.0203241327110.27560-100000@hkn.eecs.berkeley.edu> <20020324220138.GA11090@dman.ddts.net> <02040522425802.00703@utopia>
Message-ID: <20020405213822.GA1114@dman.ddts.net>

On Fri, Apr 05, 2002 at 10:42:58PM +0200, Nicole Seitz wrote:
| Am Sonntag, 24. M=E4rz 2002 23:01 schrieb dman:
| >
| > | For people who are interested: here's a similar problem: "Given a text
| > | file and an integer K, you are to print the K most common words in the
| > | file (and the number of their occurences) in decreasing frequency."
| >
| > <cheater's hint>
| > Search the tutor archives.  With only a couple minor modifications the
| > answer is already there.
| > </cheater's hint>
|=20
| Some hint WHERE in the archives I could find the answer?Month?Year?

I don't remember, but try googling for :
    python tutor word count slow perl

which yields this as the second result :
    http://mail.python.org/pipermail/tutor/2001-February/003403.html

apparently it was February 1, 2001.

Enjoy :-).

-D

--=20

Failure is not an option.  It is bundled with the software.




From urnerk@qwest.net  Fri Apr  5 21:45:31 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 05 Apr 2002 13:45:31 -0800
Subject: [Tutor] combining tuples in a list  [NP complete reduction]
In-Reply-To: <NGEALAODAKLOJADDLGPAMEEICBAA.brad.reisfeld@colostate.edu>
References: <Pine.LNX.4.44.0204051157310.7010-100000@hkn.eecs.berkeley.edu>
Message-ID: <4.2.0.58.20020405133357.019ae310@pop3.norton.antivirus>

At 01:43 PM 4/5/2002 -0700, Brad Reisfeld wrote:
>I agree that is seems like a hard problem (although this is
>probably because my brain is a bit muddled), but I don't
>believe that this is a restatement of the traveling salesman
>problem.
>
>The problem seems to be one of enumeration (since the 'splicing'
>dictates the paths), rather than one of optimization (to find
>the paths).
>
>-Brad

I would agree that it's a somewhat different problem.

Here's a stab at a solution.  Somewhat complicated, but
uses dictionaries and is fairly fast.  If you check this
out on a few examples, and the results conform to your
expectations, then I can elucidate the algorithm more.
If it fails to meet your expectation, show me where it
breaks down (provide example inlist, output) and maybe
I can fix it for ya.

    def mkdict(thelist):
         """
         File all tuples by first letter, allowing
         multiple tuples per key if necessary
         """
         tupdict = {}
         for t in thelist:
             tupdict[t[0]] = tupdict.get(t[0],[]) + [t]
         return tupdict

    def splice(thelist):
         tupledict = {}   # keeps all current tuples
         for t in thelist:
             tupledict[t] = 1
         thedict = mkdict(tupledict.keys())  # 1st letter index
         for t in thelist:
             last = t[-1]
             # only process tuple if (a) still current and
             # (b) its last letter matches another's first
             if tupledict.get(t,0) and thedict.get(last,0):
                 for t2 in thedict[last]:
                     newtuple = t + t2[1:]   # build new tuple
                     tupledict[newtuple] = 1 # file in current
                     del tupledict[t2] # get rid of used tuple
                 del tupledict[t]      # get rid of used tuple
                 thedict = mkdict(tupledict.keys()) # rebuild index
         return tupledict.keys()  # list unprocessed + new tuples

  >>> inlist
  [('c', 'p', 'l'), ('d', 'e', 'f'), ('c', 'h', 'i'),
  ('f', 'w', 'x'), ('a', 'b', 'c'), ('g', 'h', 'i'), ('r', 'z', 'd')]
  >>> splice(inlist)
  [('g', 'h', 'i'), ('r', 'z', 'd', 'e', 'f', 'w', 'x'),
  ('a', 'b', 'c', 'p', 'l'), ('a', 'b', 'c', 'h', 'i')]

Kirby





From jeff@ccvcorp.com  Fri Apr  5 21:56:41 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 05 Apr 2002 13:56:41 -0800
Subject: [Tutor] Working with files, Truckers log
References: <E16tbU7-0006RD-00@mail.python.org>
Message-ID: <3CAE1D99.F2D85894@ccvcorp.com>

> Alexandre Ratti <alex@gabuzomeu.net> wrote:
>
> >This is a timely subject for me :-). I want to save data that is in a list
> >to a file , to be  used later to append the list.  The list contains decimal
> >numbers.
> >
> >Here is a sample list [ 8.5,8,9.5,10.75,6.25 ]
> >
> >I think I know how to read and write to a file ,but how do I insert this data
> >into the list in my program ?
>
> If you store your values in a text file, for instance one per line, it will
> be fairly simple to load them back and append them to a list. You can use
> eval() to transform a string value into a decimal value.

Why on earth should eval() be used for this, when there's perfectly good conversion
functions??

>>> mylist = ['3.75\n', '8.5\n', '6.0\n']
>>> # to simulate lines that have been
>>> # read in from file.readlines()
>>> [ float(x) for x in mylist ]
[3.75, 8.5, 6.0]
>>>

There really is almost never a reason to use eval().  Really.  :)

Jeff Shannon
Technician/Programmer
Credit International





From irishpnk@yahoo.com  Fri Apr  5 22:04:18 2002
From: irishpnk@yahoo.com (Brian Callahan)
Date: Fri, 5 Apr 2002 14:04:18 -0800 (PST)
Subject: [Tutor] Tkinter problem
Message-ID: <20020405220418.39569.qmail@web10705.mail.yahoo.com>

Max and Bryce,

 Thanx for you help.  It worked great. 

Brian

__________________________________________________
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
http://taxes.yahoo.com/



From urnerk@qwest.net  Fri Apr  5 22:29:28 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 05 Apr 2002 14:29:28 -0800
Subject: [Tutor] combining tuples in a list  [NP complete reduction]
In-Reply-To: <4.2.0.58.20020405133357.019ae310@pop3.norton.antivirus>
References: <NGEALAODAKLOJADDLGPAMEEICBAA.brad.reisfeld@colostate.edu>
 <Pine.LNX.4.44.0204051157310.7010-100000@hkn.eecs.berkeley.edu>
Message-ID: <4.2.0.58.20020405142156.01996520@pop3.norton.antivirus>

At 01:45 PM 4/5/2002 -0800, Kirby Urner wrote:

>If it fails to meet your expectation, show me where it
>breaks down (provide example inlist, output) and maybe
>I can fix it for ya.

Looking at this some more, I think I've oversimplified,
even if I get the right result for the example given

Consider:

inlist = [('c', 'p', 'l'),
           ('d', 'e', 'f'),
           ('c', 'h', 'i'),
           ('f', 'w', 'x'),
           ('i', 'k', 'h'),
           ('a', 'b', 'c'),
           ('g', 'h', 'i'),
           ('r', 'z', 'd')]

Here the ('c','h','i') chain connects on both ends.
Should ('a','b','c','h','i','k','h') be one of the
results?  And ('g','h','i','k','h') as well.  Given
how you're prefixing ('a','b','c') to *both* tuples
beginning with 'c', it seems like you'd want ('i','k'
'h') to append to every tuple it can.

Kirby




From ak@silmarill.org  Fri Apr  5 23:38:17 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 5 Apr 2002 18:38:17 -0500
Subject: [Tutor] impact of OO
In-Reply-To: <05196BDE-482A-11D6-B534-00039351FE6A@mac.com>
References: <05196BDE-482A-11D6-B534-00039351FE6A@mac.com>
Message-ID: <20020405233817.GA4176@ak.silmarill.org>

On Thu, Apr 04, 2002 at 07:13:56PM -0500, Erik Price wrote:
> But everywhere I used to read about programming would talk about how OO 
>
Every book I've read said "You know how every book talks about how OO
revolutionized programming? It ain't true. OO is way helpful, but it's
not a panacea, in fact for some tasks it's not even the best strategy."

> had revolutionized programming.  Now that I know what it is, although I 
> really appreciate it and will use it whenever I can (it's so... clean 
> compared to what I was doing before), but I still don't really see how 
> it's that big a deal -- it's simply a different way of organizing code, 
> as far as I can tell.
>
It's more of a big deal with larger projects, I gather. You know, with
inheritance and what-not.

> 
> Please prove me wrong and help me see how OO "changed everything".
> 
> Erik
> 
> 
> 
> 
> 
> PS:  Also, I have heard someone say that "in Java everything is an 
> object".  What does this mean?  I think I am interested in learning 
> Java, especially since there are many employers in my area (Boston) 
> advertising an interest in Java programmers (and I will be out of a job 
> as soon as my project is finished).  Sadly, much more than Python or 
> PHP.  But it seems like a big language to learn.
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From hysterix240@yahoo.com  Sat Apr  6 06:06:32 2002
From: hysterix240@yahoo.com (Galen Senogles)
Date: Fri, 5 Apr 2002 22:06:32 -0800 (PST)
Subject: [Tutor] Actually using programs
Message-ID: <20020406060632.37349.qmail@web11701.mail.yahoo.com>

        Hello, I have a very easy question to solve,
that I just cant quite find in the tutors.  Basically
I just want to know how to actually apply whatever
programs to your computer.  Is there a way to actually
apply them?  Or are the programs just only to be run
in the python program that recieves the input from the
user and processes it, i know that is still very
usefull but I just want to know how to actually use
the programs...if I'm still to vague just let my know
and I'll try to explain more.

__________________________________________________
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
http://taxes.yahoo.com/



From qhup@yahoo.com  Sat Apr  6 06:59:20 2002
From: qhup@yahoo.com (Justin khup)
Date: Fri, 5 Apr 2002 22:59:20 -0800 (PST)
Subject: [Tutor] executing compiled python (.pyc) files
Message-ID: <20020406065920.17922.qmail@web10805.mail.yahoo.com>

--0-406111140-1018076360=:16185
Content-Type: text/plain; charset=us-ascii


Hi there,

           When I execute a compiled python file (say file.pyc) like  "$ python file.pyc"  in unix ,it works fine .

          But even after changing the mode to chmod +x and trying "$file.pyc", I can't execute getting the following error: 

Cannot execute binary file.
play.pyc: Exec format error   

        What could be the reason since a compiled c code for example just works fine.

  Hope anyone soon help me out.

Thanks in advance.

Justin khup



---------------------------------
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
--0-406111140-1018076360=:16185
Content-Type: text/html; charset=us-ascii

<P>Hi there,</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; When I execute a compiled python file (say file.pyc) like&nbsp; "$ python file.pyc"&nbsp; in unix ,it works fine .</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; But even after changing the mode to chmod +x and trying "$file.pyc", I can't execute getting the following error:&nbsp;</P>
<P>Cannot execute binary file.<BR>play.pyc: Exec format error&nbsp;&nbsp; </P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; What could be the reason since a compiled c code for example just works fine.</P>
<P>&nbsp; Hope anyone soon help me out.</P>
<P>Thanks in advance.</P>
<P>Justin khup</P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
<a href="$rd_url/welcome/?http://taxes.yahoo.com/">Yahoo! Tax Center</a> - online filing with TurboTax
--0-406111140-1018076360=:16185--



From paulsid@shaw.ca  Sat Apr  6 07:12:52 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sat, 06 Apr 2002 00:12:52 -0700
Subject: [Tutor] Actually using programs
References: <20020406060632.37349.qmail@web11701.mail.yahoo.com>
Message-ID: <3CAE9FF4.1866B6A3@shaw.ca>

Galen Senogles wrote:

>         Hello, I have a very easy question to solve,
> that I just cant quite find in the tutors.  Basically
> I just want to know how to actually apply whatever
> programs to your computer.  Is there a way to actually
> apply them?  Or are the programs just only to be run
> in the python program that recieves the input from the
> user and processes it, i know that is still very
> usefull but I just want to know how to actually use
> the programs...if I'm still to vague just let my know
> and I'll try to explain more.

This was a bit vague, but I think I understand.  If not, please ignore. 
:-)

Generally Python programs always run in the interpreter (python.exe
under Windows, just python in Unix environments).  Being an interpreted
language this is rather unavoidable.

Assuming you're under Windows (since Unix people are generally more
familiar with the concept that Python uses) you should be able to put
your program into one or more .py files and double-click the main .py
file to start it.  (If it's something you will use regularly, you can
put a shortcut on your desktop like any other program.)  The Python
interpreter will startup and begin to execute your program
automatically, and will terminate when your program finishes.

(This assumes nothing is strange about your Python installation, which
is not always the case - for example, double-clicking .py files doesn't
work for me.  It might be because I had a 2.2 alpha version installed at
one point but have since uninstalled it and gone back to 2.1.)

If that's not good enough, i.e. if you really want to make your programs
independent, then you'll have to check out py2exe which will let you put
your Python program its own .exe file, again for Windows only.

BTW if you're familiar with QuickBASIC or older Visual Basic, just think
of python.exe as BRUN45.EXE or VBRUNxxx.DLL.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From shalehperry@attbi.com  Sat Apr  6 07:41:56 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 05 Apr 2002 23:41:56 -0800 (PST)
Subject: [Tutor] executing compiled python (.pyc) files
In-Reply-To: <20020406065920.17922.qmail@web10805.mail.yahoo.com>
Message-ID: <XFMail.20020405234156.shalehperry@attbi.com>

On 06-Apr-2002 Justin khup wrote:
> 
> Hi there,
> 
>            When I execute a compiled python file (say file.pyc) like  "$
> python file.pyc"  in unix ,it works fine .
> 
>           But even after changing the mode to chmod +x and trying
> "$file.pyc", I can't execute getting the following error: 
> 
> Cannot execute binary file.
> play.pyc: Exec format error   
> 
>         What could be the reason since a compiled c code for example just
> works fine.
> 

the program loader does not know how to load a python pyc file.  It sees that
it is not in the normal executable format and complains.

Under linux (and I think the bsds) there is support for adding arbitrary
executable file types.  You can then tell the kernel that 'pyc' is to be run by
python.

If you tell python to run foo.py and there is a recent enough foo.pyc it will
use the pyc and ignore the .py.



From wolf_binary@hotmail.com  Sat Apr  6 14:20:19 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sat, 6 Apr 2002 08:20:19 -0600
Subject: [Tutor] impact of OO
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C50D@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <DAV20tgr3SU0hXCRQcq000007cf@hotmail.com>

Hi all,

I saw this post on the wire and wanted to ask how you know what should have
the behavior and how to organize the program.  I am making a simple message
encryption program and wanted to see if implementing OOP practices would be
difficult or not.  It is not a small program at all.  By the time it will be
done it will be a couple thousand lines at least.  I will add the GUI part
to the program later, but for now it is text based.  Is there any place I
could just learn about UML?

> > I have a general question about Object Oriented programming
> > in general:  why is it so lauded by... well, by everyone?
>
> Its not. There are several minority groups who believe that
> OO is a retrograde step. Others believe that things like
> Functional Programming are more important etc etc. But
> the general opinion is that OO is a big improvement on
> traditional "Structured Methods"
>
>
> There are lots of reasons, most only relevant to large
> projects so its hard for the newbie writing programs of
> only a few hundred lines to see the avantages. But one
> your prohgrams get into the tens of thousands of lines
> the benefits become far more obvious. However...
>
> > to with a group of variable names.  It's hard to describe, but this
> > makes it much easier --
>
> ... even in smaller projects it can show benefits in ease
> of comprehension - as you've seen.
>
> > but it is far more organized and cleaner.
>
> We used to have one maintenance programmer looking after,
> on average 20,000 lines of code(in C) when we moved to
> OO designs we have one programmer looking after 100,000
> lines. A 5 to 1 improvement, mainly due to the better
> cohesion of the designs using OOP.
>
> > ...but I still don't really see how
> > it's that big a deal -- it's simply a different way of
> > organizing code, as far as I can tell.
>
> Which is the hardest aspect of industrial grade
> software engineering. Organizing code such that when one
> bit changes you don't need to change everything elsder
> with it has been the biggest headache in softwae since
> the start of commercial programming. OOP helps do just that.
>
> > Please prove me wrong and help me see how OO "changed everything".
>
> It doesn't change everything but it helps a lot.
>
> There are other aspects to OOP too that we haven't
> touched on. The ease of extending existing code without
> changing it (and thus breaking existing code relying
> on the bit being extended) via inheritance. The way
> OOP eliminates long if/elif/else chains (or switch
> statements)via polymorphism (see the OOP page in my
> tutor for a discussion of polymorphism and inheritance)
>
> The ability to build whoile abstract frameworks which
> act as application templates. These can quickly be
> added to to produce new apps - most GUI frameworks
> are done this way.
>
>
> > PS:  Also, I have heard someone say that "in Java everything is an
> > object".
>
> Its a lie. In Java everything is in a class...
> only some things are objects. There is a big difference
> which the Java community seems to disregard. But claiming
> that everything is anobject is a big marketing coup!
>
>
> > Java, especially since there are many employers
>
> This sadly is true. Mainly a result of the "emperors new clothes" syndrome
> but none the less Java is taking over.
>
>
> in my area (Boston)
> > advertising an interest in Java programmers (and I will be
> > out of a job
> > as soon as my project is finished).  Sadly, much more than Python or
> > PHP.  But it seems like a big language to learn.
> >
> >
> >
> >
> >
> >
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From alex@gabuzomeu.net  Sat Apr  6 17:48:16 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Sat, 06 Apr 2002 19:48:16 +0200
Subject: [Tutor] Working with files, Truckers log
In-Reply-To: <E16ttZ1-0003YP-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020406192644.00b9f8e0@pop3.norton.antivirus>

Hello Jeff,


At 12:00 06/04/2002 -0500, you wrote:
>Date: Fri, 05 Apr 2002 13:56:41 -0800
>From: "Jeff Shannon" <jeff@ccvcorp.com>
>Subject: Re: [Tutor] Working with files, Truckers log

> > If you store your values in a text file, for instance one per line, it will
> > be fairly simple to load them back and append them to a list. You can
> > use eval() to transform a string value into a decimal value.
>
>Why on earth should eval() be used for this, when there's perfectly good 
>conversion functions??
>
> >>> mylist = ['3.75\n', '8.5\n', '6.0\n']
> >>> # to simulate lines that have been
> >>> # read in from file.readlines()
> >>> [ float(x) for x in mylist ]
>[3.75, 8.5, 6.0]
> >>>

Yes, you are correct. Somehow I missed the obvious solution (oh well).

>There really is almost never a reason to use eval().  Really.  :)

How about this kind of use:

def factoryFromName(className, *args):
     "className is a string."
     return eval(className)(*args)

Admittedly, I can't think up any reason to use this code in a real app 
right now :-)


Cheers.

Alexandre





From sentinel805@netscape.net  Sat Apr  6 17:53:52 2002
From: sentinel805@netscape.net (nova812)
Date: Sat, 06 Apr 2002 12:53:52 -0500
Subject: [Tutor] wxPython timer
Message-ID: <3CAF3630.6010401@netscape.net>

I have two questions....
1  Whats wrong with my timer here?  the tmrOneSec_expired method isn't 
being called.  
2  How can I add my own methods to the Mainloop  without using a timer?

<pre>
from wxPython.wx import *

class EggTimer(wxFrame):
  def __init__(self):
    wxFrame. __init__(self, NULL, -1, 
'wxPython',wxDefaultPosition,(200,100))
    timeLeft = 3

    btnSetTimer = wxButton(self, 111,'&Set')
    EVT_BUTTON(self, 111, self.btnSetTimer_click)

    tmrOneSec = wxTimer(self,222)
    EVT_TIMER(self,222, self.tmrOneSec_expired)
    tmrOneSec.Start(1000)

  def btnSetTimer_click(self, event):
    dlg = wxMessageDialog(self,'"Set" button clicked','Alert',wxOK)
    dlg.ShowModal()
    dlg.Destroy()

  def tmrOneSec_expired(self):
    self.timeLeft = timeLeft - 1
    if (timeLeft < 1):
      self.alertTimesUp()

  def alertTimesUp(self):
    dlg = wxMessageDialog(self,'Times UP!!!','Alert',wxOK)
    dlg.ShowModal()
    dlg.Destroy()

class App(wxApp):
  def OnInit(self):
    frame = EggTimer()
    frame.Show(true)
    return true

app = App(0)
app.MainLoop()

</pre>




From dmanxiii@yahoo.com  Sat Apr  6 17:52:15 2002
From: dmanxiii@yahoo.com (bob fitzgerald)
Date: Sat, 6 Apr 2002 09:52:15 -0800 (PST)
Subject: [Tutor] Tkinter problems
Message-ID: <20020406175215.32742.qmail@web20902.mail.yahoo.com>

--0-997267976-1018115535=:32641
Content-Type: text/plain; charset=us-ascii


Hi people,

I'm new to programming with python(new to programming at all) and I was just trying to figure out how some of these concepts and things work.  But anyways...  I was working on getting buttons with Tkinter, but I can't.  I get the Tkinter window to open up when I run the code, but the button(s) won't show up.  IDLE doesn't show any errors.  I don't understand what's happening.  If someone could please enlighten me I would be grateful.(maybe show me a few lines of sample code?)  

Thanks people,

Derek Hoffmeister



---------------------------------
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
--0-997267976-1018115535=:32641
Content-Type: text/html; charset=us-ascii

<P>Hi people,</P>
<P>I'm new to programming with python(new to programming at all) and I was just trying to figure out how some of these concepts and things work.&nbsp; But anyways...&nbsp; I was working on getting buttons with Tkinter, but I can't.&nbsp; I get the Tkinter window to open up when I run the code, but the button(s) won't show up.&nbsp; IDLE doesn't show any errors.&nbsp; I don't understand what's happening.&nbsp; If someone could please enlighten me I would be grateful.(maybe show me a few lines of sample code?)&nbsp; </P>
<P>Thanks people,</P>
<P>Derek Hoffmeister</P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
<a href="$rd_url/welcome/?http://taxes.yahoo.com/">Yahoo! Tax Center</a> - online filing with TurboTax
--0-997267976-1018115535=:32641--



From virketis@fas.harvard.edu  Sat Apr  6 18:06:31 2002
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Sat, 6 Apr 2002 13:06:31 -0500
Subject: [Tutor] Tkinter problems
In-Reply-To: <20020406175215.32742.qmail@web20902.mail.yahoo.com>
Message-ID: <200204061807.g36I73Z02143@smtp1.fas.harvard.edu>

<HTML><HEAD>
<BASEFONT FACE=3D"Arial" SIZE=3D"2" COLOR=3D"#000000">
</HEAD>
<BODY>
<div>Dear Bob,<br></div>
<div><br>
<FONT COLOR=3D"#000080">&gt;someone could please enlighten me I=
 would be grateful.(maybe show me</FONT><br>
<FONT COLOR=3D"#000080">&gt;a few lines of sample=
 code?)&nbsp;&nbsp; &nbsp; &nbsp;</FONT><br>
<br>
Maybe *you* would like to show *us* the code you are trying to=
 run. :) Is there any particular part where you get the snag?=
 Paste it into your message!<br></div>
<div>&nbsp;</div>
<div>Cheers, <br></div>
<div>&nbsp;</div>
<div>Pijus<br></div>
<div>-- <br></div>
<div>Pijus Virketis, virketis@fas.harvard.edu on=
 04/06/2002<br></div>
</body></html>




From printers@sendme.cz  Sat Apr  6 20:31:06 2002
From: printers@sendme.cz (A)
Date: Sat, 6 Apr 2002 22:31:06 +0200
Subject: [Tutor] How to remove a newline character
Message-ID: <3CAF772A.32178.10B2B72@localhost>

Hi,
Can you please let me know  if it is possible to replace 
new line characters( '\n') in a list in one step?

I have list like

MyList=['272580\n', '23232432\n']

and I would like to have 
,MyList=['272580', '23232432']

so I tried
re.sub('\n','',MyList)
but I received 
TypeError: expected string or buffer

Your help would be appreciated
Thanks.
Ladislav

I look forward to hearing from you soon.

Best Regards,
Ladislav Blazek( Mr.)

BMA TRADING Ltd.
email: export@sendme.cz
email2: export@bmatrading.com
Fax:/Tel +420 506 447921
Tel:+420 506 447920, +420 602 849309





From python@rcn.com  Sat Apr  6 20:37:38 2002
From: python@rcn.com (Raymond Hettinger)
Date: Sat, 6 Apr 2002 15:37:38 -0500
Subject: [Tutor] Re: [Python-Help] How to remove a newline character
References: <3CAF772A.32178.10B2B72@localhost>
Message-ID: <001801c1ddaa$e5502c20$dab53bd0@othello>

There is a string function that may meet your needs.
Try:

>>> MyList=['272580\n', '23232432\n']
>>> import string
>>> map(string.strip, MyList)
['272580', '23232432']


Raymond Hettinger

P.S.  No need to cross-post.  Any one of your targets will answer.

----- Original Message -----
From: "A" <printers@sendme.cz>
To: <python-help@python.org>; <activepython@listserv.ActiveState.com>;
<tutor@python.org>
Sent: Saturday, April 06, 2002 3:31 PM
Subject: [Python-Help] How to remove a newline character


> Hi,
> Can you please let me know  if it is possible to replace
> new line characters( '\n') in a list in one step?
>
> I have list like
>
> MyList=['272580\n', '23232432\n']
>
> and I would like to have
> ,MyList=['272580', '23232432']
>
> so I tried
> re.sub('\n','',MyList)
> but I received
> TypeError: expected string or buffer
>
> Your help would be appreciated
> Thanks.
> Ladislav
>
> I look forward to hearing from you soon.
>
> Best Regards,
> Ladislav Blazek( Mr.)
>
> BMA TRADING Ltd.
> email: export@sendme.cz
> email2: export@bmatrading.com
> Fax:/Tel +420 506 447921
> Tel:+420 506 447920, +420 602 849309
>
>
>
>
> _______________________________________________
> Python-Help maillist  -  Python-Help@python.org
> http://mail.python.org/mailman/listinfo/python-help
>




From tbrauch@tbrauch.com  Sat Apr  6 20:51:30 2002
From: tbrauch@tbrauch.com (tbrauch@tbrauch.com)
Date: Sat, 6 Apr 2002 15:51:30 -0500
Subject: [Tutor] How to remove a newline character
In-Reply-To: <3CAF772A.32178.10B2B72@localhost>
Message-ID: <3CA3680400008403@mta07.san.yahoo.com>

>Hi,
>Can you please let me know  if it is possible to replace 
>new line characters( '\n') in a list in one step?

It's possible to replace it.  I don't know about in one step, but I was
able to do it in two lines.

>I have list like
>
>MyList=3D['272580\n', '23232432\n']
>
>and I would like to have 
>,MyList=3D['272580', '23232432']
>
>so I tried
>re.sub('\n','',MyList)

That looks like the right pattern, but I think that re.sub only takes a
string, not a list of strings.  (I might be wrong on this, though).

>but I received 
>TypeError: expected string or buffer

Ah, yes, it looks like re.sub expected a string, not a list.

>Your help would be appreciated
>Thanks.
>Ladislav

So, we need to look at each string in the list.  This can be done with a
for loop.

Let's try...
Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> MyList =3D ['272580\n', '23232432\n']
>>> MyList2 =3D []
>>> for item in MyList:
	MyList2.append(re.sub('\n','',item))

	
>>> MyList2
['272580', '23232432']
>>> 

That seems to work.  re.sub was happy when I gave it a string, not a list=

of strings.

Another, yet less obvious way to try this, if the list is always numbers,=

is to do:

>>> MyList =3D ['272580\n', '23232432\n']
>>> MyList2 =3D []
>>> for item in MyList:
	MyList2.append(str(int(item)))

	
>>> MyList2
['272580', '23232432']

Then you don't have to worry about using re.

So, I couldn't do it in one step.  And, I had to create a new list to do
it.  I'm sure someone out there is better and can improve on what I did.

 - Tim




From pythontutor@venix.com  Sat Apr  6 22:12:15 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 06 Apr 2002 17:12:15 -0500
Subject: [Tutor] How to remove a newline character
References: <3CA3680400008403@mta07.san.yahoo.com>
Message-ID: <3CAF72BF.1040509@venix.com>

The regular expression processing is overkill for what you are trying to do.
The string.strip function removes all leading and trailing whitespace, which
includes spaces, tabs, and newlines.  Usually this is what you want to clean
up a data file.  Use string.rstrip to only remove the trailing whitespace.
string.whitespace lists the whitespace characters.

If you really want to only remove the linefeed from the end of a list of lines,
I would use:
lines = [line[:-1] for line in lines]
This simply chops off the last character.  Be sure to only do this once.

I use this function to get small data files for processing:
def stripFileLines( filename):
	infile = open( filename, 'r')	#read access
	contents = map(string.strip, infile.readlines())
	infile.close()
	return contents

tbrauch@tbrauch.com wrote:

>>Hi,
>>Can you please let me know  if it is possible to replace 
>>new line characters( '\n') in a list in one step?
>>
> 
> It's possible to replace it.  I don't know about in one step, but I was
> able to do it in two lines.
> 
> 
>>I have list like
>>
>>MyList=['272580\n', '23232432\n']
>>
>>and I would like to have 
>>,MyList=['272580', '23232432']
>>
>>so I tried
>>re.sub('\n','',MyList)
>>
> 
> That looks like the right pattern, but I think that re.sub only takes a
> string, not a list of strings.  (I might be wrong on this, though).
> 
> 
>>but I received 
>>TypeError: expected string or buffer
>>
> 
> Ah, yes, it looks like re.sub expected a string, not a list.
> 
> 
>>Your help would be appreciated
>>Thanks.
>>Ladislav
>>
> 
> So, we need to look at each string in the list.  This can be done with a
> for loop.
> 
> Let's try...
> Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.8 -- press F1 for help
> 
>>>>MyList = ['272580\n', '23232432\n']
>>>>MyList2 = []
>>>>for item in MyList:
>>>>
> 	MyList2.append(re.sub('\n','',item))
> 
> 	
> 
>>>>MyList2
>>>>
> ['272580', '23232432']
> 
> 
> That seems to work.  re.sub was happy when I gave it a string, not a list
> of strings.
> 
> Another, yet less obvious way to try this, if the list is always numbers,
> is to do:
> 
> 
>>>>MyList = ['272580\n', '23232432\n']
>>>>MyList2 = []
>>>>for item in MyList:
>>>>
> 	MyList2.append(str(int(item)))
> 
> 	
> 
>>>>MyList2
>>>>
> ['272580', '23232432']
> 
> Then you don't have to worry about using re.
> 
> So, I couldn't do it in one step.  And, I had to create a new list to do
> it.  I'm sure someone out there is better and can improve on what I did.
> 
>  - Tim
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From STavares@doc.state.ri.us  Thu Apr  4 15:56:17 2002
From: STavares@doc.state.ri.us (STavares@doc.state.ri.us)
Date: Thu, 4 Apr 2002 10:56:17 -0500
Subject: [Tutor] Simple HelloWorld cgi script
Message-ID: <BDA406CE9FA12E4FBC913071BE7733BF0C6F07@doc5.doc.state.ri.us>

This is a multi-part message in MIME format.

------_=_NextPart_001_01C1DBF1.415753F8
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Could somene please me to a simple heloworld cgi script written in =
python?


TIA

-ScottTavares-

------_=_NextPart_001_01C1DBF1.415753F8
Content-Type: text/html;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Diso-8859-1">
<META NAME=3D"Generator" CONTENT=3D"MS Exchange Server version =
6.0.5762.3">
<TITLE>Simple HelloWorld cgi script</TITLE>
</HEAD>
<BODY>
<!-- Converted from text/rtf format -->

<P><FONT SIZE=3D2 FACE=3D"Arial">Could somene please me to a simple =
heloworld cgi script written in python?</FONT>
</P>
<BR>

<P><FONT SIZE=3D2 FACE=3D"Arial">TIA</FONT>
</P>

<P><FONT SIZE=3D2 FACE=3D"Arial">-ScottTavares-</FONT>
</P>

</BODY>
</HTML>
------_=_NextPart_001_01C1DBF1.415753F8--



From bembry@westhost33.westhost.net  Fri Apr  5 20:48:20 2002
From: bembry@westhost33.westhost.net (bembry@westhost33.westhost.net)
Date: Fri, 5 Apr 2002 14:48:20 -0600 (CST)
Subject: [Tutor] Tkinter problem
In-Reply-To: <20020405182953.51352.qmail@web10707.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0204051446300.32119-100000@westhost33.westhost.net>

Also, if you are running the code from inside IDLE, the root.mainloop() 
can cause it to lock things up.  If you are running from shell or command 
line, you'll be fine (which is what it looks like), but from IDLE it can 
cause a mess. 

Bryce

On Fri, 5 Apr 2002, Brian Callahan wrote:

> Hi everyone.  I'm trying to learn Tkinter right now
> and I've run into a problem.  One of my examples is to
> create a button widget.  I've entered the code and
> when I try to run it, it tells me that I have a syntax
> errors and points to the button event.  I've tripple
> checked the code to make sure I didn't type anything
> wrong.  Any other suggestions??? I'm including a copy
> of the code. Thanx.
> #!/usr/local/bin/python
> 
> import sys
> from Tkinter import *
> 
> def die(event):
>     sys.exit(0)
> 
> root = Tk()
>  button = Button(root)
>  button["text"] = "Ave atque vale!"
>  button.bind("<Button-1>", die)
>  button.pack()
>  root.mainloop()
> 
> 
> 
> __________________________________________________
> Do You Yahoo!?
> Yahoo! Tax Center - online filing with TurboTax
> http://taxes.yahoo.com/
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From dtanthony@earthlink.net  Sat Apr  6 15:04:43 2002
From: dtanthony@earthlink.net (Darren Anthony)
Date: Sat, 6 Apr 2002 07:04:43 -0800
Subject: [Tutor] Help
Message-ID: <MFEKJEJIGIIAACBIOFCMKEDACAAA.dtanthony@earthlink.net>

I want to make python print a sum like:
What is 7 times 2 ?
where the two numbers are generated randomly, between 1 and 10.

So far I have random_between(1,10)
but how do I include the "What is" and "times" and "?"


I'm trying to figure out a tutorial problem from livewires.org.uk/python/




From sheila@thinkspot.net  Sat Apr  6 23:52:21 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sat, 6 Apr 2002 15:52:21 -0800
Subject: [Tutor] Simple HelloWorld cgi script
In-Reply-To: <BDA406CE9FA12E4FBC913071BE7733BF0C6F07@doc5.doc.state.ri.us>
Message-ID: <9B04EB55B60@kserver.org>

On Thu, 4 Apr 2002 10:56:17 -0500, STavares@doc.state.ri.us wrote:
> Could somene please me to a simple heloworld cgi script written in
> python?
>
>
>
> TIA
>
> -ScottTavares-

I have one posted here:
http://www.thinkspot.net/sheila/computers/Python.html

Hope this helps,

-- 
Sheila King, sheila@thinkspot.net on 04/06/2002




From tbrauch@tbrauch.com  Sun Apr  7 00:02:35 2002
From: tbrauch@tbrauch.com (tbrauch@tbrauch.com)
Date: Sat, 6 Apr 2002 19:02:35 -0500
Subject: [Tutor] poplib help
Message-ID: <3CA36804000084FD@mta07.san.yahoo.com>

I am trying to write a small script that will check my email and return
the subject and senders of those emails.

I am almost there.  I can get the full headers, but I am unsure about how=

to extract the 'from' and 'subject' out of it.  Below is an interactive
attempt, I will eventually code this all up nicely.

Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import poplib
>>> yahoo =3D poplib.POP3('pop.mail.yahoo.com')
>>> yahoo.getwelcome()
'+OK hello from popgate(2.22)'
>>> yahoo.user(user_name)
'+OK password required.'
>>> yahoo.pass_(password)
'+OK maildrop ready, 1 message (8101 octets) (1283637 6291456)'
>>> yahoo.top(1,0)
('+OK 8101 octets', ['X-Apparently-To: *******@yahoo.com via web11201.mai=
l.yahoo.com;
06 Apr 2002 12:52:38 -0800 (PST)', 'X-YahooFilteredBulk: 65.43.242.234',
'X-Track: 247: 20', 'Return-Path: <whosaidthat@lists.brainyquote.com>',
'Received: from adsl-65-43-242-234.dsl.chcgil.ameritech.net  (HELO lists.=
brainyquote.com)
(65.43.242.234)', '  by mta599.mail.yahoo.com with SMTP; 06 Apr 2002 12:5=
2:37
-0800 (PST)', 'Received: from brainyquote.com by lists.brainyquote.com wi=
th
SMTP; Sat, 6', ' Apr 2002 11:49:11 -0600', 'Message-ID: <20020406114905.0=
30534@pop.brainyquote.com>',
'X-Mailer: SMTPit - FileMaker Pro Email Plugin (mac ver. 3.0.0)', 'Mime-V=
ersion:
1.0', 'Content-Type: multipart/alternative;   ', ' boundary=3D"=3D Multip=
art
Boundary 20020406114905.010506"', 'Date: Sat, 6 Apr 2002 11:49:05 -0600',=

'To: "Who Said That" <whosaidthat@lists.brainyquote.com>', 'From: BrainyQ=
uote
Who Said That <service@brainyquote.com>', 'Subject: Who Said That? Websit=
es...',
'Sender: <whosaidthat@lists.brainyquote.com>', 'Precedence: Bulk', ''],
974)
>>> yahoo.quit()
'+OK server signing off.'

As you can see, yahoo.top returns a tuple of size 3.  yahoo.top[1] is the=

header of the message in question.  How can I pull out the 'from' and 'su=
bject'
lines in that mess?  I feel like it will involve regular expressions, of
which I am not very good with.

Thanks for any help you can offer...

 - Tim




From pythontutor@venix.com  Sun Apr  7 00:08:52 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 06 Apr 2002 19:08:52 -0500
Subject: [Tutor] Help
References: <MFEKJEJIGIIAACBIOFCMKEDACAAA.dtanthony@earthlink.net>
Message-ID: <3CAF8E14.5010000@venix.com>

Possible code:
a = random_between(1,10)
b = random_between(1,10)
print "What is %d times %d?" % (a, b)

This uses the Python format operator (the % character) to insert values
into a string.  The %d is used for inserting an integer.  This is patterned
after the printf function in C.

It is roughly equivalent to:
print "What is " + str(a) + " times " + str(b) + "?"

Darren Anthony wrote:

> I want to make python print a sum like:
> What is 7 times 2 ?
> where the two numbers are generated randomly, between 1 and 10.
> 
> So far I have random_between(1,10)
> but how do I include the "What is" and "times" and "?"
> 
> 
> I'm trying to figure out a tutorial problem from livewires.org.uk/python/
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From kalle@gnupung.net  Sun Apr  7 00:09:19 2002
From: kalle@gnupung.net (Kalle Svensson)
Date: Sun, 7 Apr 2002 02:09:19 +0200
Subject: [Tutor] Help
In-Reply-To: <MFEKJEJIGIIAACBIOFCMKEDACAAA.dtanthony@earthlink.net>
References: <MFEKJEJIGIIAACBIOFCMKEDACAAA.dtanthony@earthlink.net>
Message-ID: <20020407000919.GA29361@proton.lysator.liu.se>

[Darren Anthony]
> I want to make python print a sum like:
> What is 7 times 2 ?
> where the two numbers are generated randomly, between 1 and 10.
> 
> So far I have random_between(1,10)
> but how do I include the "What is" and "times" and "?"

Here's one way:

>>> import random
>>> x, y = random.randrange(10), random.randrange(10)
>>> s = "What is %d times %d?" % (x,y)
>>> print s
What is 8 times 5?

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]



From e.kotyk@shaw.ca  Sat Apr  6 17:53:29 2002
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Sat, 06 Apr 2002 17:53:29 +0000
Subject: [Tutor] Conflicted
Message-ID: <20020406175329.5a9d83d0.e.kotyk@shaw.ca>

--=.9LZKRIJBNfd0Za
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit

Hello,

I finally got to trying the suggestions you all have made for reading a
text file, removing a string from a text line and writing the text file
to .bak.  Thank you.

I managed to make the following version work for me...though it removes
the whole line and not just the particular text for which I asked.

Here is the code I used:
import string   #need to import the string module

x = 'spam'      #identify the string that is to be removed

inp = open('menu.txt', 'r') #open to read original file
outp = open('menu.bak', 'w') #open to write .bak file
for line in inp.readlines():    #loop
    if line.find(x):            #using built-in method to find string
requested        line.replace(x, '')     #using built-in method to
replace found string        outp.write(line)        #writing new string
to menu.bak

inp.close()     #closing input file
outp.close()    #closing output file


Here is the troublesome part.  This works when I run it from Idle but if
I run it at the command line I get the following:

python files.py
Traceback (innermost last):
  File "files.py", line 14, in ?
    if line.find(x):            #using built-in method to find string
requested AttributeError: 'string' object has no attribute 'find'

I may know why.  A short while ago I upgraded to python v2.2 but the
original 1.5 version is still resident on my system.  Is it possible
that at the command line the older version is running the script?  If so
how to I correct this?  Is it as simple as removing the python 1.5
files?

E
  


-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm

--=.9LZKRIJBNfd0Za
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE8rzYcyxm8dPG0oMIRAh9mAKC7ZFCpWWH/eBc42R5pARjhZcQy2ACgldyj
zjlWIHUd/+Yw0pshSRxAZCI=
=xmkP
-----END PGP SIGNATURE-----

--=.9LZKRIJBNfd0Za--




From dmanxiii@yahoo.com  Sun Apr  7 00:34:44 2002
From: dmanxiii@yahoo.com (Mr. Derek L. Hoffmeister)
Date: Sat, 6 Apr 2002 16:34:44 -0800 (PST)
Subject: [Tutor] Tkinter problems
Message-ID: <20020407003444.67385.qmail@web20905.mail.yahoo.com>

--0-145114988-1018139684=:67163
Content-Type: text/plain; charset=us-ascii


Sorry People,

I guess I should have been more specific.  Anyways, here's the code I am trying to run.  

from Tkinter import *

class App:

    def _init_(self, master):

        frame = Frame(master)
        frame.pack()

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

    def say_hi(self):
        print "Hi, Derek"

root = Tk()

app = App

root.mainloop()

The example I looked at had app=App(root), but when I run this I get: type error: this constructor takes no agruments.  So I took the arguments out...

Thanks People,

Derek Hoffmeister




---------------------------------
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
--0-145114988-1018139684=:67163
Content-Type: text/html; charset=us-ascii

<P>Sorry People,</P>
<P>I guess I should have been more specific.&nbsp; Anyways, here's the code I am trying to run.&nbsp; </P>
<P>from Tkinter import *</P>
<P>class App:</P>
<P>&nbsp;&nbsp;&nbsp; def _init_(self, master):</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; frame = Frame(master)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; frame.pack()</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.hi_there = Button(frame, text="Hello", command=self.say_hi)<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.hi_there.pack(side=LEFT)</P>
<P>&nbsp;&nbsp;&nbsp; def say_hi(self):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print "Hi, Derek"</P>
<P>root = Tk()</P>
<P>app = App</P>
<P>root.mainloop()</P>
<P>The example I looked at had app=App(root), but when I run this I get: type error: this constructor takes no agruments.&nbsp; So I took the arguments out...</P>
<P>Thanks People,</P>
<P>Derek Hoffmeister<BR></P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
<a href="$rd_url/welcome/?http://taxes.yahoo.com/">Yahoo! Tax Center</a> - online filing with TurboTax
--0-145114988-1018139684=:67163--



From e.kotyk@shaw.ca  Sat Apr  6 18:40:55 2002
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Sat, 06 Apr 2002 18:40:55 +0000
Subject: [Tutor] Conflicted
In-Reply-To: <20020406175329.5a9d83d0.e.kotyk@shaw.ca>
References: <20020406175329.5a9d83d0.e.kotyk@shaw.ca>
Message-ID: <20020406184055.6260e81d.e.kotyk@shaw.ca>

--=.CTC.hOE68G1/C0
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit

 
> I may know why.  A short while ago I upgraded to python v2.2 but the
> original 1.5 version is still resident on my system.  Is it possible
> that at the command line the older version is running the script?  If
> so how to I correct this?  Is it as simple as removing the python 1.5
> files?

Uh hmmm.  I think I can answer my own question here.  I simply moved
python to python.OLD and moved python2.2 to python.  I did not get any
errors when running the script below.

> import string   
> x = 'spam'      
> inp = open('menu.txt', 'r') 
> outp = open('menu.bak', 'w') 
> for line in inp.readlines():   
>     if line.find(x):          
	line.replace(x, '')    
>	outp.write(line)        
> 
> inp.close()    
> outp.close()  

I am however not quite clear as to why the whole line is being replace
rather than just the string requested.    > 
> E
>   
> 
> 
> -- 
> 
> ekotyk
> 
> http://members.shaw.ca/e.kotyk/virtualstudio.htm
> 


-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm

--=.CTC.hOE68G1/C0
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE8r0E8yxm8dPG0oMIRAn5UAKCQiXFdbGpH3bwoySV81tMzx5zodQCfdf8k
BKT/hMkM/CYY6hDQ25Njm9w=
=cYT1
-----END PGP SIGNATURE-----

--=.CTC.hOE68G1/C0--




From shalehperry@attbi.com  Sun Apr  7 00:58:59 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 06 Apr 2002 16:58:59 -0800 (PST)
Subject: [Tutor] Conflicted
In-Reply-To: <20020406184055.6260e81d.e.kotyk@shaw.ca>
Message-ID: <XFMail.20020406165859.shalehperry@attbi.com>

> 
> I am however not quite clear as to why the whole line is being replace
> rather than just the string requested.    > 

>>> s = 'My name is mud'
>>> s.replace('mud', 'Sean')
'My name is Sean'
>>> s
'My name is mud'

s.replace returns the new string.  Keep this mantra in memory at all times when
coding in python -- "A string is a constant, I can not change it".  The only
way to change a string is to make a new one.

line = line.replace(x, '') # for instance.



From python@rcn.com  Sun Apr  7 03:05:54 2002
From: python@rcn.com (Raymond Hettinger)
Date: Sat, 6 Apr 2002 21:05:54 -0500
Subject: [Tutor] Conflicted
References: <XFMail.20020406165859.shalehperry@attbi.com>
Message-ID: <001301c1ddd8$c0a81580$ab61accf@othello>

The implication is, of course, that you should never
let your name become mud because you'll never live it down ;)

Raymond

----- Original Message -----
From: "Sean 'Shaleh' Perry" <shalehperry@attbi.com>
To: "Eve Kotyk" <e.kotyk@shaw.ca>
Cc: <tutor@python.org>
Sent: Saturday, April 06, 2002 7:58 PM
Subject: Re: [Tutor] Conflicted


> >
> > I am however not quite clear as to why the whole line is being replace
> > rather than just the string requested.    >
>
> >>> s = 'My name is mud'
> >>> s.replace('mud', 'Sean')
> 'My name is Sean'
> >>> s
> 'My name is mud'
>
> s.replace returns the new string.  Keep this mantra in memory at all times
when
> coding in python -- "A string is a constant, I can not change it".  The
only
> way to change a string is to make a new one.
>
> line = line.replace(x, '') # for instance.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From e.kotyk@shaw.ca  Sat Apr  6 20:12:22 2002
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Sat, 06 Apr 2002 20:12:22 +0000
Subject: [Tutor] Conflicted
In-Reply-To: <XFMail.20020406165859.shalehperry@attbi.com>
References: <20020406184055.6260e81d.e.kotyk@shaw.ca>
 <XFMail.20020406165859.shalehperry@attbi.com>
Message-ID: <20020406201222.7cffb0bd.e.kotyk@shaw.ca>

--=.)M/uXGul8f..Ci
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit


> > I am however not quite clear as to why the whole line is being
> > replace rather than just the string requested.    > 
> 
> >>> s = 'My name is mud'
> >>> s.replace('mud', 'Sean')
> 'My name is Sean'
> >>> s
> 'My name is mud'

Ok, perhaps I'm being a little dim but if I do

s = 'Spam is not ham'
s.replace('Spam', '')
and write it to a new file, should I not get 'is not ham'?

Instead I am getting an empty file or in the case of multiple lines in
the file, the whole of the line 'Spam is not ham' is gone but 'I'm fond
of ham' remains. 

E
- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm

--=.)M/uXGul8f..Ci
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE8r1apyxm8dPG0oMIRAorvAJ9G53Vd3sS1v0ctC0NcpXBTZlOCDwCglozV
LUnOvVVqEikt+REURaFVbmM=
=Qndy
-----END PGP SIGNATURE-----

--=.)M/uXGul8f..Ci--




From tbrauch@tbrauch.com  Sun Apr  7 03:20:59 2002
From: tbrauch@tbrauch.com (tbrauch@tbrauch.com)
Date: Sat, 6 Apr 2002 21:20:59 -0500
Subject: [Tutor] mail checker
Message-ID: <3CA3680400008576@mta07.san.yahoo.com>

I figured out my re problem, sort of.  I just didn't use them and hope my=

program will still work.

Anyway, I wrote a dirty script to check and print email on a POP3 account=


From tbrauch@tbrauch.com  Sun Apr  7 03:26:41 2002
From: tbrauch@tbrauch.com (tbrauch@tbrauch.com)
Date: Sat, 6 Apr 2002 21:26:41 -0500
Subject: [Tutor] mail checker
In-Reply-To: <3CA3680400008576@mta07.san.yahoo.com>
Message-ID: <3CA368040000857B@mta07.san.yahoo.com>

>From: tbrauch@tbrauch.com
>
>I figured out my re problem, sort of.  I just didn't use them and hope
my
>program will still work.
>
>Anyway, I wrote a dirty script to check and print email on a POP3 accoun=
t

And somehow that message got cut short.

You can view my code at http://hemlock.centre.edu/~tmbrau00/mail_check.tx=
t
 Please comment on it.  I remember someone hosting a website where we cou=
ld
post code for others to look at and comment on (with syntx highlight no
less), but I cannot remember where that was else I would have posted my
code there.

I hope to add IMAP support to this along with making it more failsafe. 
Right now, I can think of hundreds of problems with it, but I was just tr=
ying
to get it to work the first time.  Go back and improve later.

 - Tim




From shalehperry@attbi.com  Sun Apr  7 04:58:03 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 06 Apr 2002 19:58:03 -0800 (PST)
Subject: [Tutor] Conflicted
In-Reply-To: <20020406201222.7cffb0bd.e.kotyk@shaw.ca>
Message-ID: <XFMail.20020406195803.shalehperry@attbi.com>

> 
> Ok, perhaps I'm being a little dim but if I do
> 
> s = 'Spam is not ham'
> s.replace('Spam', '')
> and write it to a new file, should I not get 'is not ham'?
> 
> Instead I am getting an empty file or in the case of multiple lines in
> the file, the whole of the line 'Spam is not ham' is gone but 'I'm fond
> of ham' remains. 
> 

s should be left completely alone as your code is right now.



From sheila@thinkspot.net  Sun Apr  7 05:57:16 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sat, 6 Apr 2002 20:57:16 -0800
Subject: [Tutor] Checking for Control Characters
Message-ID: <3F64522E24@kserver.org>

I'm writing a cgi script right now, for changing passwords on an 
account.

I have to check my input, and the account's username is not allowed 
to have any of the following characters:

not_allowed = '!"#$%(),:;<>@[]|& '  #characters not allowed in 
usernames

This is no problem, and I'm basically checking this with a piece of 
code similar to the following:

    for char in username:
        if char in not_allowed:
            <do stuff for bad data entry>

And of course, that works fine.

However, I am also not supposed to permit any control characters in 
the username,
and was told the following:

Not allowed: control characters \000-\037 \0177

Now, I'm sure I could fiddle around with this, but I was hoping 
someone might have some advice or recommendations on a good way to 
proceed for checking for the control characters. Any and all advice 
welcome,

Thanks,

-- 
Sheila King
http://www.thinkspot.net/sheila/




From shalehperry@attbi.com  Sun Apr  7 06:04:41 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 06 Apr 2002 21:04:41 -0800 (PST)
Subject: [Tutor] Checking for Control Characters
In-Reply-To: <3F64522E24@kserver.org>
Message-ID: <XFMail.20020406210441.shalehperry@attbi.com>

> 
> Now, I'm sure I could fiddle around with this, but I was hoping 
> someone might have some advice or recommendations on a good way to 
> proceed for checking for the control characters. Any and all advice 
> welcome,
> 

def validateInput(input):
    import string

    valid = string.letters + string.digits + '_'
    for char in input:
        if char not in valid:
            return 0
    return 1

validateInput('shaleh') # should be 1
validateInput('\tJim\r') # should be 0




From sheila@thinkspot.net  Sun Apr  7 06:09:47 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sat, 6 Apr 2002 21:09:47 -0800
Subject: [Tutor] Checking for Control Characters
In-Reply-To: <XFMail.20020406210441.shalehperry@attbi.com>
Message-ID: <4AD0E81D59@kserver.org>

On Sat, 06 Apr 2002 21:04:41 -0800 (PST), Sean 'Shaleh' Perry wrote:
> >
> >
> > Now, I'm sure I could fiddle around with this, but I was hoping
> > someone might have some advice or recommendations on a good way
> > to proceed for checking for the control characters. Any and all
> > advice welcome,
> >
>
>
> def validateInput(input): import string
>
> valid = string.letters + string.digits + '_' for char in input: if
> char not in valid: return 0 return 1
>
> validateInput('shaleh') # should be 1 validateInput('\tJim\r') #
> should be 0
>
>

Sean,

Tha's a little too restrictive. For example, you will notice from the 
list of 'not allowed' characters that I listed previously, that the 
single quote character is allowed. Also, the back quote, and the 
tilde, etc.

The instructions I've been given (by the person I'm writing this 
script for) are to NOT ALLOW certain characters. So, I'm trying to 
check for those.

In any case, I would still like to know the best way to check to 
determine whether a character is among the list \000-\037, \0177
which are the control characters I've been told to not allow.


Sheila King
http://www.thinkspot.net/sheila/




From paulsid@shaw.ca  Sun Apr  7 06:17:59 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sat, 06 Apr 2002 22:17:59 -0700
Subject: [Tutor] Checking for Control Characters
References: <4AD0E81D59@kserver.org>
Message-ID: <3CAFD687.A6072E5F@shaw.ca>

Sheila King wrote:

> In any case, I would still like to know the best way to check to
> determine whether a character is among the list \000-\037, \0177
> which are the control characters I've been told to not allow.

List comprehensions to the rescue:

>>> ctrlchars = [chr(i) for i in range(040)] + ['0177']
>>> ctrlchars
['\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08',
'\t', '\n', '\x0b', '\x0c', '\r', '\x0e', '\x0f', '\x10', '\x11',
'\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a',
'\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '0177']

Then just use the in operator to check for membership as you've been
doing.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From paulsid@shaw.ca  Sun Apr  7 06:19:35 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sat, 06 Apr 2002 22:19:35 -0700
Subject: [Tutor] Checking for Control Characters
References: <4AD0E81D59@kserver.org> <3CAFD687.A6072E5F@shaw.ca>
Message-ID: <3CAFD6E7.FAA290E@shaw.ca>

Paul Sidorsky wrote:

> >>> ctrlchars = [chr(i) for i in range(040)] + ['0177']

Whoops, forgot the \ in front of 0177 but you get the idea I'm sure...

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From sheila@thinkspot.net  Sun Apr  7 06:23:08 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sat, 6 Apr 2002 21:23:08 -0800
Subject: [Tutor] Checking for Control Characters
In-Reply-To: <3CAFD687.A6072E5F@shaw.ca>
Message-ID: <57170D2924@kserver.org>

On Sat, 06 Apr 2002 22:17:59 -0700, Paul Sidorsky wrote:
> Sheila King wrote:
>
> > In any case, I would still like to know the best way to check to
> > determine whether a character is among the list \000-\037, \0177
> > which are the control characters I've been told to not allow.
>
>
> List comprehensions to the rescue:
>
> > > > ctrlchars = [chr(i) for i in range(040)] + ['0177']
> > > > ctrlchars
> ['\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
> '\x08', '\t', '\n', '\x0b', '\x0c', '\r', '\x0e', '\x0f', '\x10',
> '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18',
> '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '0177']
>
>
> Then just use the in operator to check for membership as you've
> been doing.
>

Ah, thanks Paul. That is something like what I was looking for, but I 
couldn't quite put my finger on it. :)

-- 
Sheila King
http://www.thinkspot.net/sheila/





From shalehperry@attbi.com  Sun Apr  7 06:29:15 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 06 Apr 2002 21:29:15 -0800 (PST)
Subject: [Tutor] Checking for Control Characters
In-Reply-To: <4AD0E81D59@kserver.org>
Message-ID: <XFMail.20020406212915.shalehperry@attbi.com>

> 
> In any case, I would still like to know the best way to check to 
> determine whether a character is among the list \000-\037, \0177
> which are the control characters I've been told to not allow.
> 

okie dokie:

def validateInput(input):
    for char in input:
        i = ord(char)
        if (0x0 < i > 0x1f) and i != 0x7f: continue
        return 0
    return 1

hex is easier than octal (for me anyways).



From paulsid@shaw.ca  Sun Apr  7 06:42:35 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sat, 06 Apr 2002 22:42:35 -0700
Subject: [Tutor] Checking for Control Characters
References: <57170D2924@kserver.org>
Message-ID: <3CAFDC4B.B50530FB@shaw.ca>

Sheila King wrote:

> > > > > ctrlchars = [chr(i) for i in range(040)] + ['0177']
> 
> Ah, thanks Paul. That is something like what I was looking for, but I
> couldn't quite put my finger on it. :)

Whoops again, I just realized that '\0177' isn't what it looks like.  I
forgot that character codes are limited to 3 digits, so '\0177' ==
'\x0f7' == '\x0f' + '7', i.e. the length is 2.   '\177' is correct, but
chr(0177) is probably smarter and more consistent.

Sorry about all the errors - I rarely do anything using octal.  :-)

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From dyoo@hkn.eecs.berkeley.edu  Sun Apr  7 07:17:43 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 6 Apr 2002 22:17:43 -0800 (PST)
Subject: [Tutor] Tkinter problems
In-Reply-To: <20020407003444.67385.qmail@web20905.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0204062213210.21589-100000@hkn.eecs.berkeley.edu>

On Sat, 6 Apr 2002, Mr. Derek L. Hoffmeister wrote:

> Sorry People,
>
> I guess I should have been more specific.

Don't worry about it.


> Anyways, here's the code I am trying to run.
>
> from Tkinter import *
>
> class App:
>
>     def _init_(self, master):
>
>         frame = Frame(master)
>         frame.pack()
>
>         self.hi_there = Button(frame, text="Hello", command=self.say_hi)
>         self.hi_there.pack(side=LEFT)

Ah!  The special "initializer" function that a class uses to create new
instances needs to be named '__init__' --- that is, with two underscores
on both sides of the name.  If you rename your '_init_' function to
'__init__', this should fix the problem.

These "special" method names have double underscores on both sides to
indicate their specialness to Python.  If you'd like to see a list of
them, you can take a look here:

    http://www.python.org/doc/current/ref/specialnames.html

(Be aware that the above link is reference material, so it may be a
little... dry.  *grin*)


Good luck to you!




From dyoo@hkn.eecs.berkeley.edu  Sun Apr  7 07:27:42 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 6 Apr 2002 22:27:42 -0800 (PST)
Subject: [Tutor] Conflicted  [Strings are immutable]
In-Reply-To: <20020406201222.7cffb0bd.e.kotyk@shaw.ca>
Message-ID: <Pine.LNX.4.44.0204062218420.21589-100000@hkn.eecs.berkeley.edu>

On Sat, 6 Apr 2002, Eve Kotyk wrote:

>
> > > I am however not quite clear as to why the whole line is being
> > > replace rather than just the string requested.    >
> >
> > >>> s = 'My name is mud'
> > >>> s.replace('mud', 'Sean')
> > 'My name is Sean'
> > >>> s
> > 'My name is mud'
>
> Ok, perhaps I'm being a little dim but if I do
>
> s = 'Spam is not ham'
> s.replace('Spam', '')
> and write it to a new file, should I not get 'is not ham'?


Strings are 'immutable' in Python --- they don't change.  Whenever we do
manipulations on strings, Python creates whole new strings and doesn't
modify the old ones.

It helps if we try your example in the interpreter:

###
>>> s = "Spam is not ham"
>>> s.replace('Spam', '')
' is not ham'
###

Up to this point, what we're seeing is that the expression:

    s.replace('Spam', '')

is giving back to us the string that we're expecting.  However, this does
not change what 's' itself contains:

###
>>> s
'Spam is not ham'
###


What you probably want to do is capture the string that the replace()
gives in another variable.  Here's an example:

###
>>> s_without_spam = s.replace('Spam', '')
>>> s_without_spam
' is not ham'
>>> s
'Spam is not ham'
###


The 's_without_spam' is something you can write to your file.  If we want
to make it look like s is being changed itself, we can just reuse 's' as
our variable:

###
>>> s
'Spam is not ham'
>>> s = s.replace(' ', '/')
>>> s
'Spam/is/not/ham'
###


Python strings are designed with this sense of immutability in them, just
like numbers.  If we multiply 3 and 4:

###
>>> 3 * 4
12
###

... this doesn't "hurt" 3 or 4 or make any changes to them.  Immutability
with strings is the same idea:

###
>>> "three" * 4
'threethreethreethree'
###


Please feel free to ask more questions about this; it's a somewhat subtle
issue but important to understand.  Good luck!




From sheila@thinkspot.net  Sun Apr  7 10:13:34 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sun, 7 Apr 2002 01:13:34 -0800
Subject: [Tutor] Using popen
In-Reply-To: <Pine.LNX.4.44.0204031206570.7983-100000@hkn.eecs.berkeley.edu>
Message-ID: <12A068A787B@kserver.org>

On Wed, 3 Apr 2002 12:25:28 -0800 (PST), Danny Yoo wrote:

> So the value that the close() returns is actually a combination of
> the "exit status" that we're looking for, along with a "signal"
> number.  And to get the true exit status, we'll want to grab the
> high byte.  One way to do this is to just push the signal number
> part right off by using bitwise right shifting:
>
> ###
> > > > 256 >> 8
> 1 ###
>
> That is, just shift the number by 8 bits.  What's left is the
> return value that we're looking for.  (By the way, this bit shift
> is equivalent to what Sean was doing with the modulo 255
> arithmetic.)

>
> You're actually getting an exit code of 1, so your program may be
> signalling an error of some sort.

I just wanted to follow up and say, that I finally figured out what 
my problem was, and why I was getting an exit code of 1.

I needed to include a trailing "newline" character on the password, 
and I was omitting it. Thus, the error code. Now that I'm including 
the trailing newline character, it is working fine.

(Reading the docs carefully always helps!!!)

-- 
Sheila King
http://www.thinkspot.net/sheila/





From e.kotyk@shaw.ca  Sun Apr  7 09:18:15 2002
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Sun, 07 Apr 2002 08:18:15 +0000
Subject: [Tutor] Conflicted  [Strings are immutable]
In-Reply-To: <Pine.LNX.4.44.0204062218420.21589-100000@hkn.eecs.berkeley.edu>
References: <20020406201222.7cffb0bd.e.kotyk@shaw.ca>
 <Pine.LNX.4.44.0204062218420.21589-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020407081815.5f69649f.e.kotyk@shaw.ca>

--TJRqo7tl=.geJVG.
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit


> 
> Strings are 'immutable' in Python --- they don't change.  Whenever we
> do manipulations on strings, Python creates whole new strings and
> doesn't modify the old ones.
> 
> It helps if we try your example in the interpreter:
> 
> ###
> >>> s = "Spam is not ham"
> >>> s.replace('Spam', '')
> ' is not ham'
> ###
> 
> Up to this point, what we're seeing is that the expression:
> 
>     s.replace('Spam', '')
> 
> is giving back to us the string that we're expecting.  However, this
> does not change what 's' itself contains:
> 
> ###
> >>> s
> 'Spam is not ham'
> ###

I was beginning to understand this from Sean's post.  This makes it very
clear. 

> What you probably want to do is capture the string that the replace()
> gives in another variable.  Here's an example:
> 
> ###
> >>> s_without_spam = s.replace('Spam', '')
> >>> s_without_spam
> ' is not ham'
> >>> s
> 'Spam is not ham'
> ###
> 
> The 's_without_spam' is something you can write to your file.  If we
> want to make it look like s is being changed itself, we can just reuse
> 's' as our variable:
> 
> ###
> >>> s
> 'Spam is not ham'
> >>> s = s.replace(' ', '/')
> >>> s
> 'Spam/is/not/ham'
> ###
> 
> 
> Python strings are designed with this sense of immutability in them,
> just like numbers.  If we multiply 3 and 4:
> 
> ###
> >>> 3 * 4
> 12
> ###
> 
> ... this doesn't "hurt" 3 or 4 or make any changes to them. 
> Immutability with strings is the same idea:
> 
> ###
> >>> "three" * 4
> 'threethreethreethree'
> ###
> 
> 
> Please feel free to ask more questions about this; it's a somewhat
> subtle issue but important to understand.  Good luck!
> 
Thanks.  This was great!

E

-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm

--TJRqo7tl=.geJVG.
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE8sADLyxm8dPG0oMIRAgm1AJ4ghPzxcEjcQ4C6DEQDVwEOf6SgtACbBPrz
WadBe7vZwwQK1XkwTzh/pWo=
=3KIg
-----END PGP SIGNATURE-----

--TJRqo7tl=.geJVG.--




From dtanthony@earthlink.net  Sun Apr  7 17:54:38 2002
From: dtanthony@earthlink.net (Darren Anthony)
Date: Sun, 7 Apr 2002 09:54:38 -0700
Subject: [Tutor] Loop help
Message-ID: <MFEKJEJIGIIAACBIOFCMOEDGCAAA.dtanthony@earthlink.net>

I'm trying to write a simple times-table testing program.
The program generates two random numbers and multiplies them and ask the
user for the answer. The user inputs answer and the program verifies the
answer. I want to write a loop into the program to ask 10 questions and then
end. How do I create the loop and what line do I place the code?

I'm using python for windows.

Here is my code:

from livewires import*

x = random_between(1,10)
y = random_between(1,10)
s = "What is %d times %d?" % (x,y)
print s
r=read_number()
z=x*y
if z==r:
   print "That's right --well done"
else:
   print "No, I'm afraid the answer is"
print z


raw_input("Press return to exit: ")





From sentinel805@netscape.net  Sun Apr  7 18:16:21 2002
From: sentinel805@netscape.net (nova812)
Date: Sun, 07 Apr 2002 13:16:21 -0400
Subject: [Tutor] How many web sites....
Message-ID: <3CB07EE5.6040208@netscape.net>

I'm learning python and write a bunch of silly code for the purpose of 
learning.  currently I focus my efforts to learning python as it relates 
to wxPython and pygame.  Some of the simplest things I struggle with 
because I sometimes have trouble finding source code to edit.
I would like to share the code I write with other newbies.   I sent code 
to Useless Python site, but it doesn't seem to published.  How many 
other sites like Useless Python are there where I might be able to 
share/exchange code.


nova812
http://www.lowerstandard.com/python/uselesspython1.html




From wolf_binary@hotmail.com  Sun Apr  7 18:59:23 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sun, 7 Apr 2002 12:59:23 -0500
Subject: [Tutor] matrices
Message-ID: <DAV45Viyp4Z9hPYXZY300003a7c@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0006_01C1DE34.0A351080
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi all,

If you make a compound list like this:

>>> l =3D ["1","1","1"]
>>> ll =3D ["2","2","2"]
>>> lll=3D ["3","3","3"]
>>> ll =3D [l,l,l]
>>> lll =3D [ll,ll,]
>>> lll
[[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'], =
['1', '1', '1'], ['1', '1', '1']]]

are you making a matrix?

Cameron

------=_NextPart_000_0006_01C1DE34.0A351080
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>If you make a compound list like =
this:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; l =3D =
["1","1","1"]<BR>&gt;&gt;&gt; ll =3D=20
["2","2","2"]<BR>&gt;&gt;&gt; lll=3D ["3","3","3"]<BR>&gt;&gt;&gt; ll =
=3D=20
[l,l,l]<BR>&gt;&gt;&gt; lll =3D [ll,ll,]<BR>&gt;&gt;&gt; lll<BR>[[['1', =
'1', '1'],=20
['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'], ['1', '1', '1'], =
['1', '1',=20
'1']]]</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>are you making a matrix?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Cameron</FONT></DIV></BODY></HTML>

------=_NextPart_000_0006_01C1DE34.0A351080--



From dyoo@hkn.eecs.berkeley.edu  Sun Apr  7 19:17:13 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 7 Apr 2002 11:17:13 -0700 (PDT)
Subject: [Tutor] How many web sites....
In-Reply-To: <3CB07EE5.6040208@netscape.net>
Message-ID: <Pine.LNX.4.44.0204071113460.31682-100000@hkn.eecs.berkeley.edu>


On Sun, 7 Apr 2002, nova812 wrote:

> I'm learning python and write a bunch of silly code for the purpose of
> learning.  currently I focus my efforts to learning python as it relates
> to wxPython and pygame.  Some of the simplest things I struggle with
> because I sometimes have trouble finding source code to edit.
> I would like to share the code I write with other newbies.   I sent code
> to Useless Python site, but it doesn't seem to published.  How many
> other sites like Useless Python are there where I might be able to
> share/exchange code.

You can use ChalkBoard as a temporary holding place for your code:

    http://www.decrem.com:8080/ChalkBoard

I have to admit that this page is not really ready for general consumption
yet; I haven't had the time to polish it.  Still, it should work well
enough to post code.

Good luck!




From wolf_binary@hotmail.com  Sun Apr  7 19:15:03 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sun, 7 Apr 2002 13:15:03 -0500
Subject: [Tutor] Loop help
References: <MFEKJEJIGIIAACBIOFCMOEDGCAAA.dtanthony@earthlink.net>
Message-ID: <DAV21zp2IZuSTOk0gaP0000129f@hotmail.com>

Look down in your code to where I have added code to yours.  It will be a
while loop.

> I'm trying to write a simple times-table testing program.
> The program generates two random numbers and multiplies them and ask the
> user for the answer. The user inputs answer and the program verifies the
> answer. I want to write a loop into the program to ask 10 questions and
then
> end. How do I create the loop and what line do I place the code?
>
> I'm using python for windows.
>
> Here is my code:
>
> from livewires import*
>
> x = random_between(1,10)
> y = random_between(1,10)
> s = "What is %d times %d?" % (x,y)
> print s
### start of loop
while q <=10:
    r=read_number() inside the loop
#To not include your next lines of code to be repeated they need to be at
the same
#level as the while statement
#example:
#while x < 10:
#    x = x + 1
#     print x
#end of while loop
> z=x*y
> if z==r:
>    print "That's right --well done"
> else:
>    print "No, I'm afraid the answer is"
> print z
>
>
> raw_input("Press return to exit: ")
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

If you need more help just email the tutor again.

Cameron Stoner




From wolf_binary@hotmail.com  Sun Apr  7 19:18:36 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sun, 7 Apr 2002 13:18:36 -0500
Subject: [Tutor] How many web sites....
References: <3CB07EE5.6040208@netscape.net>
Message-ID: <DAV42xw00dSdVudU5N30000396c@hotmail.com>

If you are looking for little demo programs of how things work, just ask me
and I might be able to help.  I have been in your shoes and know enough now
that I can hopefully help you in your predicament.  What kind of examples
are you looking for?  Are you coming from a complete Non-Programmer
position?  Help me to understand your circumstances.

Cameron Stoner

> I'm learning python and write a bunch of silly code for the purpose of
> learning.  currently I focus my efforts to learning python as it relates
> to wxPython and pygame.  Some of the simplest things I struggle with
> because I sometimes have trouble finding source code to edit.
> I would like to share the code I write with other newbies.   I sent code
> to Useless Python site, but it doesn't seem to published.  How many
> other sites like Useless Python are there where I might be able to
> share/exchange code.
>
>
> nova812
> http://www.lowerstandard.com/python/uselesspython1.html
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From wolf_binary@hotmail.com  Sun Apr  7 19:23:57 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sun, 7 Apr 2002 13:23:57 -0500
Subject: [Tutor] Loop help
References: <MFEKJEJIGIIAACBIOFCMOEDGCAAA.dtanthony@earthlink.net>
Message-ID: <DAV418sZTWC2Jr5EVQi00003956@hotmail.com>

It just dawned on me that you need to test it 10 times too.
Look down at your code and you will see what I mean.
----- Original Message -----
From: "Darren Anthony" <dtanthony@earthlink.net>
To: <tutor@python.org>
Sent: Sunday, April 07, 2002 11:54 AM
Subject: [Tutor] Loop help


> I'm trying to write a simple times-table testing program.
> The program generates two random numbers and multiplies them and ask the
> user for the answer. The user inputs answer and the program verifies the
> answer. I want to write a loop into the program to ask 10 questions and
then
> end. How do I create the loop and what line do I place the code?
>
> I'm using python for windows.
>
> Here is my code:
>
> from livewires import*
>
> x = random_between(1,10)
> y = random_between(1,10)
> s = "What is %d times %d?" % (x,y)
> print s
#while x <= 10:
#    x = x + 1
>    r=read_number()
>    z=x*y
>    if z==r:
>        print "That's right --well done"
>    else:
>        print "No, I'm afraid the answer is"
#end of loop
> print z
>
>
> raw_input("Press return to exit: ")
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From urnerk@qwest.net  Sun Apr  7 16:37:18 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 7 Apr 2002 11:37:18 -0400
Subject: [Tutor] matrices
In-Reply-To: <DAV45Viyp4Z9hPYXZY300003a7c@hotmail.com>
References: <DAV45Viyp4Z9hPYXZY300003a7c@hotmail.com>
Message-ID: <E16uHTj-0005no-00@mail.python.org>

On Sunday 07 April 2002 01:59 pm, Cameron Stoner wrote:
> Hi all,
>
> If you make a compound list like this:
> >>> l = ["1","1","1"]
> >>> ll = ["2","2","2"]
> >>> lll= ["3","3","3"]
> >>> ll = [l,l,l]
> >>> lll = [ll,ll,]
> >>> lll
>
> [[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'],
> ['1', '1', '1'], ['1', '1', '1']]]
>
> are you making a matrix?
>
> Cameron

This looks more complicated than you'd need for an ordinary
two-dimensional matrix (same as 2D array).  For example, a 
math book might have the following matrix:

         1  3  5
        -1  0  0
        -2  1  0

If you wanted that in a 2D array, you could just go:

matrix = [[1, 3, 5],[-1,0,0],[-2,1,0]]

A difference from math texts is they usually use 1-based
indexing, i.e. upper left entry is row 1, column 1, whereas
in Python (and many other computer languages), zero-based
indexing is the norm.  So we get:

 >>> matrix[0][0]
 1
 >>> matrix[1][1]
 0

and so on.

However, a more typical implementation of a matrix in 
Python would be as a class definition, with operator 
overriding used to endow the instances with the powers
matrices usually have, such as the power to multiply,
add, subtract, invert (if square).  

I've done such a matrix implementation, with the square 
matrix (having even more powers, such as determinant) 
a subclass of the more generic rectangular matrix.  I can 
point you to a website with the source code if you're 
interested.

I think you'll find many implementations of the matrix 
concept in Python, saved in the various stashes.  And 
then, of course, there's Numeric, or NumPy, which 
implements an indigenous from of n-dimensional array, 
with fancier ways of slicing and dicing them, along with 
a whole linear algebra package.  But that's overkill in
some contexts (plus less instructive than rolling one's
own).

Kirby



From erikprice@mac.com  Sun Apr  7 20:15:32 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 7 Apr 2002 15:15:32 -0400
Subject: [Tutor] impact of OO
In-Reply-To: <6036.1017995657@www50.gmx.net>
Message-ID: <D49A03E3-4A5B-11D6-BFB4-00039351FE6A@mac.com>

On Friday, April 5, 2002, at 03:34  AM, J=F6rg W=F6lke wrote:

>> I have a general question about Object Oriented programming in =
general:
>> why is it so lauded by... well, by everyone?
>
> Not me.I think it's evil.
>
> [ snip ]
>
>> Erik
>
> SCNR J"o!
>
>> object".  What does this mean?  I think I am interested in learning
>> Java, especially since there are many employers in my area (Boston)
>> advertising an interest in Java programmers (and I will be out of a =
job
>> as soon as my project is finished).  Sadly, much more than Python or
>> PHP.  But it seems like a big language to learn.
>
> In Python everything is an Object, too. And it means exactly that ;-)
> BTW: Java is evil.

But... if OO is evil... and Java is evil... and in Java everything is an=20=

object... and if in Python everything is an object... and Python is=20
object-oriented... Python could be evil!

;)



Erik




From erikprice@mac.com  Sun Apr  7 20:42:54 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 7 Apr 2002 15:42:54 -0400
Subject: [Tutor] Working with files
In-Reply-To: <83697490-4898-11D6-B633-00039351FE6A@mac.com>
Message-ID: <A78A4218-4A5F-11D6-BFB4-00039351FE6A@mac.com>

On Friday, April 5, 2002, at 08:24  AM, Erik Price wrote:

> But you're right, one still needs to find a way to manage overlaps 
> between chunksizes.  Perhaps something like this pseudocode:
>
> # won't work; pseudocode
> # needle = string to search for
> chunk_size = len(needle)
> if (!f = open('filename')):
>   print 'Could not open ', haystack, ' for searching'
> else:
>   while 1:
>     # pointer_multiplier is used to set read position in file
>     pointer_multiplier = 1
>     # read a section of the file twice the length of needle
>     haystack = f.read(chunk_size * 2)
>     # if needle is found, report it and stop
>     if re.search(needle, haystack):
>       print 'Found ', needle, '!'
>       break
>     else:
>       # here's the pseudocode b/c I don't know how to write this yet
>       # (and I'm late for work so I can't look it up)
>
>       move internal file pointer (chunk_size * pointer_multiplier) 
> bytes forward from start of file
>       pointer_multiplier = pointer_multiplier + 1

I just realized that I did in fact overlook something -- at the end of 
the while loop, I bump up the pointer_multiplier by one, so that the 
internal pointer for the file moves forward.  But I end up reassigning 
pointer_multiplier to 1 again at the top of the while loop.  I'd have to 
assign the pointer_multiplier to 1 before the while loop starts for this 
code to work.


Erik




From erikprice@mac.com  Sun Apr  7 22:40:52 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 7 Apr 2002 17:40:52 -0400
Subject: [Tutor] Simple HelloWorld cgi script
In-Reply-To: <BDA406CE9FA12E4FBC913071BE7733BF0C6F07@doc5.doc.state.ri.us>
Message-ID: <21FDB4C8-4A70-11D6-B17B-00039351FE6A@mac.com>

On Thursday, April 4, 2002, at 10:56  AM, <STavares@doc.state.ri.us> 
wrote:

> Could somene please me to a simple heloworld cgi script written in 
> python?
>

Not exactly what you asked for, but hopefully helpful:

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



Erik




From me@mikerobin.com  Sat Apr  6 21:22:28 2002
From: me@mikerobin.com (Michael Robin)
Date: Sat, 6 Apr 2002 13:22:28 -0800
Subject: [Tutor] RE: How to remove a newline character
In-Reply-To: <3CAF772A.32178.10B2B72@localhost>
Message-ID: <DHEEKAFNPOKNEBEBLCIAAECGCJAA.me@mikerobin.com>

[ s.replace('\n','') for s in MyList]

mike

-----Original Message-----
From: activepython-admin@listserv.ActiveState.com
[mailto:activepython-admin@listserv.ActiveState.com]On Behalf Of A
Sent: Saturday, April 06, 2002 12:31 PM
To: python-help@python.org; activepython@listserv.activestate.com;
tutor@python.org
Subject: How to remove a newline character


Hi,
Can you please let me know  if it is possible to replace 
new line characters( '\n') in a list in one step?

I have list like

MyList=['272580\n', '23232432\n']

and I would like to have 
,MyList=['272580', '23232432']

so I tried
re.sub('\n','',MyList)
but I received 
TypeError: expected string or buffer

Your help would be appreciated
Thanks.
Ladislav

I look forward to hearing from you soon.

Best Regards,
Ladislav Blazek( Mr.)

BMA TRADING Ltd.
email: export@sendme.cz
email2: export@bmatrading.com
Fax:/Tel +420 506 447921
Tel:+420 506 447920, +420 602 849309


_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs




From cnichol4@columbus.rr.com  Sat Apr  6 21:56:53 2002
From: cnichol4@columbus.rr.com (Charles 'MoHawkeman' Nichols)
Date: Sat, 6 Apr 2002 16:56:53 -0500
Subject: [Tutor] Re: How to remove a newline character
References: <3CAF772A.32178.10B2B72@localhost>
Message-ID: <001001c1ddb5$fcf4b840$b1b9d018@sabbastian>

import re
MyList=['272580\n', '23232432\n']

for i in MyList:
    re.sub('\n','',str(i))

----- Original Message -----
From: "A" <printers@sendme.cz>
To: <python-help@python.org>; <activepython@listserv.ActiveState.com>;
<tutor@python.org>
Sent: Saturday, April 06, 2002 3:31 PM
Subject: How to remove a newline character


> Hi,
> Can you please let me know  if it is possible to replace
> new line characters( '\n') in a list in one step?
>
> I have list like
>
> MyList=['272580\n', '23232432\n']
>
> and I would like to have
> ,MyList=['272580', '23232432']
>
> so I tried
> re.sub('\n','',MyList)
> but I received
> TypeError: expected string or buffer
>
> Your help would be appreciated
> Thanks.
> Ladislav
>
> I look forward to hearing from you soon.
>
> Best Regards,
> Ladislav Blazek( Mr.)
>
> BMA TRADING Ltd.
> email: export@sendme.cz
> email2: export@bmatrading.com
> Fax:/Tel +420 506 447921
> Tel:+420 506 447920, +420 602 849309
>
>
> _______________________________________________
> ActivePython mailing list
> ActivePython@listserv.ActiveState.com
> To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
>




From roelsch@acm.org  Sat Apr  6 22:06:21 2002
From: roelsch@acm.org (Robert L. Oelschlaeger)
Date: Sat, 6 Apr 2002 16:06:21 -0600
Subject: [Tutor] Re: How to remove a newline character
References: <3CAF772A.32178.10B2B72@localhost>
Message-ID: <000f01c1ddb7$498a7950$010b1bac@WORKGROUP>

# Try: strip() from the string module:
#
# strip(s)
#Return a copy of s without leading or trailing whitespace.

MyList=['272580\n', '23232432\n']
print MyList

import string
MyList = map(string.strip, MyList)
print MyList

----- Original Message -----
From: "A" <printers@sendme.cz>
To: <python-help@python.org>; <activepython@listserv.activestate.com>;
<tutor@python.org>
Sent: Saturday, April 06, 2002 2:31 PM
Subject: How to remove a newline character


> Hi,
> Can you please let me know  if it is possible to replace
> new line characters( '\n') in a list in one step?
>
> I have list like
>
> MyList=['272580\n', '23232432\n']
>
> and I would like to have
> ,MyList=['272580', '23232432']
>
> so I tried
> re.sub('\n','',MyList)
> but I received
> TypeError: expected string or buffer
>
> Your help would be appreciated
> Thanks.
> Ladislav
>
> I look forward to hearing from you soon.
>
> Best Regards,
> Ladislav Blazek( Mr.)
>
> BMA TRADING Ltd.
> email: export@sendme.cz
> email2: export@bmatrading.com
> Fax:/Tel +420 506 447921
> Tel:+420 506 447920, +420 602 849309
>
>
> _______________________________________________
> ActivePython mailing list
> ActivePython@listserv.ActiveState.com
> To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs




From paiarunk@yahoo.com  Sun Apr  7 08:39:50 2002
From: paiarunk@yahoo.com (Arun Kumar)
Date: Sat, 6 Apr 2002 23:39:50 -0800 (PST)
Subject: [Tutor] Led buttons in python
Message-ID: <20020407073950.83676.qmail@web11102.mail.yahoo.com>

--0-1981585698-1018165190=:82682
Content-Type: text/plain; charset=us-ascii


hai,

i am new to python

how can i create LED buttons for displaying the status ?

also where i can get sample gui applications ?

 

bye

arun



---------------------------------
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
--0-1981585698-1018165190=:82682
Content-Type: text/html; charset=us-ascii

<P>hai,</P>
<P>i am new to python</P>
<P>how can i create LED buttons for displaying the status ?</P>
<P>also where i can get sample gui applications ?</P>
<P>&nbsp;</P>
<P>bye</P>
<P>arun</P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
<a href="$rd_url/welcome/?http://taxes.yahoo.com/">Yahoo! Tax Center</a> - online filing with TurboTax
--0-1981585698-1018165190=:82682--



From alan.gauld@bt.com  Sun Apr  7 22:55:11 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 22:55:11 +0100
Subject: [Tutor] Tkinter problems
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C512@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C1DE7E.E3B28E60
Content-type: text/plain; charset="ISO-8859-1"

> working on getting buttons with Tkinter, but I can't.  I get the Tkinter
window  
>  to open up when I run the code, but the button(s) won't show up.   
 
I suspect you've forgoptten to pack the buttons.
You create them as widgets but before they show up you have 
to pack() them(or place() them or grod() them)
 
But without any sample code its kind of hard to be sure...
 
This should work to test my theory:
 
>>> from Tkinter import *
>>> tk = Tk()   # window appears
>>> b = Button(text = "Hello")   # create button widget
>>> b.pack()    # button widget appears
>>> tk.mainloop()   # run the GUI, quit via titlebar icon
 
See my tutor's intro to Tkinter for more on this
 
>  IDLE doesn't show any errors.   
 
I really recommend not running Tkinter programs from 
within IDLE. I know there are workarounds (like not 
calling mainloop() ) but I find it much better to use 
IDLE as an editor if you must but run the programs 
from an OS prompt.
 
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld
<http://www.freenetpages.co.uk/hp/alan.gauld>  

 

------_=_NextPart_001_01C1DE7E.E3B28E60
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.50.4807.2300" name=GENERATOR></HEAD>
<BODY>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt;&nbsp;</FONT></SPAN>working on getting buttons with Tkinter, but I 
can't.&nbsp; I get the Tkinter window&nbsp;<SPAN class=380514921-07042002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>to open up when I run the code, but the 
button(s) won't show up.&nbsp;&nbsp;<SPAN class=380514921-07042002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>I suspect you've forgoptten to pack the buttons.</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>You create them as widgets but before they show up you have 
</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>to pack() them(or place() them or grod() them)</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>But without any sample code its kind of hard to be 
sure...</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>This should work to test my theory:</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt;&gt;&gt; from Tkinter import *</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt;&gt;&gt; tk = Tk()&nbsp;&nbsp; # window appears</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt;&gt;&gt; b = Button(text = "Hello")&nbsp;&nbsp; # create button 
widget</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt;&gt;&gt; b.pack()&nbsp;&nbsp;&nbsp; # button widget 
appears</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt;&gt;&gt; tk.mainloop()&nbsp;&nbsp; # run the GUI, quit via titlebar 
icon</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>See my tutor's intro to Tkinter for more on this</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002></SPAN><SPAN 
class=380514921-07042002></SPAN><SPAN class=380514921-07042002></SPAN><SPAN 
class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>IDLE doesn't show any errors.&nbsp;&nbsp;<SPAN 
class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>I really recommend not running Tkinter programs from </FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>within IDLE. I know there are workarounds (like not </FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>calling mainloop() ) but I find it much better to use 
</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>IDLE as an editor if you must but run the programs </FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>from an OS prompt.</FONT></SPAN></DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=380514921-07042002><FONT face="Courier New" color=#0000ff 
size=2>
<P><FONT size=2>Alan g.<BR>Author of the 'Learning to Program' web site<BR><A 
target=_blank 
href="http://www.freenetpages.co.uk/hp/alan.gauld">http://www.freenetpages.co.uk/hp/alan.gauld</A></FONT> 
</P></FONT></SPAN><SPAN class=380514921-07042002><FONT face="Courier New" 
color=#0000ff size=2></FONT></SPAN></DIV>
<DIV><FONT face="Courier New" color=#0000ff 
size=2></FONT>&nbsp;</DIV></BODY></HTML>

------_=_NextPart_001_01C1DE7E.E3B28E60--



From dyoo@hkn.eecs.berkeley.edu  Mon Apr  8 00:11:37 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 7 Apr 2002 16:11:37 -0700 (PDT)
Subject: [Tutor] Loop help (fwd)
Message-ID: <Pine.LNX.4.44.0204071449310.3756-100000@hkn.eecs.berkeley.edu>

Hi Jeff,

I'm forwarding your question to the main Tutor list at "tutor@python.org".
(You had sent it to tutor-admin, but that only reaches the list
administrators here.)


About your question, let's take a look at the code:

###
while x <= 10:
    x = x + 1
    r=read_number()
    z=x*y
    if z==r:
        print "That's right --well done"
    else:
        print "No, I'm afraid the answer is"
###


Hmmm... actually, I'd like a for loop here:

###
for x in range(1, 11):
    r=read_number()
    z=x*y
    if z==r:
        print "That's right --well done"
    else:
        print "No, I'm afraid the answer is"
###

To make sure that this has the same effect as the previous code, we need
to start the range from 1 instead of zero.


Hope this helps!


---------- Forwarded message ----------
Date: Sun, 7 Apr 2002 15:31:11 -0400
From: Jeff Davis <knowhere@fuse.net>
To: tutor-admin@python.org
Subject: Re: [Tutor] Loop help

On 7 Apr 2002 at 13:15, Cameron Stoner wrote:

> Look down in your code to where I have added code to yours.  It will
> be a while loop.

Why is a "while" loop more appropriate than a "for" loop in this
case?









From alan.gauld@bt.com  Sun Apr  7 23:02:17 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:02:17 +0100
Subject: [Tutor] How to remove a newline character
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C513@mbtlipnt02.btlabs.bt.co.uk>

> MyList=['272580\n', '23232432\n']
> 
> and I would like to have 
> MyList=['272580', '23232432']

MyList = map(lamda s: s.strip(), MyList)

Or more explicitly

for n in range(len(MyList)): 
    MyList[n] = MyList[n].strip()


If you don't want to use strip then just use slicing to 
get rid of the last char:

    MyList[n] = MyList[n][:-1]  # strip off last char

Alan G



From alan.gauld@bt.com  Sun Apr  7 23:08:17 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:08:17 +0100
Subject: [Tutor] Help
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C514@mbtlipnt02.btlabs.bt.co.uk>

> I want to make python print a sum like:
> What is 7 times 2 ?
> where the two numbers are generated randomly, between 1 and 10.
> 
> So far I have random_between(1,10)
> but how do I include the "What is" and "times" and "?"

Try the first page of the second section of my tutor,
it covers printing things like that using format strings.

You've cracked the hard bit which is the random numbers!

Alternatively you could just string it together in 
a print statement like this:

num1 = ....
num2 = ....
print "What is ", num1, " times ", num2

For more complex things format strings tend to be 
easier IMHO

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Sun Apr  7 23:15:46 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:15:46 +0100
Subject: [Tutor] Conflicted
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C515@mbtlipnt02.btlabs.bt.co.uk>

> for line in inp.readlines():    #loop
>     if line.find(x): 
>          line.replace(x, '')     #using built-in method to

I think that should be

           line = line.replace(x,'')

replace creates a new string it doesn't alter the original.

> I may know why.  A short while ago I upgraded to python v2.2 but the
> original 1.5 version is still resident on my system.  

Sounds like the roblem.
What happens when you just type python in a DOS box? 
Is is 2 or 1.35 that comes up?

In either case remove Python 1.5 from the system, if 
possible using the Control Panel remove programs applet
since it will cleanse the registry too...

If necessary reinstall v2 after.


Alan G.



From alan.gauld@bt.com  Sun Apr  7 23:17:22 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:17:22 +0100
Subject: [Tutor] Tkinter problems
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C516@mbtlipnt02.btlabs.bt.co.uk>

> class App:
> 
> root = Tk()

creates the window

> 
> app = App

but you missed the parens so did not create an instance of App!

Alan G



From alan.gauld@bt.com  Sun Apr  7 23:23:50 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:23:50 +0100
Subject: [Tutor] Conflicted
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C517@mbtlipnt02.btlabs.bt.co.uk>

> > > I am however not quite clear as to why the whole line is being
> > > replace rather than just the string requested.    

Neither am I.
Are you sure the code you posted is exactly what you are 
running?
You don't perchance have an else clause for the file output, 
like this:

if s.find('Spam'):
    ....do stuff...
else:
   file.write(s)

If so then the line containing spam won't get written....

Its all I can think of!

Alan G



From rob@jam.rr.com  Sun Apr  7 23:33:27 2002
From: rob@jam.rr.com (Rob Andrews)
Date: Sun, 07 Apr 2002 17:33:27 -0500
Subject: [Tutor] How many web sites....
References: <3CB07EE5.6040208@netscape.net>
Message-ID: <3CB0C937.2000001@jam.rr.com>

<violins />

Hopefully this will be my last sad little apology for the state of 
Useless Python. My health has been restored almost completely, but once 
the word circulated that I was out of bed, I was put immediately to work 
in the field for up to 13 hours per day. I'm told that I'll be put back 
on a vaguely regular schedule at the end of this week, since I've been 
threatening to "start bagging groceries" and get my life back. They also 
seem to want me to do some Python development once I'm not doing this 
"three cities each day" stuff.

My rough count of files awaiting upload to Useless Python since I 
started making an endless stream of excuses is 50 or so. So this next 
update should be a good one. I'd imagine I'll have a good sample of 
arse-kissing to the Python learning community on the front page for 
having to tolerate the delays.

The Vaults of Parnassus and the Python Cookbook are also available, to 
answer your question about other sites. And, of course, the ChalkBoard.

Rob

nova812 wrote:

<snip />
> I would like to share the code I write with other newbies.   I sent code 
> to Useless Python site, but it doesn't seem to published.  How many 
> other sites like Useless Python are there where I might be able to 
> share/exchange code.





From alan.gauld@bt.com  Sun Apr  7 23:31:34 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:31:34 +0100
Subject: [Tutor] Loop help
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C518@mbtlipnt02.btlabs.bt.co.uk>

> I'm trying to write a simple times-table testing program.
....
> How do I create the loop and what line do I place the code?

Try the looping chapter in my tutorial which shows both 
forms of loop in Python(for and while) in the context 
of multiplication tables oddly enough!

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Sun Apr  7 23:36:36 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:36:36 +0100
Subject: [Tutor] matrices
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C519@mbtlipnt02.btlabs.bt.co.uk>

If you make a compound list like this:

>>> l = ["1","1","1"]
>>> ll = ["2","2","2"]
>>> lll= ["3","3","3"]
>>> ll = [l,l,l]  # just overwrote the version above???
>>> lll = [ll,ll,]  # and again
>>> lll
[[['1', '1', '1'], ['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'],
['1', '1', '1'], ['1', '1', '1']]]

> are you making a matrix?

Not quite because you have ll containing three references 
to the same list l and lll has 2 references to the same ll.
Thus all your inner lists are references to the same oject!

To see the impact try changing l[1] to '5' and evaluating lll

Search the tutor archives and you should find some stuff 
on how to get round this safely.

Alan G.



From alan.gauld@bt.com  Sun Apr  7 23:42:34 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:42:34 +0100
Subject: [Tutor] Led buttons in python
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C51A@mbtlipnt02.btlabs.bt.co.uk>

> i am new to python
> how can i create LED buttons for displaying the status ?

Assuming you use Tkinter for the GUI then I suggest a Label 
object with an embedded image. Use any paint program to 
produce the colored LED graphics you need in GIF format 
and switch these in the image object that you embed in 
the Label.

Sounds more comnplex than it is. Grab my hangman game 
from Useless Python and see how I changed the Hangman 
states for an example.

If that didn't make any sense then shout and we'll 
start from closer to the beginning! :-)

Alan g.



From erikprice@mac.com  Sun Apr  7 23:55:21 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 7 Apr 2002 18:55:21 -0400
Subject: [Tutor] impact of OO
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C50D@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <89DAC414-4A7A-11D6-BF58-00039351FE6A@mac.com>

On Friday, April 5, 2002, at 05:19  AM, alan.gauld@bt.com wrote:

> There are other aspects to OOP too that we haven't
> touched on. The ease of extending existing code without
> changing it (and thus breaking existing code relying
> on the bit being extended) via inheritance. The way
> OOP eliminates long if/elif/else chains (or switch
> statements)via polymorphism (see the OOP page in my
> tutor for a discussion of polymorphism and inheritance)

Hm... I understand the idea of inheritance (that a class can extend 
another class, making a more-specific subclass).  But polymorphism, 
though I had seen the term bandied about, wasn't very clear to me until 
I read the relevant page in your tutor.  I'd like to make sure that I 
understand what it is, though.

It sounds as though it's really nothing more than a way of taking 
several different classes which might be used in similar (though 
different) ways, and giving them identical method names so that they can 
be accessed without having to write special-circumstance code that 
applies specifically to that particular class.  The example you provide 
on your web page seems perfect -- assign a name to all elements in an 
array ("shape"); use that name to access the contents of those elements; 
use a single method call (".calculateArea") to perform work on each 
object in the contents of those elements.  If you did not use this 
technique, then you would have to check for the type of object and do 
something like "if shape isanobject(triangle) then... else if shape 
isanobject(square) then...".

That's what it seems like -- so polymorphism is really just a term for 
abiding by a certain convention in naming class methods.  Is this a 
correct interpretation?

If so, then this leads directly to the concept of overriding, which I 
have also just recently learned of -- that a subclass of a parent class 
contains a method with the same name as a method in the parent class, so 
that the subclass's method supplants the parent class's method.  I'm 
sure that the reason why you would ever want to do this will come to me 
someday in the future when I have a chance to do some advanced 
programming with classes and inheritance, but for now it doesn't seem to 
be very worthwhile to me when you could just give the subclass its own, 
different, method name.  Unless you were trying to use a trick like 
polymorphism, in which case having the same name, so that you do not 
need to customize the code that calls the method, would be beneficial.


Erik




From alan.gauld@bt.com  Sun Apr  7 23:49:52 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 7 Apr 2002 23:49:52 +0100
Subject: [Tutor] impact of OO
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C51B@mbtlipnt02.btlabs.bt.co.uk>

> the behavior and how to organize the program.  I am making a 
> simple message encryption program and wanted to see if 
> implementing OOP practices would be difficult or not.  

We need more info.
A "simple message encryption" could be as simple as two 
functions - one to encrypt one to decrypt.

> It is not a small program at all.  By the time it will 
> be done it will be a couple thousand lines at least.  

So what are the features? Multiple algorithms? Multiple 
users with keyrings and digital signatures etc etc?

This approach is deprecated these days but works well 
for first OO projects. write down a single paragraph 
description of your programs function. Underline all 
nouns. They are likely objects. If generic or proper 
nouns they are probably classes otherwise they are 
instances and yuou need to decide what the class will be.


NOw look at the verbs. They are the methods. The subject 
of a verb is the object that has the method. Look for 
adjectives they will be attributes of the objects.

> could just learn about UML?

Try a search on cetus-links for all things OO including UML.

Also visit the Rational.com web site they have lots of stuff.

But UML is not needed for OO design unless its a biggie

Alan G.



From wolf_binary@hotmail.com  Sun Apr  7 23:53:07 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sun, 7 Apr 2002 17:53:07 -0500
Subject: [Tutor] declarations
Message-ID: <DAV26ZWxmUniLP0As3a000048d4@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_000D_01C1DE5D.12FD4EC0
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi all,

Can you declare variable types like in C++ in Python.
example:

int variableName =3D 0
float variableName =3D 0.0
char variableName =3D " "

Python must take care of these declarations for you, but I want to know =
if you can still make the declarations or not.

Thanks for any help on this,
Cameron Stoner

------=_NextPart_000_000D_01C1DE5D.12FD4EC0
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Can you declare variable types like in =
C++ in=20
Python.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>example:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>int variableName =3D 0</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>float variableName =3D 0.0</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>char variableName =3D " "</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Python must take care of these =
declarations for=20
you, but I want to know if you can still make the declarations or=20
not.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks for any help on =
this,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Cameron =
Stoner</FONT></DIV></BODY></HTML>

------=_NextPart_000_000D_01C1DE5D.12FD4EC0--



From shalehperry@attbi.com  Mon Apr  8 01:07:17 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 07 Apr 2002 16:07:17 -0800 (PDT)
Subject: [Tutor] declarations
In-Reply-To: <DAV26ZWxmUniLP0As3a000048d4@hotmail.com>
Message-ID: <XFMail.20020407160717.shalehperry@attbi.com>

On 07-Apr-2002 Cameron Stoner wrote:
> Hi all,
> 
> Can you declare variable types like in C++ in Python.
> example:
> 
> int variableName = 0
> float variableName = 0.0
> char variableName = " "
> 
> Python must take care of these declarations for you, but I want to know if
> you can still make the declarations or not.
> 

variableName = int(0)
variableName = float(0)
variableName = ""



From dyoo@hkn.eecs.berkeley.edu  Sun Apr  7 23:14:45 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 7 Apr 2002 15:14:45 -0700 (PDT)
Subject: [Tutor] Loop help (fwd)
In-Reply-To: <Pine.LNX.4.44.0204071449310.3756-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0204071501311.3756-100000@hkn.eecs.berkeley.edu>

Hi everyone,

Yikes, there was a bug in the code I had posted.  The first loop has x
going through the values [x, 11]:

> ###
> x = random_between(1,10)
> y = random_between(1,10)
> while x <= 10:
>     x = x + 1
[Some code cut]
> ###


But the for loop I wrote only goes through [1, 10]:

> ###
> for x in range(1, 11):
[Some code cut]
> ###


I wasn't paying as much attention to the boundary of the range as I should
have.  Here's a corrected loop:

###
for x in range(x+1, 12):
###

But there's something here that might be a little confusing, since 'x'
appears in two places in the for loop!  Even worse, this really has the
potential of tripping someone up who doesn't know that the range() is
computed only once, and not every time through the loop.


This is probably why we might prefer the while loop here, just to avoid
tricking people.  *grin* Hope this helps!




From virketis@fas.harvard.edu  Mon Apr  8 00:13:17 2002
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Sun, 7 Apr 2002 19:13:17 -0400
Subject: [Tutor] declarations
In-Reply-To: <DAV26ZWxmUniLP0As3a000048d4@hotmail.com>
Message-ID: <200204072313.g37NDul08400@smtp2.fas.harvard.edu>

<HTML><HEAD>
<BASEFONT FACE=3D"Arial" SIZE=3D"2" COLOR=3D"#000000">
</HEAD>
<BODY>
<div>Cameron,<br></div>
<div>&nbsp;</div>
<div>I am definitely not an expert on the deep issues of typing,=
 because I have not done much with static type languages, and in=
 Python potential pitfalls are usually notable only by their=
 absence ... :) But the only area where advance typing is useful=
 in my experience is when you want to take advantage of some=
 method unique to a given type. Example:<br></div>
<div>&nbsp;</div>
<div>list =3D []&nbsp; &nbsp;&nbsp;# I have to make sure Python=
 knows this will be a list<br></div>
<div>list.append(&quot;a&quot;) <br></div>
<div>&nbsp;</div>
<div>There is little real advantage of saying &quot;variable =3D=
 0&quot; at the top of the program, because it seems to me there=
 is nothing preventing you from assigning a string to this=
 &quot;variable&quot; twenty lines down in Python. Or maybe I am=
 just missing the point ... :)<br></div>
<div>&nbsp;</div>
<div>Cheers, <br></div>
<div>&nbsp;</div>
<div>Pijus<br></div>
<div>-- <br></div>
<div>All bad precedents began as justifiable measures. -- Gaius=
 Julius Caesar, quoted in &quot;The Conspiracy of Catiline&quot;,=
 by Sallust <br></div>
</body></html>




From alan.gauld@bt.com  Mon Apr  8 00:13:34 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 8 Apr 2002 00:13:34 +0100
Subject: [Tutor] impact of OO
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C51C@mbtlipnt02.btlabs.bt.co.uk>

> > tutor for a discussion of polymorphism and inheritance)
> I read the relevant page in your tutor.  I'd like to make sure that I 
> understand what it is, though.
> 
> It sounds as though it's really nothing more than a way of taking 
> several different classes which might be used in similar (though 
> different) ways, and giving them identical method names so 
> that they can be accessed without having to write 
> special-circumstance code that applies specifically to that 
> particular class.  

Absolutely correct. It is *the* cornerstone of OOD(as opposed 
to OOP!).

> object in the contents of those elements.  If you did not use this 
> technique, then you would have to check for the type of object and do 
> something like "if shape isanobject(triangle) then... else if shape 
> isanobject(square) then...".

Exactly so.
The point being that you can take a bunch of objects (shapes 
in this case) and treat them generically, relying on each 
object to 'know' how to respond to the messages. In practice 
we do that by coding each object class with its own version 
of the operation and leave the language to figure out which 
one is needed. (This is *much* harder to do in statically 
typed languagesc like Javaand C++ BTW)

> abiding by a certain convention in naming class methods.  

Just so, in fact this has its own name in OO circles its 
called defining the "common protocol" of the objects.

[ Getting more esoteric still its related to a bit of 
  Computer Science called the Liskoff Substitution Principle 
  which describes how to define abstract data types such 
  that they appear identical to the basic data type from 
  which they are descended. It is actually stricter than 
  normal OO inheritance/polymorphism rules. But if you are 
  interested there are some fairly heavy papers on the web 
  to read ]

> If so, then this leads directly to the concept of overriding, 

Yes although overridding in languages less flexible than 
Python can have wider ramifications and is slightly different 
to polymorphism. C++ users sometimes call overriding static 
polymorphism whereas polymorphism via inheritance is called 
dynamic polymorphism. In Smalltalk and Python etc we don't 
have to care or worry :-)

> that the subclass's method supplants the parent class's method.  

The commonest case is probably operator overriding which is
what we do inpython when we define our own __add__() method 
or __getitem__() etc. But as you say you can do it with any
method.

One thing you an't do in Python but can in some languages 
is override the same method name within the same class, 
like this:

class C:
   def F(self, anInt): ...
   def F(self, aString): C.F(self,int(aString))
   def F(self, aList):map(lambda n: C.F(self,int(n)),aList)
   def F(self, intA,intB,intC): C.F(self,intA+intB+intC)
 
This won't work min Python because its dynamically typed 
so they all look the same to the interpreter. But in C++ 
its how you have the same method name but can pass different 
typed arguments (and different numbers of arguments) to it.

We can do some of that using default params and the ret 
using dynamic typechecking:

 if type(p) == types.integer:
 elif type(p) == types.string:

etc

> subclass its own, different, method name.  

But then you can't put your new object type in a list and expect 
the old list handling code to use your new class. It would 
have to be modified to call the new method name - baaaaad...

HTH

Alan G



From gayers7@cogeco.ca  Mon Apr  8 01:15:07 2002
From: gayers7@cogeco.ca (Gordon W. Ayers)
Date: Sun, 07 Apr 2002 19:15:07 -0500
Subject: [Tutor] Help with dictionary
Message-ID: <3CB0E10B.17016CF6@cogeco.ca>

PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on
win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
>>> a =
{"server":"mpilgrim","database":"master","uid":"sa","pwd":"secret"}
>>> a
{'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server':
'mpilgrim'}
>>>

In the above session, why is the dictionary contents reversed when I
redisplay
the dictionary?
TIA
                                            Gord






From shalehperry@attbi.com  Mon Apr  8 01:50:00 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 07 Apr 2002 16:50:00 -0800 (PDT)
Subject: [Tutor] Help with dictionary
In-Reply-To: <3CB0E10B.17016CF6@cogeco.ca>
Message-ID: <XFMail.20020407165000.shalehperry@attbi.com>

On 07-Apr-2002 Gordon W. Ayers wrote:
> PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on
> win32.
> Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) -
> see 'Help/About PythonWin' for further copyright information.
>>>> a =
> {"server":"mpilgrim","database":"master","uid":"sa","pwd":"secret"}
>>>> a
> {'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server':
> 'mpilgrim'}
>>>>
> 
> In the above session, why is the dictionary contents reversed when I
> redisplay
> the dictionary?

dictionaries are fast because they store their contents in a special data
structure.  You can make *NO* guarantees about what the data looks like in a
dictionary.  If you change the dictionary everything may be in a completely
different order.

If you must keep the data in a certain order you should use a list.



From erikprice@mac.com  Mon Apr  8 01:13:35 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 7 Apr 2002 20:13:35 -0400
Subject: [Tutor] impact of OO
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C51C@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <7819B7CB-4A85-11D6-BF58-00039351FE6A@mac.com>

On Sunday, April 7, 2002, at 07:13  PM, alan.gauld@bt.com wrote:

> Exactly so.
> The point being that you can take a bunch of objects (shapes
> in this case) and treat them generically, relying on each
> object to 'know' how to respond to the messages. In practice
> we do that by coding each object class with its own version
> of the operation and leave the language to figure out which
> one is needed. (This is *much* harder to do in statically
> typed languagesc like Javaand C++ BTW)

Is it achieved in the way you describe toward the bottom of the email?  
(By using multiple methods of the same name, but each takes a different 
'type'?  Because if so, this only seems like more work, and not *much* 
harder, but then having never done anything like that, what do I know -- 
I hope to find out at some point!)

>> abiding by a certain convention in naming class methods.
>
> Just so, in fact this has its own name in OO circles its
> called defining the "common protocol" of the objects.
>
> [ Getting more esoteric still its related to a bit of
>   Computer Science called the Liskoff Substitution Principle
>   which describes how to define abstract data types such
>   that they appear identical to the basic data type from
>   which they are descended. It is actually stricter than
>   normal OO inheritance/polymorphism rules. But if you are
>   interested there are some fairly heavy papers on the web
>   to read ]

Interested, but already hundreds of pages behind in books to read -- and 
this sounds like something that can wait :)  I seem to do best when I 
take it one step at a time... it took me a few months to get to the 
point where I can ask these questions about OOP.

> One thing you an't do in Python but can in some languages
> is override the same method name within the same class,
> like this:
>
> class C:
>    def F(self, anInt): ...
>    def F(self, aString): C.F(self,int(aString))
>    def F(self, aList):map(lambda n: C.F(self,int(n)),aList)
>    def F(self, intA,intB,intC): C.F(self,intA+intB+intC)
>
> This won't work min Python because its dynamically typed
> so they all look the same to the interpreter. But in C++
> its how you have the same method name but can pass different
> typed arguments (and different numbers of arguments) to it.

The above is the snip that I am referring to at the beginning of this 
email -- is this the way that statically-typed languages get around 
being unable to flexibly pass different types to different methods?

>> subclass its own, different, method name.
>
> But then you can't put your new object type in a list and expect
> the old list handling code to use your new class. It would
> have to be modified to call the new method name - baaaaad...

I think I have lost focus of the thread and am not sure what I should 
watch out for here -- :(   .


I am trying to use Object Oriented techniques in my PHP code for my work 
project.  Most of the work revolves around accessing and inserting and 
updating data in a database -- it is a web-based application and that is 
what most web applications do.  I have defined a class "recipient", 
which contains methods which accept user input, check the input via 
regexes for dangerous input, and then if it passes the error check then 
the input is stored as an attribute of the object.  There could be any 
number of "Recipient" objects being processed at any given time, so it 
seems perfect.  But I will really have to think of a clever way to take 
advantage of polymorphism, so that I do not waste time writing extra 
code -- because in addition to "Recipients" there will be "Senders", 
etc, and the fields will not necessarily all be identical.  So, what 
should I do in this case, where I care about a Recipient's name, 
address, and phone number, but for Senders I have a name and a FedEx 
code number?  It doesn't seem that the two different classes line up as 
well as the "Shapes" example -- FedEx code doesn't line up well with 
Address or Phone number.  Is this not a case where I should try to use 
polymorphism?  The reason I have assumed that I could is because in the 
end, all data is going to be inserted into a database, which is really 
the same thing -- just different table/field names, depending.  But it 
seems that these details could be worked into the class, whereas the 
method names could be "generic-ized" -- I just can't think of a good 
scheme.



Erik




From dtanthony@earthlink.net  Mon Apr  8 02:55:15 2002
From: dtanthony@earthlink.net (Darren Anthony)
Date: Sun, 7 Apr 2002 18:55:15 -0700
Subject: [Tutor] More on loops
Message-ID: <MFEKJEJIGIIAACBIOFCMMEDMCAAA.dtanthony@earthlink.net>

I still don't have loops down.

To make things a little more understandable for me, 
I have a very basic program:


from livewires import*
num1 = random_between(1,10)
print num1
raw_input("Press return to exit: ")

This program generates one random number in the range of (1,10)

I would like the program to repeat itself at least 10 times each
time randomly getting another number and displaying the number.

This is where a loop comes in. If I could understand the loop 
concept on something basic like this I can expand to my times-
table loop.

Thank You






From shalehperry@attbi.com  Mon Apr  8 05:53:49 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun, 07 Apr 2002 20:53:49 -0800 (PDT)
Subject: [Tutor] More on loops
In-Reply-To: <MFEKJEJIGIIAACBIOFCMMEDMCAAA.dtanthony@earthlink.net>
Message-ID: <XFMail.20020407205349.shalehperry@attbi.com>

On 08-Apr-2002 Darren Anthony wrote:
> I still don't have loops down.
> 
> To make things a little more understandable for me, 
> I have a very basic program:
> 
> 
> from livewires import*
> num1 = random_between(1,10)
> print num1
> raw_input("Press return to exit: ")
> 
> This program generates one random number in the range of (1,10)
> 
> I would like the program to repeat itself at least 10 times each
> time randomly getting another number and displaying the number.
> 
> This is where a loop comes in. If I could understand the loop 
> concept on something basic like this I can expand to my times-
> table loop.
> 

ok, real simple loop:

for current in range(10):
    num = random_between(1,10)
    print num
    input = raw_input("Press 'q' to quit:")
    if input == 'q': break

a wrinkle, stop if the random number matches the current loop number

for current in range(10):
    num = randome_between(1,10)
    print num
    if num == current: break




From dman@dman.ddts.net  Mon Apr  8 06:13:57 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 8 Apr 2002 00:13:57 -0500
Subject: [Tutor] Checking for Control Characters
In-Reply-To: <3F64522E24@kserver.org>
References: <3F64522E24@kserver.org>
Message-ID: <20020408051357.GA18317@dman.ddts.net>

On Sat, Apr 06, 2002 at 08:57:16PM -0800, Sheila King wrote:
| I'm writing a cgi script right now, for changing passwords on an 
| account.
| 
| I have to check my input, and the account's username is not allowed 
| to have any of the following characters:
| 
| not_allowed = '!"#$%(),:;<>@[]|& '  #characters not allowed in 
| usernames
| 
| This is no problem, and I'm basically checking this with a piece of 
| code similar to the following:
| 
|     for char in username:
|         if char in not_allowed:
|             <do stuff for bad data entry>

I recommend using a regex instead of a linear search.  It will likely
be faster, if the number of taboo characters increases or if you check
multiple passwords with the same python process (persistent cgi?).

-D

-- 

The lot is cast into the lap,
but its every decision is from the Lord.
        Proverbs 16:33




From dman@dman.ddts.net  Mon Apr  8 06:15:55 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 8 Apr 2002 00:15:55 -0500
Subject: [Tutor] declarations
In-Reply-To: <DAV26ZWxmUniLP0As3a000048d4@hotmail.com>
References: <DAV26ZWxmUniLP0As3a000048d4@hotmail.com>
Message-ID: <20020408051555.GB18317@dman.ddts.net>

On Sun, Apr 07, 2002 at 05:53:07PM -0500, Cameron Stoner wrote:
| Hi all,
| 
| Can you declare variable types like in C++ in Python.
| example:
| 
| int variableName = 0
| float variableName = 0.0
| char variableName = " "
| 
| Python must take care of these declarations for you, but I want to
| know if you can still make the declarations or not.

Nah, everything is a PyObject* :-).  Python checks the type when you
actually use the object somewhere.  If the object supports the
operation you attempt, its type "matches" and there's no problem.
Kinda like C++ templates, but the check is runtime instead of
compile-time.

-D

-- 

Religion that God our Father accepts as pure and faultless is this: to
look after orphans and widows in their distress and to keep oneself from
being polluted by the world.
        James 1:27




From sheila@thinkspot.net  Mon Apr  8 06:13:41 2002
From: sheila@thinkspot.net (Sheila King)
Date: Sun, 7 Apr 2002 22:13:41 -0700
Subject: [Tutor] Checking for Control Characters
In-Reply-To: <20020408051357.GA18317@dman.ddts.net>
Message-ID: <574CF495701@kserver.org>

On Mon, 8 Apr 2002 00:13:57 -0500, dman wrote:
        <do stuff for bad data entry>
>
> I recommend using a regex instead of a linear search.  It will 
likely
> be faster, if the number of taboo characters increases or if you 
check
> multiple passwords with the same python process (persistent cgi?).

Actually, I did have a script I worked with a short while ago, where 
we had a version that used string methods, and then we changed it in 
the next version to use regex. And we found the regex to be slower.

In Python, regex is not as fast as in Perl (I believe). If you have 
some fairly comlicated searches to do, or a lot of searches, then it 
may be worth the overhead, and regex may be more efficient. But for 
something as simple as what I am doing, I believe the simple string 
methods will be quicker.

I am not doing persistent cgi, nor do I expect the number of taboo 
characters to increase, nor will I be checking multiple passwords. 
Otherwise, I would look into the regex, as you suggest.

Thanks,

-- 
Sheila King
http://www.thinkspot.net/sheila/






From dyoo@hkn.eecs.berkeley.edu  Mon Apr  8 08:43:55 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 8 Apr 2002 00:43:55 -0700 (PDT)
Subject: [Tutor] declarations
In-Reply-To: <20020408051555.GB18317@dman.ddts.net>
Message-ID: <Pine.LNX.4.44.0204080031150.27655-100000@hkn.eecs.berkeley.edu>

On Mon, 8 Apr 2002, dman wrote:

> On Sun, Apr 07, 2002 at 05:53:07PM -0500, Cameron Stoner wrote:
> | Hi all,
> |
> | Can you declare variable types like in C++ in Python.
> | example:
> |
> | int variableName = 0
> | float variableName = 0.0
> | char variableName = " "


Not quite --- what we think of as a "type" in Python is tied to the values
that we can compute or assign directly.  In contrast, a static language
like C++ ties the "type" to the variable name.


As a concrete example, the following in Python:

###### Python
>>> x = 4
>>> x + 2
6
>>> x = "four"
>>> x + "two"
'fourtwo'
######

shows that 'x' can refer to different "types" of things.


In contrast, C++ forces variable names to hold only specific variable
types.

////// C++
int x = 4.2;    // <-- Should probably produce a warning and truncate
                // x to 4.
//////


If it helps, think of Python variable names as big arrows pointing at
values like "42":


x --------------> "42"


C++ variables would look more like rigid boxes that contain things:

  x
+----+
| 42 |
+----+

and the rigidity comes into effect when we try stuffing in different
values like floats --- different types will either bend (if the compiler
like to be quiet), or will protest vehemently (if we turn on all
warnings).

To force values to bend into a variable's type in C++, we can use a
typecast... but if your teacher is a C++ guru, they'll yell at me for
saying that.  *grin*


Hope this helps!




From karthikg@aztec.soft.net  Mon Apr  8 09:06:45 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Mon, 8 Apr 2002 13:36:45 +0530
Subject: [Tutor] Problem with a simple External Method in ZOpe
In-Reply-To: <574CF495701@kserver.org>
Message-ID: <NEBBJNMDEKBIBCMCNMBDKEOPDIAA.karthikg@aztec.soft.net>

hi all,

we will be doing a prototype using zope @ our place.
Since it's not possible to open files/etc
writing simple python scripts in Zope, am trying to use
an external method.

I just wrote a simple script which opens a file and
writes some stuff to it and closes it.

In the end am even returning a string indicating success to the browser.
The string gets returned but the file does'nt get created when accessed thro
the browser. Am setting the strieng value inside the try..except block
wherein i open the file.
I don't get any exceptions either.

The program when run as a standalone script works fine but not thro' zope.
Any help?

thanks,
karthik



From dyoo@hkn.eecs.berkeley.edu  Mon Apr  8 10:39:34 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 8 Apr 2002 02:39:34 -0700 (PDT)
Subject: [Tutor] Problem with a simple External Method in ZOpe
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDKEOPDIAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.44.0204080230420.31437-100000@hkn.eecs.berkeley.edu>

> I just wrote a simple script which opens a file and writes some stuff to
> it and closes it.
>
> In the end am even returning a string indicating success to the browser.
> The string gets returned but the file does'nt get created when accessed
> thro the browser. Am setting the strieng value inside the try..except
> block wherein i open the file. I don't get any exceptions either.
>
> The program when run as a standalone script works fine but not thro'
> zope. Any help?


Hi Karthik,

Hmmm... You may want to check file permissions, just in case.  Zope runs
as the user who started it, so if the directory doesn't allow the Zope
user to write to it, you should see an IOError.

If you can show us the code for the external method, we can try it on our
end and see what's going on.  Also, how are you calling the external
method?


Finally, you might also want to send your question to the Zope user's
list:

    http://lists.zope.org/mailman/listinfo/zope

It's high volume, but it should be useful for you.


Best of wishes!




From karthikg@aztec.soft.net  Mon Apr  8 11:10:44 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Mon, 8 Apr 2002 15:40:44 +0530
Subject: [Tutor] Problem with a simple External Method in ZOpe
In-Reply-To: <Pine.LNX.4.44.0204080230420.31437-100000@hkn.eecs.berkeley.edu>
Message-ID: <NEBBJNMDEKBIBCMCNMBDAEPGDIAA.karthikg@aztec.soft.net>

> Hi Karthik,

> Hmmm... You may want to check file permissions, just in case.  Zope runs
> as the user who started it, so if the directory doesn't allow the Zope
> user to write to it, you should see an IOError.
> 
> If you can show us the code for the external method, we can try it on our
> end and see what's going on.  Also, how are you calling the external
> method?

> Finally, you might also want to send your question to the Zope user's
> list:

>     http://lists.zope.org/mailman/listinfo/zope

> It's high volume, but it should be useful for you.

hi Danny,
This is the simple code snippet:

def sayHello():
    retVal = "" 
    try:
        fp = open("test.txt","w")
	  fp.write("Zope scripts\n")
        fp.write("Python\n")
        fp.close()
        retVal = "success"
    except IOError,e:
        retVal = "failure"
    return "hello " + str(retVal)

if __name__ == '__main__':
    print sayHello()

tested my script using the "test" tab on the top of the external method 
			AND
accessed it through this URl as well.

http://localhost:8080//id_test/id_new/id_py_file/hello

I can see "hello success" getting printed.

regards
karthik.


	




From alan.gauld@bt.com  Mon Apr  8 11:27:31 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 8 Apr 2002 11:27:31 +0100
Subject: [Tutor] declarations
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C51F@mbtlipnt02.btlabs.bt.co.uk>

> Can you declare variable types like in C++ in Python.
> example:
>
> int variableName = 0
> float variableName = 0.0

No. Python variables are references to objects. The objects 
all have a type but the variables themselves are essentially 
typeless. Thus you can change the type of object a Python 
variable references:

foo = 7       # initially foo is an integer
foo = "baz"   # now foo is a string....

This is one of the ways that Python is much more flexible 
than C++. C++ tries to eliminate some errors at compile 
time by checking that the types passed to functions are 
consistent, Python performs this check at runtime so we 
need to use try/except handling to catch and handle the 
errors.. There are pros/cons with each approach.

Alan g.



From erikprice@mac.com  Mon Apr  8 12:32:11 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 8 Apr 2002 07:32:11 -0400
Subject: [Tutor] Checking for Control Characters
In-Reply-To: <574CF495701@kserver.org>
Message-ID: <44368F71-4AE4-11D6-94D4-00039351FE6A@mac.com>

On Monday, April 8, 2002, at 01:13  AM, Sheila King wrote:

> In Python, regex is not as fast as in Perl (I believe). If you have
> some fairly comlicated searches to do, or a lot of searches, then it
> may be worth the overhead, and regex may be more efficient. But for
> something as simple as what I am doing, I believe the simple string
> methods will be quicker.
>
> I am not doing persistent cgi, nor do I expect the number of taboo
> characters to increase, nor will I be checking multiple passwords.
> Otherwise, I would look into the regex, as you suggest.

I'm not sure about Python's regex implementation, but in PHP it is 
definitely not as fast as a simple string replacement -- when possible I 
use string replacement functions, but if the search is even remotely 
complicated then regexes are the only way.

One thing this has taught me is that it is worth learning how to write 
an efficient regex -- an interesting corollary to Perl (even though 
regexes predate Perl IIRC) is that there's more than one way to write 
some of them, and you can write one better than another.  Yet another 
thing which may not be immediately obvious is that different regex 
engines work in different ways, sometimes even with different syntax.  
"Mastering Regular Expressions" is the definitive guide to learn more 
about optimizing a regex as well as which form to use for which language 
(covers Perl, Python, Emacs, Tcl/Tk, Yacc, and a host of other tools).

Oh, one other thing -- if the flavor of regular expressions happens to 
be Perl-style (NFA), then you are more likely to be able to "optimize" 
it, whereas if the flavor happens to be "egrep"-style (DFA) then the 
regex is more likely already working as fast as it can -- this really 
depends on the situation, though, and isn't a hard and fast rule.  
Optimizing regexes can be esoteric but it may be worth a few hours 
studying them if your application will make heavy use of them.


Erik




From sentinel805@netscape.net  Mon Apr  8 14:57:33 2002
From: sentinel805@netscape.net (sentinel805)
Date: Mon, 08 Apr 2002 09:57:33 -0400
Subject: [Tutor] How many web sites....
References: <3CB07EE5.6040208@netscape.net> <DAV42xw00dSdVudU5N30000396c@hotmail.com>
Message-ID: <3CB1A1CD.1000500@netscape.net>

Im looking for mainly wxPython exmples and pygame examples.  Mainly 
wxPython for now.  (the examples that come with pyGame are pretty good. 
)   I would realy like to see an wxPython example that posistions 
several controlls on a frame using absolute positioning and sizing.  for 
example....

(this is not syntaticly correct)

frame = (size = (a,b))
aButton (size = (c,d), position=(e,f))
textBox =(size = (g,h), position=(i,j))
blah...
blah..

I'm not new to programming but I am new to python.  If you would like to 
see an example of my python skill level I recently source code to

http://www.decrem.com:8080/ChalkBoard

nova




wolf_binary@hotmail.com wrote:

>If you are looking for little demo programs of how things work, just ask me
>and I might be able to help.  I have been in your shoes and know enough now
>that I can hopefully help you in your predicament.  What kind of examples
>are you looking for?  Are you coming from a complete Non-Programmer
>position?  Help me to understand your circumstances.
>
>Cameron Stoner
>
>>I'm learning python and write a bunch of silly code for the purpose of
>>learning.  currently I focus my efforts to learning python as it relates
>>to wxPython and pygame.  Some of the simplest things I struggle with
>>because I sometimes have trouble finding source code to edit.
>>I would like to share the code I write with other newbies.   I sent code
>>to Useless Python site, but it doesn't seem to published.  How many
>>other sites like Useless Python are there where I might be able to
>>share/exchange code.
>>
>>
>>nova812
>>http://www.lowerstandard.com/python/uselesspython1.html
>>
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>





From alan.gauld@bt.com  Mon Apr  8 16:00:38 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 8 Apr 2002 16:00:38 +0100
Subject: [Tutor] More on loops
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C523@mbtlipnt02.btlabs.bt.co.uk>

> from livewires import*

for iteration in range(10):
   num1 = random_between(1,10)
   print num1
   raw_input("Press return to exit: ")

This basically says that we are going to set the value 
of iteration to each value of range(10) in turn. For 
each value assignment we will carry out the code thats 
indented.

Thus in the case above we execute your code 10 times.

If we don't know or can't calculate the number of 
iterations in advbance we can use a while loop, like so:

iterate = 'y'
while iterate in 'yY':
   num1 = random_between(1,10)
   print num1
   raw_input("Press return to exit: ")
   iterate = raw_input("Go again(Y/N)? ")


This time we initialise iterate to 'y'.
Then so long as iterate keeps a value of either 'y' or 'Y'
we exectute the indented block, ewhich now includes a 
prompt to set the value of iterate. The user can now 
repeat as oftwen as they like.

If thats still not clear then what exactly don't you 
understand about loops? Can you be specific about 
whats puzzling you?

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld




From alan.gauld@bt.com  Mon Apr  8 16:06:35 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 8 Apr 2002 16:06:35 +0100
Subject: [Tutor] Checking for Control Characters
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C524@mbtlipnt02.btlabs.bt.co.uk>

Dman sayeth:
> > I recommend using a regex instead of a linear search.  
> > It will likely be faster, 
Shiela replies:
> In Python, regex is not as fast as in Perl (I believe). 

This is irrelevant surely?
The question is whether Python re.search is faster than 
Python string.find or the 'in' operation. Dman suggests 
it is, I don't know. But comparisons with Perl are 
spurious surely? 

(FWIW They aren't much slower than Perl IME they just 
require a module import before use wheras Perl regex is 
builtin... - the old regex module of course is a different 
matter!)


Alan g.



From garber@centralcatholic.org  Mon Apr  8 16:59:04 2002
From: garber@centralcatholic.org (Robert Garber)
Date: Mon,  8 Apr 2002 11:59:04 -0400
Subject: [Tutor] What next?
Message-ID: <200204081159.AA441516450@centralcatholic.org>

Hello All,

  I have a question, where should I go next? I feel I have e good grip on the basics of Python ( at least for the stuff I need to know). I have access to Delphi and VB Basic. Should I try to learn these next. most of what I am working on will be windows  apps. As well as wanting them to be GUI. My project I want to work on is going to be an SQL type database. Any help guidence would be great.

Thank you,
Robert



From STavares@doc.state.ri.us  Mon Apr  8 13:08:25 2002
From: STavares@doc.state.ri.us (STavares@doc.state.ri.us)
Date: Mon, 8 Apr 2002 08:08:25 -0400
Subject: [Tutor] Simple HelloWorld cgi script
Message-ID: <BDA406CE9FA12E4FBC913071BE7733BF0C6F08@doc5.doc.state.ri.us>

Thank you.



-----Original Message-----
From: Sheila King [mailto:sheila@thinkspot.net]
Sent: Saturday, April 06, 2002 6:52 PM
To: Tavares, Scott; tutor@python.org
Subject: Re: [Tutor] Simple HelloWorld cgi script


On Thu, 4 Apr 2002 10:56:17 -0500, STavares@doc.state.ri.us wrote:
>=A0Could somene please me to a simple heloworld cgi script written in
>=A0python?
>
>
>
>=A0TIA
>
>=A0-ScottTavares-

I have one posted here:
http://www.thinkspot.net/sheila/computers/Python.html

Hope this helps,

--=20
Sheila King, sheila@thinkspot.net on 04/06/2002




From STavares@doc.state.ri.us  Mon Apr  8 13:08:51 2002
From: STavares@doc.state.ri.us (STavares@doc.state.ri.us)
Date: Mon, 8 Apr 2002 08:08:51 -0400
Subject: [Tutor] Simple HelloWorld cgi script
Message-ID: <BDA406CE9FA12E4FBC913071BE7733BF0C6F0A@doc5.doc.state.ri.us>

Thank you.

-----Original Message-----
From: Erik Price [mailto:erikprice@mac.com]
Sent: Sunday, April 07, 2002 5:41 PM
To: Tavares, Scott
Cc: tutor@python.org
Subject: Re: [Tutor] Simple HelloWorld cgi script



On Thursday, April 4, 2002, at 10:56  AM, <STavares@doc.state.ri.us>=20
wrote:

> Could somene please me to a simple heloworld cgi script written in=20
> python?
>

Not exactly what you asked for, but hopefully helpful:

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



Erik




From willi_santiago@groton.pfizer.com  Mon Apr  8 13:57:05 2002
From: willi_santiago@groton.pfizer.com (Pfizer Inc)
Date: Mon, 08 Apr 2002 08:57:05 -0400
Subject: [Tutor] ActiveX containers
Message-ID: <3CB193A1.775BC6D9@groton.pfizer.com>

Hi-

Is there an activeX container for Python?  I'd like to integrate an RTF
object into my Python application.

I'm using a wxFrame.

Thanks

Willi




From churmtom@hotmail.com  Mon Apr  8 16:57:30 2002
From: churmtom@hotmail.com (Tom Churm)
Date: Mon, 08 Apr 2002 17:57:30 +0200
Subject: [Tutor] why do i need to surround file names in inputs with quotes?
Message-ID: <LAW2-F44zQXTVQxabZu00018875@hotmail.com>

hi,

i've found & adapted the following simple python script that copies one text 
file to another text file.  the script works o.k., but only when i enter the 
name of the text file (both original, and the name of the new text file) 
surrounded by "double quotes".

i don't understand why this is.  and worse, i don't know how to change the 
script so that the filenames inserted by the user no longer require these 
double quotes.

this should be a real easy one, but, being a python newbie, i'd appreciate 
any suggestions.

copyText2Text.py follows:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
import os
thecwd = os.getcwd()
print ""
print "Python Text File Copier"
print ""
print "Current Working Directory: "+thecwd
a = input('Type name of file to copy surrounded by doublequotes')
b = input('Type name of new file surrounded by doublequotes')

#this was my attempt to add the double quotes automatically to the
#names given by the users' input - but it doesn't work!
#is this just a matter of knowing the proper escape characters??
#a = ""+a+""
#b = ""+b+""

fullfile1 = thecwd+"\\"+a

inp = open(fullfile1,"r")

fullfile2 = thecwd+"\\"+b

outp = open(fullfile2,"w")
for line in inp.readlines():
    outp.write(line)
print "Text file '"+fullfile1+"' copied successfully"
print "to"
print fullfile2
inp.close()
outp.close()

_________________________________________________________________
MSN Photos is the easiest way to share and print your photos: 
http://photos.msn.com/support/worldwide.aspx




From python-help@python.org  Mon Apr  8 17:02:06 2002
From: python-help@python.org (Alex Martelli)
Date: Mon, 8 Apr 2002 18:02:06 +0200
Subject: [Tutor] Re: [Python-Help] why do i need to surround file names in inputs with quotes?
In-Reply-To: <LAW2-F44zQXTVQxabZu00018875@hotmail.com>
References: <LAW2-F44zQXTVQxabZu00018875@hotmail.com>
Message-ID: <E16ubay-0002vI-00@mail.python.org>

On Monday 08 April 2002 05:57 pm, Tom Churm wrote:
> hi,
>
> i've found & adapted the following simple python script that copies one
> text file to another text file.  the script works o.k., but only when i
> enter the name of the text file (both original, and the name of the new
> text file) surrounded by "double quotes".

The built-in function called input wants the user to enter a Python
expression -- and the Python expression for a string needs quotes
(single or double ones, indifferently).

If you just want a string, not an expression, use raw_input instead, i.e.:

> a = input('Type name of file to copy surrounded by doublequotes')
> b = input('Type name of new file surrounded by doublequotes')

change to:

a = raw_input("Type name of file to copy: ")
b = raw_input("Type name of new file: ")


Note: please don't crosspost as widely as that -- just python-help
would be fine, thanks!


Alex



From alan.gauld@bt.com  Mon Apr  8 18:14:52 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 8 Apr 2002 18:14:52 +0100
Subject: [Tutor] What next?
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C52D@mbtlipnt02.btlabs.bt.co.uk>

>   I have a question, where should I go next? I feel I have e 
> good grip on the basics of Python ( at least for the stuff I 
> need to know). I have access to Delphi and VB Basic. 

Interesting question and there are good reasons to go either way.

Delphi: it has a similar object model to Python so the OOP 
stuff should be more similar than in VB. BUT its strictly 
typed which will be a bit oof a culture shock. OTOH Its 
a great way to see both ends of the spectrum of programming.
Delphi is what I use for all my 'serious' Windoze programming.
The Delphi GUI builder environment is much more open than 
VB too so you can map it back to things like Tkinter more 
easily than VB.

VB: A Dynamic language like Python but with a very different 
syntax and a fairly primitive underlying model. The whole 
way objects etc work is completely different. But it does 
offer lots of wizards which make cOM access very easy for 
example.

I'd personally say the biggest pain but also the biggest 
gain will be in the Delphi area. You will learn a lot more 
about programming and it'll be a useful bridge to say 
Java or C++.

It depends on whether you just want a productive windoze 
native environment fast(VB) or whether you want to learn 
more about good programming practice (as well as 
getting a good GUI building tool)

Both make SQL access easy but they each have their own 
very different ways of achieving that.


Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From jeff@ccvcorp.com  Mon Apr  8 19:20:30 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 08 Apr 2002 11:20:30 -0700
Subject: [Tutor] How many web sites....
References: <E16uZhg-0003ZH-00@mail.python.org>
Message-ID: <3CB1DF6E.745B2BF4@ccvcorp.com>

> sentinel805 <sentinel805@netscape.net> wrote:
>

> Im looking for mainly wxPython exmples and pygame examples.  Mainly
> wxPython for now.  (the examples that come with pyGame are pretty good.
> )   I would realy like to see an wxPython example that posistions
> several controlls on a frame using absolute positioning and sizing.  for
> example....

If you want wxPython examples, you can get a *lot* of information from the demo
program that ships with wxPython -- it's designed to show not only what you can
do with the package, but *how* to do it, as well.  I'd also suggest joining the
wxPython-users mailing list (see wxpython.org to join), and you can look at the
wxPyWiki while you're there.

Finding wxPython examples that use absolute positioning might be difficult,
though -- absolute positioning is rarely used.  It's typically much better to
use sizers, which will automatically resize and reposition your controls for
you.  It's almost impossible to create an absolute positioning scheme that will
work well on more than one platform, but sizers will automatically adjust
everything as required for each platform.  However, if you feel that you *must*
use absolute sizing, it's done something like this:

button = wxButton(parent, wxNewId(), "Press Me", \
                   pos=wxPosition(50,100), size=wxSize(200,100))

(from memory, and untested -- check the wxWindows/wxPython docs for exact
details)

Jeff Shannon
Technician/Programmer
Credit International





From jeff@ccvcorp.com  Mon Apr  8 19:32:35 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 08 Apr 2002 11:32:35 -0700
Subject: [Tutor] Working with files, Truckers log
References: <4.3.2.7.2.20020406192644.00b9f8e0@pop3.norton.antivirus>
Message-ID: <3CB1E242.B2E86B8@ccvcorp.com>

Alexandre Ratti wrote:

> Hello Jeff,
>
>
> >Why on earth should eval() be used for this, when there's perfectly good
> >conversion functions??
> [...]

> >There really is almost never a reason to use eval().  Really.  :)
>
> How about this kind of use:
>
> def factoryFromName(className, *args):
>      "className is a string."
>      return eval(className)(*args)
>
> Admittedly, I can't think up any reason to use this code in a real app
> right now :-)

Well, in this sort of case, I'd probably pass in a class object, instead of a
classname string.  But, if I *had* to get the object from a name string, I'd
probably use getattr() on the module -- I'd expect the class to be defined in some
other module, and just do this:

def FactoryFromName(module, classname, *args):
    return getattr(module, classname)(*args)

Or, if the class was defined in the current module:

def FactoryFromName(classname, *args):
    import ThisModule
    return getattr(ThisModule, classname)(*args)

(Yes, it *is* legal to import the current module from within a function like this.
You can't do it at the top level -- if this import code executes while the module
is first being imported, you'll end up with an endless recursion.  But once the
module is imported elsewhere, you can execute this function to get access to the
current module's namespace.)

Jeff Shannon
Technician/Programmer
Credit International






From dmanxiii@yahoo.com  Mon Apr  8 22:45:12 2002
From: dmanxiii@yahoo.com (Mr. Derek L. Hoffmeister)
Date: Mon, 8 Apr 2002 14:45:12 -0700 (PDT)
Subject: [Tutor] Labels??? and Entry fields
In-Reply-To: <E16ubZw-0002p4-00@mail.python.org>
Message-ID: <20020408214512.40391.qmail@web20910.mail.yahoo.com>

--0-773546806-1018302312=:40173
Content-Type: text/plain; charset=us-ascii


Hi People,

Does Python have labels as in basic(or the form of basic I have on my TI-86 graphing calculator) and If it does how would someone use it?  And I have one other question.  In Tkinter I can get an entry field up, but I can't do anything with the text that is entered...how would one get to use that text(check it against another string for equality let's say)

Thanks

Derek Hoffmeister



---------------------------------
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
--0-773546806-1018302312=:40173
Content-Type: text/html; charset=us-ascii

<P>Hi People,</P>
<P>Does Python have labels as in basic(or the form of basic I have on my TI-86 graphing calculator) and If it does how would someone use it?&nbsp; And I have one other question.&nbsp; In Tkinter I can get an entry field up, but I can't do anything with the text that is entered...how would one get to use that text(check it against another string for equality let's say)</P>
<P>Thanks</P>
<P>Derek Hoffmeister</P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
<a href="$rd_url/welcome/?http://taxes.yahoo.com/">Yahoo! Tax Center</a> - online filing with TurboTax
--0-773546806-1018302312=:40173--



From me@mikerobin.com  Mon Apr  8 19:14:13 2002
From: me@mikerobin.com (Michael Robin)
Date: Mon, 8 Apr 2002 11:14:13 -0700
Subject: [Tutor] RE: why do i need to surround file names in inputs with quotes?
In-Reply-To: <LAW2-F44zQXTVQxabZu00018875@hotmail.com>
Message-ID: <DHEEKAFNPOKNEBEBLCIAKEDACJAA.me@mikerobin.com>

Input evaluates the input string that the user
enters, which you don't want here. Try using
raw_input.
mike
-------------------
>From the docs:

input([prompt])
Equivalent to eval(raw_input(prompt)). Warning: This function is not safe
from user errors! It expects a valid Python expression as input; if the
input is not syntactically valid, a SyntaxError will be raised. Other
exceptions may be raised if there is an error during evaluation. (On the
other hand, sometimes this is exactly what you need when writing a quick
script for expert use.)
If the readline module was loaded, then input() will use it to provide
elaborate line editing and history features.

Consider using the raw_input() function for general input from users.


-----Original Message-----
From: activepython-admin@listserv.ActiveState.com
[mailto:activepython-admin@listserv.ActiveState.com]On Behalf Of Tom
Churm
Sent: Monday, April 08, 2002 8:58 AM
To: python-help@python.org; activepython@listserv.ActiveState.com;
tutor@python.org
Subject: why do i need to surround file names in inputs with quotes?


hi,

i've found & adapted the following simple python script that copies one text
file to another text file.  the script works o.k., but only when i enter the
name of the text file (both original, and the name of the new text file)
surrounded by "double quotes".

i don't understand why this is.  and worse, i don't know how to change the
script so that the filenames inserted by the user no longer require these
double quotes.

this should be a real easy one, but, being a python newbie, i'd appreciate
any suggestions.

copyText2Text.py follows:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
import os
thecwd = os.getcwd()
print ""
print "Python Text File Copier"
print ""
print "Current Working Directory: "+thecwd
a = input('Type name of file to copy surrounded by doublequotes')
b = input('Type name of new file surrounded by doublequotes')

#this was my attempt to add the double quotes automatically to the
#names given by the users' input - but it doesn't work!
#is this just a matter of knowing the proper escape characters??
#a = ""+a+""
#b = ""+b+""

fullfile1 = thecwd+"\\"+a

inp = open(fullfile1,"r")

fullfile2 = thecwd+"\\"+b

outp = open(fullfile2,"w")
for line in inp.readlines():
    outp.write(line)
print "Text file '"+fullfile1+"' copied successfully"
print "to"
print fullfile2
inp.close()
outp.close()

_________________________________________________________________
MSN Photos is the easiest way to share and print your photos:
http://photos.msn.com/support/worldwide.aspx

_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs




From jyoungqu@journal-courier.com  Mon Apr  8 18:27:32 2002
From: jyoungqu@journal-courier.com (Joseph Youngquist)
Date: Mon, 8 Apr 2002 13:27:32 -0400
Subject: [Tutor] RE: why do i need to surround file names in inputs with quotes?
In-Reply-To: <LAW2-F44zQXTVQxabZu00018875@hotmail.com>
Message-ID: <000301c1df22$ab5d8700$9b1a010a@lafonline02>

I'm a newbi too, but I think I read that input is for integers and rawinput
is for strings...might help

Joe Youngquist

-----Original Message-----
From: activepython-admin@listserv.ActiveState.com
[mailto:activepython-admin@listserv.ActiveState.com]On Behalf Of Tom
Churm
Sent: Monday, April 08, 2002 10:57 AM
To: python-help@python.org; activepython@listserv.ActiveState.com;
tutor@python.org
Subject: why do i need to surround file names in inputs with quotes?


hi,

i've found & adapted the following simple python script that copies one text
file to another text file.  the script works o.k., but only when i enter the
name of the text file (both original, and the name of the new text file)
surrounded by "double quotes".

i don't understand why this is.  and worse, i don't know how to change the
script so that the filenames inserted by the user no longer require these
double quotes.

this should be a real easy one, but, being a python newbie, i'd appreciate
any suggestions.

copyText2Text.py follows:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
import os
thecwd = os.getcwd()
print ""
print "Python Text File Copier"
print ""
print "Current Working Directory: "+thecwd
a = input('Type name of file to copy surrounded by doublequotes')
b = input('Type name of new file surrounded by doublequotes')

#this was my attempt to add the double quotes automatically to the
#names given by the users' input - but it doesn't work!
#is this just a matter of knowing the proper escape characters??
#a = ""+a+""
#b = ""+b+""

fullfile1 = thecwd+"\\"+a

inp = open(fullfile1,"r")

fullfile2 = thecwd+"\\"+b

outp = open(fullfile2,"w")
for line in inp.readlines():
    outp.write(line)
print "Text file '"+fullfile1+"' copied successfully"
print "to"
print fullfile2
inp.close()
outp.close()

_________________________________________________________________
MSN Photos is the easiest way to share and print your photos:
http://photos.msn.com/support/worldwide.aspx

_______________________________________________
ActivePython mailing list
ActivePython@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs




From erikprice@mac.com  Tue Apr  9 03:32:24 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 8 Apr 2002 22:32:24 -0400
Subject: [Tutor] impact of OO
In-Reply-To: <4.2.0.58.20020404204915.00afe9b0@pop3.norton.antivirus>
Message-ID: <071253B8-4B62-11D6-9D76-00039351FE6A@mac.com>

Thanks very much to Kirby, Alan, and everyone else on the list who 
contributed their thoughts and experiences to this thread.  I found it 
informative and reassuring, although also eye-opening -- there is a lot 
ahead to learn.  (Both a comfortable and a hungry thought.)

On Friday, April 5, 2002, at 12:30  AM, Kirby Urner wrote:

> The promise of OO was that it would promote reusability,
> and I think it's helped do this.  Programmers now think
> naturally along the lines made explicit by JavaBeans (you
> have to hand it to Sun, they were very clever with the
> whole coffee terminology, which has mnemonic and metaphoric
> power -- a case study in good meme design (I'm sure some
> find it all too sickly-cute and don't share my appreciative
> attitude)).  More programmers now think in terms of writing
> these nifty little utilities and packaging them as objects
> designed to be accessed using dot notation in the context
> of other peoples' programs.

I like the name "Java" myself.  I also like "Python", though I'm not the 
craziest fan of the films (does that brand me a traitor in these 
parts?).  What is a JavaBean?  I have recently become familiar with web 
services, that ambiguous name for standalone web applications that use 
XML-RPC or SOAP to be cross-platform compatible.  It's a very neat idea, 
and an interest in web technologies is what pushed me in the direction 
of programming.  But while I have encountered attempts to define a 
JavaBean on a couple of occasions, it seems that most of the definitions 
draw upon a priori knowledge of Java, which I don't have.  For that 
matter, I don't really understand what is the difference between Java 2 
and Java 2 Enterprise Edition.  Would someone please elaborate on that 
if possible?

> Step 1 of learning these languages is to get comfortable with
> basic syntax, but a lot of what comes next is growing familiar
> with this large class hierarchy.  Now other languages, like
> C/C++, offer huge, well-developed libraries.  But to embed
> so much functionality into a class hierarchy provides more
> of a systematic ordering scheme, a taxonomy, a structure, a
> way of thinking about HTML parsers as sub-classes of SGML
> parsers, or CGI-capable web servers as subclasses of more
> primitive servers.

If I could pause for just one moment, and make sure that I'm following 
you in this.  Are you contrasting a huge, well-developed library with a 
class hierarchy, or are you suggesting that they are similar?  My 
interpretation is that a huge, well-developed library is one way in 
which a language is supported, which depends on the user having access 
to and knowledge of modules or functions or code so that they can write 
their software to take advantage of these pre-written code entities.  (I 
suppose this is the luxury of a compiled language, that you do not need 
to provide modules and libraries and ensure that your user has access to 
the interpreter to be able to run the code.)  And that as opposed to a 
bundle of code to use, a hierarcy of objects (like JavaScript's 
"Document Object Model") helps the programmer to intuitively know what 
can be done with various branches of the code because it is similar to 
other branches of the code.  I suppose that this is another instance 
where polymorphism is useful, so that you can use a branch of code 
quickly and similarly to another branch of code that you are already 
familiar with.

But I have made an assumption about what you meant, and I could be wrong.

> Python's standard library is far less tree-like than Java's
> internal hierarchy, but it's module syntax follows the grain
> of OO, i.e. modules are a lot like classes, as we were
> discussing a bit earlier.  You import them, and then access
> them using the very same dot notation, to get at their
> variables and methods.

How is Python's organization less tree-like than Java's?  Is this 
related to the phrase "in Java everything is a class" that was mentioned 
last week (I think Alan suggested this)?

> In sum, OO has been, on balance, a very positive development
> and influence in the programming world.  But as with any
> such positive, some people go overboard and hype it to the
> hilt, which overtaxes the tolerance of others, who feel
> compelled to supply a skeptical dissenting voice.
>
> These are all ancient patterns, in no way confined to
> programming world.  My advice is to not get sucked in to
> some partisan camp which wastes a lot of energy fighting
> on either side in this debate, as OO is here to stay, and
> not-OO is also here to stay.

It seems to be a clearer way of expressing... well, objects!  I'm trying 
to take advantage of the similarity between an object and a database row 
in my code at work, but it's still very new to me.

Erik




From Birdhouse3387@aol.com  Tue Apr  9 03:21:33 2002
From: Birdhouse3387@aol.com (Birdhouse3387@aol.com)
Date: Mon, 8 Apr 2002 22:21:33 EDT
Subject: [Tutor] Hey rookie here
Message-ID: <110.1042f15b.29e3aa2d@aol.com>

--part1_110.1042f15b.29e3aa2d_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

Hey My name's nick i'm a real rookie @ this but i can learn real fast and I 
HATE the system. If some one can help me learn the basics and maybe some 
advanced stuff i could be a pro(maybe). (If anyone gets this that lives in 
asheville NC write me back ASAP ) 
                                        Thanks

--part1_110.1042f15b.29e3aa2d_boundary
Content-Type: text/html; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

<HTML><FONT FACE=arial,helvetica><BODY BGCOLOR="#000000"><FONT  SIZE=5 FAMILY="SERIF" FACE="Rockwell Condensed" LANG="0"><B>Hey My name's nick i'm a real rookie @ this but i can learn real fast and I HATE the system. If some one can help me learn the basics and maybe some advanced stuff i could be a pro(maybe). (If anyone gets this that lives in asheville NC write me back ASAP ) 
<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Thanks</B></FONT></HTML>

--part1_110.1042f15b.29e3aa2d_boundary--



From linuxconsult@yahoo.com.br  Tue Apr  9 08:09:58 2002
From: linuxconsult@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Tue, 9 Apr 2002 04:09:58 -0300
Subject: [Tutor] Problems understanding semantics of readlines()
Message-ID: <20020409070957.GA3944@ime.usp.br>

	Dear people,

	I'm a newbie in Python and I'm trying to read the Guido's
	tutorial.

	So far, things have been ok and I'm quite excited with
	learning Python, but now, at chapter 7 (on input/output), I
	have a problem. I'm trying to understand the exact semantics
	of readlines() (note the plural), but the description doesn't
	seem to match what the method does.

	More specifically, I am interested to know what readlines()
	should do when called with an argument. Let's suppose that f
	is an open file object. I thought that given an integer n,
	f.readlines(n) would return a list of lines (from the current
	point in the file f) with total length <= n and which were all
	terminated with "\n".

	following interactive session shows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
dumont:/home/rbrito> python2.2
Python 2.2.1c1 (#1, Mar 15 2002, 08:13:47) 
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("/tmp/file.txt", "w+")
>>> f.write("a"*128*1024+"\n"+"b"*10)
>>> f.seek(0)
>>> f.readlines(15)
['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(...)
aaaa\n', 'bbbbbbbbbb']
>>> f.close()
>>> 
dumont:/home/rbrito>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	I would expect it to show me just a list with zero or one
	element (BTW, which one is correct? The documentation is a bit
	confusing here, and I can interpret it both ways), but not two
	elements.

	The strange thing here is that Jython behaves differently than
	Cpython with the exact steps above: Jython 2.1 w/ j2sdk 1.3.1
	just gives me a list with one element (the first line, with
	a's), as I would expect.

	So, I'm confused here. Can anybody help this poor newbie?


	Thanks in advance for any help, Roger...

P.S.: I'm sorry if this is a FAQ.



From paulsid@shaw.ca  Tue Apr  9 08:27:12 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Tue, 09 Apr 2002 01:27:12 -0600
Subject: Java (was Re: [Tutor] impact of OO)
References: <071253B8-4B62-11D6-9D76-00039351FE6A@mac.com>
Message-ID: <3CB297D0.F2BBCDBC@shaw.ca>

Erik Price wrote:

> I like the name "Java" myself.  I also like "Python", though I'm not the
> craziest fan of the films (does that brand me a traitor in these
> parts?).  

I never liked the name "Java" actually but I guess it's not too bad. 
Also, no other language name (even Python) has given birth to so many
other names and ideas that revolve around its theme.  :-)

Anyhow, here are some quick answers since I'm not ready for bed yet.  I
have limited experience with Java, so you've been warned.

> What is a JavaBean?  

It's just a custom GUI component.  I think to be considered an actual
JavaBean it has to meet some kind of standard, but basically it's the
same thing.

> For that
> matter, I don't really understand what is the difference between Java 2
> and Java 2 Enterprise Edition.  Would someone please elaborate on that
> if possible?

Not really sure.  J2EE might support CORBA and a bunch of other
enterprise stuff, but that's just a guess.  Unless you're doing
something bleeding edge, Java 2 or even 1.2 or 1.3 should be fine.

> How is Python's organization less tree-like than Java's?  Is this
> related to the phrase "in Java everything is a class" that was mentioned
> last week (I think Alan suggested this)?

Yes, in Java everything except for the basic datatypes (int, float,
bool, etc.) descends from a class simply called "Object".  Also you can
ask Java to provide Object-based ints, etc. if you need them, e.g. to
store in a container (which store Object types of course).  So the
"family tree" of every class traces back to the Object type at some
point.

I suppose in many ways it's not really any different from Python, since
if you always used Object types for function parameters & returns you'd
be able to pass anything[1].  In Java it's just the whole thing is
highly formalized.

Java is generally a nice language, certainly nicer than C++.  Learn it
if you can, if nothing else just because it might be useful to know at
times.  Also it opens up Jython to you which certainly could be very
useful.  (One of my personal projects for the summer will be to do some
work with Jython just to see what it can do while brushing up my Java
knowledge at the same time.)

[1] Of course you would almost never want to do this because to operate
on an object of a specific type you always have to cast it.  The extent
that casting is needed in Java (at least in 1.x, I heard they were
slated to do something about it though) is one of those things you have
to just shake your head at and accept; once you can do this the language
as I said isn't all that bad.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From paulsid@shaw.ca  Tue Apr  9 09:08:44 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Tue, 09 Apr 2002 02:08:44 -0600
Subject: [Tutor] Problems understanding semantics of readlines()
References: <20020409070957.GA3944@ime.usp.br>
Message-ID: <3CB2A18C.CDE0B364@shaw.ca>

Rog=E9rio Brito wrote:

>         More specifically, I am interested to know what readlines()
>         should do when called with an argument. Let's suppose that =
f
>         is an open file object. I thought that given an integer n,
>         f.readlines(n) would return a list of lines (from the curre=
nt
>       point in the file f) with total length <=3D n and which were =
all
>         terminated with "\n".

No, the parameter is called sizeHINT (my emphasis) because it's just =
a
suggestion.  Results should be expected to vary by platform and
implementation, as you already discovered.  From the library referenc=
e:

> If given an optional parameter sizehint, it reads that many bytes=
=20
> from the file and enough more to complete a line, and returns the=
=20
> lines from that.=20

Thus you're guaranteed to get the entire first line no matter what si=
ze
you ask for.  As for the second line, I suspect (though this is a bit=
 of
a guess) that there was enough room left over in the internal buffer =
to
grab the entire second line because the first line was 128K+1 bytes a=
nd
the buffer was probably a multiple of 512 or 1K bytes.  So you got th=
e
second line for free, whether you wanted it or not.

I think readlines(sizehint) has been semi-deprecated by xreadlines().=
=20
(Perhaps the tutorial should be updated?)  You can use f.xreadlines()=
 to
iterate over a file on a guaranteed per-line basis with the same
efficient memory usage.  Actually, according to the docs, xreadlines(=
)
uses readlines(sizehint) to do its thing, but it's cleaner and more
predictable.

One last thing to note is that the second line won't have a \n at the
end because one was not written to the end of the file.  readline() &
readlines() won't add one if one doesn't exist.

Hope that helps.  BTW I got the same results you did using WinME &
Python 2.1.

--=20
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D
Paul Sidorsky                                          Calgary, Canad=
a
paulsid@shaw.ca                        http://members.shaw.ca/paulsid=
/




From alex@gabuzomeu.net  Tue Apr  9 10:12:49 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Tue, 09 Apr 2002 11:12:49 +0200
Subject: [Tutor] Working with files, Truckers log
In-Reply-To: <E16umVC-0002vD-00@mail.python.org>
Message-ID: <4.3.2.7.2.20020409104013.00b7fbc0@pop3.norton.antivirus>

Hello,


At 23:40 08/04/2002 -0400, you wrote:
>Date: Mon, 08 Apr 2002 11:32:35 -0700
>From: "Jeff Shannon" <jeff@ccvcorp.com>
>Subject: Re: [Tutor] Working with files, Truckers log

> > How about this kind of use:
> >
> > def factoryFromName(className, *args):
> >      "className is a string."
> >      return eval(className)(*args)

>Well, in this sort of case, I'd probably pass in a class object, instead of a
>classname string.  But, if I *had* to get the object from a name string, I'd
>probably use getattr() on the module -- I'd expect the class to be defined 
>in some other module, and just do this:
>
>def FactoryFromName(module, classname, *args):
>     return getattr(module, classname)(*args)

OK, thanks.

>Or, if the class was defined in the current module:
>
>def FactoryFromName(classname, *args):
>     import ThisModule
>     return getattr(ThisModule, classname)(*args)
>
>(Yes, it *is* legal to import the current module from within a function 
>like this. You can't do it at the top level -- if this import code 
>executes while the module is first being imported, you'll end up with an 
>endless recursion. But once the module is imported elsewhere, you can 
>execute this function to get access to the current module's namespace.)

That's interesting. Now, "ThisModule" is the module name. How can we avoid 
hard-coding it in the function? Is is possible to retrieve the name of the 
module the function object is defined in?

Also, how can you refer to "me" in a function? For a class instance, it's 
self. Is there a similar solution for a function object?


Cheers.

Alexandre




From alan.gauld@bt.com  Tue Apr  9 11:27:13 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 9 Apr 2002 11:27:13 +0100
Subject: [Tutor] Labels??? and Entry fields
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C532@mbtlipnt02.btlabs.bt.co.uk>

> Does Python have labels as in basic

The main purpose of labels is to allow GOTO constructs. 
As GOTO is now considered bad programming practice 
(too easily abused to produce unmaintainable code) 
Python doesn't have them. What were you thinking of 
using them for? There is nearly always a nicer 
Pythonic alternative!

> I can get an entry field up, but I can't do anything 
> with the text that is entered...

There are two ways to access the text.
1) The direct way using the getText() method of the entry widget

str = ent.get()

and set it with

ent.insert('0.1',str)  # NB check the syntax!

OR

2) Creating an StrVar variable and associating that with 
   the entry(via the textvariable attribute).
   Using this approach the variable will be automatically 
   populated with the entry value everytime its changed 
   and similarly you can set the variable and the value 
   will appear in the text box. This piece of 'magic' 
   is performed at the Tcl/Tk level so you have to use 
   a StrVar object not a normal Python variable.

Alan G.



From alan.gauld@bt.com  Tue Apr  9 12:04:47 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue, 9 Apr 2002 12:04:47 +0100
Subject: [Tutor] impact of OO
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C533@mbtlipnt02.btlabs.bt.co.uk>

> informative and reassuring, although also eye-opening -- 
> there is a lot ahead to learn.  

In programming there always is its why I'm still here.
In OOP its even more so because the rules and definitions 
are still not fully drawn up and agreed.

> What is a JavaBean?  

A component in Java terminology.
Its an object which has methods for getting and setting 
its attributes which follow a naming convention 
(getXXXX, setXXXX etc). The advantage of this is that 
tools can query the innards and provide some dynamic
capabilirties at design time(live database tables in 
a GUI desiner for example).

Its a horrible hack like most things in Java and 
Python's 'properties' specifiers(borrowed from Delphi!) 
are much nicer IMHO.

> between Java 2 and Java 2 Enterprise Edition.  

If anyone knowsw better please jump in, as y'all may have 
figured out I'm a fairly reluctant Java user!
Java 2 is just a development of the basic Java platform 
with some new classes and frameworks(GUI bits and security 
stuff etc) J2EE is a different beast entirely and is all 
about producing large scale (Enterprise) computing 
platform with middleware, systems management, persistency, 
transactional support etc. Its kind of Suns alternative 
to Microsofts .NET/COM+ architectures. Its one of the few 
bits of Java that I don't hate completely, although it 
is pretty complex - most powerful things are!

I'm sure somebody else can give a better story than that!

> Are you contrasting a huge, well-developed library with a 
> class hierarchy, or are you suggesting that they are similar?  

In Java and many other OO lanbguages they are the same. The 
whole library is implemented as an enormous class hierarchy 
starting with a top level 'Object' class.(Delphi/Kyliix 
and Smalltalk both take this approach.)

> suppose this is the luxury of a compiled language, that you 
> do not need to provide modules and libraries and ensure 
> that your user has access to the interpreter to be able 
> to run the code.)  

Correct, BUT you still need those modules and libraries 
to *build* the code so from the languagfe provider/programmer 
view it dsoesn't make much difference, only the end user 
sees the gain....

> bundle of code to use, a hierarcy of objects (like JavaScript's 
> "Document Object Model") helps the programmer to intuitively 
> know what can be done with various branches of the code 
> because it is similar to other branches of the code.  

That's the theory. How well it works depends on the skill 
of the heirarchy designer. I only need to mention MFC v1 
to have the grey beareded ones amongst us cringing from 
the memory! Comparing MFC with the new .NET CLR GUI 
classes shows the difference a good heirarcxhy design 
can make.

One of the disadvantages of C+++ vv Java is that C++ libraries 
are much les well integrated, Java has one enormous and 
mostly consistent heirarchy, C++ has traditionally used lots 
of mini heirarchies from lots of different designers. The new 
Standard Library partially addresses this but its scope is 
far more limited than Java's library of classes.

> where polymorphism is useful, so that you can use a branch of code 
> quickly and similarly to another branch of code that you are already 
> familiar with.

Absolutely - see Pythons parser/formatter modules for 
examples of how polymorphism is used in that way in a library.

> But I have made an assumption about what you meant, and I 
> could be wrong.

I don't think you are far away.

> How is Python's organization less tree-like than Java's?  

Consider the string module. Its functional in form and not 
related to any other classes. Similarly the sockets module.
In this respect Pythons library is more like C++ in that 
some modules are related to each oither but most are 
decoupled. Because of Pythons dynamic capabilities this 
is much less of a problem than in a strictly typed language 
like C++ (where type inconsistencies between modules cause 
huge headaches)

> related to the phrase "in Java everything is a class" that 
> was mentioned last week (I think Alan suggested this)?

Only accidentally. Because everything in Java is a class and 
all Classes must inherit from Object then all library 
"functions" translate to methods of a class which in 
turn is part of a single object heirarchy. BUT many Java
library functions(type conversion for example) are static 
methods which means that they udse classes exactly like 
we use non OO modules. You can call a Java static method 
via the class you don't need to instantiate an object.

Java is riddled with this and one reason I call Java 
"class oriented" rather than "object oriented". Java 
programmers call these static methods class methods but 
even that is a distortion of proper classs methods. 
Class methods should e used to act on the class as 
a whole not to convert a single instance into another 
type - yekkk!

> to take advantage of the similarity between an object and a 
> database row in my code at work, but it's still very new to me.

Here be dragons. The analogy breaks down rapidly when you 
introduce inheritance. Which table do inherited attributes 
live in? Do you have a key linking the parent object table 
to the derived object table and then get the SQL to JOIN 
them? Do you create a view to produce a virtual table of 
both classes? Or do you create a new superset table for 
the derived class? Whole books and learned papers have 
been written on how to map the OO paradigm to relational 
databases.

Alan G.



From pythontutor@venix.com  Tue Apr  9 14:03:44 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 09 Apr 2002 09:03:44 -0400
Subject: [Tutor] ActiveX containers
References: <3CB193A1.775BC6D9@groton.pfizer.com>
Message-ID: <3CB2E6B0.1010400@venix.com>

If I understand Microsoft terminology properly, activeX is used to denote
COM objects that include GUI interface support.  I do NOT know how to do that in pure
Python.  The win32all extensions provide very good COM support.  I've always
used other programs (e.g. VB) to access my Python COM objects.

The book "Python Programming on Win32" by Mark Hammond and Andy Robinson
provides excellent coverage.

Pfizer Inc wrote:

> Hi-
> 
> Is there an activeX container for Python?  I'd like to integrate an RTF
> object into my Python application.
> 
> I'm using a wxFrame.
> 
> Thanks
> 
> Willi
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From bryce@bembry.org  Tue Apr  9 15:03:34 2002
From: bryce@bembry.org (Bryce Embry)
Date: Tue, 09 Apr 2002 09:03:34 -0500
Subject: [Tutor] Labels??? and Entry fields
In-Reply-To: <20020408214512.40391.qmail@web20910.mail.yahoo.com>
References: <E16ubZw-0002p4-00@mail.python.org>
Message-ID: <5.1.0.14.0.20020409083018.00ae4aa0@www.bembry.org>

In Tkinter, the Entry widget has a method called get() that will retrieve 
the information entered in a text field.  I'm a bit new to Tkinter, but a 
code like this should do the trick:

 >>>
from Tkinter import *
root = Tk()
name = Entry(root, width = 30)
name.grid()
         # I use grid as a geometry manager.  You can use name.pack() or 
name.place() instead.

# Type stuff into the entry box
username = name.get()
print username

This is a short example from in IDLE.  Most likely, you'll want to set this 
up so that it only gets the text when a button is pressed.  Here is a short 
script for that:


from Tkinter import *
root = Tk()

Label(root, text = "Enter your name").grid(row = 0, column = 0)

namebox = Entry(root, width = 30)
namebox.grid(row = 1, column = 0)

def getname(event):
     username = namebox.get()
     textbox.insert(END, username)

btn = Button(root, text = "Enter")
btn.bind('<Button-1>', getname)
btn.grid(row = 2, column = 0)

textbox = Text(root, height= 5, width = 20, bg = "blue", fg = "white")
textbox.grid(row = 3, colum = 0)


This script does not compare the text entered to another string.  This is 
just a script that gets the text and displays it in a blue box on the 
window.  Hope this helps

Bryce Embry
Geek-of-All-Trades, Master-of-None


--------------------------------------------------------------------------------------------
"Lord, you establish peace for us.
All that we have accomplished
you have done for us" -- Isaiah 26:12




From pythontutor@venix.com  Tue Apr  9 15:18:11 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 09 Apr 2002 10:18:11 -0400
Subject: [Tutor] ActiveX containers
References: <129BE00D9DC8D411927600805FA71528600BC4@groexmbcr11.pfizer.com>
Message-ID: <3CB2F823.4000908@venix.com>

In researching another issue, I discovered that there are sample
activeX scripts in the win32comext\axscript directory.  That may be
what you are looking for.  There is a readme.htm file in the win32com
directory with some info.

Santiago, Willi wrote:

> Thanks!
> 
> It sounds like you're about where I am.  We have the book.  I can make a
> Python app into a COM object, but am having trouble the other way around.
> 
> thanks
> 
> W
> 
> -----Original Message-----
> From: Lloyd Kvam [mailto:pythontutor@venix.com]
> Sent: Tuesday, April 09, 2002 9:04 AM
> To: Pfizer Inc
> Cc: tutor@python.org
> Subject: Re: [Tutor] ActiveX containers
> 
> 
> If I understand Microsoft terminology properly, activeX is used to denote
> COM objects that include GUI interface support.  I do NOT know how to do
> that in pure
> Python.  The win32all extensions provide very good COM support.  I've always
> used other programs (e.g. VB) to access my Python COM objects.
> 
> The book "Python Programming on Win32" by Mark Hammond and Andy Robinson
> provides excellent coverage.
> 
> Pfizer Inc wrote:
> 
> 
>>Hi-
>>
>>Is there an activeX container for Python?  I'd like to integrate an RTF
>>object into my Python application.
>>
>>I'm using a wxFrame.
>>
>>Thanks
>>
>>Willi
>>
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From dman@dman.ddts.net  Tue Apr  9 15:35:51 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 9 Apr 2002 09:35:51 -0500
Subject: [Tutor] Problem with a simple External Method in ZOpe
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDAEPGDIAA.karthikg@aztec.soft.net>
References: <Pine.LNX.4.44.0204080230420.31437-100000@hkn.eecs.berkeley.edu> <NEBBJNMDEKBIBCMCNMBDAEPGDIAA.karthikg@aztec.soft.net>
Message-ID: <20020409143551.GA31830@dman.ddts.net>

On Mon, Apr 08, 2002 at 03:40:44PM +0530, Karthik Gurumurthy wrote:
 
| > Hmmm... You may want to check file permissions, just in case.  Zope runs
| > as the user who started it, so if the directory doesn't allow the Zope
| > user to write to it, you should see an IOError.
| > 
| > If you can show us the code for the external method, we can try it on our
| > end and see what's going on.  Also, how are you calling the external
| > method?
 
| This is the simple code snippet:
| 
| def sayHello():
|     retVal = "" 
|     try:
|         fp = open("test.txt","w")

Note that this is a relative path.  You may want to try an absolute
path such as /tmp/test.txt and also check your filesystem to see where
this was created.  For example either
    updatedb && locate test.txt
        or
    find / -name test.txt -print


| I can see "hello success" getting printed.

HTH,
-D

-- 

Be sure of this:  The wicked will not go unpunished,
but those who are righteous will go free.
        Proverbs 11:21




From Ed Hopkins" <ed.hopkins@ntlworld.com  Tue Apr  9 15:32:52 2002
From: Ed Hopkins" <ed.hopkins@ntlworld.com (Ed Hopkins)
Date: Tue, 9 Apr 2002 15:32:52 +0100
Subject: [Tutor] Unable to Import :  Numeric
Message-ID: <009801c1dfd3$6e68f3f0$67526bd5@FAMILY>

Hi guys,

I'm new to Python and installed numeric.

When I try to import numeric I get this response:

>>> import numeric
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
ImportError: No module named numeric

?????  Thee is a folder in my python directory called numeric filled with
lots of goodies related to numeric.

I'm running PythonWin 2.1 212

Now i'm lost.  Any ideas?

#### Answer ####

Just before I sent the message I tried again but this time changing
'numeric' to 'Numeric'

>>> Import Numeric

Voilla

Sorted !

Just thought I'd let everyone know the good news anyway!

Since it's a bit quiet in the group.

Ed






From dman@dman.ddts.net  Tue Apr  9 15:42:48 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 9 Apr 2002 09:42:48 -0500
Subject: [Tutor] impact of OO
In-Reply-To: <071253B8-4B62-11D6-9D76-00039351FE6A@mac.com>
References: <4.2.0.58.20020404204915.00afe9b0@pop3.norton.antivirus> <071253B8-4B62-11D6-9D76-00039351FE6A@mac.com>
Message-ID: <20020409144248.GB31830@dman.ddts.net>

On Mon, Apr 08, 2002 at 10:32:24PM -0400, Erik Price wrote:

| What is a JavaBean?

In its simplest form, it is just a class that follows certain naming
conventions for its members and methods.  For example
    class StupidBean
    {
        private int amember ;
        public void setAmember( int v ) { this.amember = v ; }
        public int getAmember() { return this.amember ; }
    }

The idea is that tools can be created to "discover" what the class can
do through reflection.

Enterprise Java Beans are a different beast altogether.  Again, they
are classes that follow some conventions, but they are to be used in a
J2EE container.  They are a java-specific distributed object system.
If you think you want to use an EJB or servlet, try Zope instead.  I
recently had a use for Zope, so I sat down and read the tutorial.  It
is really quite easy to use, once you can wrap your head around the
overall architecture.

For more on java beans :
    http://developer.java.sun.com/developer/onlineTraining/Beans/beans02/
    http://developer.java.sun.com/developer/technicalArticles/ebeans/ejb20/

HTH,
-D

-- 

He who belongs to God hears what God says.  The reason you do not hear
is that you do not belong to God.
        John 8:47




From dman@dman.ddts.net  Tue Apr  9 15:46:07 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 9 Apr 2002 09:46:07 -0500
Subject: [Tutor] debugging classes with a __setattr__ method
In-Reply-To: <3CA8DF51.2010706@venix.com>
References: <3CA8DF51.2010706@venix.com>
Message-ID: <20020409144607.GC31830@dman.ddts.net>

On Mon, Apr 01, 2002 at 05:29:37PM -0500, Lloyd Kvam wrote:
| I have a class for processing DataBase records that keeps a dictionary of 
| the
| actual field values from the database in a separate dictionary from the
| Class's __dict__ dictionary.  When I try to step through the program using 
| the
| debugger,  I can no longer step into the called methods.  Deleting the
| __setattr__ method restores normal debugging capabilities.
| 
| Is this a normal side effect on the debugger?  Very little of the code 
| depends
| on the __setattr__ method, so I can remove it, debug and then put it back.
| However, there may be a better way.  Any suggestions?

Use 'print' :-).  It is the least invasive mechanism for debugging,
and is nicely portable across languages and development environments.
To date I've rarely used an actual debugger, and I've had projects in
Eiffel, C++, C, Java, Python, and Perl.  Occaisonally a debugger is
helpful (especially if you don't have any idea where a problem lies,
or if you need a stack trace from a core dump), but sometimes
(especially for multithreaded apps) it just can't do the job.

HTH,
-D

-- 

Only two things are infinite, the universe and human stupidity, and I'm
not sure about the former.
        Albert Einstein




From pythontutor@venix.com  Tue Apr  9 16:58:56 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 09 Apr 2002 11:58:56 -0400
Subject: [Tutor] debugging classes with a __setattr__ method
References: <3CA8DF51.2010706@venix.com> <20020409144607.GC31830@dman.ddts.net>
Message-ID: <3CB30FC0.3050101@venix.com>

Yes, print works very nicely when all else fails.  I do have print statements
strategically placed.  However sometimes things just don't work right, but
there is no traceback and nothing suspicious in the print output.  I've found
the debugger very helpful for stepping through those cases.

dman wrote:

> On Mon, Apr 01, 2002 at 05:29:37PM -0500, Lloyd Kvam wrote:
> | I have a class for processing DataBase records that keeps a dictionary of 
> | the
> | actual field values from the database in a separate dictionary from the
> | Class's __dict__ dictionary.  When I try to step through the program using 
> | the
> | debugger,  I can no longer step into the called methods.  Deleting the
> | __setattr__ method restores normal debugging capabilities.
> | 
> | Is this a normal side effect on the debugger?  Very little of the code 
> | depends
> | on the __setattr__ method, so I can remove it, debug and then put it back.
> | However, there may be a better way.  Any suggestions?
> 
> Use 'print' :-).  It is the least invasive mechanism for debugging,
> and is nicely portable across languages and development environments.
> To date I've rarely used an actual debugger, and I've had projects in
> Eiffel, C++, C, Java, Python, and Perl.  Occaisonally a debugger is
> helpful (especially if you don't have any idea where a problem lies,
> or if you need a stack trace from a core dump), but sometimes
> (especially for multithreaded apps) it just can't do the job.
> 
> HTH,
> -D
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From urnerk@qwest.net  Tue Apr  9 17:29:35 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 09 Apr 2002 09:29:35 -0700
Subject: [Tutor] Unable to Import :  Numeric
In-Reply-To: <009801c1dfd3$6e68f3f0$67526bd5@FAMILY>
Message-ID: <4.2.0.58.20020409092915.01631100@pop3.norton.antivirus>

At 03:32 PM 4/9/2002 +0100, Ed Hopkins wrote:
>Hi guys,
>
>I'm new to Python and installed numeric.
>
>When I try to import numeric I get this response:
>
> >>> import numeric


It's case sensitive.

Try

import Numeric

instead.

Kirby




From wesc@deirdre.org  Tue Apr  9 20:06:18 2002
From: wesc@deirdre.org (Wesley Chun)
Date: Tue, 9 Apr 2002 12:06:18 -0700 (PDT)
Subject: [Tutor] ANN: BayPIGgies this WED nite 7:30pm
Message-ID: <Pine.LNX.4.31.0204091203010.8204-100000@emperor.deirdre.org>

What:    BayPIGgies meeting
When:    Wed, 10 Apr 2002, 7:30-9 PM
Where:   Stanford University, Palo Alto, CA
Agenda:  Newbies Night
Speaker: everyone...

Invite everyone you know who may be interested in Python but have
questions, would like to learn more about it, or need some advice on
an application! These meetings have been very popular in the past,
with a good mix of newbies as well as old hands. They are even more
fun when one or more Perl experts come around wondering what the big
deal is about Python. :-) Come join us for this interactive session!

Next Meeting (5/8): Eating Out with Python (our meeting room will not
be available, so we will meet and chat over dinner at a local
restaurant!)

---------------------------------------------------------------------------=
-----
Call For Talks: We are actively seeking speakers for BayPIGgies! If
you would like to give a talk at one of our meetings (any Python
related topic), contact us to coordinate!

for more information including driving and public transit directions:

http://deirdre.org/baypiggies

-wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

"Core Python Programming", Prentice Hall PTR, =A9 2001
    http://starship.python.net/crew/wesc/cpp/

Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies)
    http://deirdre.org/baypiggies

wesley.j.chun :: wesc at deirdre.org
cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com
http://roadkill.com/~wesc/cyberweb/




From charlie@begeistert.org  Tue Apr  9 20:35:37 2002
From: charlie@begeistert.org (Charlie Clark)
Date: Tue, 09 Apr 2002 21:35:37 +0200
Subject: [Tutor] Re: Impact of OO
In-Reply-To: <E16uy3v-0004TH-00@mail.python.org>
References: <E16uy3v-0004TH-00@mail.python.org>
Message-ID: <20020409215353.6096.15@gormenghast.1018293384.fake>

On 2002-04-09 at 18:00:09 [+0200], tutor-request@python.org wrote:
> Enterprise Java Beans are a different beast altogether.  Again, they are 
> classes that follow some conventions, but they are to be used in a J2EE 
> container.  They are a java-specific distributed object system. If you 
> think you want to use an EJB or servlet, try Zope instead.  I recently 
> had a use for Zope, so I sat down and read the tutorial.  It is really 
> quite easy to use, once you can wrap your head around the overall 
> architecture.

Have to agree here. Zope's interface makes OO so transparent that you don't notice you're dealing with it: the website structure looks like a hierarchical folder structure and works just like one. Headers and footers get inherited by sub-folders unless you (over)write new ones. But this applies to all kinds of objects. I had a big wow experience the other week when I realised that 20 sub-folders doing the same thing with different parameters all had access via inheritance to the method I wanted and the parameter was just a "property" of the sub-folders. Very clean. This is the way to do web development. Zope isn't perfect but it is inspiring and that's more than I can say for most comparable systems I've seen.

Charlie



From wolf_binary@hotmail.com  Tue Apr  9 22:06:38 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Tue, 9 Apr 2002 16:06:38 -0500
Subject: [Tutor] nested functions
Message-ID: <DAV72D543TuylJc0xvl00000eb5@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01C1DFE0.87E0A780
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi all,

Is it a good or bad idea to call functions with in functions?  What =
could you do to not have functions calling functions? I have given an =
example of this bellow.

def splitter(sentence):
 import string
 list =3D string.split(sentence, sep=3D" ")
 return list

# Encrypt sentences
def encryptsent(sentence):
 list =3D splitter(sentence) # list is the list of the
      # the words in the sentence
 count_of_sent =3D len(list)
 count =3D count_of_sent - 1 # -1 of count_of_sent to account for =
slicing
 # initialize variables
 x =3D 0
 list_sentence =3D []
=20
 while x <=3D count: # x is the counter of each word to be processed
  word =3D list[x]
  word_encrypted =3D encrypting(word) # encrypt word
 =20
  quashed_word =3D flow(word_encrypted) # mash character encryption
          # together
  list_sentence.append(quashed_word)
 =20
  x =3D x + 1
  message =3D flow(list_sentence)
=20
 return message

Thanks,
Cameron Stoner



------=_NextPart_000_0005_01C1DFE0.87E0A780
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Is it a good or bad idea to call =
functions with in=20
functions?&nbsp; What could you do to not have functions calling =
functions? I=20
have given an example of this bellow.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>def splitter(sentence):<BR>&nbsp;import =

string<BR>&nbsp;list =3D string.split(sentence, sep=3D" =
")<BR>&nbsp;return=20
list</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2># Encrypt sentences<BR>def=20
encryptsent(sentence):<BR>&nbsp;list =3D splitter(sentence) # list is =
the list of=20
the<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # the words in the=20
sentence<BR>&nbsp;count_of_sent =3D len(list)<BR>&nbsp;count =3D =
count_of_sent - 1 #=20
-1 of count_of_sent to account for slicing<BR>&nbsp;# initialize=20
variables<BR>&nbsp;x =3D 0<BR>&nbsp;list_sentence =3D =
[]<BR>&nbsp;<BR>&nbsp;while x=20
&lt;=3D count: # x is the counter of each word to be =
processed<BR>&nbsp;&nbsp;word=20
=3D list[x]<BR>&nbsp;&nbsp;word_encrypted =3D encrypting(word) # encrypt =

word<BR>&nbsp;&nbsp;<BR>&nbsp;&nbsp;quashed_word =3D =
flow(word_encrypted) # mash=20
character =
encryption<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #=20
together<BR>&nbsp;&nbsp;list_sentence.append(quashed_word)<BR>&nbsp;&nbsp=
;<BR>&nbsp;&nbsp;x=20
=3D x + 1<BR>&nbsp;&nbsp;message =3D =
flow(list_sentence)<BR>&nbsp;<BR>&nbsp;return=20
message</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Cameron Stoner</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0005_01C1DFE0.87E0A780--



From shalehperry@attbi.com  Tue Apr  9 23:24:52 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 09 Apr 2002 14:24:52 -0800 (PDT)
Subject: [Tutor] nested functions
In-Reply-To: <DAV72D543TuylJc0xvl00000eb5@hotmail.com>
Message-ID: <XFMail.20020409142452.shalehperry@attbi.com>

On 09-Apr-2002 Cameron Stoner wrote:
> Hi all,
> 
> Is it a good or bad idea to call functions with in functions?  What could you
> do to not have functions calling functions? I have given an example of this
> bellow.
> 

functions are an important building block, nothing wrong with functions calling
functions calling more functions.

now DEFINING nested functions can be messy:

def foo(item):
  def bar(that):
      print that

  bar(item)



From wolf_binary@hotmail.com  Tue Apr  9 23:11:27 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Tue, 9 Apr 2002 17:11:27 -0500
Subject: [Tutor] nested functions
References: <XFMail.20020409142452.shalehperry@attbi.com>
Message-ID: <DAV14D3JkUwWpSWerOc00000f8d@hotmail.com>

Why would you want to define functions inside functions?  It seems kinda
like a class with methods.  When would you want to do something like this?
>
> now DEFINING nested functions can be messy:
>
> def foo(item):
>   def bar(that):
>       print that
>
>   bar(item)
>

Cameron Stoner



From virketis@fas.harvard.edu  Tue Apr  9 23:28:49 2002
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Tue, 9 Apr 2002 18:28:49 -0400
Subject: [Tutor] nested functions
In-Reply-To: <DAV14D3JkUwWpSWerOc00000f8d@hotmail.com>
Message-ID: <200204092228.g39MSv313374@smtp1.fas.harvard.edu>

<HTML><HEAD>
<BASEFONT FACE=3D"Arial" SIZE=3D"2" COLOR=3D"#000000">
</HEAD>
<BODY>
<div>Cameron,<br></div>
<div><br>
<FONT COLOR=3D"#000080">&gt;Why would you want to define functions=
 inside functions? &nbsp;It seems</FONT><br>
<FONT COLOR=3D"#000080">&gt;kinda like a class with methods.=
 &nbsp;When would you want to do </FONT><br></div>
<div><FONT COLOR=3D"#000080">&gt; something like this?</FONT><br>
<br></div>
<div>Not that I take advantage of this possibility often, but you=
 could have your code generate other code on the fly: it's the=
 big selling point of LISP and its dialects, as far as I know.=
 You recognise some input, and then you create create the right=
 function. The rest of your code can expect &quot;foo()&quot; to=
 be the right tool for the job in the context, no matter what had=
 to go into making it. <br></div>
<div>&nbsp;</div>
<div>Cheers, <br></div>
<div>&nbsp;</div>
<div>Pijus<br></div>
<div>-- <br></div>
<div>All bad precedents began as justifiable measures. -- Gaius=
 Julius Caesar, quoted in &quot;The Conspiracy of Catiline&quot;,=
 by Sallust <br></div>
</body></html>




From dyoo@hkn.eecs.berkeley.edu  Wed Apr 10 03:04:29 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 9 Apr 2002 19:04:29 -0700 (PDT)
Subject: [Tutor] nested functions  [differentation / C++ comparision]
In-Reply-To: <200204092228.g39MSv313374@smtp1.fas.harvard.edu>
Message-ID: <Pine.LNX.4.44.0204091718290.32473-100000@hkn.eecs.berkeley.edu>

On Tue, 9 Apr 2002, Pijus Virketis wrote:

> Cameron,
>
> >Why would you want to define functions inside functions?  It seems
> >kinda like a class with methods.  When would you want to do
> > something like this?
>
> Not that I take advantage of this possibility often, but you could have
> your code generate other code on the fly: it's the big selling point of
> LISP and its dialects, as far as I know. You recognise some input, and
> then you create create the right function. The rest of your code can
> expect "foo()" to be the right tool for the job in the context, no
> matter what had to go into making it.


Here's a math-motivated example.  In Calculus, there's an operation called
'differentiation' that works on many mathy functions.  For example, the
function:

    f(x) = x^2

has the derivative:

    d f(x) = 2x
   ---
   dx

(Differentiation tells us that if we take a tangent line to the point, (x,
f(x)), we'll find the slope is equal to the value of the differentated
function at that point too.)


What's particularly unique about differentiation is that it's main
target are functions!  That is, differentiation take a function, and
returns a whole new function.

We can model this in Python --- we can imagine some Python function called
'diff' that takes in a function, and returns its derivative.  Here's a
sample implementation:

###
def diff(f, epsilon=0.0001):
    """We take the function f and creates a whole new function g that
    approximates the derivative of f."""
    def g(x):
        return (f(x+epsilon) - f(x)) / epsilon
    ## The key step here is to return this new g function!
    return g
###

The above definition is just something I pulled out of a calculus book,
and is only a numerical approximation.  Still, it should work well enough
for this example.  Let's see how it works:

###
>>> diffed_square = diff(square)
>>> square(10)
100
>>> diffed_square(10)
20.000099999890608
###

When we make functions that return new functions, we'll find ourselves
creating an inner function definition, just so we can give it to someone
else.





C++ doesn't allow us do do wacky things like writing functions in
functions.  However, we can can simulate this effect with the judicious
use of classes.  Here's what the example with differentiation would look
like in C++:

//////
#include <iostream>

class Function {
    // Here, we define that a Function is something that knows how
    // to evaluate itself at a certain point 'x'.
public:
    virtual float eval(float x) = 0;
};


class SquareFunction : public Function {
    // Here's one particular example of a Function class.
public:
    float eval(float x) {
        return x * x;
    }
};


class DiffFunction : public Function {
    // We can differentiate a particular Function instance by using
    // DifferentiatedFunction.
public:
    DiffFunction(Function *f, float epsilon=0.0001) {
        this->f = f;
        this->epsilon=epsilon;
    }
    float eval(float x) {
        return (f->eval(x + epsilon) - f->eval(x)) / epsilon;
    }
    Function *f;
    float epsilon;
};


// Small test function
int main() {
    cout << "Let's test this out.\n";
    Function *square = new SquareFunction;
    Function *diff_square = new DiffFunction(square);
    cout << square->eval(10) << " is what square(10) gives us.\n";
    cout << diff_square->eval(10) << "is what diff_square(10) "
         << "gives us.\n";
    return 0;
}
//////


But as you can tell, this is somewhat... painful compared to the Python
code.  *grin* So it's possible to live without being able to make nested
functions if we have classes, but the resulting code is just not as
elegant or straightforward as the nested-function approach.


We can give more examples of functions in functions that aren't math
related.  I just picked the math one because I was reviewing tangents and
limits last night.

If you have more questions, please feel free to ask!  Good luck!




From pilotncontrol@hotmail.com  Tue Apr  9 07:00:12 2002
From: pilotncontrol@hotmail.com (Darren Anthony)
Date: Mon, 08 Apr 2002 23:00:12 -0700
Subject: [Tutor] importing modules -windows version of python
Message-ID: <F456YHkidcDjoYAPNXR00000045@hotmail.com>

I can "import time" from the command prompt but when I write code in windows 
notepad,  The module doesn't import.

How do I fix this?  Do I change a path.......

_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From dyoo@hkn.eecs.berkeley.edu  Wed Apr 10 02:10:39 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 9 Apr 2002 18:10:39 -0700 (PDT)
Subject: [Tutor] How to interrupt in IDLE
In-Reply-To: <002901c1dca8$e311de20$e3df84d2@thinkpad1200>
Message-ID: <Pine.LNX.4.44.0204061526490.12650-100000@hkn.eecs.berkeley.edu>


On Fri, 5 Apr 2002, Roman Suzuki wrote:

> Hi, everyone
>
> I'v just started learning Python language. and I am doing "Python Tutorial".
> When I tried following example on  Section 4.5 "IDLE for Windows" freezed.
> # example ----------
> >>> while 1:
>     pass
> # example ----------
>
> I had to push Ctrl+Alt+Del to kill IDLE.. If you know right way to interrupt
> in IDLE, tell me that, please.

Hi Roman,

Yikes!  I would have thought that Ctrl-C would have done it, but
apparently this doesn't work in IDLE when it's busy running the program.
Hmmm... this is bad.  I'll ask on the IDLE-Dev developers list to see if
there's a workaround.




From urnerk@qwest.net  Wed Apr 10 03:26:57 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 09 Apr 2002 19:26:57 -0700
Subject: [Tutor] nested functions
In-Reply-To: <DAV14D3JkUwWpSWerOc00000f8d@hotmail.com>
References: <XFMail.20020409142452.shalehperry@attbi.com>
Message-ID: <4.2.0.58.20020409184316.0159ad00@pop3.norton.antivirus>

At 05:11 PM 4/9/2002 -0500, Cameron Stoner wrote:
>Why would you want to define functions inside functions?
>It seems kinda like a class with methods.  When would you
>want to do something like this?

Indeed, as Danny pointed out, you might use a function
in a function to create a custom function.

Here's another math example -- also links to matrices,
an earlier topic.

To rotate point around the x-axis in the XYZ coordinate
system, we use the rotation matrix:

def xmatrix(theta):
     return [[1            ,0      , 0],
             [0, cos(theta),-sin(theta)],
             [0, sin(theta), cos(theta)]]

where theta is the angle you want to rotate by.  Notice
we use a function with theta as an argument.  Other,
similar matrices are used to rotate around the Y and
Z axes respectively:

def ymatrix(theta):
     return [[cos(theta), 0,-sin(theta)],
             [0         , 1         , 0],
             [sin(theta), 0, cos(theta)]]


def zmatrix(theta):
     return [[ cos(theta),-sin(theta),0],
             [ sin(theta), cos(theta),0],
             [ 0         ,0         , 1]]

Notice the matrix data structure:  rows are lists
within a list.  Each row has the same number of
entries.  These happen to be 3x3 square matrices.

Now suppose we frequently need to rotate points a fixed
amount, say 45 degrees around Z.  We can manufacture a
function that does this.

The function called mkrot() below takes one of the
above matrix functions, and the angle of rotation, as
its inputs:

def mkrot(matrix,theta):
     """
     Makes functions that rotate a point around a
     fixed axis by theta degrees
     """
     theta = theta*(pi/180)
     R = matrix(theta)  # R is a specific rotation matrix
     def rotate(v):
        "Matrix multiplication of R by v (a vector)"
        newcoords = []
        for row in R:
           newcoords.append(
                 reduce(add,map(mul,v.xyz,row)))
        return Vector(newcoords)  # vector points in new direction
     return rotate

Now let's use this function.  we pass zmatrix as the first
argument.  Recall that zmatrix is a function, which expects
and angle as its argument.  So we also pass the angle (45.)
which gets converted from degrees to radians in the first
line of mkrot().

zrot45  = mkrot(zmatrix,45.)

So theta gets passed to the matrix function (zmatrix in
this case -- might have been xmatrix or ymatrix) to create
rotation matrix R, and R features inside the internal
rotate() function.  It's this internal rotate() function
which mkrot() returns, i.e. it's returning a *function*
which rotates a point 45 degrees around the Z axis.

So zrot45 is now a function.  It expects a Vector object
as input (defined elsewhere).  Let's use it:

  >>> zrot45
  <function rotate at 0x00B003F0>
  >>> v = Vector([1,0,0])  # Vector an imported class
  >>> zrot45(v)
  Vector (0.70710678118654757, 0.70710678118654746, 0.0)

The arrow has moved.  (1,0,0) points to 3'oclock, but
after zrot45 does its job, the arrow has moved counter
clockwise by 45 degrees (the Z axis sticks through the
clock face, so rotations around it are in the plane of
the clock).

The guts of zrot45 is a simple matrix multiplication of
R (fixed by mkrot) times the single argument vector.

In a module I added to recently, I use this system to
compose two rotation functions, i.e. to make a single
rotation out of components:

theta = acos(-1/3.)*180/pi/2
xrot54  = mkrot(xmatrix,theta)
zrot45  = mkrot(zmatrix,45.)

def rotxz(v):
     return xrot54(zrot45(v))

rotxz will return a function that rotates any input vector
45 degrees around the Z axis, and then about 54 degrees
around the X axis.  I can now use rotxz(v) anywhere I
like in my program, knowing what it's been pre-programmed
to do.  And I can use mkrot() to manufacture other fixed
rotation functions, simply by handing it a matrix and an
angle.

Kirby






From erikprice@mac.com  Wed Apr 10 03:34:37 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 9 Apr 2002 22:34:37 -0400
Subject: [Tutor] constructors
Message-ID: <80421E46-4C2B-11D6-B2EE-00039351FE6A@mac.com>

When writing a class, is it recommended to always take advantage of 
constructors?  I have written a class called Person, which helps me to 
organize my user-input error-checking (by confining error-checking 
functions to the methods that set instance attributes).  I don't have a 
constructor, because sometimes I use this class to build a new Person 
and sometimes I use this class to pull an already-existing Person's 
attributes from a database table.  But constructors are seen as a 
"really good thing", but as far as I can see a constructor is just a 
shortcut.  Please share your thoughts on using constructors, if you 
would?


Thank you,

Erik




From shalehperry@attbi.com  Wed Apr 10 03:42:32 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 09 Apr 2002 19:42:32 -0700 (PDT)
Subject: [Tutor] constructors
In-Reply-To: <80421E46-4C2B-11D6-B2EE-00039351FE6A@mac.com>
Message-ID: <XFMail.20020409194232.shalehperry@attbi.com>

On 10-Apr-2002 Erik Price wrote:
> When writing a class, is it recommended to always take advantage of 
> constructors?  I have written a class called Person, which helps me to 
> organize my user-input error-checking (by confining error-checking 
> functions to the methods that set instance attributes).  I don't have a 
> constructor, because sometimes I use this class to build a new Person 
> and sometimes I use this class to pull an already-existing Person's 
> attributes from a database table.  But constructors are seen as a 
> "really good thing", but as far as I can see a constructor is just a 
> shortcut.  Please share your thoughts on using constructors, if you 
> would?

Good, you are thinking for yourself.  You are thinking correctly as well.  a
constructor is often handy but not always necessary.  Like any other tool, use
it when you need it.



From urnerk@qwest.net  Wed Apr 10 04:48:36 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 09 Apr 2002 20:48:36 -0700
Subject: [Tutor] importing modules -windows version of python
In-Reply-To: <F456YHkidcDjoYAPNXR00000045@hotmail.com>
Message-ID: <4.2.0.58.20020409204453.0199cf00@pop3.norton.antivirus>

At 11:00 PM 4/8/2002 -0700, you wrote:
>I can "import time" from the command prompt but when I write
>code in windows notepad,  The module doesn't import.

What have you been able to do with notepad?  Do you save
a .py file and then run it in a DOS box, by going

  > python mything.py

If you get that far, then mything.py should be able to
include an

import time

at the top -- or import any other standard library
module, of which there are a gazillion.

>How do I fix this?  Do I change a path.......

Not sure how you're running Python.  Have you tried IDLE's
text editor?  Why are you using Notepad I wonder?

Of course Notepad is just a text editor, so until you
save the file with a .py extension, and feed it to
python, nothing will happen.

Kirby




From dman@dman.ddts.net  Wed Apr 10 05:25:02 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 9 Apr 2002 23:25:02 -0500
Subject: [Tutor] constructors
In-Reply-To: <80421E46-4C2B-11D6-B2EE-00039351FE6A@mac.com>
References: <80421E46-4C2B-11D6-B2EE-00039351FE6A@mac.com>
Message-ID: <20020410042502.GB5587@dman.ddts.net>

On Tue, Apr 09, 2002 at 10:34:37PM -0400, Erik Price wrote:
| When writing a class, is it recommended to always take advantage of 
| constructors?  I have written a class called Person, which helps me to 
| organize my user-input error-checking (by confining error-checking 
| functions to the methods that set instance attributes).  I don't have a 
| constructor, because sometimes I use this class to build a new Person 
| and sometimes I use this class to pull an already-existing Person's 
| attributes from a database table.  But constructors are seen as a 
| "really good thing", but as far as I can see a constructor is just a 
| shortcut.  Please share your thoughts on using constructors, if you 
| would?

Constructors are much more essential in a language like C++ than they
are for Python.  In fact, a class in C++ _always_ has at least one
constructor, if you don't write it yourself the compiler will insert
it automatically.  In C++ you must statically specify all the members
that instances of the class will have.  In a ctor you initialze those
members to sensible values.  If you don't, you'll have garbage
(random) values in them.  (don't even try to consider what happens if
an exception is thrown from a ctor or dtor.  I've glanced over some
discussions before, and it is beyond me)  With python you have the
ability to create members after-the-fact, so it isn't such an issue.

I say use a ctor (called __init__ in python) if you need/want to
initialize the members of the object to some value when it is created.
If you don't need/want that, then don't bother writing an empty one.
I have found that most of the time you do want a ctor (though that
may be my C++/Java background there).  You can use default arguments
to allow for variations in usage.  For example :

class Person :
    def __init__( self , name="Not Specified" , age="Not Specified" ) :
        self.name = name
        self.age = age

p1 = Person()
p2 = Person( get_name_from_db() , get_age_from_db() )

-D

-- 

The fear of the Lord leads to life:
Then one rests content, untouched by trouble.
        Proverbs 19:23




From paulsid@shaw.ca  Wed Apr 10 05:49:14 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Tue, 09 Apr 2002 22:49:14 -0600
Subject: [Tutor] nested functions  [differentation / C++ comparision]
References: <Pine.LNX.4.44.0204091718290.32473-100000@hkn.eecs.berkeley.edu>
Message-ID: <3CB3C44A.B9B2B9FC@shaw.ca>

Danny Yoo wrote:

> We can model this in Python --- we can imagine some Python function called
> 'diff' that takes in a function, and returns its derivative.  Here's a
> sample implementation:
> 
> ###
> def diff(f, epsilon=0.0001):
>     """We take the function f and creates a whole new function g that
>     approximates the derivative of f."""
>     def g(x):
>         return (f(x+epsilon) - f(x)) / epsilon
>     ## The key step here is to return this new g function!
>     return g
> ###

I thought this was a neat example so I tried to run it and got the
errors below.  I'm using Python 2.1; turning on nested scopes didn't
change anything.  Any ideas?  Do I need 2.2 for this to work?

Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import diff
E:\Python21\diff.py:1: SyntaxWarning: local name 'f' in 'diff' shadows
use of 'f' as global in nested scope 'g'
  def diff(f, epsilon=0.0001):
E:\Python21\diff.py:1: SyntaxWarning: local name 'epsilon' in 'diff'
shadows use of 'epsilon' as global in nested scope 'g'
  def diff(f, epsilon=0.0001):
>>> def sq(x): return x**2

>>> sq(4)
16
>>> sqprime = diff.diff(sq)
>>> sqprime(4)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in ?
    sqprime(4)
  File "E:\Python21\diff.py", line 5, in g
    return (f(x+epsilon) - f(x)) / epsilon
NameError: global name 'f' is not defined

It wouldn't work in the interpreter directly (the SyntaxWarning becomes
a SyntaxError).

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From urnerk@qwest.net  Wed Apr 10 06:21:16 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 09 Apr 2002 22:21:16 -0700
Subject: [Tutor] nested functions  [differentation / C++
 comparision]
In-Reply-To: <3CB3C44A.B9B2B9FC@shaw.ca>
References: <Pine.LNX.4.44.0204091718290.32473-100000@hkn.eecs.berkeley.edu>
Message-ID: <4.2.0.58.20020409221858.019a5140@pop3.norton.antivirus>

>
>It wouldn't work in the interpreter directly (the SyntaxWarning
>becomes a SyntaxError).

There's a problem with importing nested scopes in
shell mode in IDLE in 2.1.  Cut and paste the code
to a text file with

from __future__ import nested_scopes

at the top of the file.  Save as danny.py or whatever
and import e.g.

from danny import diff

This will cause nested scopes to kick in and allow you
to use diff interactively.

Kirby




From karthikg@aztec.soft.net  Wed Apr 10 06:44:55 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 10 Apr 2002 11:14:55 +0530
Subject: [Tutor] An example of something extremely difficult to express in Java
In-Reply-To: <3CB3C44A.B9B2B9FC@shaw.ca>
Message-ID: <NEBBJNMDEKBIBCMCNMBDAEFEDJAA.karthikg@aztec.soft.net>

Hi all,

can someone give me neat examples of something which
is *extremely* difficult to express in java but can be easily
represented in python?

i liked the

__getattr__ thing.

where you can wrap a object with a wrapper and then change the
wrapped object midway and still manage to delegate calls to the wrapped
object w/o any code change.

regards,
karthik.





From shalehperry@attbi.com  Wed Apr 10 06:50:24 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 09 Apr 2002 22:50:24 -0700 (PDT)
Subject: [Tutor] constructors
In-Reply-To: <20020410042502.GB5587@dman.ddts.net>
Message-ID: <XFMail.20020409225024.shalehperry@attbi.com>

> 
> I say use a ctor (called __init__ in python) if you need/want to
> initialize the members of the object to some value when it is created.
> If you don't need/want that, then don't bother writing an empty one.
> I have found that most of the time you do want a ctor (though that
> may be my C++/Java background there).  You can use default arguments
> to allow for variations in usage.  For example :
> 

there are many times when there is no way to define a default version of an
object, so having a constructor makes sense.  This is especially true when you
are modelling the real world or your objects represent items.



From karthikg@aztec.soft.net  Wed Apr 10 07:28:00 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 10 Apr 2002 11:58:00 +0530
Subject: [Tutor] constructors
In-Reply-To: <80421E46-4C2B-11D6-B2EE-00039351FE6A@mac.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDIEFEDJAA.karthikg@aztec.soft.net>

Hi Erik,

> and sometimes I use this class to pull an already-existing Person's

coming from a java background, there is a concept of cloning to do the
copying part.
I guess it's there in most OO languages ( i guess it the copy constructor in
C++ ?? and so on...)
It c'd be as simple as having a method clone() on your Person class to do
it, the way it is in java.
It just fills up another instance with the current Person's attributes and
w'd return that.

typically used as

 p1 = person(name="abc")
 p2 = p1.clone()

am not sure if this is considered a good practice in Python too.

regards,
karthik.




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



From dyoo@hkn.eecs.berkeley.edu  Wed Apr 10 08:25:01 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Apr 2002 00:25:01 -0700 (PDT)
Subject: [Tutor] constructors
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDIEFEDJAA.karthikg@aztec.soft.net>
Message-ID: <Pine.LNX.4.44.0204100018050.13779-100000@hkn.eecs.berkeley.edu>

> coming from a java background, there is a concept of cloning to do the
> copying part.
> I guess it's there in most OO languages ( i guess it the copy constructor in
> C++ ?? and so on...)
> It c'd be as simple as having a method clone() on your Person class to do
> it, the way it is in java.
> It just fills up another instance with the current Person's attributes and
> w'd return that.
>
> typically used as
>
>  p1 = person(name="abc")
>  p2 = p1.clone()
>
> am not sure if this is considered a good practice in Python too.

Yes the 'copy' module actually allows us to do what Java's clone() does:

    http://www.python.org/doc/lib/module-copy.html


copy.copy() or copy.deepcopy() should work pretty well with normal Python
classes, and by defining a __copy__() function, we can control how
functions are cloned off.

For example:


###
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...     def greet(self):
...         print "Hello, my name is %s" % self.name
...     def __copy__(self):
...         return Person(self.name.replace('u', 'uu'))
...
>>> import copy
>>> star = Person("luke")
>>> star.greet()
Hello, my name is luke
>>> cloned_star = copy.copy(star)
>>> cloned_star.greet()
Hello, my name is luuke
###


May the force be with you.




From dyoo@hkn.eecs.berkeley.edu  Wed Apr 10 08:28:47 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Apr 2002 00:28:47 -0700 (PDT)
Subject: [Tutor] constructors
In-Reply-To: <Pine.LNX.4.44.0204100018050.13779-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0204100026580.13779-100000@hkn.eecs.berkeley.edu>

> copy.copy() or copy.deepcopy() should work pretty well with normal Python
> classes, and by defining a __copy__() function, we can control how
> functions are cloned off.
  ^^^^^^^^^

Sorry, I meant to say:

"... and by defining a __copy__() method, we can control how instances are
cloned off."


I have functions on the brain today.  *grin*


Hope this helps!




From alex@gabuzomeu.net  Wed Apr 10 10:41:20 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 10 Apr 2002 11:41:20 +0200
Subject: [Tutor] constructors
In-Reply-To: <20020410025001.6193.34023.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020410105201.00b70ac0@pop3.norton.antivirus>

Hi Erik,


At 22:50 09/04/2002 -0400, you wrote:
>Date: Tue, 9 Apr 2002 22:34:37 -0400
>From: Erik Price <erikprice@mac.com>
>Subject: [Tutor] constructors
>
>When writing a class, is it recommended to always take advantage of
>constructors?  I have written a class called Person, which helps me to
>organize my user-input error-checking (by confining error-checking
>functions to the methods that set instance attributes).  I don't have a
>constructor, because sometimes I use this class to build a new Person
>and sometimes I use this class to pull an already-existing Person's
>attributes from a database table.  But constructors are seen as a
>"really good thing", but as far as I can see a constructor is just a
>shortcut.  Please share your thoughts on using constructors, if you
>would?

My understanding is that a constructor is useful to make sure that the 
object and its default values are initialised properly.

The __init__ constructor is executed when a class instance is created, 
hence you are sure it runs once (at least in "classic" classes; the rules 
may have changed for the new-type classes in Python 2.2).

Example:

class Foo:
         """Just a silly class."""

         def __init__(self):
                 """Initialise the class."""
                 theList = []

         def addBar(self, bar):
                 """Store bar."""
                 # Here you do not need to test if theList exists.
                 theList.append(bar)


Cheers.

Alexandre




From scarblac@pino.selwerd.nl  Wed Apr 10 10:52:01 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Wed, 10 Apr 2002 11:52:01 +0200
Subject: [Tutor] constructors
In-Reply-To: <4.3.2.7.2.20020410105201.00b70ac0@pop3.norton.antivirus>; from alex@gabuzomeu.net on Wed, Apr 10, 2002 at 11:41:20AM +0200
References: <20020410025001.6193.34023.Mailman@mail.python.org> <4.3.2.7.2.20020410105201.00b70ac0@pop3.norton.antivirus>
Message-ID: <20020410115201.A9394@pino.selwerd.nl>

On  0, Alexandre Ratti <alex@gabuzomeu.net> wrote:
> Example:
> 
> class Foo:
>          """Just a silly class."""
> 
>          def __init__(self):
>                  """Initialise the class."""
>                  theList = []
> 
>          def addBar(self, bar):
>                  """Store bar."""
>                  # Here you do not need to test if theList exists.
>                  theList.append(bar)

Oops. You need to use 'self.theList' instead of just 'theList' in both
cases, the way you have it now won't work. Just a correction.

-- 
Remco Gerlich



From alex@gabuzomeu.net  Wed Apr 10 11:45:25 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 10 Apr 2002 12:45:25 +0200
Subject: [Tutor] constructors
Message-ID: <4.3.2.7.2.20020410124054.00cf0100@pop3.norton.antivirus>

Hello,


here is a corrected version (thanks Remco). Sorry folks, I should have 
tested the code before sending it.


At 22:50 09/04/2002 -0400, you wrote:
>Date: Tue, 9 Apr 2002 22:34:37 -0400
>From: Erik Price <erikprice@mac.com>
>Subject: [Tutor] constructors
>
>When writing a class, is it recommended to always take advantage of
>constructors?  I have written a class called Person, which helps me to
>organize my user-input error-checking (by confining error-checking
>functions to the methods that set instance attributes).  I don't have a
>constructor, because sometimes I use this class to build a new Person
>and sometimes I use this class to pull an already-existing Person's
>attributes from a database table.  But constructors are seen as a
>"really good thing", but as far as I can see a constructor is just a
>shortcut.  Please share your thoughts on using constructors, if you
>would?

My understanding is that a constructor is useful to make sure that the 
object and its default values are initialised properly.

The __init__ constructor is executed when a class instance is created, 
hence you are sure it runs once (at least in "classic" classes; the rules 
may have changed for the new-type classes in Python 2.2).

Example:

class Foo:
     """Just a silly class."""

     def __init__(self):
         """Initialise the class."""
         self.theList = []

     def addBar(self, bar):
         """Store bar."""
         # Here you do not need to test if theList exists.
         self.theList.append(bar)
         print self.theList

 >>> foo = Foo()
 >>> foo.addBar("truc")
 >>> ['truc']


Cheers.

Alexandre




From erikprice@mac.com  Wed Apr 10 12:35:13 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 10 Apr 2002 07:35:13 -0400
Subject: [Tutor] constructors
In-Reply-To: <4.3.2.7.2.20020410124054.00cf0100@pop3.norton.antivirus>
Message-ID: <0610390F-4C77-11D6-A863-00039351FE6A@mac.com>

On Wednesday, April 10, 2002, at 06:45  AM, Alexandre Ratti wrote:

> My understanding is that a constructor is useful to make sure that the 
> object and its default values are initialised properly.

Since Python is loosely/weakly/dynamically typed, does initializing 
really matter a great deal?  Or is it just to allow us to use 
polymorphism in a later method (by not requiring that later method to 
specify a tuple over a list, for instance, because a tuple has already 
been specified in the constructor, which makes the later method more 
"general").

> The __init__ constructor is executed when a class instance is created, 
> hence you are sure it runs once (at least in "classic" classes; the 
> rules may have changed for the new-type classes in Python 2.2).

I am using 2.2 and probably won't need to use an older version.  But can 
you tell me a bit more about "new-type classes"?  And how they're 
different from "classic" classes?



Thank you,

Erik




From erikprice@mac.com  Wed Apr 10 12:38:33 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 10 Apr 2002 07:38:33 -0400
Subject: [Tutor] constructors
In-Reply-To: <Pine.LNX.4.44.0204100018050.13779-100000@hkn.eecs.berkeley.edu>
Message-ID: <7D2660A2-4C77-11D6-A863-00039351FE6A@mac.com>

On Wednesday, April 10, 2002, at 03:25  AM, Danny Yoo wrote:

> copy.copy() or copy.deepcopy() should work pretty well with normal 
> Python
> classes, and by defining a __copy__() function, we can control how
> functions are cloned off.
>
> For example:
>
>
> ###
>>>> class Person:
> ...     def __init__(self, name):
> ...         self.name = name
> ...     def greet(self):
> ...         print "Hello, my name is %s" % self.name
> ...     def __copy__(self):
> ...         return Person(self.name.replace('u', 'uu'))
> ...
>>>> import copy
>>>> star = Person("luke")
>>>> star.greet()
> Hello, my name is luke
>>>> cloned_star = copy.copy(star)
>>>> cloned_star.greet()
> Hello, my name is luuke
> ###

I read the "copy" document you linked to, above, but it assumes a priori 
knowledge about cloning to some extent.  What it doesn't explain is 
-why- you would use cloning.  Karthik mentioned that it is similar to 
something done in Java, but I'm still a little confused about cloning -- 
is it simply a "special" (two-underscores) method that you can use to 
flesh out an object instance and make it unique?  That's what the 
example above, with Luke and Luuke, seems to suggest.  Or is there more 
to it?

Thank you,


Erik




From erikprice@mac.com  Wed Apr 10 12:41:13 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 10 Apr 2002 07:41:13 -0400
Subject: [Tutor] constructors
In-Reply-To: <20020410042502.GB5587@dman.ddts.net>
Message-ID: <DC760105-4C77-11D6-A863-00039351FE6A@mac.com>

On Wednesday, April 10, 2002, at 12:25  AM, dman wrote:

> I say use a ctor (called __init__ in python) if you need/want to
> initialize the members of the object to some value when it is created.
> If you don't need/want that, then don't bother writing an empty one.
> I have found that most of the time you do want a ctor (though that
> may be my C++/Java background there).  You can use default arguments
> to allow for variations in usage.  For example :
>
> class Person :
>     def __init__( self , name="Not Specified" , age="Not Specified" ) :

This seems like a sensible idea.  This use of a constructor makes a lot 
more sense to me.

Erik




From karthikg@aztec.soft.net  Wed Apr 10 13:15:16 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Wed, 10 Apr 2002 17:45:16 +0530
Subject: [Tutor] constructors
In-Reply-To: <7D2660A2-4C77-11D6-A863-00039351FE6A@mac.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDCEGADJAA.karthikg@aztec.soft.net>

> From: Erik Price [mailto:erikprice@mac.com]
> I read the "copy" document you linked to, above, but it assumes a priori
> knowledge about cloning to some extent.  What it doesn't explain is
> -why- you would use cloning.  Karthik mentioned that it is similar to
> something done in Java, but I'm still a little confused about cloning --
> is it simply a "special" (two-underscores) method that you can use to
> flesh out an object instance and make it unique?  That's what the
> example above, with Luke and Luuke, seems to suggest.  Or is there more
> to it?

you would do cloning to achieve exactly what you wanted to..
ie get a new instance (ie clone the instance) of a class from an existing
one with all it's attributes copied.

Using the copy module happens to be a *standard* way of getting a copy in
python.
So a client who uses your class will call copy.deepcopy() to achieve it
since it is the norm.

You could very well give another method (say getCopy()) to do the same.
But then you w'd be required to educate the client about this new method!
which ideally you w'd'nt want to.

If you don't give an implementation of __copy__ (clone equivalent), copy
module would use
the default implementation. ie make a copy of all the attributes.

Next comes something called shallow copying. which i guess copy.copy() does.
Danny correct me! ..:-)..

But as Danny pointed out, you can give your own implementation of __copy__()
(which is what copy module
actually calls) and do something different.
In this case he does return another instance with a small change in the
attribute value.

     def __copy__(self):
         return Person(self.name.replace('u', 'uu'))


HTH,
karthik.




From alex@gabuzomeu.net  Wed Apr 10 13:20:49 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 10 Apr 2002 14:20:49 +0200
Subject: [Tutor] constructors
In-Reply-To: <0610390F-4C77-11D6-A863-00039351FE6A@mac.com>
References: <4.3.2.7.2.20020410124054.00cf0100@pop3.norton.antivirus>
Message-ID: <4.3.2.7.2.20020410140310.00ce2800@pop3.norton.antivirus>

Hello,


At 07:35 10/04/2002 -0400, Erik Price wrote:
>>My understanding is that a constructor is useful to make sure that the 
>>object and its default values are initialised properly.
>
>Since Python is loosely/weakly/dynamically typed, does initializing really 
>matter a great deal?

I believe it makes your code simpler. If you do not initialise a class 
internal variable (is it called a "class member"?), you can't be sure it 
exists at all. Then you'll need to test its existence in every method where 
it is accessed. This may get messy when using many such variables.

>Or is it just to allow us to use polymorphism in a later method (by not 
>requiring that later method to specify a tuple over a list, for instance, 
>because a tuple has already been specified in the constructor, which makes 
>the later method more "general").

I'm not sure about polymorphism in this context. Maybe somebody can elaborate?

>>The __init__ constructor is executed when a class instance is created, 
>>hence you are sure it runs once (at least in "classic" classes; the rules 
>>may have changed for the new-type classes in Python 2.2).
>
>I am using 2.2 and probably won't need to use an older version.  But can 
>you tell me a bit more about "new-type classes"?  And how they're 
>different from "classic" classes?

I haven't used the new classes yet; I understand they allow you to subclass 
build-in types such as lists or dictionaries. There are other differences. 
See:

http://www.amk.ca/python/2.2/index.html#SECTION000310000000000000000


Cheers.

Alexandre




From pythontutor@venix.com  Wed Apr 10 13:22:40 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed, 10 Apr 2002 08:22:40 -0400
Subject: [Tutor] constructors
References: <7D2660A2-4C77-11D6-A863-00039351FE6A@mac.com>
Message-ID: <3CB42E90.8020403@venix.com>

I will clone an object before passing it on to a User Interface edit routine.
If the user presses CANCEL, I stick with the original.  If they exit with OK,
I keep the object with their changes.

Also note that Python supports an alternative way to have default values.  You
can define them at the class level.

 >>> class Person:
... 	name = "Not Specified"
... 	age = "Not Specified"
... 	
 >>> newguy = Person()
 >>> newguy.name
'Not Specified'
 >>> newguy.name = "Erik"
 >>> newguy.name
'Erik'
 >>> Person.name
'Not Specified'

I have found class level defaults very useful for classes that represent
database tables.  The class defaults can easily be built from information
provided by the database.

Erik Price wrote:

> 
> On Wednesday, April 10, 2002, at 03:25  AM, Danny Yoo wrote:
> 
>> copy.copy() or copy.deepcopy() should work pretty well with normal Python
>> classes, and by defining a __copy__() function, we can control how
>> functions are cloned off.
>>
>> For example:
>>
>>
>> ###
>>
>>>>> class Person:
>>>>
>> ...     def __init__(self, name):
>> ...         self.name = name
>> ...     def greet(self):
>> ...         print "Hello, my name is %s" % self.name
>> ...     def __copy__(self):
>> ...         return Person(self.name.replace('u', 'uu'))
>> ...
>>
>>>>> import copy
>>>>> star = Person("luke")
>>>>> star.greet()
>>>>
>> Hello, my name is luke
>>
>>>>> cloned_star = copy.copy(star)
>>>>> cloned_star.greet()
>>>>
>> Hello, my name is luuke
>> ###
> 
> 
> I read the "copy" document you linked to, above, but it assumes a priori 
> knowledge about cloning to some extent.  What it doesn't explain is 
> -why- you would use cloning.  Karthik mentioned that it is similar to 
> something done in Java, but I'm still a little confused about cloning -- 
> is it simply a "special" (two-underscores) method that you can use to 
> flesh out an object instance and make it unique?  That's what the 
> example above, with Luke and Luuke, seems to suggest.  Or is there more 
> to it?
> 
> Thank you,
> 
> 
> Erik
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From alan.gauld@bt.com  Wed Apr 10 15:14:00 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 10 Apr 2002 15:14:00 +0100
Subject: [Tutor] constructors
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53C@mbtlipnt02.btlabs.bt.co.uk>

> On Tue, Apr 09, 2002 at 10:34:37PM -0400, Erik Price wrote:
> | When writing a class, is it recommended to always take advantage of 
> | constructors?  

> | and sometimes I use this class to pull an already-existing Person's 
> | attributes from a database table.  

This ties us back to the arlier comments about overridding.
In C++ and Delphi you can override constructors 
- unfortunately you can't do that in Python.
So you could have a non parameterised list that created a 
brand new 'empty' person. A parameterised one that created 
a full blown person and a third that took a personID that 
instantiated the person from the database. In C++/Java the 
constructors would all have the same name in Delphi you 
can give them different names because they are actually 
class methods. thus you would call:

P1 := Person.New	// no args, empty person

P2 := Person.Create('Alan','Gauld', 43, 'M', 8795)  // with attributes

P3 = Person.Read(OracleID, PersonID)  // from database with ID

Thuis constructors are still 'a good thing' provided you can write several
versions.

In Python we fake it with default params and key values:

class Person:
   def __init__(self, 
                name1='',name2='',age=0,sex='',phone=0,  #attributes
                dbID=0,PID=0)					   #
database
      if dbID: #get from DB
      elif name: # set attributes
      else: just zero everything


Now we can create persons with:

p = Person('Al','Gauld',44,'M',8795)

OR

p = Person(dbID = OracleID, PID = PersonID)

OR

p = Person()

But if you really don't have anything useful to do in the 
constructor then its not necessary. Never write code just
for the sake of it!

Alan G.



From alan.gauld@bt.com  Wed Apr 10 15:17:15 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 10 Apr 2002 15:17:15 +0100
Subject: [Tutor] An example of something extremely difficult to expres s in
 Java
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53D@mbtlipnt02.btlabs.bt.co.uk>

> can someone give me neat examples of something which
> is *extremely* difficult to express in java but can be easily
> represented in python?

Not *extremely* difficult in Java(at least not Java2) but 
a pain none the less is anything which takes a function 
as a parameter. Try writing the Python map() function 
in Java say... Thats not too bad, now try using it for 
a few cases... You'll soon see what I mean.

Now try writing Danny differentiator function builder....


Alan G.



From alan.gauld@bt.com  Wed Apr 10 15:23:25 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 10 Apr 2002 15:23:25 +0100
Subject: [Tutor] constructors
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53E@mbtlipnt02.btlabs.bt.co.uk>

> My understanding is that a constructor is useful to make 
> sure that the object and its default values are initialised 
> properly.

That's the best reason. It ensures that the "pre conditions" 
of the objects methods are all met. Usually that translates 
to setting attributes but it could also be things like 
checking a hardware device was functioning correctly or 
even existed. This saves each and every function from doing the precondition
check itself. (Actually for hardware you 
probably should still check coz somebody might unplug it!)

It also means you the user get a check on whether its even 
worth attempting the operation.

Alan g.



From tjenkins@devis.com  Wed Apr 10 15:33:43 2002
From: tjenkins@devis.com (Tom Jenkins)
Date: 10 Apr 2002 10:33:43 -0400
Subject: [Tutor] ActiveX containers
In-Reply-To: <3CB193A1.775BC6D9@groton.pfizer.com>
References: <3CB193A1.775BC6D9@groton.pfizer.com>
Message-ID: <1018449224.3445.41.camel@asimov>

On Mon, 2002-04-08 at 08:57, Pfizer Inc wrote:
> Hi-
> 
> Is there an activeX container for Python?  I'd like to integrate an RTF
> object into my Python application.
> 
> I'm using a wxFrame.
> 

Since it looks like you are using wxPython (wxFrame) then there is a
component _I_THINK_ in wxPython that is an activeX container.  The
wxPython mailing list is
http://lists.wxwindows.org/mailman/listinfo/wxpython-users

-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com





From shendric@arches.uga.edu  Wed Apr 10 16:36:31 2002
From: shendric@arches.uga.edu (shendric@arches.uga.edu)
Date: Wed, 10 Apr 2002 10:36:31 -0500
Subject: [Tutor] CGI pitfalls
Message-ID: <1018449391.smmsdV1.1.1@mail.arches.uga.edu>

Hi all,

I wrote a small cgi progam for a website that I'm maintaining and I was 
wondering what security issues I should be considering.  Right now, the 
program simply provides a way to dynamically create pages for the site, 
which will make it easier to maintain as the site grows.

There is a base webpage that includes links that call the cgi with an id 
variable:

http://www.uga.edu/lsava-bin/archivetest.cgi?id=Smith

as an example.

The cgi then uses that id to look up appropriate links related to that 
id and create a page of links.

What I'm concerned with would be the kinds of things a person (say a 
*bad* person) might be able to do by putting something in the id 
variable.

Any thoughts?

Sean





From dman@dman.ddts.net  Wed Apr 10 16:04:22 2002
From: dman@dman.ddts.net (dman)
Date: Wed, 10 Apr 2002 10:04:22 -0500
Subject: [Tutor] constructors
In-Reply-To: <7D2660A2-4C77-11D6-A863-00039351FE6A@mac.com>
References: <Pine.LNX.4.44.0204100018050.13779-100000@hkn.eecs.berkeley.edu> <7D2660A2-4C77-11D6-A863-00039351FE6A@mac.com>
Message-ID: <20020410150421.GB9778@dman.ddts.net>

On Wed, Apr 10, 2002 at 07:38:33AM -0400, Erik Price wrote:
| On Wednesday, April 10, 2002, at 03:25  AM, Danny Yoo wrote:
 
| I read the "copy" document you linked to, above, but it assumes a priori 
| knowledge about cloning to some extent.  What it doesn't explain is 
| -why- you would use cloning.

You would use cloning any time you wanted a duplicate of an object.
Typically this is used in algorithms or implementations that act
"destructively" on the object.

For example, suppose you were testing out a Stack class and wanted to
print out the entire contents of the stack.  A stack only has "push"
and "pop" operations.  Thus you need to "pop" each item off the stack
in order to print it and get the next one.  However, that destroys the
stack.  So you can first make a clone and use that for printing,
keeping the original safe and sound.  (this example could also be done
with two stacks -- push the popped object on the second stack, and
reverse it when you are done; I think a shallow copy would be the most
efficient method here but you'd have to profile it to find out; the
copy method is also better in a multi-threaded environment where other
threads still need to use the stack while you're traversing it)

-D

-- 

The truly righteous man attains life,
but he who pursues evil goes to his death.
        Proverbs 11:19




From dman@dman.ddts.net  Wed Apr 10 16:10:32 2002
From: dman@dman.ddts.net (dman)
Date: Wed, 10 Apr 2002 10:10:32 -0500
Subject: [Tutor] constructors
In-Reply-To: <0610390F-4C77-11D6-A863-00039351FE6A@mac.com>
References: <4.3.2.7.2.20020410124054.00cf0100@pop3.norton.antivirus> <0610390F-4C77-11D6-A863-00039351FE6A@mac.com>
Message-ID: <20020410151032.GC9778@dman.ddts.net>

On Wed, Apr 10, 2002 at 07:35:13AM -0400, Erik Price wrote:
| On Wednesday, April 10, 2002, at 06:45  AM, Alexandre Ratti wrote:
 
| >The __init__ constructor is executed when a class instance is created, 
| >hence you are sure it runs once (at least in "classic" classes; the 
| >rules may have changed for the new-type classes in Python 2.2).
| 
| I am using 2.2 and probably won't need to use an older version.  But can 
| you tell me a bit more about "new-type classes"?  And how they're 
| different from "classic" classes?

If you're not doing anything special, they are the same.  The
differences are :
    o   all have a common ancestor class 'object'
    o   since the built-in types are now new-style classes you can
            subclass them (this makes your class a new-style class)
    o   attributes (see amk's summary for a brief explanation of them,
            and compare that to java "properties")
    o   superclass method lookups -- a "diamond" inheritance tree now
            works as expected (it used to be like C++ and Java, which
            don't quite work as intuitively expected)
    o   maybe something else I forgot, but see amk's "What's New"
            summary for a list of changes

-D

-- 

"Wipe Info uses hexadecimal values to wipe files. This provides more 
security than wiping with decimal values." -- Norton SystemWorks 2002 Manual




From ddjones_70@yahoo.com  Wed Apr 10 16:54:10 2002
From: ddjones_70@yahoo.com (Daniel Jones)
Date: Wed, 10 Apr 2002 08:54:10 -0700 (PDT)
Subject: [Tutor] Newbie help
Message-ID: <20020410155410.99599.qmail@web20803.mail.yahoo.com>

I just got into python about 2 weeks ago and need some possible direction. I am
workin on a script for the company I am working for that removes all temporary
files from Windoze 95 systems. The script needs to search for these types of
files - *.chk *.tmp *.wbk & ~*.* . Can anyone point me in the right direction?

__________________________________________________
Do You Yahoo!?
Yahoo! Tax Center - online filing with TurboTax
http://taxes.yahoo.com/



From linuxconsul@yahoo.com.br  Wed Apr 10 10:09:36 2002
From: linuxconsul@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Wed, 10 Apr 2002 06:09:36 -0300
Subject: [Tutor] Problems understanding semantics of readlines()
In-Reply-To: <3CB2A18C.CDE0B364@shaw.ca>
References: <20020409070957.GA3944@ime.usp.br> <3CB2A18C.CDE0B364@shaw.ca>
Message-ID: <20020410090936.GA831@ime.usp.br>

	First of all, Paul, thank you very much for your answer.

On Apr 09 2002, Paul Sidorsky wrote:
> No, the parameter is called sizeHINT (my emphasis) because it's just a
> suggestion.  Results should be expected to vary by platform and
> implementation, as you already discovered.  From the library reference:

	Yes, I read the library reference before posting here. I tried
	to do my homework as well as I could (as I always try). :-)

> > If given an optional parameter sizehint, it reads that many bytes 
> > from the file and enough more to complete a line, and returns the 
> > lines from that. 
> 
> Thus you're guaranteed to get the entire first line no matter what
> size you ask for.

	No problems here.

> As for the second line, I suspect (though this is a bit of a guess)
> that there was enough room left over in the internal buffer to grab
> the entire second line because the first line was 128K+1 bytes and
> the buffer was probably a multiple of 512 or 1K bytes.  So you got
> the second line for free, whether you wanted it or not.

	Well, I'd prefer if the semantics of the functions were more
	clearly defined. In my understanding, the function is supposed
	to work in the way that Jython does it, not in the way that
	CPython does.

	Anyway, I tried the following program and I still see the b's
	appearing in my list:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#!/usr/bin/python

f = open("/tmp/file.txt", "w+")
f.write("a"*128*1024+"\n"+"b"*1024*1024) # notice the lack of \n after b's
f.seek(0)
print f.readlines(10)
f.close()
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

> I think readlines(sizehint) has been semi-deprecated by xreadlines(). 

	I don't know if it is that much relevant here, since
	readlines() is still available.

> (Perhaps the tutorial should be updated?)

	I didn't see any mentions of it being buggy or deprecated,
	though, besides, according to the documentation of
	xreadlines(), readlines() shouldn't be deprecated so soon.

> You can use f.xreadlines() to iterate over a file on a guaranteed
> per-line basis with the same efficient memory usage.

	My idea wasn't exactly to iterate over a file. :-) I am just a
	newbie (in Python, but not in Programming) trying the examples
	of the tutorial. :-)

> Actually, according to the docs, xreadlines() uses
> readlines(sizehint) to do its thing, but it's cleaner and more
> predictable.

	I can see why it would be "cleaner" (relatively), but I don't
	see why why it would be more predictable. Could you elaborate
	on the predictability? I'd like to keep myself aside from the
	unpredictable parts of the language, with the exception of
	(pseudo)random number generators. :-)
	
	Anyway, I tried the following code and the behavior still
	included the b's:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#!/usr/bin/python

import xreadlines;

f = open("/tmp/file.txt", "w+")
f.write("a"*128*1024+"\n"+"b"*1024*1024) # notice the lack of \n after b's
f.seek(0)
lines = []
for l in xreadlines.xreadlines(f): lines.append(l)
print lines
f.close()
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	Any help here?

> One last thing to note is that the second line won't have a \n at
> the end because one was not written to the end of the file.
> readline() & readlines() won't add one if one doesn't exist.

	Oh, yes. It was intentional that the last line wasn't
	terminated because I read in the tutorial that "Only complete
	lines will be returned". :-(

	I was testing that. I was a bit disappointed by the divergence
	of the documentation and of the observed behaviour. :-(

	Am I using the functions in illegal ways? If not, should the
	documentation be changed or should it be reported as a bug?
	Any help here is more than welcome.

> Hope that helps.  BTW I got the same results you did using WinME &
> Python 2.1.

	Well, I'd expect that, since (I'm guessing) the implementation
	of both is based on the CPython sources, right? (I'm not sure
	what I'm talking about in this paragraph).


	Thank you very much for your kind answer, Roger...

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



From linuxconsul@yahoo.com.br  Wed Apr 10 10:09:36 2002
From: linuxconsul@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Wed, 10 Apr 2002 06:09:36 -0300
Subject: [Tutor] Problems understanding semantics of readlines()
In-Reply-To: <3CB2A18C.CDE0B364@shaw.ca>
References: <20020409070957.GA3944@ime.usp.br> <3CB2A18C.CDE0B364@shaw.ca>
Message-ID: <20020410090936.GA831@ime.usp.br>

	First of all, Paul, thank you very much for your answer.

On Apr 09 2002, Paul Sidorsky wrote:
> No, the parameter is called sizeHINT (my emphasis) because it's just a
> suggestion.  Results should be expected to vary by platform and
> implementation, as you already discovered.  From the library reference:

	Yes, I read the library reference before posting here. I tried
	to do my homework as well as I could (as I always try). :-)

> > If given an optional parameter sizehint, it reads that many bytes 
> > from the file and enough more to complete a line, and returns the 
> > lines from that. 
> 
> Thus you're guaranteed to get the entire first line no matter what
> size you ask for.

	No problems here.

> As for the second line, I suspect (though this is a bit of a guess)
> that there was enough room left over in the internal buffer to grab
> the entire second line because the first line was 128K+1 bytes and
> the buffer was probably a multiple of 512 or 1K bytes.  So you got
> the second line for free, whether you wanted it or not.

	Well, I'd prefer if the semantics of the functions were more
	clearly defined. In my understanding, the function is supposed
	to work in the way that Jython does it, not in the way that
	CPython does.

	Anyway, I tried the following program and I still see the b's
	appearing in my list:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#!/usr/bin/python

f = open("/tmp/file.txt", "w+")
f.write("a"*128*1024+"\n"+"b"*1024*1024) # notice the lack of \n after b's
f.seek(0)
print f.readlines(10)
f.close()
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

> I think readlines(sizehint) has been semi-deprecated by xreadlines(). 

	I don't know if it is that much relevant here, since
	readlines() is still available.

> (Perhaps the tutorial should be updated?)

	I didn't see any mentions of it being buggy or deprecated,
	though, besides, according to the documentation of
	xreadlines(), readlines() shouldn't be deprecated so soon.

> You can use f.xreadlines() to iterate over a file on a guaranteed
> per-line basis with the same efficient memory usage.

	My idea wasn't exactly to iterate over a file. :-) I am just a
	newbie (in Python, but not in Programming) trying the examples
	of the tutorial. :-)

> Actually, according to the docs, xreadlines() uses
> readlines(sizehint) to do its thing, but it's cleaner and more
> predictable.

	I can see why it would be "cleaner" (relatively), but I don't
	see why why it would be more predictable. Could you elaborate
	on the predictability? I'd like to keep myself aside from the
	unpredictable parts of the language, with the exception of
	(pseudo)random number generators. :-)
	
	Anyway, I tried the following code and the behavior still
	included the b's:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#!/usr/bin/python

import xreadlines;

f = open("/tmp/file.txt", "w+")
f.write("a"*128*1024+"\n"+"b"*1024*1024) # notice the lack of \n after b's
f.seek(0)
lines = []
for l in xreadlines.xreadlines(f): lines.append(l)
print lines
f.close()
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

	Any help here?

> One last thing to note is that the second line won't have a \n at
> the end because one was not written to the end of the file.
> readline() & readlines() won't add one if one doesn't exist.

	Oh, yes. It was intentional that the last line wasn't
	terminated because I read in the tutorial that "Only complete
	lines will be returned". :-(

	I was testing that. I was a bit disappointed by the divergence
	of the documentation and of the observed behaviour. :-(

	Am I using the functions in illegal ways? If not, should the
	documentation be changed or should it be reported as a bug?
	Any help here is more than welcome.

> Hope that helps.  BTW I got the same results you did using WinME &
> Python 2.1.

	Well, I'd expect that, since (I'm guessing) the implementation
	of both is based on the CPython sources, right? (I'm not sure
	what I'm talking about in this paragraph).


	Thank you very much for your kind answer, Roger...

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



From hall@nhn.ou.edu  Wed Apr 10 19:15:44 2002
From: hall@nhn.ou.edu (Isaac Hall)
Date: Wed, 10 Apr 2002 13:15:44 -0500
Subject: [Tutor] event binding
Message-ID: <02041013345100.24647@ouhep1>

Hi everyone:

I was wondering if anyone with Tkinter experience and/or Pmw experience can
help me

Right now I have this class we will call MyClass for this letter
and there are several instances of MyClass gridded in a notebook,  one per page.

Now MyClass is set to display some histograms and such (defined by another
class, but that isnt the important part).....so without trying to explain too
much, Ill give you example code


class MyClass(Frame):
	def __init__(self, parent, <otherstuff>):
		<do something not really important with the otherstuff>
		self.bind("<Visibility>", self.update_graphics)  #IMPORTANT

	def onUpdate(self):
		if self.winfo_viewable:
			<update our display>	
		#this guy exists so we can also update from outside
		#the class (but only if we can see it)
		<do some other not really important stuff>

	def update_graphics(self, event):
		self.onUpdate()


so as you can see here, the idea is that the outside can call the update
function but the graphics only get updated (since this takes up most of the
time for the program) when we are looking at the instance of MyClass.
and if we happen to switch pages in between updates from the outside, the
MyClass instance we switch to should call its update method and pop up the
pretty pictures.  However, this does not seem to work as planned.  Instead the
updating takes place twice when pages are switched (and although I can probably
work around that bug, I would rather have it not exist)  so I am wondering if
there is anything I am doing wrong in order to have this happen the way I want
it to.  Like maybe a better event binding to use or something,  or even a
self-defined event (I don't feel comfortable making those), so if someone could
help here, (even if it is to show me how to create events to bind to, wether or
not that is helpful in this case) I would greatly appreciate it.

Thank you in advance  :)

Ike



From shalehperry@attbi.com  Wed Apr 10 19:44:04 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 10 Apr 2002 11:44:04 -0700 (PDT)
Subject: [Tutor] Newbie help
In-Reply-To: <20020410155410.99599.qmail@web20803.mail.yahoo.com>
Message-ID: <XFMail.20020410114404.shalehperry@attbi.com>

On 10-Apr-2002 Daniel Jones wrote:
> I just got into python about 2 weeks ago and need some possible direction. I
> am
> workin on a script for the company I am working for that removes all
> temporary
> files from Windoze 95 systems. The script needs to search for these types of
> files - *.chk *.tmp *.wbk & ~*.* . Can anyone point me in the right
> direction?
> 

look at the 'os' and 'os.path' modules.



From budgester@budgester.com  Wed Apr 10 20:32:06 2002
From: budgester@budgester.com (Martin Stevens)
Date: Wed, 10 Apr 2002 20:32:06 +0100
Subject: [Tutor] Tk and Classes
Message-ID: <20020410193206.GA1832@akira.budgenet>

Hi, I'm probably going about this the wrong way, but i'm trying to teach
myself classes and TK at the same time (They seem very interwoven)

Here the code.
============
from Tkinter import *
import sys


class food:
 def showfood(chosen):
  newform = Toplevel()
  Button(newform, text=chosen).pack()

root = Tk()
FoodOption = StringVar()
FoodOption.set('Spam')
OptionMenu(root, FoodOption , 'Spam', 'Egg', 'Chips', command=food.showfood(FoodOption)).pack()

Button(root, text = 'quit', command=sys.exit).pack()

root.mainloop()

============

and this is the error

TypeError: unbound method showfood() must be called with instance as first argument

Can someone explain what i'm doing wrong, or modify the example so it works 
and i can see what changed.

Thanks

Budgester

-- 
Budgester Technologies Ltd
Office : 01992 718568
Mobile : 07815 982380
mailto:martin@budgester.com
http://www.budgester.com



From wolf_binary@hotmail.com  Wed Apr 10 20:35:18 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Wed, 10 Apr 2002 14:35:18 -0500
Subject: [Tutor] nested functions  [differentation / C++ comparision]
References: <Pine.LNX.4.44.0204091718290.32473-100000@hkn.eecs.berkeley.edu>
Message-ID: <DAV54F98vvwNeZsjSFU00001baf@hotmail.com>

I put your test code in and it give me this error:

diffed_square = diff(square)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in ?
    diffed_square = diff(square)
NameError: name 'square' is not defined

I don't quite understand how this function in a function thing works with
what you put down for here:

> The above definition is just something I pulled out of a calculus book,
> and is only a numerical approximation.  Still, it should work well enough
> for this example.  Let's see how it works:
>
> ###
> >>> diffed_square = diff(square)
> >>> square(10)
> 100
> >>> diffed_square(10)
> 20.000099999890608
> ###

Square isn't defined so what are you passing into diff?  I am very
interested in this making code on the fly building idea.  It has so many
possibilities.

Cameron Stoner


>
> On Tue, 9 Apr 2002, Pijus Virketis wrote:
>
> > Cameron,
> >
> > >Why would you want to define functions inside functions?  It seems
> > >kinda like a class with methods.  When would you want to do
> > > something like this?
> >
> > Not that I take advantage of this possibility often, but you could have
> > your code generate other code on the fly: it's the big selling point of
> > LISP and its dialects, as far as I know. You recognise some input, and
> > then you create create the right function. The rest of your code can
> > expect "foo()" to be the right tool for the job in the context, no
> > matter what had to go into making it.
>
>
> Here's a math-motivated example.  In Calculus, there's an operation called
> 'differentiation' that works on many mathy functions.  For example, the
> function:
>
>     f(x) = x^2
>
> has the derivative:
>
>     d f(x) = 2x
>    ---
>    dx
>
> (Differentiation tells us that if we take a tangent line to the point, (x,
> f(x)), we'll find the slope is equal to the value of the differentated
> function at that point too.)
>
>
> What's particularly unique about differentiation is that it's main
> target are functions!  That is, differentiation take a function, and
> returns a whole new function.
>
> We can model this in Python --- we can imagine some Python function called
> 'diff' that takes in a function, and returns its derivative.  Here's a
> sample implementation:
>
> ###
> def diff(f, epsilon=0.0001):
>     """We take the function f and creates a whole new function g that
>     approximates the derivative of f."""
>     def g(x):
>         return (f(x+epsilon) - f(x)) / epsilon
>     ## The key step here is to return this new g function!
>     return g
> ###
>
>
> When we make functions that return new functions, we'll find ourselves
> creating an inner function definition, just so we can give it to someone
> else.
>
>

TOOK CODE FROM HERE

>
>
>
> C++ doesn't allow us do do wacky things like writing functions in
> functions.  However, we can can simulate this effect with the judicious
> use of classes.  Here's what the example with differentiation would look
> like in C++:
>
> //////
> #include <iostream>
>
> class Function {
>     // Here, we define that a Function is something that knows how
>     // to evaluate itself at a certain point 'x'.
> public:
>     virtual float eval(float x) = 0;
> };
>
>
> class SquareFunction : public Function {
>     // Here's one particular example of a Function class.
> public:
>     float eval(float x) {
>         return x * x;
>     }
> };
>
>
> class DiffFunction : public Function {
>     // We can differentiate a particular Function instance by using
>     // DifferentiatedFunction.
> public:
>     DiffFunction(Function *f, float epsilon=0.0001) {
>         this->f = f;
>         this->epsilon=epsilon;
>     }
>     float eval(float x) {
>         return (f->eval(x + epsilon) - f->eval(x)) / epsilon;
>     }
>     Function *f;
>     float epsilon;
> };
>
>
> // Small test function
> int main() {
>     cout << "Let's test this out.\n";
>     Function *square = new SquareFunction;
>     Function *diff_square = new DiffFunction(square);
>     cout << square->eval(10) << " is what square(10) gives us.\n";
>     cout << diff_square->eval(10) << "is what diff_square(10) "
>          << "gives us.\n";
>     return 0;
> }
> //////
>
>
> But as you can tell, this is somewhat... painful compared to the Python
> code.  *grin* So it's possible to live without being able to make nested
> functions if we have classes, but the resulting code is just not as
> elegant or straightforward as the nested-function approach.
>
>
> We can give more examples of functions in functions that aren't math
> related.  I just picked the math one because I was reviewing tangents and
> limits last night.
>
> If you have more questions, please feel free to ask!  Good luck!
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From bryce@bembry.org  Wed Apr 10 20:56:49 2002
From: bryce@bembry.org (Bryce Embry)
Date: Wed, 10 Apr 2002 14:56:49 -0500
Subject: [Tutor] Tk and Classes
In-Reply-To: <20020410193206.GA1832@akira.budgenet>
Message-ID: <5.1.0.14.0.20020410143351.00af1b18@www.bembry.org>

Martin,
I thought about taking that same approach (learning classes and Tkinter 
simultaneously),  but I ended up doing learning first.  I would strongly 
recommend choosing one of these to learn first and going from there.

The problem with the class you posted is that every function (aka method) 
in a class must take itself as an argument (have "self" in the 
parenthesis).  So, you should have:

class food:
         def showfood(self, chosen):
                 # Your commands here

Whenever you call a class you create an instance of the class.  To access 
the function (method) inside the class, the class needs to know which 
instance of the class is calling it, so the first argument passed in is 
essentially saying "who am I".  These keeps your different calls to the 
class from getting all crossed up and confused.

Again, I would recommend learning Tkinter and classes separately.  They are 
two different concepts and its hard to wrap your head around them both at 
the same time.   I can understand wnating to learn them simultaneously, 
especially since so many Tkinter tutorials rely very heavily on 
classes.  But Tkinter will work fine without using classes.

If you want to learn Tkinter first, you can check out the notes I have 
online (www.bembry.org/tech/python).  I am currently teaching Tkinter to my 
high school class, and the notes do not assume an understanding of 
classes.  I have the notes from the first two lessons up and the students 
have found it "very easy" (personally, it's been a big challenge to make it 
easy for them).  The next lesson should be up by tomorrow.

For learning classes, I'd suggest http://www.devshed.com/Server_Side/Python 
and check the OOP tutorials.  I found these very useful. I also have some 
notes on my website which you might find useful.

Hope that helps.  Good luck.

Bryce Embry

At 02:32 PM 4/10/2002, you wrote:
>Hi, I'm probably going about this the wrong way, but i'm trying to teach
>myself classes and TK at the same time (They seem very interwoven)
>
>Here the code.
>============
>from Tkinter import *
>import sys
>
>
>class food:
>  def showfood(chosen):
>   newform = Toplevel()
>   Button(newform, text=chosen).pack()
>
>root = Tk()
>FoodOption = StringVar()
>FoodOption.set('Spam')
>OptionMenu(root, FoodOption , 'Spam', 'Egg', 'Chips', 
>command=food.showfood(FoodOption)).pack()
>
>Button(root, text = 'quit', command=sys.exit).pack()
>
>root.mainloop()
>
>============
>
>and this is the error
>
>TypeError: unbound method showfood() must be called with instance as first 
>argument
>
>Can someone explain what i'm doing wrong, or modify the example so it works
>and i can see what changed.
>
>Thanks
>
>Budgester
>
>--
>Budgester Technologies Ltd
>Office : 01992 718568
>Mobile : 07815 982380
>mailto:martin@budgester.com
>http://www.budgester.com
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

--------------------------------------------------------------------------------------------
"Lord, you establish peace for us.
All that we have accomplished
you have done for us" -- Isaiah 26:12




From slime@vsnl.net  Wed Apr 10 21:28:18 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Wed, 10 Apr 2002 16:28:18 -0400
Subject: [Tutor] Music player for various formats
In-Reply-To: <4.3.2.7.2.20020404175549.00cd99f0@pop3.norton.antivirus>
References: <E16t95o-0008La-00@mail.python.org> <4.3.2.7.2.20020404175549.00cd99f0@pop3.norton.antivirus>
Message-ID: <E16vOhV-00028g-00@mail.python.org>

Hi,

On Thu, 04 Apr 2002 Alexandre Ratti spewed into the ether:
[-- snippity --]
> There is a code example in Dive into Python that might help you:
> 
>         http://diveintopython.org/fileinfo_divein.html

Thanks ! This a cool book. But, unfortunately, this does not deal with
anything beyond the ID3 tag :-(

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Better to use medicines at the outset than at the last moment.





From slime@vsnl.net  Wed Apr 10 21:28:20 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Wed, 10 Apr 2002 16:28:20 -0400
Subject: [Tutor] Music player for various formats
In-Reply-To: <Pine.GSO.4.10.10204040702330.881-100000@isis.visi.com>
References: <E16t56D-000586-00@mail.python.org> <Pine.GSO.4.10.10204040702330.881-100000@isis.visi.com>
Message-ID: <E16vOhX-00028g-00@mail.python.org>

Hi,

On Thu, 04 Apr 2002 Tim Wilson spewed into the ether:
> On Thu, 4 Apr 2002, Prahlad Vaidyanathan wrote:
> 
> > Also, I haven't found a decent module to handle MP3 files, and I was
> > wondering if anyone here has seen/written something I could use.
> 
> Pygame can play MP3s. (http://www.pygame.org/) I've got a student
> writing an MP3 player for his spring project.

Hmm .. Just checked, and pygame-1.4 does not seem to support MP3s ...

$ python
Python 2.2 (#2, Feb 25 2002, 20:10:48)
[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> import pygame.mixer
>>> pygame.mixer.init()
>>> sf = pygame.mixer.Sound('test/test.mp3')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  pygame.error: Unrecognized file type (not VOC)
>>>

I've also just asked on the pygame-users list, and am awaiting
replies. Thanks !

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Never buy what you do not want because it is cheap; it will be dear to you.
		-- Thomas Jefferson





From slime@vsnl.net  Wed Apr 10 21:28:21 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Wed, 10 Apr 2002 16:28:21 -0400
Subject: [Tutor] << operator ?
Message-ID: <E16vOhZ-00028g-00@mail.python.org>

Hi,

What does this "<<" operator do ? IIRC, it is a bit-wise shift operator,
but I don't know what that means either :-(

Actually, I didn't come across it till today, when I saw this piece of
code :

"""
class MP3Header:
    ....
    def read_byte(self, prev):
        nextbyte = self.fp.read(1)
        if nextbyte == "":
            return ""
        return (prev << 8) | ord(nextbyte)

    def find_marker(self):
        while 1 :
            data = (ord(self.fp.read(1)) << 8) | ord(self.fp.read(1))
            self.fp.seek(-1, 1)
            if data & 0xffe0 == 0xffe0 :
                self.fp.seek(-1, 1)
                return self.fp.tell()
        return 0
    ...
"""

This operator is used all over the place in this script, and I have no
idea what it does. Please enlighten me.

Thanks !

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Is it weird in here, or is it just me?
		-- Steven Wright





From dyoo@hkn.eecs.berkeley.edu  Wed Apr 10 21:44:02 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Apr 2002 13:44:02 -0700 (PDT)
Subject: [Tutor] nested functions  [differentation / C++ comparision]
In-Reply-To: <DAV54F98vvwNeZsjSFU00001baf@hotmail.com>
Message-ID: <Pine.LNX.4.44.0204101342460.3016-100000@hkn.eecs.berkeley.edu>


On Wed, 10 Apr 2002, Cameron Stoner wrote:

> I put your test code in and it give me this error:
>
> diffed_square = diff(square)
> Traceback (most recent call last):
>   File "<pyshell#1>", line 1, in ?
>     diffed_square = diff(square)
> NameError: name 'square' is not defined

Yikes, I think I forgot to post up my definition of square.  Put this in
front:

###
>>> def square(x): return x * x
...
###

Sorry about that; I didn't copy-and-paste properly.  Try the above first,
and then the diff() example should work.




From paulsid@shaw.ca  Wed Apr 10 21:51:55 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Wed, 10 Apr 2002 14:51:55 -0600
Subject: [Tutor] << operator ?
References: <E16vOhZ-00028g-00@mail.python.org>
Message-ID: <3CB4A5EB.4E4B8BC7@shaw.ca>

Prahlad Vaidyanathan wrote:

> What does this "<<" operator do ? IIRC, it is a bit-wise shift operator,
> but I don't know what that means either :-(

It's a left bit-shift, used to move bits around.  Shifting, or rotating,
bits is like shoving the binary digits.  For example, if you shift
00101101 left a few times:

00101101     (0 shifts)
01011010     (1 shift)
10110100     (2 shifts)
01101000     (3 shifts)

The 1s are not "wrapped" to the other side like one might expect.  In
the above I used 8 bits as the "width", I think Python uses 32.

Of course you can also shift right with >>.  Because no wrapping occurs
the two operations can't strictly be considered inverses, but
conceptually they are.

The code in the posted example is used to construct a word (2 bytes)
from two single bytes.  Shifting left by 8 moves one byte to the "upper"
byte of the word, and OR-ing it with another byte fills the "lower"
byte.

x << y is equivalent to x*(2**y), and x >> y is equivalent to x/(2**y)
(by integer division) but in practice it's much easier to think of the
operations in terms of binary.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From jeff@ccvcorp.com  Wed Apr 10 22:04:52 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 10 Apr 2002 14:04:52 -0700
Subject: [Tutor] Problems understanding semantics of readlines()
References: <20020410202918.12460.10441.Mailman@mail.python.org>
Message-ID: <3CB4A8F4.B6687D0@ccvcorp.com>

> Rogerio Brito <linuxconsul@yahoo.com.br> wrote:
>
> On Apr 09 2002, Paul Sidorsky wrote:
> > As for the second line, I suspect (though this is a bit of a guess)
> > that there was enough room left over in the internal buffer to grab
> > the entire second line because the first line was 128K+1 bytes and
> > the buffer was probably a multiple of 512 or 1K bytes.  So you got
> > the second line for free, whether you wanted it or not.
>
>         Well, I'd prefer if the semantics of the functions were more
>         clearly defined. In my understanding, the function is supposed
>         to work in the way that Jython does it, not in the way that
>         CPython does.

The issue here is that you're interacting with the underlying I/O buffering in unusual ways.
Really, it's almost never done to call readlines() with a sizehint.  If you want to read the entire
file, you use readlines() with no argument.  If the file is too large to fit easily in memory, then
you use xreadlines(), again with no argument.  The reason that the behavior changes between CPython
and Jython is that the underlying I/O buffer systems are different.  Python *tries* to isolate you
from those differences, but by providing sizehints, you're trying to tell it how to do its
business, so that cancels out that attempt at isolation. ;)

FWIW, the semantics *are* clearly defined -- they're just defined as being dependent upon the
underlying implementation.


> > I think readlines(sizehint) has been semi-deprecated by xreadlines().
>
>         I don't know if it is that much relevant here, since
>         readlines() is still available.
>
> > (Perhaps the tutorial should be updated?)
>
>         I didn't see any mentions of it being buggy or deprecated,
>         though, besides, according to the documentation of
>         xreadlines(), readlines() shouldn't be deprecated so soon.

The use of readlines(), with no argument, is not likely to ever be deprecated.  It's the use of the
sizehint in readlines() that's not recommended.  Of course, the fact that it's called sizeHINT
instead of just size is a clue that you may not get exactly what you ask for...


> > Actually, according to the docs, xreadlines() uses
> > readlines(sizehint) to do its thing, but it's cleaner and more
> > predictable.
>
>         I can see why it would be "cleaner" (relatively), but I don't
>         see why why it would be more predictable. Could you elaborate
>         on the predictability? I'd like to keep myself aside from the
>         unpredictable parts of the language, with the exception of
>         (pseudo)random number generators. :-)

The unpredictability is due to the fact that, by specifying a sizehint, you're fiddling with the
I/O buffering mechanisms, which vary depending on the underlying implementation.  (I'd expect
different results, not only between CPython and Jython, but between different platforms under
CPython.)


>         Anyway, I tried the following code and the behavior still
>         included the b's:
>
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> #!/usr/bin/python
>
> import xreadlines;
>
> f = open("/tmp/file.txt", "w+")
> f.write("a"*128*1024+"\n"+"b"*1024*1024) # notice the lack of \n after b's
> f.seek(0)
> lines = []
> for l in xreadlines.xreadlines(f): lines.append(l)
> print lines
> f.close()
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>
>         Any help here?

Well, other than the fact that it's easier to not import xreadlines, and just use f.xreadlines()
instead...  ;)

This is doing exactly what you're telling it to -- it's just that your expectations are not quite
in line with what is really happening....  :)


> > One last thing to note is that the second line won't have a \n at
> > the end because one was not written to the end of the file.
> > readline() & readlines() won't add one if one doesn't exist.
>
>         Oh, yes. It was intentional that the last line wasn't
>         terminated because I read in the tutorial that "Only complete
>         lines will be returned". :-(
>
>         I was testing that. I was a bit disappointed by the divergence
>         of the documentation and of the observed behaviour. :-(

The "divergence" here is in your expectation, not the documentation.  The difference is that
"complete lines" don't necessarily end with '\n' -- they can also end with EOF.  (Obviously, only
the last line of the file can end with EOF, but it is still considered a complete line.)  Thus,
returning the entire line of b's is expected behavior.  Consider that otherwise, using
file.readlines() couldn't be guaranteed to read the entire file.

There's really very little reason to use readlines(sizehint), so the documentation isn't extremely
specific about the vagaries of its use, but it *does* behave as described in the documents, given
the correct reading of the docs.  ;)

Jeff Shannon
Technician/Programmer
Credit International





From kalle@gnupung.net  Wed Apr 10 22:06:46 2002
From: kalle@gnupung.net (Kalle Svensson)
Date: Wed, 10 Apr 2002 23:06:46 +0200
Subject: [Tutor] << operator ?
In-Reply-To: <E16vOhZ-00028g-00@mail.python.org>
References: <E16vOhZ-00028g-00@mail.python.org>
Message-ID: <20020410210646.GB1577@proton.lysator.liu.se>

[Prahlad Vaidyanathan]
> What does this "<<" operator do ? IIRC, it is a bit-wise shift operator,
> but I don't know what that means either :-(

Consider a number, say 4711.  It is represented in the computer as the
binary number 00000000 00000000 00010010 01100111.

When shifted one step to the left (<< 1), this becomes
00000000 00000000 00100100 11001110, or 9422.  This is, as you can
see, twice the original number.

4711 << 8 is 00000000 00010010 01100111 00000000, 1206016, 256 * 4711.

The >> operator works in the same way, but a different direction:
4711 >> 8 is 00000000 00000000 00000000 00010010, 18, 4711 / 256.

Any clearer?

Med utmärkt högaktning,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]



From dyoo@hkn.eecs.berkeley.edu  Wed Apr 10 22:07:22 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 10 Apr 2002 14:07:22 -0700 (PDT)
Subject: [Tutor] << operator ?  [left bitwise shifting]
In-Reply-To: <E16vOhZ-00028g-00@mail.python.org>
Message-ID: <Pine.LNX.4.44.0204101349461.3016-100000@hkn.eecs.berkeley.edu>

On Wed, 10 Apr 2002, Prahlad Vaidyanathan wrote:

> What does this "<<" operator do ? IIRC, it is a bit-wise shift operator,
> but I don't know what that means either :-(

On most computer systems, when computers count, they count in two's
because they don't have ten fingers.  So when we start counting like this:

    "0...1...2...3...4...5...6...7...8...9...10...11...12..."

Computers often do something like this:

    "0...1...10...11...100...101...110...111...1000...1001...1010...1011
     ...1100...1101...1110...1111..."

And this is what we mean when we say that computers count in base-two
arithmetic --- they represent numbers by using on/off switches --- "bits".
On most systems that Python runs on, each integer is made up of 32 bits.


It turns out that bits are really useful because we don't have to say that
32 bits always stand for a number: we can use those bits as 32 individual
"yes/no" choices!


Here's a concrete example: the Unix operating system uses numeric codes to
say if a particular file is readable, writable, or executable --- each
file has a "permission" number connected to it.  The number "7", for
example, has the following bit representation:

    111

and could mean "This file is both readable, writable, and executable."
The number "5" is represented as:

    101

and could mean "This file is readable, not writable, and executable."  So
here we can use a number just for the sake of its bit pattern.


The neat thing to see is that we can use numbers for more than just
arithmetic: we can treat numbers as patterns of ones and zeros.  The left
shift operator '<<' allows us to push the bits of a number toward the
left.  Let's try it out:

###
>>> x = 1
>>> x << 1
2
>>> x << 2
4
>>> x << 3
8
>>> x << 4
16
###

X contains the bit pattern:

    1 == "00000000000000000000000000000001"

(32 bits)  So left shifting it once shoves the leftmost zero out into
space, and moves everything else one place to the left.

    2 == "00000000000000000000000000000010"

And it turns out that when we left shift a number, it effectively
"doubles".


Hope this is making some sort of sense... *grin* Please feel free to ask
more questions about this.




From alex@gabuzomeu.net  Wed Apr 10 22:56:32 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Wed, 10 Apr 2002 23:56:32 +0200
Subject: [Tutor] Music player for various formats
In-Reply-To: <20020410202918.12460.10441.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020410235141.00b74100@pop3.norton.antivirus>

Hi Prahlad,


At 16:29 10/04/2002 -0400, you wrote:
>From: Prahlad Vaidyanathan <slime@vsnl.net>
>Subject: Re: [Tutor] Music player for various formats
>Date: Wed, 10 Apr 2002 16:28:18 -0400

> > There is a code example in Dive into Python that might help you:
> >
> >         http://diveintopython.org/fileinfo_divein.html
>
>Thanks ! This a cool book. But, unfortunately, this does not deal with
>anything beyond the ID3 tag :-(

Yes. I also came across this reference a couple of days ago, but I think it 
also focuses on ID3 tags:

<QUOTE>
id3py

I've released version 1.2 of ID3.py, the simple ID3v1 MP3 tag 
reader/manipulator class for Python.

This version includes an exciting new dictionary-based interface, 
compatible with the ogg.vorbis class, to read all ID3 tags at once. Also, 
the default genre when creating an ID3 tag has been changed from 0 
("Blues") to 255 ("Unknown"). ID3.py is hosted by SourceForge. Its home 
page is:

http://id3-py.sourceforge.net/

You can always download the latest release of ID3.py from:

http://id3-py.sourceforge.net/id3-py.tar.gz
</QUOTE>


Cheers.

Alexandre





From paulsid@shaw.ca  Wed Apr 10 23:21:22 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Wed, 10 Apr 2002 16:21:22 -0600
Subject: [Tutor] nested functions  [differentation / C++ comparision]
References: <Pine.LNX.4.44.0204091718290.32473-100000@hkn.eecs.berkeley.edu>
 <4.2.0.58.20020409221858.019a5140@pop3.norton.antivirus>
Message-ID: <3CB4BAE2.9299A3B5@shaw.ca>

Kirby Urner wrote:

> There's a problem with importing nested scopes in
> shell mode in IDLE in 2.1.  Cut and paste the code
> to a text file with
> 
> from __future__ import nested_scopes
> 
> at the top of the file.  Save as danny.py or whatever
> and import e.g.
> 
> from danny import diff
> 
> This will cause nested scopes to kick in and allow you
> to use diff interactively.

Thanks, that fixed it.  I'd forgotten about that bug.  

Cool example, Danny!

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From wilson@isis.visi.com  Thu Apr 11 04:06:32 2002
From: wilson@isis.visi.com (Tim Wilson)
Date: Wed, 10 Apr 2002 22:06:32 -0500 (CDT)
Subject: [Tutor] Music player for various formats
In-Reply-To: <E16vOhX-00028g-00@mail.python.org>
Message-ID: <Pine.GSO.4.10.10204102206001.2651-100000@isis.visi.com>

On Wed, 10 Apr 2002, Prahlad Vaidyanathan wrote:

> Hmm .. Just checked, and pygame-1.4 does not seem to support MP3s ...

See
http://groups.google.com/groups?selm=mailman.1015034704.11911.python-list%40python.org

-Tim

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




From slime@vsnl.net  Thu Apr 11 04:31:14 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Wed, 10 Apr 2002 23:31:14 -0400
Subject: [Tutor] << operator ?
Message-ID: <E16vVIo-0003sv-00@mail.python.org>


[ Resending because the previous one didn't reach the list ]

Hi,

What does this "<<" operator do ? IIRC, it is a bit-wise shift operator,
but I don't know what that means either :-(

Actually, I didn't come across it till today, when I saw this piece of
code :

"""
class MP3Header:
    ....
    def read_byte(self, prev):
        nextbyte = self.fp.read(1)
        if nextbyte == "":
            return ""
        return (prev << 8) | ord(nextbyte)

    def find_marker(self):
        while 1 :
            data = (ord(self.fp.read(1)) << 8) | ord(self.fp.read(1))
            self.fp.seek(-1, 1)
            if data & 0xffe0 == 0xffe0 :
                self.fp.seek(-1, 1)
                return self.fp.tell()
        return 0
    ...
"""

This operator is used all over the place in this script, and I have no
idea what it does. Please enlighten me.

Thanks !

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Is it weird in here, or is it just me?
		-- Steven Wright






From erikprice@mac.com  Thu Apr 11 05:03:19 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 00:03:19 -0400
Subject: [Tutor] << operator ?  [left bitwise shifting]
In-Reply-To: <Pine.LNX.4.44.0204101349461.3016-100000@hkn.eecs.berkeley.edu>
Message-ID: <0F2F0573-4D01-11D6-A9F0-00039351FE6A@mac.com>

On Wednesday, April 10, 2002, at 05:07  PM, Danny Yoo wrote:

> (32 bits)  So left shifting it once shoves the leftmost zero out into
> space, and moves everything else one place to the left.
>
>     2 == "00000000000000000000000000000010"
>
> And it turns out that when we left shift a number, it effectively
> "doubles".
>
>
> Hope this is making some sort of sense... *grin* Please feel free to ask
> more questions about this.

Having seen the bitwise shift operator but having no idea what it was 
for, I appreciate this and the other explanations given here on the list 
(even though it wasn't me who asked the question... thanks Prahlad!).

But now I'm just curious what it's for -- why you would use it?  Just to 
double numbers?  And if that's the case, then what's the right bitwise 
shift operator for?


Erik




From erikprice@mac.com  Thu Apr 11 05:06:32 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 00:06:32 -0400
Subject: [Tutor] constructors
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53E@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <82209C39-4D01-11D6-A9F0-00039351FE6A@mac.com>

Okay, I had a whole bunch more questions about this constructors thread, 
so instead of flooding the list with a ton of individual emails, I have 
cut and paste everything into this one -- it responds to points made by 
Lloyd, Karthik, Alan, and Alexandre.

====

On Wednesday, April 10, 2002, at 10:23  AM, alan.gauld@bt.com wrote:

> That's the best reason. It ensures that the "pre conditions"
> of the objects methods are all met. Usually that translates
> to setting attributes but it could also be things like
> checking a hardware device was functioning correctly or
> even existed. This saves each and every function from doing the 
> precondition
> check itself. (Actually for hardware you
> probably should still check coz somebody might unplug it!)

So, if I had an class with a method that did a database access, then the 
constructor could do something like initialize the variables used in the 
class, and create a database connection.  If the database connection 
fails, then the constructor could return false, which would fail the 
creation of the object instance, so that we don't waste our time 
accessing the methods of the class since we already know we couldn't 
establish a database connection.

...does this sound right?

====

On Wednesday, April 10, 2002, at 08:20  AM, Alexandre Ratti wrote:

> I haven't used the new classes yet; I understand they allow you to 
> subclass build-in types such as lists or dictionaries. There are other 
> differences. See:
>
> http://www.amk.ca/python/2.2/index.html#SECTION000310000000000000000

This link, plus what dman explains, resembles what little I know of 
Java -- the new-style classes all descend from some other base class, 
which is "object" if there is no base class that is more suitable.  I 
haven't written extended classes yet, but I'll have to keep in mind that 
for the "new" style, I'll need to extend -something-, even if it has to 
be the generic "object".

====

On Wednesday, April 10, 2002, at 08:15  AM, Karthik Gurumurthy wrote:

> you would do cloning to achieve exactly what you wanted to..
> ie get a new instance (ie clone the instance) of a class from an 
> existing
> one with all it's attributes copied.
>
> Using the copy module happens to be a *standard* way of getting a copy 
> in
> python.
> So a client who uses your class will call copy.deepcopy() to achieve it
> since it is the norm.

I'm curious why you couldn't just assign a new reference to the object 
to get a copy.  OR.... would the new reference point to the SAME 
instance?  I just thought of this possibility now, as I wrote this.  Is 
that why you would want to copy an instance with this technique?

====

On Wednesday, April 10, 2002, at 08:22  AM, Lloyd Kvam wrote:

> Also note that Python supports an alternative way to have default 
> values.  You
> can define them at the class level.
>
> >>> class Person:
> ... 	name = "Not Specified"
> ... 	age = "Not Specified"
> ... 	
> >>> newguy = Person()
> >>> newguy.name
> 'Not Specified'
> >>> newguy.name = "Erik"
> >>> newguy.name
> 'Erik'
> >>> Person.name
> 'Not Specified'
>
> I have found class level defaults very useful for classes that represent
> database tables.  The class defaults can easily be built from 
> information
> provided by the database.

This technique of using class level defaults seems better than using 
default arguments to the constructor, since you can do something more 
complex to define the variables (like pull data from a database and use 
that as the defaults).  I haven't seen this before in Python -- in fact, 
I've only ever seen methods as part of a class, never standalone 
variables like this.

====

Thanks to all who have contributed to this thread, it's been very 
informative -- and, as with most of my questions, keeps bifurcating into 
two new questions for every answer I get!





Erik




From linuxconsult@yahoo.com.br  Thu Apr 11 05:10:41 2002
From: linuxconsult@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Thu, 11 Apr 2002 01:10:41 -0300
Subject: [Tutor] constructors
In-Reply-To: <82209C39-4D01-11D6-A9F0-00039351FE6A@mac.com>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53E@mbtlipnt02.btlabs.bt.co.uk> <82209C39-4D01-11D6-A9F0-00039351FE6A@mac.com>
Message-ID: <20020411041041.GA1796@ime.usp.br>

On Apr 11 2002, Erik Price wrote:
> I'm curious why you couldn't just assign a new reference to the
> object to get a copy.  OR.... would the new reference point to the
> SAME instance?

	Yes, that's exactly the case. The instance of the class would
	have one more reference pointing to it, instead of being an
	independent instance.

	[]s, Roger...

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



From urnerk@qwest.net  Thu Apr 11 02:22:57 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 10 Apr 2002 21:22:57 -0400
Subject: [Tutor] constructors
In-Reply-To: <82209C39-4D01-11D6-A9F0-00039351FE6A@mac.com>
References: <82209C39-4D01-11D6-A9F0-00039351FE6A@mac.com>
Message-ID: <E16vW30-0001RO-00@mail.python.org>

On Thursday 11 April 2002 12:06 am, Erik Price wrote:

> I'm curious why you couldn't just assign a new reference to the object
> to get a copy.  OR.... would the new reference point to the SAME
> instance?  I just thought of this possibility now, as I wrote this.  Is
> that why you would want to copy an instance with this technique?
>

That's right -- new reference would point to same object, not
a copy.

> This technique of using class level defaults seems better than using
> default arguments to the constructor, since you can do something more
> complex to define the variables (like pull data from a database and use
> that as the defaults).  I haven't seen this before in Python -- in fact,
> I've only ever seen methods as part of a class, never standalone
> variables like this.
>

You still need to provide a way to change class level defaults on
a per instance basis, so if you don't provide this in the constructor,
some other method will need to shoulder the burden.  

Class variables are shared across all instances, and may still be
accessed even if self.property has been reset in a given instance, 
by referencing [the class].property, e.g.:

  class Foo:
      prop1 = "Test"
      def __init__(self, prop1=None):
	if prop1:
	    self.prop1 = prop1

 >>> myobj = Foo("Hello")
 >>> myobj.prop1
 "Hello"
 >>> Foo.prop1
 "Test"

You can change the class-level properties at runtime, meaning all new
instances will get the new default, and old instances will have a new
class-level value as well (which may not matter, if it was reset).

 >>> Foo.prop1 = "world"
 >>> myobj.__class__
 <class __main__.Foo at 0x828137c>
 >>> myobj.__class__.prop1
 'world'
 >>> newobj = Foo()
 >>> newobj.prop1
 'world'

Kirby



From karthikg@aztec.soft.net  Thu Apr 11 05:23:55 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Thu, 11 Apr 2002 09:53:55 +0530
Subject: [Tutor] constructors
In-Reply-To: <82209C39-4D01-11D6-A9F0-00039351FE6A@mac.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDMEIKDJAA.karthikg@aztec.soft.net>

> So, if I had an class with a method that did a database access, then the
> constructor could do something like initialize the variables used in the
> class, and create a database connection.  If the database connection
> fails, then the constructor could return false, which would fail the
> creation of the object instance, so that we don't waste our time
> accessing the methods of the class since we already know we couldn't
> establish a database connection.

> ...does this sound right?

Yes Perfect!. you have picked up a nice example.
Normally constructors do not have a return value. Instead they throw
exceptions.

So if you have a DatabaseManager class which control access to the database,
you w'd probabyl try
initializing the connections in the constructor. If it fails, you w'd
probably signal the same by throwing
an exception. So the client w'd'nt be able to use that object.

IF a constructor throws an exception, in java , the reference is no longer
valid since the object construction did'nt go through successfully. Am not
so sure if this holds true for all OO languages...s'd be.

> I'm curious why you couldn't just assign a new reference to the object
> to get a copy.  OR.... would the new reference point to the SAME
> instance?  I just thought of this possibility now, as I wrote this.  Is
> that why you would want to copy an instance with this technique?

that means there is actually just one object in memory with 2 refernces
pointing to them.
So a change made to the object using one reference w'd be seen by both the
references.
If you are lookign for copies, then you probably are not looking for such an
effect.

Infact this is what happens when you pass an object reference to another
function.

def func():
	t = test()
	t.name="hello"
      method(t)
      print t.name --> something
def method(ref):
	ref.name="something"

In my short programming career, i have found that assigning references (like
you pointed out)
is widely used because that is what you normally do..create an object and
then fill it up with something,
pass it on to someone else to make sense out of it.

HTH
karthik.












From jar@mminternet.com  Thu Apr 11 05:25:53 2002
From: jar@mminternet.com (James A Roush)
Date: Wed, 10 Apr 2002 21:25:53 -0700
Subject: [Tutor] How do you make a module
Message-ID: <000001c1e110$f7ba69c0$0400000a@thor>

I have several functions that I've written and use in multiple programs.  I
would like to put them in a module for easier maintainability.  Could
somebody point me to a tutorial that will explain how?

Once it's made, what directory does it go in?





From shalehperry@attbi.com  Thu Apr 11 06:21:18 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 10 Apr 2002 22:21:18 -0700 (PDT)
Subject: [Tutor] How do you make a module
In-Reply-To: <000001c1e110$f7ba69c0$0400000a@thor>
Message-ID: <XFMail.20020410222118.shalehperry@attbi.com>

On 11-Apr-2002 James A Roush wrote:
> I have several functions that I've written and use in multiple programs.  I
> would like to put them in a module for easier maintainability.  Could
> somebody point me to a tutorial that will explain how?
> 
> Once it's made, what directory does it go in?

you make a module every time you create a .py file.  When you want to import it
you use the filename without the '.py' extension.  So 'foo.py' becomes 'import
foo'.

If you have a directory like:

this/
     foo.py
     bar.py
     this.py

this.py could be:

#!/usr/bin/python

import foo, bar

bar.command()
x = foo.variable
print x + 2

python looks in the current directory first.  If you have a module of nifty
python code you have written and want all of your programs to use it then the
answer depends on your OS.

Under linux (bsd, unix, whatever) you can either make a ~/python directory and
add that to PYTHONPATH (see the docs for more info) or more easily just drop it
in /usr/local/lib/site-python and python should see it automatically without
further work.

My preference is to include small modules with any project that needs them and
to install bigger ones in the system directory.

Hope that helps.



From paulsid@shaw.ca  Thu Apr 11 06:42:32 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Wed, 10 Apr 2002 23:42:32 -0600
Subject: [Tutor] << operator ?  [left bitwise shifting]
References: <0F2F0573-4D01-11D6-A9F0-00039351FE6A@mac.com>
Message-ID: <3CB52248.84797C0F@shaw.ca>

Erik Price wrote:

> But now I'm just curious what it's for -- why you would use it?  Just to
> double numbers?  And if that's the case, then what's the right bitwise
> shift operator for?

Both are used extensively for working with binary protocols, hardware,
compact binary file formats, etc.  These don't show up very often in
Python, which is why many people may never see it in use.  Nevertheless
here's an example, with roots in the real world:

A common thing in hardware is to query a device (e.g. the video card)
and get back a byte, word, or dword with a bunch of status information. 
The information is given in this compact form because hardware access is
relatively expensive and space is usually at a premium.  

Say we know that when we request a status from the video card we get
back a 16-bit word with unused bits 14-15 (the leftmost) the current
video mode is in bits 10-13, the maximum possible number of buffers for
the current mode is in bits 8-9, and the current vertical refresh rate
in Hz is in bits 0-7 (the rightmost).  (Don't worry if you don't know
what any of this means, but do note that bits are numbered from 0 to 15
going from right to left if you didn't know that.)  We want to store
these numbers in Python variables.  Say also that we've stored this
status word in a variable called 'status', but for annotation purposes
I'll just assign status a value so we can watch how it gets used. 
Here's how this would be done:

status = 0x2746       # In binary, status = 0010 0110 0100 0110

# Isolate bits 0-7.
t = status & 0x00FF   # t = binary 0000 0000 0100 0100 = 70
# Refresh rate is in lowest bits, so no shifting needed.
refreshrate = t       # 70 Hz vertical refresh.
# Now isolate bits 8-9.
t = status & 0x0300   # t = binary 0000 0010 0000 0000 = 0x0200 = 512
# Shift the number of buffers so it makes sense.
t = t >> 8            # t = binary 0000 0000 0000 0010 = 2
buffers = t           # 2 video buffers, we can use double-buffering!
# Lastly, isolate bits 10-14.
t = status & 0x3C00   # t = binary 0010 0100 0000 0000 = 0x2400 = big!
# Shift the video moder number into place.
t = t >> 10           # t = binary 0000 0000 0000 1001 = 9
videomode = t         # Video mode #9, whatever that means.

Of course we could have done all of this by division, but this is a bit
clearer.  Since we know the number of buffers starts in bit 8 and the
video mode starts in bit 10, once we isolate those bits we can just
shift the result by 8 or 10 bits, respectively, to get the actual value.

If we were later going to set the status and had to pass a status word
with of the same format, we can use this code to build the new status
word:

status = (videomode << 10) | (buffers << 8) | refreshrate

Again, we could do this by multiplication but using the shift operator
is somewhat more straightforward.

The clarity of videomode << 10 over videomode * 2**10 is debatable, but
what isn't debatable is the speed gain.  Most processors support
shifting as built in instructions, and these instructions are almost
always a LOT faster than general multiplication, because it's easy to
build very fast circuitry that can shift bits around.  

Thus this kind of thing shows up a lot in C and assembler code.  In
fact, for very performance-intensive code programmers will often use
shift operations to do their multiplication and division!  x>>1 is an
extemely common and extremely fast integer divide-by-2, and x<<2 makes
for a quick multiply-by-4.  (Notice I didn't put spaces around the
operators.  It's a a curious phenomenon that programmers writing some
form of optimized code tend to optimize on whitespace as well; I've
almost never seen the properly-spaced version in optimized code.)

Searching the entire standard library for << produced only about 30
hits.  So don't worry about it too much.  Odds are you probably won't
need to shift bits, at least when working with Python.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From karthikg@aztec.soft.net  Thu Apr 11 09:09:03 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Thu, 11 Apr 2002 13:39:03 +0530
Subject: [Tutor] An example of something extremely difficult to expres s in        Java
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53D@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <NEBBJNMDEKBIBCMCNMBDEEJCDJAA.karthikg@aztec.soft.net>

> can someone give me neat examples of something which
> is *extremely* difficult to express in java but can be easily
> represented in python?

> Not *extremely* difficult in Java(at least not Java2) but
> a pain none the less is anything which takes a function
> as a parameter. Try writing the Python map() function
> in Java say... Thats not too bad, now try using it for
> a few cases... You'll soon see what I mean.

> Alan G.

i tried writing a command interface to encapsulate a method..i mean the way
Runnable is...to accomodate
a function object. i tried returning an ArrayList.
I did figure out that it is a little complicated.

> Now try writing Danny differentiator function builder....
where can i find this?


ok if we look at the implementation of the proxy pattern in Python,
and the way it's done in java using Dynamic proxy's , we can conclude that
the java equivalne tis quite complicated. It turns out to be a breeze in
Python!

Something along those lines.

I mean when we embed xsl processor into our java-application, XML Stylesheet
language does something which
java w'd find it very difficult to achieve.(ie transformation). Fine the
processor is implemented in Java.
So can we embed python that way and get something *radically* different done
in a highly simplified way?

Sometimes i feel that's not possible simply because Python and Java are very
similar languages by design??
XSL c'd do something for us because Java and XSL are languages meant to
achieve different goals
just some thoughts...

thanks!
karthik.



From Ed Hopkins" <ed.hopkins@ntlworld.com  Thu Apr 11 09:25:38 2002
From: Ed Hopkins" <ed.hopkins@ntlworld.com (Ed Hopkins)
Date: Thu, 11 Apr 2002 09:25:38 +0100
Subject: [Tutor] What is foo?
Message-ID: <000b01c1e132$75e52350$67526bd5@FAMILY>

Hi,

Been studying Python for a while.  Even bought a couple of books.  The most
annoying thing is that nowhere does anyone explain what 'foo' means.

Any ideas?

Ed





From budgester@budgester.com  Thu Apr 11 09:45:47 2002
From: budgester@budgester.com (Martin Stevens)
Date: Thu, 11 Apr 2002 09:45:47 +0100
Subject: [Tutor] What is foo?
In-Reply-To: <000b01c1e132$75e52350$67526bd5@FAMILY>
References: <000b01c1e132$75e52350$67526bd5@FAMILY>
Message-ID: <20020411084547.GA1063@akira.budgenet>

Try

http://www.tuxedo.org/jargon/html/entry/foo.html

As always there is more information here than you'd ever want :-)

On Thu, Apr 11, 2002 at 09:25:38AM +0100, Ed Hopkins wrote:
> Hi,
> 
> Been studying Python for a while.  Even bought a couple of books.  The most
> annoying thing is that nowhere does anyone explain what 'foo' means.
> 
> Any ideas?
> 
> Ed
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Budgester Technologies Ltd
Office : 01992 718568
Mobile : 07815 982380
mailto:martin@budgester.com
http://www.budgester.com



From scarblac@pino.selwerd.nl  Thu Apr 11 10:01:11 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Thu, 11 Apr 2002 11:01:11 +0200
Subject: [Tutor] What is foo?
In-Reply-To: <000b01c1e132$75e52350$67526bd5@FAMILY>; from ed.hopkins@ntlworld.com on Thu, Apr 11, 2002 at 09:25:38AM +0100
References: <000b01c1e132$75e52350$67526bd5@FAMILY>
Message-ID: <20020411110111.A15338@pino.selwerd.nl>

On  0, Ed Hopkins <ed.hopkins@ntlworld.com> wrote:
> Hi,
> 
> Been studying Python for a while.  Even bought a couple of books.  The most
> annoying thing is that nowhere does anyone explain what 'foo' means.
> 
> Any ideas?

Well the Jargon entry maybe over-explains it...

In many code examples, words like that are just used as meaningless
placeholders. You need a variable name, it's just a short example so it
doesn't really have a meaning other than being some variable, name it foo.
If you need another, you'd usually call it bar.

In Python code you'll often see Monty Python things used for this,
especially "spam".

Others just use a,b,c, x,y,z, etc. I used to hack a lot of code with some
Dutch friends, and we used "koe", "aap" en "vla" for this purpose, out of
some drunken tradition no-one remembers.

Anyway, just ignore it, it's not special :)

-- 
Remco Gerlich



From Aedin@chah.ucc.ie  Thu Apr 11 13:13:25 2002
From: Aedin@chah.ucc.ie (Aedin Culhane)
Date: Thu, 11 Apr 2002 13:13:25 +0100 (BST)
Subject: [Tutor] creating tempfile in cgi script
In-Reply-To: <20020410202918.12460.10441.Mailman@mail.python.org>
Message-ID: <Pine.OSF.3.96.1020411130004.20933A-100000@chah.ucc.ie>

Dear Tutor
I am new to cgi scripts and python but I am creating a html form that
accept takes user input, processes it and then tries to display it using
chime. I have been processing the input as a string, and have tried to
avoid creating a tempfile on our server, as I have heard that this has
security implications.  However chime requires its input as a filename. 

What are the security implications by making tempfiles (/tmp)?
I tried StringIO, but this creates an instance rather than file, it there
any way to "mimic" a file?

Thanks a million for your help
Aedin

--------------------------------
Aedin Culhane
Bioinformatics Group
Biochemistry Department
University College Cork
Cork, Ireland





From erikprice@mac.com  Thu Apr 11 12:42:54 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 07:42:54 -0400
Subject: [Tutor] constructors
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDMEIKDJAA.karthikg@aztec.soft.net>
Message-ID: <4325E2D0-4D41-11D6-9F94-00039351FE6A@mac.com>

On Thursday, April 11, 2002, at 12:23  AM, Karthik Gurumurthy wrote:

>> So, if I had an class with a method that did a database access, then 
>> the
>> constructor could do something like initialize the variables used in 
>> the
>> class, and create a database connection.  If the database connection
>> fails, then the constructor could return false, which would fail the
>> creation of the object instance, so that we don't waste our time
>> accessing the methods of the class since we already know we couldn't
>> establish a database connection.
>
>> ...does this sound right?
>
> Yes Perfect!. you have picked up a nice example.
> Normally constructors do not have a return value. Instead they throw
> exceptions.
>
> So if you have a DatabaseManager class which control access to the 
> database,
> you w'd probabyl try
> initializing the connections in the constructor. If it fails, you w'd
> probably signal the same by throwing
> an exception. So the client w'd'nt be able to use that object.

I see.  The use of constructors is becoming much more concrete to me.  
Thank you Karthik.  But as always, this conversation now brings up yet 
another question! :)  It's a simple one though.  I'm just wondering 
whether it would be better to throw an exception from within the class 
method (or constructor), or whether it would be better to simply do an 
"if" test and have it return false -- and then throw an exception from 
the calling script itself, if the "new object" calling fails.  I would 
have leaned toward the former -- returning false from a failed method, 
and then throwing up an error message from the calling script because 
the creation of a new object instance failed, but that's because I'm not 
totally clear on exceptions yet (they don't have them in PHP AFAIK, I 
just write my own error-handling code).


Erik




From erikprice@mac.com  Thu Apr 11 12:48:13 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 07:48:13 -0400
Subject: [Tutor] How do you make a module
In-Reply-To: <XFMail.20020410222118.shalehperry@attbi.com>
Message-ID: <0145E958-4D42-11D6-9F94-00039351FE6A@mac.com>

On Thursday, April 11, 2002, at 01:21  AM, Sean 'Shaleh' Perry wrote:

> Under linux (bsd, unix, whatever) you can either make a ~/python 
> directory and
> add that to PYTHONPATH (see the docs for more info) or more easily just 
> drop it
> in /usr/local/lib/site-python and python should see it automatically 
> without
> further work.

Also, if you fire up the interpreter (or execute an executable script) 
from within directory "spam/", and the module you want to use is in that 
same directory ("spam/eggs.py"), then the module should also be 
available.  I'm not sure if this works on windows, but it works in Unix 
systems.


Erik




From erikprice@mac.com  Thu Apr 11 12:55:45 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 07:55:45 -0400
Subject: [Tutor] << operator ?  [left bitwise shifting]
In-Reply-To: <3CB52248.84797C0F@shaw.ca>
Message-ID: <0EC50D28-4D43-11D6-9F94-00039351FE6A@mac.com>

On Thursday, April 11, 2002, at 01:42  AM, Paul Sidorsky wrote:

> Searching the entire standard library for << produced only about 30
> hits.  So don't worry about it too much.  Odds are you probably won't
> need to shift bits, at least when working with Python.

That's good.  I understand now what it's for (sort of a way of 
"encoding/compressing" data like reducing an AIF file to MP3 for 
internet transmission, but without lossiness, but it's not really 
encoding is it).  But I don't think I ever want to use it.  Or maybe I 
would, but not anytime soon.  Thanks for the explanation Paul.

Incidentally,

> (Notice I didn't put spaces around the
> operators.  It's a a curious phenomenon that programmers writing some
> form of optimized code tend to optimize on whitespace as well; I've
> almost never seen the properly-spaced version in optimized code.)

have you ever looked at the source code for Google pages?  Very little 
whitespace, no verbosity at all.  It's like the opposite of XML 
(designed to be human-readable and where compactness is very 
deprioritized).  In fact, they don't use XHTML at all, like <br />, 
since <br /> has two more bytes than you really need and it can add up 
if you use a lot of <br />s.  (It's like the opposite of my code, I tend 
to overdo it with comments and I try to use XHTML over standard HTML.)




From lumbricus@gmx.net  Thu Apr 11 13:08:03 2002
From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=)
Date: Thu, 11 Apr 2002 14:08:03 +0200 (MEST)
Subject: [Tutor] creating tempfile in cgi script
References: <Pine.OSF.3.96.1020411130004.20933A-100000@chah.ucc.ie>
Message-ID: <24323.1018526883@www29.gmx.net>

> Dear Tutor

[ snip ]

> What are the security implications by making tempfiles (/tmp)?

If the names of your tempfiles are not unique an unpredictable, 
another user could create symbolic links with the predicted names
of your file.

> I tried StringIO, but this creates an instance rather than file, it there
> any way to "mimic" a file?

import tempfile
dir(tempfile)

> Thanks a million for your help
> Aedin
> 

HTH, HAND and 
Greetings, J"o!

-- 
sigfault

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net




From erikprice@mac.com  Thu Apr 11 13:16:09 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 08:16:09 -0400
Subject: [Tutor] constructors
In-Reply-To: <200204110418.g3B4IwuI010494@smtpin12.mac.com>
Message-ID: <E8067415-4D45-11D6-9F94-00039351FE6A@mac.com>

On Wednesday, April 10, 2002, at 09:22  PM, Kirby Urner wrote:

> You still need to provide a way to change class level defaults on
> a per instance basis, so if you don't provide this in the constructor,
> some other method will need to shoulder the burden.
>
> Class variables are shared across all instances, and may still be
> accessed even if self.property has been reset in a given instance,
> by referencing [the class].property, e.g.:
>
>   class Foo:
>       prop1 = "Test"
>       def __init__(self, prop1=None):
> 	if prop1:
> 	    self.prop1 = prop1

I see.  So a constructor is useful for individualizing an instance, 
whereas a class level default could set class level defaults (obviously) 
which will be the same across all instances unless another method 
changes them (which is what the constructor is sometimes used for).

Is this manipulation of class variables a side effect of how Python 
works, or is that desired behavior?  I haven't seen their use either 
(such as Classname.classvariablename) so I wonder if there is any reason 
to stay away from this kind of functionality.


Erik




From karthikg@aztec.soft.net  Thu Apr 11 13:19:37 2002
From: karthikg@aztec.soft.net (Karthik Gurumurthy)
Date: Thu, 11 Apr 2002 17:49:37 +0530
Subject: [Tutor] constructors
In-Reply-To: <4325E2D0-4D41-11D6-9F94-00039351FE6A@mac.com>
Message-ID: <NEBBJNMDEKBIBCMCNMBDGEJNDJAA.karthikg@aztec.soft.net>

>> So, if I had an class with a method that did a database access, then
>> the
>> constructor could do something like initialize the variables used in
>> the
>> class, and create a database connection.  If the database connection
>> fails, then the constructor could return false, which would fail the
>> creation of the object instance, so that we don't waste our time
>> accessing the methods of the class since we already know we couldn't
>> establish a database connection.
>
>> ...does this sound right?
>
> Yes Perfect!. you have picked up a nice example.
> Normally constructors do not have a return value. Instead they throw
> exceptions.
>
> So if you have a DatabaseManager class which control access to the
> database,
> you w'd probabyl try
> initializing the connections in the constructor. If it fails, you w'd
> probably signal the same by throwing
> an exception. So the client w'd'nt be able to use that object.

> I see.  The use of constructors is becoming much more concrete to me.
> Thank you Karthik.  But as always, this conversation now brings up yet
> another question! :)  It's a simple one though.  I'm just wondering
> whether it would be better to throw an exception from within the class
> method (or constructor), or whether it would be better to simply do an
> "if" test and have it return false -- and then throw an exception from
> the calling script itself, if the "new object" calling fails.  I would
> have leaned toward the former -- returning false from a failed method,
> and then throwing up an error message from the calling script because
> the creation of a new object instance failed, but that's because I'm not
> totally clear on exceptions yet (they don't have them in PHP AFAIK, I
> just write my own error-handling code).

let me try the exception part.
ok let's consider a situation wherein you might be doing lots of things
inside a method.
set up some connections, open a file, start a server.
Now say one of these tasks fail. If you return a false, the only thing
the user probably gets to know is that *something* has gone wrong but he
still
is'nt sure as to what has actually gone wrong.

So exception c'd be a way of returning muliple return values.
So you might have ServerException, DatabaseException and SomeIOException.
The client might catch all these exceptions using the python construct
except:
The client might decide that he is ok with say ServerException getting
thrown
and might still use your object to get other things done.
This is the case only when you throw exceptions from a method and NOT a
constructor
(I mean i do java and java w'd'nt allow you to use the reference in the
first place if the constructor has failed).

There are lots of rules/best practices laid down to decide whether you need
to throw an exception / return a boolean value.

But i hope this explains one of the several uses of throwing an exception.
Basically proper error handling and exact information of the erroneous
condition(reason) etc.
Allowing the client to decide for himself , the course of action.

































From alex@gabuzomeu.net  Thu Apr 11 14:28:08 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Thu, 11 Apr 2002 15:28:08 +0200
Subject: [Tutor] What is foo?
In-Reply-To: <20020411121801.19447.19077.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020411152046.00c59b20@pop3.norton.antivirus>

Hello,


At 08:18 11/04/2002 -0400, you wrote:
>Date: Thu, 11 Apr 2002 11:01:11 +0200
>From: Remco Gerlich <scarblac@pino.selwerd.nl>
>Subject: Re: [Tutor] What is foo?

>In many code examples, words like that are just used as meaningless
>placeholders. You need a variable name, it's just a short example so it
>doesn't really have a meaning other than being some variable, name it foo.
>If you need another, you'd usually call it bar.
>
>In Python code you'll often see Monty Python things used for this,
>especially "spam".
>
>Others just use a,b,c, x,y,z, etc. I used to hack a lot of code with some
>Dutch friends, and we used "koe", "aap" en "vla" for this purpose, out of
>some drunken tradition no-one remembers.

In French, we use "toto", "titi", "tutu" etc. fairly often. It's easy to type.


Cheers.

Alexandre




From bwinton@tor.dhs.org  Thu Apr 11 14:46:39 2002
From: bwinton@tor.dhs.org (Blake Winton)
Date: Thu, 11 Apr 2002 09:46:39 -0400
Subject: [Tutor] An example of something extremely difficult to expres s in        Java
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDEEJCDJAA.karthikg@aztec.soft.net>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53D@mbtlipnt02.btlabs.bt.co.uk> <NEBBJNMDEKBIBCMCNMBDEEJCDJAA.karthikg@aztec.soft.net>
Message-ID: <20020411094639.A22173@tor.dhs.org>

* Karthik Gurumurthy <karthikg@aztec.soft.net> [020411 04:03]:
> i tried writing a command interface to encapsulate a method..i mean
> the way Runnable is...to accomodate a function object. i tried
> returning an ArrayList.  I did figure out that it is a little
> complicated.

I never thought it was that bad...
interface Command
{
    public Response execute( Request request );
}

interface Request {}
interface Response {}

Then you can make implementors of Request and Response, and stick
whatever data they want in them, and pass them to your implementors of
Command.  Just remember to cast them in your execute method...

> > Now try writing Danny differentiator function builder....
> where can i find this?

It should be in the list archives...

As another example of something that's nigh-impossible in Java, but easy
in Python, "eval/exec".  Executing arbitrary code entered by the user...
Okay, maybe it's not a good idea, but it's also nigh-impossible.  ;)

Later,
Blake.
-- 
  9:44am  up 29 days, 12:33,  2 users,  load average: 0.00, 0.00, 0.00



From urnerk@qwest.net  Thu Apr 11 13:01:17 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 11 Apr 2002 08:01:17 -0400
Subject: [Tutor] constructors
In-Reply-To: <E8067415-4D45-11D6-9F94-00039351FE6A@mac.com>
References: <E8067415-4D45-11D6-9F94-00039351FE6A@mac.com>
Message-ID: <E16vg0j-0001Mh-00@mail.python.org>

On Thursday 11 April 2002 08:16 am, Erik Price wrote:

> Is this manipulation of class variables a side effect of how Python
> works, or is that desired behavior?  I haven't seen their use either
> (such as Classname.classvariablename) so I wonder if there is any reason
> to stay away from this kind of functionality.
>

This is desired and expected behavior.  No reason to stay away.

Kirby



From bobx@linuxmail.org  Thu Apr 11 18:21:09 2002
From: bobx@linuxmail.org (Bob X)
Date: Fri, 12 Apr 2002 01:21:09 +0800
Subject: [Tutor] How to put two things together and then print to a file?
Message-ID: <20020411172109.21222.qmail@linuxmail.org>

The following works really great, except that I would like the word or words found to print first and then the line it was found on like so:

word "this is where the word was found"

Do I need to do a def to pass more than one thing to the outp.write? Something like:

def cachehit(badword, line):


=== current script ===

import sys, string

inp = open(sys.argv[1],"r")
outp = open(sys.argv[2],"w")

# build list of keywords
kw = ["word", "ape"]

# loop through the list and print the lines to a file
for line in inp.readlines():
    for badword in kw:
	if line.find(badword) > -1:
	    print badword,line	# print word and line
	    outp.write (line) # write line found
 
# close the files
inp.close()
outp.close()

# let me know when it's done doing its thang
print "Finished processing file..."
-- 

Get your free email from www.linuxmail.org 


Powered by Outblaze



From dman@dman.ddts.net  Thu Apr 11 20:14:24 2002
From: dman@dman.ddts.net (dman)
Date: Thu, 11 Apr 2002 14:14:24 -0500
Subject: [Tutor] constructors
In-Reply-To: <4325E2D0-4D41-11D6-9F94-00039351FE6A@mac.com>
References: <NEBBJNMDEKBIBCMCNMBDMEIKDJAA.karthikg@aztec.soft.net> <4325E2D0-4D41-11D6-9F94-00039351FE6A@mac.com>
Message-ID: <20020411191424.GA24388@dman.ddts.net>

On Thu, Apr 11, 2002 at 07:42:54AM -0400, Erik Price wrote:
| 
| On Thursday, April 11, 2002, at 12:23  AM, Karthik Gurumurthy wrote:
| 
| >>So, if I had an class with a method that did a database access, then 
| >>the
| >>constructor could do something like initialize the variables used in 
| >>the
| >>class, and create a database connection.  If the database connection
| >>fails, then the constructor could return false, which would fail the
| >>creation of the object instance, so that we don't waste our time
| >>accessing the methods of the class since we already know we couldn't
| >>establish a database connection.
| >
| >>...does this sound right?
| >
| >Yes Perfect!. you have picked up a nice example.
| >Normally constructors do not have a return value. Instead they throw
| >exceptions.
| >
| >So if you have a DatabaseManager class which control access to the 
| >database,
| >you w'd probabyl try
| >initializing the connections in the constructor. If it fails, you w'd
| >probably signal the same by throwing
| >an exception. So the client w'd'nt be able to use that object.
| 
| I see.  The use of constructors is becoming much more concrete to me.  
| Thank you Karthik.  But as always, this conversation now brings up yet 
| another question! :)  It's a simple one though.  I'm just wondering 
| whether it would be better to throw an exception from within the class 
| method (or constructor), or whether it would be better to simply do an 
| "if" test and have it return false -- and then throw an exception from 
| the calling script itself, if the "new object" calling fails.  I would 
| have leaned toward the former -- returning false from a failed method, 
| and then throwing up an error message from the calling script because 
| the creation of a new object instance failed, but that's because I'm not 
| totally clear on exceptions yet (they don't have them in PHP AFAIK, I 
| just write my own error-handling code).

Usually it is better to throw an exception.  In either case, you can't
return a value from __init__ -> the object already exists and is
referenced by 'self', the __init__ just initializes the data in it.
If the __init__ method completes, then the client gets the reference
to the object.  You can return 'false' or 'self' or 'fubar', but the
client will never see it.  Ex :

class False :
    def __init__( self ) :
        return 0

class Except :
    def __init__( self ) :
        raise "init failed"

print False()
print Except()


In addition, with exceptions you don't need to constantly check
functions for sentinal return values.  I once posted an example C
snippet (from a real project I did for school) and then rewrote it
using python syntax and exceptions to show how much shorter and
clearer the code became.  This was probably 2 years ago, and I don't
remember which list it was.  Google isn't helping either.

With exceptions, you raise one where there is an error, and you can be
descriptive about it.  The client code doesn't need to deal with any
errors, if it doesn't want to, and the exception propagates up the
call stack until either it is handled or the program exits with an
error.  Thus you can have stuff like :

def do_something() :
    # this function may fail, but we can't do anything about it here
    do()

try :
    print "1"
    do_something()
    print "2"
    do_somethingelse()
except Foo :
    print "foo!"


The do_something function doesn't need to do anything special (like
check a return value and propagate it by returning it) to not ignore
error conditions.  The module-level code doesn't need to interrupt the
flow of the code by checking a return value either, and can handle the
same type of error from both functions identically (if it wants to).

HTH,
-D

-- 

For society, it's probably a good thing that engineers value function
over appearance.  For example, you wouldn't want engineers to build
nuclear power plants that only _look_ like they would keep all the
radiation inside.
    (Scott Adams - The Dilbert principle)




From dman@dman.ddts.net  Thu Apr 11 20:25:44 2002
From: dman@dman.ddts.net (dman)
Date: Thu, 11 Apr 2002 14:25:44 -0500
Subject: [Tutor] An example of something extremely difficult to expres s in        Java
In-Reply-To: <20020411094639.A22173@tor.dhs.org>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53D@mbtlipnt02.btlabs.bt.co.uk> <NEBBJNMDEKBIBCMCNMBDEEJCDJAA.karthikg@aztec.soft.net> <20020411094639.A22173@tor.dhs.org>
Message-ID: <20020411192544.GB24388@dman.ddts.net>

On Thu, Apr 11, 2002 at 09:46:39AM -0400, Blake Winton wrote:
| * Karthik Gurumurthy <karthikg@aztec.soft.net> [020411 04:03]:
| > i tried writing a command interface to encapsulate a method..i mean
| > the way Runnable is...to accomodate a function object. i tried
| > returning an ArrayList.  I did figure out that it is a little
| > complicated.
| 
| I never thought it was that bad...
| interface Command
| {
|     public Response execute( Request request );
| }
| 
| interface Request {}
| interface Response {}
| 
| Then you can make implementors of Request and Response, and stick
| whatever data they want in them, and pass them to your implementors of
| Command.

So you need to make 3 extra classes just for this.  What about passing
"primitive" stuff to the method, or passing multiple arguments?  Now
you need to make even more classes.

| Just remember to cast them in your execute method...

Again, ugh.

Oh, yeah, don't forget the possiblities of throwing exceptions from
that execute method, and then catching them in the client code.
However, some methods don't throw exceptions.  Even more classes to
handle all the different cases.


It is doable, but not trivial.  I did it once for a test harness.  I
first wrote it in python (which ran in jython), then rewrote it in
java.  Unfortunately I don't have access to that code right now so
I'll give you an overview in prose :

    In the classes being tested, there were several methods with the
    same interface -- they were boolean "get/set" pairs.  The process
    of testing them was straightforward, so I made a method in my test
    super-class to take a function as the argument and test it.  Then
    I was able to iterate over all the methods in the class being
    tested and call the test function.  In python the code was really
    compact and slick.  When converting it to java I had to make 2 new
    classes just to encapsulate the idea of the method.  Their were 2
    classes because the arguments and retvals were reversed in the get
    vs. the set methods.  Then I had to create a subclass of each of
    those classes for each method to be tested.  I couldn't easily
    iterate over them because creating a sequence in java take more
    boilerplate code than in python.  What was trivial and took only a
    few lines in python took several files in java and was hard to
    follow.  C is about just as bad as java for dynamic stuff like
    that.

-D

-- 

If we claim to be without sin, we deceive ourselves and the truth is not
in us.
        I John 1:8




From j.ezequiel@spitech.com  Thu Apr 11 10:34:11 2002
From: j.ezequiel@spitech.com (Ezequiel, Justin)
Date: Thu, 11 Apr 2002 17:34:11 +0800
Subject: [Tutor] SMTP with attachments
Message-ID: <0F757892D113D611BD2E0002559C1FF4637FE0@EMAIL>

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_000_01C1E13C.095C3610
Content-Type: text/plain

How do I send an e-mail with attachments?
I am a newbie so be gentle.
I found a couple of examples (mfetch.py and MailTest.py) but could not get them to work.
MailTest.py raises an exception re "instructions.txt" not found.
mfetch.py imports "win32com.client" which I don't have and may not want to use as my program most likely will be run on a Linux box.
Please help.
 <<MailTest.py>> 
 <<mfetch.py>> 

------_=_NextPart_000_01C1E13C.095C3610
Content-Type: application/octet-stream;
	name="MailTest.py"
Content-Disposition: attachment;
	filename="MailTest.py"

import string
import MimeWriter
import mimify
import StringIO
from smtplib import SMTP
import base64


# Mails a file to the user in MIME format
# Based upon code by GVR
def mailFileToUser(_userName, _fileName):
    # We are using a string as a temporary file
    outputfp = StringIO.StringIO()

    # Create a MimeWriter object
    w = MimeWriter.MimeWriter(outputfp)
    w.addheader("subject", "File-Email from Python")
    w.addheader("MIME-Version", "1.0")
    w.flushheaders()

    # Now we create a plain text segment and write the instructions file into it
    w.startmultipartbody("mixed")
    instructions = w.nextpart()
    instFile = instructions.startbody("text/plain")
    instructions.flushheaders()
    instFile.write(open("./instructions.txt", "r").read())

    # Now we create a base64 encoded segment and write the diary file into it
    # as an attachment
    subwriter = w.nextpart()
    subwriter.addheader("Content-Transfer-Encoding", "base64")
    subwriter.addheader("Content-Disposition", 'attachment; filename="%s"' % _fileName)
    f = subwriter.startbody('application/octet-stream; name="%s"' % _fileName)
    subwriter.flushheaders()
    base64.encode(open('./%s' % _fileName, 'r'), f)
    w.lastpart()

    # Next we have to email the mail message to the user
    # the outputfp.getvalue retrieves all the stuff written to the StringIO file object
    s = SMTP("localhost")
    s.sendmail("fromme@linuxbox", _userName, outputfp.getvalue())
    s.close()

if __name__=='__main__':
    print "Testing mailFileToUser"
    mailFileToUser("myname@linuxbox", "test.doc")

------_=_NextPart_000_01C1E13C.095C3610
Content-Type: application/octet-stream;
	name="mfetch.py"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
	filename="mfetch.py"

#!/usr/bin/python=0A=
=0A=
import string,sys,types,os,tempfile,time=0A=
import mimetypes,mimetools,MimeWriter=0A=
import smtplib=0A=
import traceback=0A=
import win32com.client=0A=
=0A=
def MapiAddressToSMTP(addressEntry):=0A=
    =0A=
#    print "AddressEntry: "=0A=
#    print "  Type =3D '%s'" % addressEntry.Type=0A=
#    print "  Name =3D '%s'" % addressEntry.Name=0A=
#    print "  Addr =3D '%s'" % addressEntry.Address=0A=
    =0A=
    addrType =3D addressEntry.Type=0A=
    if addrType =3D=3D 'EX':=0A=
        # HACK!=0A=
        name =3D addressEntry.Name=0A=
        addr =3D string.join(string.split(name),'.') + =
'@comtrol.com'=0A=
	return '"%s" <%s>' % (name,addr)=0A=
    elif addrType =3D=3D 'SMTP':=0A=
	return '"%s" <%s>' % (addressEntry.Name,addressEntry.Address)=0A=
    else:=0A=
	raise "Don't know how to translate address Type '%s'" % (addrType,)=0A=
=0A=
class MailMessage:=0A=
    =0A=
    def __init__(self):=0A=
        self.__subject =3D None=0A=
        self.__sender =3D None=0A=
        self.__recipientList =3D []=0A=
        self.__bodyText =3D None=0A=
        self.__attachmentList =3D []=0A=
	self.__comObject =3D None=0A=
        =0A=
    def __del__(self):=0A=
	self.DeleteAttachments()=0A=
    =0A=
    def __str__(self):=0A=
        return "Message from %s to %s\n  subject=3D%s body: %s\n  %d =
attachments: %s" % (=0A=
                   self.__sender,=0A=
                   self.__recipientList,=0A=
                   self.__subject,=0A=
                   self.__bodyText,=0A=
                   len(self.__attachmentList),=0A=
                   self.__attachmentList)=0A=
=0A=
    def ComObject(self, ComObject):=0A=
	self.__comObject =3D ComObject=0A=
	=0A=
    def Delete(self):=0A=
	self.__comObject.Delete()=0A=
    =0A=
    def Subject(self, text=3DNone):=0A=
        if text !=3D None:=0A=
            self.__subject =3D text=0A=
        return self.__subject=0A=
            =0A=
    def Body(self, text=3DNone):=0A=
        if text !=3D None:=0A=
            self.__bodyText =3D text=0A=
        return self.__bodyText=0A=
            =0A=
    def Sender(self, senderAddress=3DNone):=0A=
        if senderAddress !=3D None:=0A=
            self.__sender =3D senderAddress=0A=
        return self.__sender=0A=
        =0A=
    def AddRecipient(self, recipientAddress):=0A=
        self.__recipientList =3D self.__recipientList + =
[recipientAddress]=0A=
            =0A=
    def AddAttachment(self,pathAndName):=0A=
        self.__attachmentList =3D self.__attachmentList + =
[pathAndName]=0A=
        =0A=
    def Attachments(self):=0A=
        return self.__attachmentList=0A=
    =0A=
    def Recipients(self):=0A=
        return self.__recipientList=0A=
=0A=
    def DeleteAttachments(self):=0A=
        if self.__attachmentList:=0A=
            for attachment in self.__attachmentList:=0A=
                filePath,fileName =3D attachment=0A=
                try:=0A=
                    # sometimes this fails -- gates only knows why=0A=
                    os.remove(filePath)=0A=
                except:=0A=
                    pass  =0A=
        self.__attachmentList =3D []=0A=
    =0A=
class MapiFetcher:=0A=
    =0A=
    def __init__(self, settings =3D "MS Exchange Settings"):=0A=
        self.sessionSettings =3D settings=0A=
        self.session =3D None=0A=
	self.debugLevel=3D0=0A=
        =0A=
    def __del__(self):=0A=
        try:=0A=
            self.session.Logoff()=0A=
        except:=0A=
            pass=0A=
        self.session =3D None=0A=
        =0A=
    def Debug(self,level):=0A=
	self.debugLevel =3D level=0A=
	=0A=
    def Logon(self):=0A=
        self.session =3D win32com.client.Dispatch("MAPI.Session")=0A=
        self.session.Logon(self.sessionSettings)=0A=
	if self.debugLevel > 1:=0A=
	    sys.stderr.write("MapiFetcher: MAPI.Session Logon() with settings =
=3D '%s'\n" % (self.sessionSettings,))=0A=
	    =0A=
=0A=
    def Logoff(self):=0A=
        self.session.Logoff()=0A=
	if self.debugLevel > 1:=0A=
	    sys.stderr.write("MapiFetcher: Logoff()\n")=0A=
    =0A=
    def CheckInbox(self):=0A=
        inbox =3D self.session.Inbox=0A=
        collmsg =3D inbox.Messages=0A=
	if self.debugLevel > 1:=0A=
	    sys.stderr.write("MapiFetcher: Found %d messages in Inbox\n" % =
(collmsg.Count,))=0A=
        messages =3D []=0A=
        msg =3D collmsg.GetFirst()=0A=
=0A=
        while msg:=0A=
            newMessage =3D MailMessage()=0A=
	    newMessage.ComObject(msg)=0A=
            newMessage.Sender(MapiAddressToSMTP(msg.Sender))=0A=
            newMessage.Subject(msg.Subject)=0A=
            newMessage.Body(msg.Text)=0A=
=0A=
	    if self.debugLevel > 2:=0A=
		sys.stderr.write("MapiFetcher: Read message #%d From: %s; Subject: =
%s; (Length=3D%d with %d Attachments)\n" % (=0A=
		                      len(messages)+1, newMessage.Sender(), =
newMessage.Subject(), len(newMessage.Body()), =
msg.Attachments.Count))=0A=
	    =0A=
            for i in range(1,msg.Recipients.Count+1):=0A=
                r =3D msg.Recipients.Item(i)=0A=
                =
newMessage.AddRecipient(MapiAddressToSMTP(r.AddressEntry))=0A=
               =0A=
            for i in range(1,msg.Attachments.Count+1):=0A=
                attachment =3D msg.Attachments.Item(i)=0A=
                path =3D tempfile.mktemp()=0A=
                if attachment.Type =3D=3D 1:=0A=
                    # file data=0A=
                    name =3D attachment.Name=0A=
                    attachment.WriteToFile(path)=0A=
                if attachment.Type =3D=3D 2:=0A=
                    # file link  (don't really know what to do, try =
WriteToFile)=0A=
                    name =3D attachment.Name=0A=
                    attachment.WriteToFile(path)=0A=
                if attachment.Type =3D=3D 3:=0A=
                    # OLE object  (don't really know what to do, try =
WriteToFile)=0A=
                    name =3D attachment.Name=0A=
                    attachment.WriteToFile(path)=0A=
                elif attachment.Type =3D=3D 4:=0A=
                    # embedded message=0A=
                    emb=3Dattachment.Source=0A=
                    tmpfile=3Dopen(path,'wb')=0A=
                    tmpfile.write("    From: %s\n" % =
MapiAddressToSMTP(emb.Sender))=0A=
                    tmpfile.write(" Subject: %s\n" % emb.Subject)=0A=
                    tmpfile.write("\n")=0A=
                    tmpfile.write(emb.Text)=0A=
                    tmpfile.write("\n")=0A=
                    tmpfile.close()=0A=
                    name =3D "AttachedMessage.txt"=0A=
                newMessage.AddAttachment((path,name))=0A=
            messages =3D messages + [newMessage]=0A=
            msg =3D collmsg.GetNext()=0A=
            =0A=
        return messages=0A=
=0A=
class SmtpWriter:=0A=
    def __init__(self, server=3D"localhost", dest=3DNone, =
src=3DNone):=0A=
	self.__server =3D server=0A=
	self.__dest   =3D dest=0A=
	self.__src    =3D src=0A=
	self.__debugLevel =3D 0=0A=
	=0A=
    def Debug(self,level):=0A=
	self.__debugLevel =3D level=0A=
=0A=
    def Message(self,sender=3D"", subject=3D"", recipients=3D[], =
body=3D"", attachments=3D[]):=0A=
	if self.__debugLevel > 2:=0A=
	    sys.stderr.write("SmtpWriter: Building RFC822 message From: %s; =
Subject: %s; (Length=3D%d with %d attachments)\n" % (=0A=
	                      sender, subject, len(body), =
len(attachments)))=0A=
	tempFileName =3D tempfile.mktemp()=0A=
	tempFile =3D open(tempFileName,'wb')=0A=
	message =3D MimeWriter.MimeWriter(tempFile)=0A=
	message.addheader("From",sender)=0A=
	message.addheader("To", reduce(lambda a,b: a + ",\n    " + b, =
recipients))=0A=
	message.addheader("Subject", subject)=0A=
	message.flushheaders()=0A=
	if len(attachments) =3D=3D 0:=0A=
	    fp =3D message.startbody('text/plain')=0A=
	    fp.write(body)=0A=
	else:=0A=
	    message.startmultipartbody('mixed')=0A=
	    submessage =3D message.nextpart()=0A=
	    fp =3D submessage.startbody('text/plain')=0A=
	    fp.write(body)=0A=
	    for attachFile in attachments:=0A=
		if type(attachFile) =3D=3D types.StringType:=0A=
		    fileName =3D attachFile=0A=
		    filePath =3D attachFile=0A=
		elif type(attachFile) =3D=3D types.TupleType and len(attachFile) =
=3D=3D 2:=0A=
		    filePath,fileName =3D attachFile=0A=
		else:=0A=
		    raise "Attachments Error: must be pathname string or =
path,filename tuple"=0A=
                =0A=
		submessage =3D message.nextpart()=0A=
		submessage.addheader("Content-Disposition", "attachment; =
filename=3D%s" % fileName)=0A=
		ctype,prog =3D mimetypes.guess_type(fileName)=0A=
		if ctype =3D=3D None: =0A=
		    ctype =3D 'unknown/unknown'=0A=
		    =0A=
		if ctype =3D=3D 'text/plain':=0A=
		    enctype =3D 'quoted-printable'=0A=
		else:=0A=
		    enctype =3D 'base64'=0A=
		submessage.addheader("Content-Transfer-Encoding",enctype)=0A=
		fp =3D submessage.startbody(ctype)=0A=
		afp =3D open(filePath,'rb')=0A=
		mimetools.encode(afp,fp,enctype)=0A=
	    message.lastpart()=0A=
	    =0A=
	tempFile.close()=0A=
    =0A=
	# properly formatted mime message should be in tmp file=0A=
            =0A=
	tempFile =3D open(tempFileName,'rb')=0A=
	msg =3D tempFile.read()=0A=
	tempFile.close()=0A=
	os.remove(tempFileName)=0A=
	try:=0A=
	    server =3D smtplib.SMTP(self.__server)=0A=
	    if self.__debugLevel > 3: server.set_debuglevel(1)=0A=
	    server.sendmail(self.__src,self.__dest,msg)=0A=
	    if self.__debugLevel > 1:=0A=
		sys.stderr.write("SmptWriter: Message sent\n")=0A=
	finally:=0A=
            if server:=0A=
                server.quit()=0A=
=0A=
from getopt import getopt=0A=
=0A=
def handleOptions(argv,options,dict):=0A=
    global progName=0A=
    progName =3D argv[0]=0A=
    arglist,args =3D getopt(sys.argv[1:], '', ['help'] + =
options.keys())=0A=
    for arg in arglist:=0A=
	if arg[0] =3D=3D '--help':=0A=
	    print "%s: available options:" % (progName,)=0A=
	    for optionKey in options.keys():=0A=
		option =3D options[optionKey]=0A=
		if option[0] =3D=3D 'boolean':=0A=
		    param=3D''=0A=
		else:=0A=
		    param=3D'<'+option[0]+'>'=0A=
		print "%12s%-10s  %s (default: '%s')" % ('--'+optionKey, param, =
option[2], eval(option[1]))=0A=
	    sys.exit(1)=0A=
	else:=0A=
	    optValue =3D arg[1]=0A=
	    optKey =3D arg[0][2:]=0A=
	    if optValue !=3D '': =0A=
		optKey =3D optKey+'=3D'=0A=
	    option =3D options[optKey]=0A=
	    optType =3D option[0]=0A=
	    optVarname =3D option[1]=0A=
	    optVarfunc =3D option[3]=0A=
	    t =3D (optVarname,optValue)=0A=
	    =0A=
	    if optVarfunc:=0A=
		optVarfunc(optValue)=0A=
	    else:=0A=
		if   optType =3D=3D 'boolean': dict[optVarname] =3D 1=0A=
	        elif optType =3D=3D 'string':  dict[optVarname] =3D =
optValue=0A=
                elif optType =3D=3D 'integer': dict[optVarname] =3D =
int(optValue)=0A=
	        else: raise "Unknown option type '%s'" % optType=0A=
=0A=
		=0A=
#command line options=0A=
=0A=
server    =3D'localhost'=0A=
dest      =3D'postmaster'=0A=
source    =3D'postmaster@localhost'=0A=
settings  =3D'MS Exchange Settings'=0A=
delete    =3D0=0A=
daemon    =3D0=0A=
debugLevel=3D0=0A=
period    =3D60=0A=
=0A=
options =3D {=0A=
   'delete': ('boolean', 'delete', 'Delete messages from server', =
None),=0A=
  'server=3D': ('string',  'server', 'SMTP server', None),=0A=
    'dest=3D': ('string',  'dest',   'Destination email address', =
None),=0A=
    'from=3D': ('string',  'source', 'Source email address', None),=0A=
'settings=3D': ('string',  'settings', 'MAPI settings to use', =
None),=0A=
   'daemon': ('boolean', 'daemon', 'Run as daemon', None),=0A=
   'debug=3D': ('integer', 'debugLevel', 'Debug level', None),=0A=
  'period=3D': ('integer', 'period', 'Polling period (seconds)', =
None)=0A=
}=0A=
=0A=
handleOptions(sys.argv,options,globals())=0A=
=0A=
# create objects used to get messages from Exchange server and=0A=
# send messages to SMTP server=0A=
    =0A=
writer  =3D SmtpWriter(server=3Dserver, dest=3Ddest, src=3Dsource)=0A=
fetcher =3D MapiFetcher(settings)=0A=
=0A=
writer.Debug(debugLevel)=0A=
fetcher.Debug(debugLevel)=0A=
=0A=
# now forward the messages=0A=
=0A=
=0A=
while 1:=0A=
    try:=0A=
        fetcher.Logon()=0A=
        messages =3D fetcher.CheckInbox()=0A=
=0A=
        for message in messages:=0A=
            try:=0A=
                writer.Message( sender =3D message.Sender(),=0A=
                        recipients =3D message.Recipients(),=0A=
			   subject =3D message.Subject(),=0A=
			      body =3D message.Body(),=0A=
		       attachments =3D message.Attachments())=0A=
            except:=0A=
                sys.stderr.write("MapiFetcher: Error delivering =
message")=0A=
                traceback.print_exc(sys.stderr);=0A=
            else:=0A=
                if delete:=0A=
                    message.Delete()=0A=
                    if (debugLevel > 1):=0A=
                        sys.stderr.write("MapiFetcher: Message =
Deleted\n")=0A=
                if debugLevel > 0:=0A=
                    sys.stderr.write("MapiFetcher: Forwarded message =
From: %s; Subject: %s; Length=3D%d with %d attachments to %s on SMTP =
server %s\n" % (=0A=
                       message.Sender(),=0A=
                       message.Subject(),=0A=
                       len(message.Body()),=0A=
                       len(message.Attachments()),=0A=
                       dest,=0A=
                       server))=0A=
            message.DeleteAttachments()=0A=
        fetcher.Logoff()=0A=
    except '':=0A=
        sys.stderr.write("MapiFetcher: Error getting messages:\n")=0A=
        traceback.print_exc(sys.stderr);=0A=
        =0A=
    if not daemon:=0A=
        break=0A=
    =0A=
    time.sleep(period)=0A=
    =0A=
=0A=
    =0A=
=0A=
=0A=
=0A=
=0A=
=0A=

------_=_NextPart_000_01C1E13C.095C3610--



From help@python.org  Thu Apr 11 11:19:29 2002
From: help@python.org (Alex Martelli)
Date: Thu, 11 Apr 2002 12:19:29 +0200
Subject: [Tutor] Re: [Python-Help] SMTP with attachments
In-Reply-To: <0F757892D113D611BD2E0002559C1FF4637FE0@EMAIL>
References: <0F757892D113D611BD2E0002559C1FF4637FE0@EMAIL>
Message-ID: <E16vbfz-00026f-00@mail.python.org>

On Thursday 11 April 2002 11:34 am, Ezequiel, Justin wrote:
> How do I send an e-mail with attachments?
> I am a newbie so be gentle.

OK, but please don't cross-post so widely -- addressing only one of the
mailing lists you chose would be best.

If you use Python 2.2 (or have installed the separately available email
package), the email package is best.

At:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86674

you'll find an example of attaching all the files in the current directory.

I hope it's reasonably easy for you to edit this recipe if you want to
be more selecting or whatever.  Note that this recipe doesn't SEND
the email, it just BUILDS it (and writes it into a file called 
dirContentsMail); there are other recipes on the Cookbook for
SENDING, e.g.:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52243

(which you can also take as an example of using the older MimeWriter
way of preparing multipart mail, such as mail with attachments, should
you be unable to use the newer email module for whatever reason).


Alex



From alan.gauld@bt.com  Thu Apr 11 23:08:49 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 11 Apr 2002 23:08:49 +0100
Subject: [Tutor] Tk and Classes
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C540@mbtlipnt02.btlabs.bt.co.uk>

> myself classes and TK at the same time (They seem very interwoven)

Bad idea IMHO. Teach yourself classes frst then do Tkinter.
Tkinter uses classes but classes don't use Tkinter...

> class food:
>  def showfood(chosen):

This needs a self as first parameter

> FoodOption = StringVar()
> FoodOption.set('Spam')
> OptionMenu(root, FoodOption , 'Spam', 'Egg', 'Chips', 
> command=food.showfood(FoodOption)).pack()

You command tries to call the showfood method but 
should instead pass a reference to it. You need to try 
something like:

...command = lambda s=FoodOption: f.showfood(s)).pack()

Note that I use f which implies that somewere you have 
instantiated the food class to:

f = food()

You are missing several bits of the class/object jigsaw, 
thats why I'd recommend stepping back a bit to just 
learn OOP then move onto Tkinter.

Consider reading my OOP, event driven and GUI tutor pages.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From tbrauch@tbrauch.com  Thu Apr 11 23:42:06 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Thu, 11 Apr 2002 18:42:06 -0400
Subject: [Tutor] The Evil eval()
Message-ID: <003501c1e1aa$1dc193c0$1f01040a@centre.edu>

I am getting ready to write a program that will read the contents of a file
and then manipulate the data.  The file consists of a single list of lists
all on  one line.  Something like:

[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

If I understand correctly, when I read the file in, I will get a string and
to make it into a list of lists, I will have to use eval().  But, I also
know that is dangerous and if someone knew I used that for this program,
they could really mess things up.  My question is, how do I make sure that
what I am eval()-ing is a list of lists (of integers)?  That is the only
thing the input file should be, and I don't want it to work if there is
something else inthe input file.

 - Tim




From tbrauch@tbrauch.com  Fri Apr 12 03:37:36 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Thu, 11 Apr 2002 22:37:36 -0400
Subject: [Tutor] [OT] My Emails
Message-ID: <000901c1e1cb$03e78600$1f01040a@centre.edu>

It seems like any emails I send to tutor aren't making it through.  Or, if
they are, I am not getting a copy.  If someone reads this, please let me
<tbrauch@tbrauch.com> know.

 - Tim




From erikprice@mac.com  Fri Apr 12 03:51:47 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 22:51:47 -0400
Subject: [Tutor] constructors
In-Reply-To: <NEBBJNMDEKBIBCMCNMBDGEJNDJAA.karthikg@aztec.soft.net>
Message-ID: <3B4E7011-4DC0-11D6-844F-00039351FE6A@mac.com>

On Thursday, April 11, 2002, at 08:19  AM, Karthik Gurumurthy wrote:

> There are lots of rules/best practices laid down to decide whether you 
> need
> to throw an exception / return a boolean value.
>
> But i hope this explains one of the several uses of throwing an 
> exception.
> Basically proper error handling and exact information of the erroneous
> condition(reason) etc.
> Allowing the client to decide for himself , the course of action.

I see.  Throwing an exception is a more flexible way of "erroring-out", 
but it requires more work to code an appropriate response if you want to 
take advantage of this flexibility.

Is there a resource with the rules/best practices of throwing exceptions 
or returning boolean false?  To date, my code is not very reuseable -- I 
write my classes with a particular script in mind, and it returns false 
because I know that in my script that if it gets a "false" then the 
whole script should fail, because if any one part fails then the whole 
script is fatal.  But if I were writing a library, or something that I 
could use in a later project, I would be better-served by writing a more 
flexible class that is not so narrow-minded in scope.

Perhaps as I use OOP more I will develop this habit.


Erik




From erikprice@mac.com  Fri Apr 12 04:02:34 2002
From: erikprice@mac.com (Erik Price)
Date: Thu, 11 Apr 2002 23:02:34 -0400
Subject: [Tutor] constructors
In-Reply-To: <20020411191424.GA24388@dman.ddts.net>
Message-ID: <BCCDBABC-4DC1-11D6-844F-00039351FE6A@mac.com>

On Thursday, April 11, 2002, at 03:14  PM, dman wrote:

> In either case, you can't
> return a value from __init__ -> the object already exists and is
> referenced by 'self', the __init__ just initializes the data in it.
> If the __init__ method completes, then the client gets the reference
> to the object.  You can return 'false' or 'self' or 'fubar', but the
> client will never see it.

Ah. This is very important -- I was thinking that if the constructor 
returned false, then the instance would not be created.  Thank you.

> The do_something function doesn't need to do anything special (like
> check a return value and propagate it by returning it) to not ignore
> error conditions.  The module-level code doesn't need to interrupt the
> flow of the code by checking a return value either, and can handle the
> same type of error from both functions identically (if it wants to).

This is nice.  In PHP, I often do such code as:

if (!$connect = mysql_connect($connection_parameters)) {
   die("Database connection failed");
}

if (!$result = mysql_query($sql, $connection_handle)) {
   die("SQL query failed");
}

etc etc.
It gets very repetitive, and makes the code look ugly.  But I hadn't 
realized that this "interrupts the flow of code".

Exceptions are sweet -- I take it that they are another Python-centric 
feature, that does not exist in C/C++/Java?


Erik




From csmith@blakeschool.org  Fri Apr 12 05:44:10 2002
From: csmith@blakeschool.org (Christopher Smith)
Date: Thu, 11 Apr 2002 23:44:10 -0500
Subject: [Tutor] referring to list elements
Message-ID: <fc.004c4b6b00943bf8004c4b6b00943bf8.943c03@blakeschool.org>

Can someone educated in comp sci tell me whether you really refer to the
elements of a list, when speaking, as zero-eth, one-eth, two-eth, etc...,
as described in the How to Think book?  What do you do when you get to the
fifth element: do you call it the four-eth element?  If you refer to them
in the natural linguistic sense as '1st', '2nd', etc..., are you always
doing a little mental gymnastics to remember that the index is one less
than the actual element position in the ordinal sense?

['1st','2nd','3rd','4th','5th'] #indices [0,1,2,3,4]

/c




From paulsid@shaw.ca  Fri Apr 12 05:52:37 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Thu, 11 Apr 2002 22:52:37 -0600
Subject: [Tutor] << operator ?  [left bitwise shifting]
References: <0EC50D28-4D43-11D6-9F94-00039351FE6A@mac.com>
Message-ID: <3CB66815.A04B70F2@shaw.ca>

Erik Price wrote:

> That's good.  I understand now what it's for (sort of a way of
> "encoding/compressing" data like reducing an AIF file to MP3 for
> internet transmission, but without lossiness, but it's not really
> encoding is it).  

That's the right idea, though.  

If you have some familiarity with compression, check out the the zipfile
module source.  That was the file with the most hits on <<.  So long as
you have a general idea of what it's trying to do it will serve as a
good real-life example of the use of <<.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From urnerk@qwest.net  Fri Apr 12 07:45:19 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 11 Apr 2002 23:45:19 -0700
Subject: [Tutor] constructors
In-Reply-To: <BCCDBABC-4DC1-11D6-844F-00039351FE6A@mac.com>
References: <20020411191424.GA24388@dman.ddts.net>
Message-ID: <4.2.0.58.20020411234436.01a30620@pop3.norton.antivirus>

>
>Exceptions are sweet -- I take it that they are another Python-centric 
>feature, that does not exist in C/C++/Java?

Java has exceptions.  Similar in a lot of ways.

Kirby




From hall@nhn.ou.edu  Fri Apr 12 08:03:49 2002
From: hall@nhn.ou.edu (Ike Hall)
Date: Fri, 12 Apr 2002 02:03:49 -0500
Subject: [Tutor] Tk and Classes
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C540@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C540@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <200204120644.g3C6iEX24426@phyast.nhn.ou.edu>

This is not necessarily the only way to go about doing this.  When I first 
began learning python, the whole reason for doing so was to create a gui 
application for use in a Physics experiment by way of Tkinter/Pmw.  Now I am 
a physics grad student, and do not really consider myself a programmer, 
althogh the other members of my collaboration are now calling me the python 
expert....eeek...anyway, before doing so, my only experience with OOP and 
classes and such was merely in passing.  I had done some programming in C and 
fortran before (simply to get thru nasty calculations quickly) and never 
needed objects.  So learning python for me began with the first few chapters 
of the python tutorial simply to see how the data types and flow structures 
worked in python, and then from there I dove straight in to Tkinter by way of 
Fredrick Lundh(sp?)'s Tkinter guide.  In doing so I was able to quickly write 
short scripts to flash pretty displays on the screen, and thus get used to 
using Tkinter when I decided that in order to write the larger application 
that was needed, widget classes would need to be created by me in order to 
make the thing work, so in order to learn how classes work in python (and 
with Tkinter) I did two things, first I looked on the web for any and all 
sample programs I could find  on the web.  This was helpful, but at the same 
time very frustrating, as some of the examples were difficult to follow due 
to sparse commenting and usage of commands and commands that a newbie like me 
at the time (and sometimes I still consider myself a newbie even tho Ive been 
working in python now almost every day for almost a year) was unfamiliar 
with.  so noting that I decided to to spend the $45 bucks or so to buy 
Programming Python by Mark Lutz, which I might add is a fine text.  By 
following many of the examples in that book (and depending on how far you 
have already progressed, not necessarily in order), I think, it is very very 
possible to learn how to manipulate classes and use Tkinter in a fluid 
manner.  I did anyway....well, ok, I still am learning too, but that is 
because I learn based on my needs.  (i.e., I need to do this, how can I do 
it).  Of course as we all know that is not always the best way to learn.  But 
I find that for me, that is the way that sticks.  However, because that is 
the way I choose to learn python, my programs have gone through countless 
revisions as I have learned new tricks and better ways of doing the same 
thing.  But I don't mind.   Anyway, sorry to get long on everyone, but I 
thought it might help to see that there are many ways of teaching yourself 
what you need to know, and this is one of them.  Good luck!!!

On Thursday 11 April 2002 05:08 pm, you wrote:
> > myself classes and TK at the same time (They seem very interwoven)
>
> Bad idea IMHO. Teach yourself classes frst then do Tkinter.
> Tkinter uses classes but classes don't use Tkinter...
>
> > class food:
> >  def showfood(chosen):
>
> This needs a self as first parameter
>
> > FoodOption = StringVar()
> > FoodOption.set('Spam')
> > OptionMenu(root, FoodOption , 'Spam', 'Egg', 'Chips',
> > command=food.showfood(FoodOption)).pack()
>
> You command tries to call the showfood method but
> should instead pass a reference to it. You need to try
> something like:
>
> ...command = lambda s=FoodOption: f.showfood(s)).pack()
>
> Note that I use f which implies that somewere you have
> instantiated the food class to:
>
> f = food()
>
> You are missing several bits of the class/object jigsaw,
> thats why I'd recommend stepping back a bit to just
> learn OOP then move onto Tkinter.
>
> Consider reading my OOP, event driven and GUI tutor pages.
>
> Alan g.
> Author of the 'Learning to Program' web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From shalehperry@attbi.com  Fri Apr 12 08:02:54 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Apr 2002 00:02:54 -0700 (PDT)
Subject: [Tutor] The Evil eval()
In-Reply-To: <003501c1e1aa$1dc193c0$1f01040a@centre.edu>
Message-ID: <XFMail.20020412000254.shalehperry@attbi.com>

On 11-Apr-2002 Timothy M. Brauch wrote:
> I am getting ready to write a program that will read the contents of a file
> and then manipulate the data.  The file consists of a single list of lists
> all on  one line.  Something like:
> 
> [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
> 
> If I understand correctly, when I read the file in, I will get a string and
> to make it into a list of lists, I will have to use eval().  But, I also
> know that is dangerous and if someone knew I used that for this program,
> they could really mess things up.  My question is, how do I make sure that
> what I am eval()-ing is a list of lists (of integers)?  That is the only
> thing the input file should be, and I don't want it to work if there is
> something else inthe input file.
> 

you could use a regex.  The input should only be whitespace, comma, [], or a
number.



From shalehperry@attbi.com  Fri Apr 12 08:04:26 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Apr 2002 00:04:26 -0700 (PDT)
Subject: [Tutor] [OT] My Emails
In-Reply-To: <000901c1e1cb$03e78600$1f01040a@centre.edu>
Message-ID: <XFMail.20020412000426.shalehperry@attbi.com>

On 12-Apr-2002 Timothy M. Brauch wrote:
> It seems like any emails I send to tutor aren't making it through.  Or, if
> they are, I am not getting a copy.  If someone reads this, please let me
> <tbrauch@tbrauch.com> know.
> 

I have received 4 on April 6th and two today (including this one).



From shalehperry@attbi.com  Fri Apr 12 08:05:51 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 12 Apr 2002 00:05:51 -0700 (PDT)
Subject: [Tutor] referring to list elements
In-Reply-To: <fc.004c4b6b00943bf8004c4b6b00943bf8.943c03@blakeschool.org>
Message-ID: <XFMail.20020412000551.shalehperry@attbi.com>

On 12-Apr-2002 Christopher Smith wrote:
> Can someone educated in comp sci tell me whether you really refer to the
> elements of a list, when speaking, as zero-eth, one-eth, two-eth, etc...,
> as described in the How to Think book?  What do you do when you get to the
> fifth element: do you call it the four-eth element?  If you refer to them
> in the natural linguistic sense as '1st', '2nd', etc..., are you always
> doing a little mental gymnastics to remember that the index is one less
> than the actual element position in the ordinal sense?
> 
> ['1st','2nd','3rd','4th','5th'] #indices [0,1,2,3,4]
> 

I use 1st, 2nd, 3rd, ... and just remember that the first element is 0, not 1.



From slime@vsnl.net  Fri Apr 12 09:29:25 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Fri, 12 Apr 2002 04:29:25 -0400
Subject: [Tutor] << operator ?  [left bitwise shifting]
In-Reply-To: <Pine.LNX.4.44.0204101349461.3016-100000@hkn.eecs.berkeley.edu>
References: <E16vOhZ-00028g-00@mail.python.org> <Pine.LNX.4.44.0204101349461.3016-100000@hkn.eecs.berkeley.edu>
Message-ID: <E16vwQv-0001YI-00@mail.python.org>

Hi,

Thanks to all for their explanations. But, let me prod a little further
(OT) ...

On Wed, 10 Apr 2002 Danny Yoo spewed into the ether:
[-- snippity --]
> And this is what we mean when we say that computers count in base-two
> arithmetic --- they represent numbers by using on/off switches --- "bits".
> On most systems that Python runs on, each integer is made up of 32 bits.

Hmm .. is this the difference between the computers used popularly
today, and the new IA-64 architecture ? If so, does a "2" on a 64-bit
machine have 32 more zeroes in front of it, than a "2" on a 32-bit
machine ?

> It turns out that bits are really useful because we don't have to say that
> 32 bits always stand for a number: we can use those bits as 32 individual
> "yes/no" choices!

Ahh .. now I remember the Boolean Algebra we did in school. Ok, that
clears it up nicely :-)

> Here's a concrete example: the Unix operating system uses numeric codes to
> say if a particular file is readable, writable, or executable --- each
> file has a "permission" number connected to it.  The number "7", for
> example, has the following bit representation:
[-- snippity --]

Ok. I think I've got a hang of what these operators do. Now to go find
a binary file to play with in "pure" python .... :-)

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

The appreciation of the average visual graphisticator alone is worth
the whole suaveness and decadence which abounds!!





From slime@vsnl.net  Fri Apr 12 09:29:25 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Fri, 12 Apr 2002 04:29:25 -0400
Subject: [Tutor] constructors
In-Reply-To: <0610390F-4C77-11D6-A863-00039351FE6A@mac.com>
References: <4.3.2.7.2.20020410124054.00cf0100@pop3.norton.antivirus> <0610390F-4C77-11D6-A863-00039351FE6A@mac.com>
Message-ID: <E16vwQv-0001YJ-00@mail.python.org>

Hi,

On Wed, 10 Apr 2002 Erik Price spewed into the ether:
[-- snippity --]
> Since Python is loosely/weakly/dynamically typed, does initializing 
> really matter a great deal?  Or is it just to allow us to use 
> polymorphism in a later method (by not requiring that later method to 

Ok, taking the risk of sounding *very* duh, 

    What does polymorphism mean ?

Going by it's name, it probably involves changing something (method,
variable, etc.) many times. Is this the same as over-riding a method of
the base class during inheritance ?
</wild guess>

> specify a tuple over a list, for instance, because a tuple has already 
> been specified in the constructor, which makes the later method more 
> "general").
> 
> >The __init__ constructor is executed when a class instance is created, 
> >hence you are sure it runs once (at least in "classic" classes; the 
> >rules may have changed for the new-type classes in Python 2.2).
> 
> I am using 2.2 and probably won't need to use an older version.  But can 
> you tell me a bit more about "new-type classes"?  And how they're 
> different from "classic" classes?

I am in the process of reading amk's document, and find the __slots__
attribute extremely cool in preventing some ghastly typos on my part :-)

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Nothing ever becomes real until it is experienced.
- John Keats





From slime@vsnl.net  Fri Apr 12 09:29:27 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Fri, 12 Apr 2002 04:29:27 -0400
Subject: [Tutor] Re:  SMTP with attachments
In-Reply-To: <0F757892D113D611BD2E0002559C1FF4637FE0@EMAIL>
References: <0F757892D113D611BD2E0002559C1FF4637FE0@EMAIL>
Message-ID: <E16vwQx-0001YW-00@mail.python.org>

Hi,

On Thu, 11 Apr 2002 Ezequiel, Justin spewed into the ether:
> How do I send an e-mail with attachments?

I recently found a module to do just that, which I find very useful.

Since I don't remember where I got it from, I've put it up here :

    http://www.symonds.net/~prahladv/files/MailMsg.py

The email module had a bug until recently when handling certain types of
attachments, so unless you have a fairly recent Python, I don't advise
using it. MimeWriter et al work fine :-)

HTH,

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

If God hadn't wanted you to be paranoid, He wouldn't have given you such
a vivid imagination.






From alex@gabuzomeu.net  Fri Apr 12 09:56:32 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 12 Apr 2002 10:56:32 +0200
Subject: [Tutor] How to put two things together and then print to a
 file?
In-Reply-To: <20020412053926.8895.31719.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020412103825.00d263b0@pop3.norton.antivirus>

Hello,


At 01:39 12/04/2002 -0400, you wrote:
>From: "Bob X" <bobx@linuxmail.org>
>Date: Fri, 12 Apr 2002 01:21:09 +0800
>Subject: [Tutor] How to put two things together and then print to a file?
>
>The following works really great, except that I would like the word or 
>words found to print first and then the line it was found on like so:
>
>word "this is where the word was found"

You want to print the word, and then the full line between quotation marks. 
Is this correct?

>import sys, string
>
>inp = open(sys.argv[1],"r")
>outp = open(sys.argv[2],"w")
>
># build list of keywords
>kw = ["word", "ape"]
>
># loop through the list and print the lines to a file
>for line in inp.readlines():
>     for badword in kw:
>         if line.find(badword) > -1:

Try this:
               # Concatenate both strings: the format string
               # is enclosed in single quotes because it contains
               # quotation marks.
               result = '%s "%s"' % (badword, line)
               # Print out the result
               print result
               # Write the result into the output file
               outp.write (result)

># close the files
>inp.close()
>outp.close()
>
># let me know when it's done doing its thang
>print "Finished processing file..."


Cheers.

Alexandre





From lha2@columbia.edu  Fri Apr 12 10:31:15 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Fri, 12 Apr 2002 05:31:15 -0400
Subject: [Fwd: Re: [Tutor] The Evil eval()]
Message-ID: <3CB6A963.AFDFCC3F@mail.verizon.net>


-------- Original Message --------
From: Lloyd Hugh Allen <l.h.allen@mail.verizon.net>
Subject: Re: [Tutor] The Evil eval()
To: Sean 'Shaleh' Perry <shalehperry@attbi.com>

Sean 'Shaleh' Perry wrote:
> 
> On 11-Apr-2002 Timothy M. Brauch wrote:
> > I am getting ready to write a program that will read the contents of a file
> > and then manipulate the data.  The file consists of a single list of lists
> > all on  one line.  Something like:
> >
> > [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
> >
> > If I understand correctly, when I read the file in, I will get a string and
> > to make it into a list of lists, I will have to use eval().  But, I also
> > know that is dangerous and if someone knew I used that for this program,
> > they could really mess things up.  My question is, how do I make sure that
> > what I am eval()-ing is a list of lists (of integers)?  That is the only
> > thing the input file should be, and I don't want it to work if there is
> > something else inthe input file.
> >
> 
> you could use a regex.  The input should only be whitespace, comma, [], or a
> number.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Which in Python 2.2 should be the module "re". A "gentle" how-to is at
<http://py-howto.sourceforge.net/regex/regex.html>.

Alternatively, if you're in a hurry and don't mind being slow, you could
run a for loop on your string and ensure that each character is in "[],
1234567890", or (more generously) in
"[],"+string.whitespace+string.digits



From alan.gauld@bt.com  Fri Apr 12 10:53:58 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 10:53:58 +0100
Subject: [Tutor] Tk and Classes
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C542@mbtlipnt02.btlabs.bt.co.uk>

> of the python tutorial simply to see how the data types and 
> flow structures worked in python, and then from there 
> I dove straight in to Tkinter by way of Fredrick Lundh(sp?)'s 
> Tkinter guide.  

There is a good point to be made here in that Tkinter 
although class based does not need to use OOP to write a GUI. 
So there is the alternative approach of using the Tkinter 
classes but in a procedural style. This gives rise to lots 
of limitations when you try to move to bigger projects 
but is certainly doable in the short term.

The problem with learning OOP and Tkinter together is that 
you are likely to learn some really bad habits on both 
sides because they are both fairly complex subjects with 
more than one way of doing it - mosty of them suboptimal!

But if you just need to throw a GUI together to do a job 
and don't care about writing the same code over and over,
or creating your own widgets etc then you can more or 
less ignore OOP and just do Tkinter.

> possible to learn how to manipulate classes and use Tkinter 

Yes you can learn how to *manipulate* classes but much 
harder to learn *about* classes as well as Tkinter. 
Depends on how you define learning about classes I guess.
You can learn about how to manipulate classes from many 
aspects of Python, including files, sequences, etc...

> the way I choose to learn python, my programs have gone 
> through countless revisions as I have learned new tricks 
> and better ways of doing the same thing.  But I don't mind.   

And thats the key. If you can afford to spend the time
rewritring/refactoring code as you progress then its a 
valid approach. If you have to produce some production 
strength code quickly a more merthodical approach is 
probably better.

> thought it might help to see that there are many ways of 
> teaching yourself what you need to know

A good point and worth making.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From budgester@budgester.com  Fri Apr 12 11:31:14 2002
From: budgester@budgester.com (Martin Stevens)
Date: Fri, 12 Apr 2002 11:31:14 +0100
Subject: [Tutor] Tk and Classes
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C542@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C542@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020412103114.GA26324@akira.budgenet>

Thanks for that,

So now i'm gonna keep plugging away, i'm sure i found this stuff easier
to learn 10 years ago when i was still a teenager.

Anyway, I think i'm moving closer to the break point when my
brain goes 'Oh yes, thats how you do it, how could i have been so thick'

Last night at a  LUG meeting i  grabbed one of the known OO coders and
asked him to explain to me some stuff, and between us we came up
with a stunning example using glasses as a class, and various methods
such as, fill, sip, empty, and smash, He then explained with the help
of a half pint, pint, and pitcher, how to create objects etc.

So once i've got rid of this hangover...........



On Fri, Apr 12, 2002 at 10:53:58AM +0100, alan.gauld@bt.com wrote:
> > of the python tutorial simply to see how the data types and 
> > flow structures worked in python, and then from there 
> > I dove straight in to Tkinter by way of Fredrick Lundh(sp?)'s 
> > Tkinter guide.  
> 
> There is a good point to be made here in that Tkinter 
> although class based does not need to use OOP to write a GUI. 
> So there is the alternative approach of using the Tkinter 
> classes but in a procedural style. This gives rise to lots 
> of limitations when you try to move to bigger projects 
> but is certainly doable in the short term.
> 
> The problem with learning OOP and Tkinter together is that 
> you are likely to learn some really bad habits on both 
> sides because they are both fairly complex subjects with 
> more than one way of doing it - mosty of them suboptimal!
> 
> But if you just need to throw a GUI together to do a job 
> and don't care about writing the same code over and over,
> or creating your own widgets etc then you can more or 
> less ignore OOP and just do Tkinter.
> 
> > possible to learn how to manipulate classes and use Tkinter 
> 
> Yes you can learn how to *manipulate* classes but much 
> harder to learn *about* classes as well as Tkinter. 
> Depends on how you define learning about classes I guess.
> You can learn about how to manipulate classes from many 
> aspects of Python, including files, sequences, etc...
> 
> > the way I choose to learn python, my programs have gone 
> > through countless revisions as I have learned new tricks 
> > and better ways of doing the same thing.  But I don't mind.   
> 
> And thats the key. If you can afford to spend the time
> rewritring/refactoring code as you progress then its a 
> valid approach. If you have to produce some production 
> strength code quickly a more merthodical approach is 
> probably better.
> 
> > thought it might help to see that there are many ways of 
> > teaching yourself what you need to know
> 
> A good point and worth making.
> 
> Alan g.
> Author of the 'Learning to Program' web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Budgester Technologies Ltd
Office : 01992 718568
Mobile : 07815 982380
mailto:martin@budgester.com
http://www.budgester.com



From alan.gauld@bt.com  Fri Apr 12 11:32:17 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 11:32:17 +0100
Subject: [Tutor] << operator ?  [left bitwise shifting]
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C543@mbtlipnt02.btlabs.bt.co.uk>

> > And it turns out that when we left shift a number, it effectively
> > "doubles".
> Having seen the bitwise shift operator but having no idea 
> what it was for, I appreciate this ...
> But now I'm just curious what it's for...
> double numbers?  And if that's the case, then what's the 
> right bitwise shift operator for?

To half numbers!

Seriously bit shifting is often used as a more efficient way 
of dividing or multiplying by powers of two. But it really 
shouldn't be unless you have to for performance reasons, 
and in Python that should mean never since if performanmce 
is that desparate rewrite in C!

Bit shifting is primarily for manipularting bit patterns.
This ois often important when dealing with low level network 
protocols where specific bits of information are contained 
within a few bits within abn octet.

Thus is some fictitious protocol:

Bit 0 - Data(1) or signalling(0)
Bit 1 - data 1/msg ID #1 
Bit 2 - data 2/msg ID #2 
Bit 3 - data 3/msg ID #3 - 3 msg bits allows 8 messages 
Bit 3 - data 4/msg data 1
Bit 5 - data 5/msg data 2
Bit 6 - data 6/msg data 3
Bit 7 - parity bit/ status indicator

Here the first bit tells the receiver that the octet 
is either a data octet or a signalling octet.
The subsequent bits depend on the first to indicate 
their meaning, if data then we have 6 data contrent 
bits plus a parity bit

If its a signalling octet then the second 3 bits 
contain the message ID and the next 3 bits again 
the message data(which could be a length to say 
that say the next 4 octets contain the real 
message data etc...

Now the receiver checks the valkue of the first 
bit by doing a bitwise AND with a bitmask or 00000001
to determine which kind of octet is being received.

if octet & 0x01: # its data
else: # its a signal

He can now extract the data bits if itsa a data octent 
using another bitmask:

data = octet & 0x7E  # 01111110

But to use them needs to shift the bits one place right:

data = data >> 1

now data contains the 6 data bits in the lowest bit 
positions of the data variable as you would expect 
in a normal variable value.

If OTOH its a signalling octet we must extract both 
the message ID and messaage data.

We could use two masks(and personally I would!) but 
another technique is to use a single mask and multiple 
shifts:

msgmask = 0x07   # 00000111

octet = octet >> 1   # lose the type bit
msg = octet & msgmask  # extract the bottom 3 bits

octet = octet >> 3   # lose ID and put data in the bottom bits
msgdata = octet & msgmask

So now we can pass the info onto our message 
handling routines:

handleMessage(msg, msgdata)

Of course we still have to extract and check our parity 
bit in the case of pure data but I leave that as an 
excercise for the reader!

At the sender we use similar techniques but left shifting 
to put the data into the octet for transmission.

octet = 0  # initialise empty octet
msgID = 5 << 1  # put ID in right place
msg data = 3 << 4 # put data in right place

# now bitwise all those together to get the octet ready to send
octet = octet & msgID & msgdata & getParity(msgdata)

Note I assume a parity checking function to produce 
the right parity bit value...

Hopefully that serves as an example of how bitmasks can 
be used outside of binary arithmetic. In fact its how 
I use them almost exclusively, if I'm doing arithmetic 
I like to make that obvious and use arithmetic operators!
If I'm doing bit twiddling I use bit twiddling operators.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Fri Apr 12 11:35:30 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 11:35:30 +0100
Subject: [Tutor] How do you make a module
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C544@mbtlipnt02.btlabs.bt.co.uk>

> I have several functions that I've written and use in 
> multiple programs.  I
> would like to put them in a module for easier maintainability.  Could
> somebody point me to a tutorial that will explain how?

Try the modules chaprter of my tutor(see sig)

> Once it's made, what directory does it go in?

Anywhere thats in your PYTHONPATH value.
Or anywhere and add that place to your PYTHONPATH....

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Fri Apr 12 11:43:14 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 11:43:14 +0100
Subject: [Tutor] << operator ?  [left bitwise shifting]
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C545@mbtlipnt02.btlabs.bt.co.uk>

> have you ever looked at the source code for Google pages?  
> Very little whitespace, no verbosity at all.  It's like 
> the opposite of XML 

Correct. Google is very popular because its fast. One 
reason its fast it they optimise the HTML they send 
so it doesn't hog bandwith sending unnecessary bytes.

Its a trait I commend to web designers everywhere!

If you are sending XML files around on a LAN then the huge 
bandwidth overhead (approximately 70% wasted bandwidth in 
XML over binary) is probably not an issue, if you are 
sending XML over the net remember that you are mostly 
just making a case for broadband!

Alan g.



From alan.gauld@bt.com  Fri Apr 12 11:46:04 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 11:46:04 +0100
Subject: [Tutor] constructors
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C546@mbtlipnt02.btlabs.bt.co.uk>

> Is this manipulation of class variables a side effect of how Python 
> works, or is that desired behavior?  

Its the definition of class variables (and indeed class 
methods which are now allowed in Python 2.2(static methods)


> I haven't seen their use either (such as 
> Classname.classvariablename) so I wonder if there is 
> any reason to stay away from this kind of functionality.

Not so long as you are clear as to why you are using them
My Python games framework and the Hangman example on 
Useless python (hmgui.zip) shows class variables in action.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alex@gabuzomeu.net  Fri Apr 12 11:57:16 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 12 Apr 2002 12:57:16 +0200
Subject: [Tutor] constructors
In-Reply-To: <20020412093302.1316.11610.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020412124103.00b8f7f0@pop3.norton.antivirus>

Hello,


At 05:33 12/04/2002 -0400, you wrote:
>From: Prahlad Vaidyanathan <slime@vsnl.net>
>Subject: Re: [Tutor] constructors
>Date: Fri, 12 Apr 2002 04:29:25 -0400

> > Since Python is loosely/weakly/dynamically typed, does initializing
> > really matter a great deal?  Or is it just to allow us to use
> > polymorphism in a later method (by not requiring that later method to
>
>Ok, taking the risk of sounding *very* duh,
>
>     What does polymorphism mean ?
>
>Going by it's name, it probably involves changing something (method,
>variable, etc.) many times. Is this the same as over-riding a method of
>the base class during inheritance ?

Here is a definition I came across:

<QUOTE>
Generally, the ability to appear in many forms. In object-oriented 
programming, polymorphism refers to a programming language's ability to 
process objects differently depending on their data type or class. More 
specifically, it is the ability to redefine methods for derived classes. 
For example, given a base class shape, polymorphism enables the programmer 
to define different circumference methods for any number of derived 
classes, such as circles, rectangles and triangles. No matter what shape an 
object is, applying the circumference method to it will return the correct 
results. Polymorphism is considered to be a requirement of any true 
object-oriented programming language (OOPL).
The type of polymorphism described above is sometimes called parametric 
polymorphism to distinguish it from another type of polymorphism called 
overloading.
</QUOTE>

Source: http://webopedia.lycos.com/TERM/P/polymorphism.html

See also: http://www.ibiblio.org/obp/thinkCSpy/chap14.htm#9


Cheers.

Alexandre




From alan.gauld@bt.com  Fri Apr 12 13:39:48 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 13:39:48 +0100
Subject: [Tutor] The Evil eval()
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C548@mbtlipnt02.btlabs.bt.co.uk>

> list of lists all on  one line.  Something like:
> 
> [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 
> 12, 16, 20]]
> 
> I will have to use eval().  

Thats the easy way to do it yes.

> know that is dangerous and if someone knew I used that for 
> this program, they could really mess things up.  

If they have access to edit the file certainly.

> My question is, how do I make sure that
> what I am eval()-ing is a list of lists (of integers)?  

The only way to be sure is to parse the entire file.
If you feel that is necessary I would actually consider 
moving the data format to XML and using the precanned 
parsers.

But is it really the case? Is there no way you can be 
confident that the data files will not be tampered with?

One other thing which is pretty secure but not bombproof 
would be to calculate a checksum for the file and store 
that somewhere. You can compare the checksum with the 
current files checksum to see if it has changed. 
Thats pretty solid but not absolutely 100%...

Alan G.



From alan.gauld@bt.com  Fri Apr 12 13:59:50 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 13:59:50 +0100
Subject: [Tutor] constructors
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C549@mbtlipnt02.btlabs.bt.co.uk>

> I see.  Throwing an exception is a more flexible way of 
> "erroring-out", but it requires more work to code 
> an appropriate response if you want to 
> take advantage of this flexibility.

Not much more in practice.

errCode = operation(foo)
if errCode == ERROR_1:
   # do something
elif errCode == ERROR_2:
   # do another
else: print "unexpected error , errCode, " occured"

try: operation(foo)
except ERROR_1: 
	# do something
except ERROR_2:
	# do another
except: print "Unexpected error "

Apart from typing raise ERROR_1 instead of return ERROR_1
the originating code isn't much doifferent either.

The only snag is that sometimes you can lose context 
which makes it harder to recover from an exception 
that a return valued error. In that case you wind up 
with a lot of

try: doit()
except: #recover here

two line pairs, but again no worse than explicit return 
value checks.

Just my 2 cents worth...

Alan g.



From alan.gauld@bt.com  Fri Apr 12 14:01:49 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 12 Apr 2002 14:01:49 +0100
Subject: [Tutor] constructors
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C54A@mbtlipnt02.btlabs.bt.co.uk>

> Exceptions are sweet -- I take it that they are another 
> Python-centric feature, that does not exist in C/C++/Java?

Au contraire, they exist in many languages 
- I think ADA was the first major one? Certainly the 
first I saw...

C++, Java and Delphi all have very similar exception 
schemes to python.

Alan g



From pythontutor@venix.com  Fri Apr 12 14:13:53 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Fri, 12 Apr 2002 09:13:53 -0400
Subject: [Tutor] The Evil eval()
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C548@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3CB6DD91.6000200@venix.com>

Does the file with the lists come from a Python program?
Do you control the creation of the file?

A somewhat off the wall approach would be to:
	change the output format to:
		thelist = [[....]]	# use a variable name that makes sense
	write the line to a python file (e.g.thelist.py)
	import thelist	# forces compilation of pyc
		# effectively you are doing the eval once when you create the list
	del / unlink the file thelist.py

	Now when you need the list data, import it using the .pyc file created earlier.

The .pyc file is harder to subvert than the simple eval of a line of text, but certainly
isn't foolproof.  You will need to determine the appropriate level of paranoia.
This kind of approach could possibly be improved using the builtin compile function.

alan.gauld@bt.com wrote:

>>list of lists all on  one line.  Something like:
>>
>>[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 
>>12, 16, 20]]
>>
>>I will have to use eval().  
>>
> 
> Thats the easy way to do it yes.
> 
> 
>>know that is dangerous and if someone knew I used that for 
>>this program, they could really mess things up.  
>>
> 
> If they have access to edit the file certainly.
> 
> 
>>My question is, how do I make sure that
>>what I am eval()-ing is a list of lists (of integers)?  
>>
> 
> The only way to be sure is to parse the entire file.
> If you feel that is necessary I would actually consider 
> moving the data format to XML and using the precanned 
> parsers.
> 
> But is it really the case? Is there no way you can be 
> confident that the data files will not be tampered with?
> 
> One other thing which is pretty secure but not bombproof 
> would be to calculate a checksum for the file and store 
> that somewhere. You can compare the checksum with the 
> current files checksum to see if it has changed. 
> Thats pretty solid but not absolutely 100%...
> 
> Alan G.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From m_konermann@gmx.de  Fri Apr 12 14:58:54 2002
From: m_konermann@gmx.de (Keule)
Date: Fri, 12 Apr 2002 15:58:54 +0200
Subject: [Tutor] Embedding a simple python module
Message-ID: <3CB6E81E.208@gmx.de>

Hi @ All !

I find the following example in the "Programming Python" book (sec. 
edition, page 1167):

file module.py:
# call this class from C to make objects

class klass:
    def method(self, x, y):
        return "brave %s %s" % (x, y)   # run me from C

and now the python function is used in C by the following code:

file objects-low.c:
#include <Python.h>
#include <stdio.h>

main() {
  /* run objects with low-level calls */
  char *arg1="sir", *arg2="robin", *cstr;
  PyObject *pmod, *pclass, *pargs, *pinst, *pmeth, *pres;

  /* instance = module.klass() */
  Py_Initialize();
  pmod   = PyImport_ImportModule("module");         /* fetch module */
  pclass = PyObject_GetAttrString(pmod, "klass");   /* fetch module.class */
  Py_DECREF(pmod);

  pargs  = Py_BuildValue("()");
  pinst  = PyEval_CallObject(pclass, pargs);        /* call class() */
  Py_DECREF(pclass);
  Py_DECREF(pargs);

  /* result = instance.method(x,y) */
  pmeth  = PyObject_GetAttrString(pinst, "method"); /* fetch bound method */
  Py_DECREF(pinst);
  pargs  = Py_BuildValue("(ss)", arg1, arg2);       /* convert to Python */
  pres   = PyEval_CallObject(pmeth, pargs);         /* call method(x,y) */
  Py_DECREF(pmeth);
  Py_DECREF(pargs);

  PyArg_Parse(pres, "s", &cstr);                    /* convert to C */
  printf("%s\n", cstr);
  Py_DECREF(pres);
}

In this example the class instance is initiated by the following:

object = module.klass()

but, what will be change if i want to initiate a class instance like the 
following:

object = module.klass(x,y,z)


Have anyone got an idea ?
Thanks a lot
Marcus






From glingl@aon.at  Fri Apr 12 15:02:17 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 12 Apr 2002 16:02:17 +0200
Subject: [Tutor] The Evil eval()
References: <003501c1e1aa$1dc193c0$1f01040a@centre.edu>
Message-ID: <003601c1e22a$a8aa6e50$1664a8c0@mega>



> I am getting ready to write a program that will read the contents of a
file
> and then manipulate the data.  The file consists of a single list of lists
> all on  one line.  Something like:
>
> [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
>
> If I understand correctly, when I read the file in, I will get a string
and
> to make it into a list of lists, I will have to use eval().  But, I also
> know that is dangerous and if someone knew I used that for this program,
> they could really mess

If this list of lists is produced by a Python program (as some of the
answers
you got until now seem to assume): why not use pickle?

>>> import pickle
>>> f = open("pickletest.data","w")
>>> a = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12,
16, 20]]
>>> pickle.dump(a,f)
>>> f.close()
>>> f = open("pickletest.data","r")
>>> b = pickle.load(f)
>>> b
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
>>>

Wouldn't this solve your problem?

Gregor





From slime@vsnl.net  Fri Apr 12 15:25:10 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Fri, 12 Apr 2002 10:25:10 -0400
Subject: [Tutor] Re:  SMTP with attachments
In-Reply-To: <m2elhl9k9n.fsf@nathan.mail.a-nugget.de> <0F757892D113D611BD2E0002559C1FF465BAA0@EMAIL>
References: <0F757892D113D611BD2E0002559C1FF4637FE0@EMAIL> <mailman.1018600250.7040.python-list@python.org> <m2elhl9k9n.fsf@nathan.mail.a-nugget.de> <0F757892D113D611BD2E0002559C1FF465BAA0@EMAIL>
Message-ID: <E16w1zC-0002tJ-00@mail.python.org>

Hi,

On Fri, 12 Apr 2002 Guido Goldstein spewed into the ether:
> 
> Hi!
> 
> On Fri, 12 Apr 2002 04:29:27 -0400
>   Prahlad Vaidyanathan <slime@vsnl.net> wrote:
> [...]
> >     http://www.symonds.net/~prahladv/files/MailMsg.py
> 
> <reply-in-browser code="403">
> You're not authorized to view this document
> The permissions set on this file says you can't view it.
> </reply-in-browser>

Oops ! Pardon my faux pas. The perms have been fixed - so try again now.

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

If practice makes perfect, and nobody's perfect, why practice?





From slime@vsnl.net  Fri Apr 12 15:45:25 2002
From: slime@vsnl.net (Prahlad Vaidyanathan)
Date: Fri, 12 Apr 2002 10:45:25 -0400
Subject: [Tutor] constructors
In-Reply-To: <4.3.2.7.2.20020412124103.00b8f7f0@pop3.norton.antivirus>
References: <20020412093302.1316.11610.Mailman@mail.python.org> <4.3.2.7.2.20020412124103.00b8f7f0@pop3.norton.antivirus>
Message-ID: <E16w2In-0005d3-00@mail.python.org>

Hi,

On Fri, 12 Apr 2002 Alexandre Ratti spewed into the ether:
[-- snippity --]
> Here is a definition I came across:
> 
> <QUOTE>
> Generally, the ability to appear in many forms. In object-oriented 
> programming, polymorphism refers to a programming language's ability to 
> process objects differently depending on their data type or class. More 
> specifically, it is the ability to redefine methods for derived classes. 

Ok, this is what I had guessed.

> For example, given a base class shape, polymorphism enables the programmer 
> to define different circumference methods for any number of derived 
> classes, such as circles, rectangles and triangles. No matter what shape an 
> object is, applying the circumference method to it will return the correct 
> results. Polymorphism is considered to be a requirement of any true 
> object-oriented programming language (OOPL).
> The type of polymorphism described above is sometimes called parametric 
> polymorphism to distinguish it from another type of polymorphism called 
> overloading.

Overloading, I presume, is redifining the double-underscore methods,
like __setitem__, __len__, etc ?

Thanks !

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

I know the answer!  The answer lies within the heart of all mankind!
The answer is twelve?  I think I'm in the wrong building.
		-- Charles Schulz






From bwinton@tor.dhs.org  Fri Apr 12 15:47:33 2002
From: bwinton@tor.dhs.org (Blake Winton)
Date: Fri, 12 Apr 2002 10:47:33 -0400
Subject: [Tutor] The Evil eval()
In-Reply-To: <003501c1e1aa$1dc193c0$1f01040a@centre.edu>
References: <003501c1e1aa$1dc193c0$1f01040a@centre.edu>
Message-ID: <20020412104733.A8033@tor.dhs.org>

* Timothy M. Brauch <tbrauch@tbrauch.com> [020412 01:38]:
> I am getting ready to write a program that will read the contents of a file
> and then manipulate the data.  The file consists of a single list of lists
> all on  one line.  Something like:
> 
> [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
> 
> If I understand correctly, when I read the file in, I will get a string and
> to make it into a list of lists, I will have to use eval().  But, I also
> know that is dangerous and if someone knew I used that for this program,
> they could really mess things up.  My question is, how do I make sure that
> what I am eval()-ing is a list of lists (of integers)?  That is the only
> thing the input file should be, and I don't want it to work if there is
> something else inthe input file.

Or you could search the archives for "Turning a string into a
tuple" and find the thread that starts at:
http://mail.python.org/pipermail/tutor/2001-September/008963.html

Or just skip down and hit my code at:
http://mail.python.org/pipermail/tutor/2001-September/008992.html

That should do exactly what you want, and maybe even a little
more...  If there's anything else you need from it, let me
know, and I'll see what I can do.

Later,
Blake.
-- 
9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07



From israel@lith.com  Fri Apr 12 16:26:51 2002
From: israel@lith.com (Israel Evans)
Date: Fri, 12 Apr 2002 08:26:51 -0700
Subject: [Tutor] Dynamically instantiating objects?
Message-ID: <AF020C5FC551DD43A4958A679EA16A15028E226C@abbott.lith.com>

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_01C1E236.7AA3242F
Content-Type: text/plain

 
 
All this talk of constructors has got me thinking and confused...  I would
think that constructors could help me out, but I can't seem to figure out
how.
 
I'm trying to instantiate a number of objects from a list.  
Say for example I have three names in a list and I want an object created
that uses the names from that list as the name of that instance.
###
names = ['maude', 'claire', 'eudelle']
 
class pip:
            def __init__(self, name, number):
                        self.name = name
                        self.number = number
 
for name in names:
            name = pip(name, number)
###
The above just sets the variable "name" to be the instance of the pip class
three times over rather than setting up the current value of the variable as
the name of the instance.
 
 
###
class dynapip:
            def __init__(self, name, number):
                        self.__name__ = name
                        self.number = number
 
for name in names:
            dynapip(name, counter)
            counter = counter + 1
 
###
This just seemed to create three instances of the class pip all with the
name __main__
 
I'm probably missing something fairly obvious, but since I'm obviously
missing something, I don't know what that something is now do I?  hmmm... ;(
I've tried using eval to pass strings along, but that doesn't seem to work
either.  Could one of you Grand Master Pythonistas perhaps clue me in here?
 
Thanks.
 
 
~Israel~
 

------_=_NextPart_001_01C1E236.7AA3242F
Content-Type: text/html
Content-Transfer-Encoding: quoted-printable

<html xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Dus-ascii">


<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 10">
<meta name=3DOriginator content=3D"Microsoft Word 10">
<link rel=3DFile-List href=3D"cid:filelist.xml@01C1E1FB.CE818480">
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"country-region"/>
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"place"/>
<!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:DoNotRelyOnCSS/>
 </o:OfficeDocumentSettings>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:DocumentKind>DocumentEmail</w:DocumentKind>
  <w:EnvelopeVis/>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
   <w:UseFELayout/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
 </w:WordDocument>
</xml><![endif]--><!--[if !mso]>
<style>
st1\:*{behavior:url(#default#ieooui) }
</style>
<![endif]-->
<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:PMingLiU;
	panose-1:2 2 3 0 0 0 0 0 0 0;
	mso-font-alt:\65B0\7D30\660E\9AD4;
	mso-font-charset:136;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:3 137232384 22 0 1048577 0;}
@font-face
	{font-family:"\@PMingLiU";
	panose-1:2 2 3 0 0 0 0 0 0 0;
	mso-font-charset:136;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:3 137232384 22 0 1048577 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-parent:"";
	margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:PMingLiU;}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;
	text-underline:single;}
p.MsoAutoSig, li.MsoAutoSig, div.MsoAutoSig
	{margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";
	mso-fareast-language:EN-US;}
span.EmailStyle17
	{mso-style-type:personal-compose;
	mso-style-noshow:yes;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;
	font-family:Arial;
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:windowtext;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.25in 1.0in 1.25in;
	mso-header-margin:.5in;
	mso-footer-margin:.5in;
	mso-paper-source:0;}
div.Section1
	{page:Section1;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */=20
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-parent:"";
	mso-padding-alt:0in 5.4pt 0in 5.4pt;
	mso-para-margin:0in;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman";}
</style>
<![endif]-->
</head>

<body lang=3DEN-US link=3Dblue vlink=3Dpurple =
style=3D'tab-interval:.5in'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>All this talk of constructors has got me =
thinking and
confused...<span style=3D'mso-spacerun:yes'>&nbsp; </span>I would think =
that
constructors could help me out, but I can't seem to figure out =
how.<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>I'm trying to instantiate a number of objects
from a list.<span style=3D'mso-spacerun:yes'>&nbsp; =
</span><o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>Say for example I have three names in a list =
and I
want an object created that uses the names from that list as the name =
of that
instance.<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>###<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>names =3D ['maude', 'claire', =
'eudelle']<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>class pip:<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>def
__init__(self, name, number):<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:2'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>self.name
=3D name<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:2'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>self.number
=3D number<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>for name in =
names:<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>name
=3D pip(name, number)<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>###<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>The above just sets the variable "name" to
be the instance of the pip class three times over rather than setting =
up the
current value of the variable as the name of the =
instance.<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>###<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>class dynapip:<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>def
__init__(self, name, number):<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:2'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>self.__name__
=3D name<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:2'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>self.number
=3D number<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>for name in =
names:<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>dynapip(name,
counter)<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><span =
style=3D'mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp; </span>counter
=3D counter + 1<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>###</span></font><font size=3D2 =
face=3DArial><span
style=3D'font-size:10.0pt;font-family:Arial;mso-fareast-font-family:"Tim=
es New Roman";
mso-fareast-language:EN-US'><o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>This just seemed to create three instances of =
the
class pip all with the name __main__<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>I'm probably missing something fairly obvious,
but since I'm obviously missing something, I don't know what that
something is now do I?<span style=3D'mso-spacerun:yes'>&nbsp; =
</span>hmmm...
;(<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>I've tried using eval to pass strings along, =
but
that doesn't seem to work either.<span =
style=3D'mso-spacerun:yes'>&nbsp;
</span>Could one of you Grand Master Pythonistas perhaps clue me in =
here?<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'>Thanks.<o:p></o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D2 face=3D"Courier New"><span =
style=3D'font-size:
10.0pt;font-family:"Courier =
New";mso-no-proof:yes'>~</span></font><st1:country-region><st1:place><fo=
nt
  size=3D2 face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
  =
mso-no-proof:yes'>Israel</span></font></st1:place></st1:country-region><=
font
size=3D2 face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
mso-no-proof:yes'>~<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt'><o:p>&nbsp;</o:p></span></font></p>

</div>

</body>

</html>

------_=_NextPart_001_01C1E236.7AA3242F--



From bryce@bembry.org  Fri Apr 12 17:01:28 2002
From: bryce@bembry.org (Bryce Embry)
Date: Fri, 12 Apr 2002 11:01:28 -0500
Subject: [Tutor] Dynamically instantiating objects?
Message-ID: <5.1.0.14.0.20020412110011.00adb318@www.bembry.org>

Israel,
I tried the same thing a few weeks ago.  The trick is to use a dictionary, 
like the following:

 >>> list = ("dog", "cat", "fish")
 >>> dict={}
 >>> class play:
         def __init__(self, name):
                 self.var = name
         def display(self):
                 print self.var


 >>> for item in list:
         dict[item]=play(item)


 >>> dict["dog"].display()
dog
 >>> dict["cat"].display()
cat
 >>> dict["fish"].display()
fish
 >>>

That's a quick answer.  There is a lot more detail in the OOPs thread from 
last month. at http://mail.python.org/pipermail/tutor/2002-March/thread.html.

Bryce Embry



--------------------------------------------------------------------------------------------
"Lord, you establish peace for us.
All that we have accomplished
you have done for us" -- Isaiah 26:12




From jeff@ccvcorp.com  Fri Apr 12 18:06:32 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 12 Apr 2002 10:06:32 -0700
Subject: [Tutor] Dynamically instantiating objects?
References: <20020412160002.22777.85260.Mailman@mail.python.org>
Message-ID: <3CB71417.C844BCE6@ccvcorp.com>

> Israel Evans <israel@lith.com> wrote:

> I'm trying to instantiate a number of objects from a list.
> Say for example I have three names in a list and I want an object created
> that uses the names from that list as the name of that instance.
> ###
> names = ['maude', 'claire', 'eudelle']
>
> class pip:
>             def __init__(self, name, number):
>                         self.name = name
>                         self.number = number
>
> for name in names:
>             name = pip(name, number)
> ###

[...]

What I would do in this case, is store your objects in a dictionary.  Given the
above class pip, if you instantiate them this way:

pips = {}
for name in names:
    pips[name] = pip(name, number)

Then you can refer to them whenever you need them as

pips['maude'].dosomething()
# or
name = 'claire'
pips[name].dosomething()
# or even
for name in pips.keys():  #if using Py2.2--for name in pips:
    pips[name].dosomething()
for each in pips.values():
    each.dosomething()

It *is* possible to create each name in your list as a global variable name,
using exec, but it really isn't recommended, and 99% of the time using a
dictionary or other collection will make your code cleaner and more sensible
anyhow.

Jeff Shannon
Technician/Programmer
Credit International





From alex@gabuzomeu.net  Fri Apr 12 18:15:37 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 12 Apr 2002 19:15:37 +0200
Subject: [Tutor] constructors
In-Reply-To: <20020412160002.22777.85260.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020412182434.00d257d0@pop3.norton.antivirus>

Hello,


At 12:00 12/04/2002 -0400, you wrote:
>From: Prahlad Vaidyanathan <slime@vsnl.net>
>Subject: Re: [Tutor] constructors
>Date: Fri, 12 Apr 2002 10:45:25 -0400

> > For example, given a base class shape, polymorphism enables the programmer
> > to define different circumference methods for any number of derived
> > classes, such as circles, rectangles and triangles. No matter what 
> shape an
> > object is, applying the circumference method to it will return the correct
> > results. Polymorphism is considered to be a requirement of any true
> > object-oriented programming language (OOPL).
> > The type of polymorphism described above is sometimes called parametric
> > polymorphism to distinguish it from another type of polymorphism called
> > overloading.
>
>Overloading, I presume, is redifining the double-underscore methods,
>like __setitem__, __len__, etc ?

In the context of Python, I believe you overload a method when you define 
in a subclass a method with the same name as a method in the parent class. 
Example:

class Toto:

     def __init__(self):
         "Initialise the class and run the method."
         self.doSomething()

     def doSomething(self):
         "Print out the class name."
         print "I am Toto."

class Titi(Toto):

     def doSomething(self):
         "Print out the subclass name."
         print "I am Titi."


# Let's create instances
toto = Toto()
 >>> I am Toto.
titi = Titi()
 >>> I am Titi.

Here Titi inherits __init__() but defines its own doSomething() method.

The double-underscore methods are special cases; they allow you to redefine 
build-in functions (len), specific actions (looping) or operators (eg. add, 
substract, etc., that's "operator overloading").


Cheers.

Alexandre





From telepathy@vsnl.com  Sun Apr  7 12:21:21 2002
From: telepathy@vsnl.com (H.S.Bajwa)
Date: Sun, 7 Apr 2002 16:51:21 +0530
Subject: [Tutor] Unsubscribe
Message-ID: <000001c1e246$08b9b1a0$7584c8cb@HIM>

This is a multi-part message in MIME format.

------=_NextPart_000_0010_01C1DE54.71DD6B40
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Sir/Madam,
                 Please unsubscribe me from the mailing list because i =
am recieving too much mail.
                                                       Thanking you in =
anticipation.
                                                   Your's faithfully,
                                       telepathy@vsnl.com


------=_NextPart_000_0010_01C1DE54.71DD6B40
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2715.400" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Sir/Madam,</FONT></DIV>
<DIV><FONT face=3DArial=20
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
Please unsubscribe me from the mailing list because i am recieving too =
much=20
mail.</FONT></DIV>
<DIV><FONT face=3DArial=20
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=20
Thanking you in anticipation.</FONT></DIV>
<DIV><FONT face=3DArial=20
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&=
nbsp;&nbsp;&nbsp;=20
Your's faithfully,</FONT></DIV>
<DIV><FONT face=3DArial=20
size=3D2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp=
;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=
&nbsp;&nbsp;&nbsp;=20
telepathy@vsnl.com</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_0010_01C1DE54.71DD6B40--




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 12 18:26:36 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Apr 2002 10:26:36 -0700 (PDT)
Subject: [Tutor] Embedding a simple python module  [C extensions]
In-Reply-To: <3CB6E81E.208@gmx.de>
Message-ID: <Pine.LNX.4.44.0204121023410.8460-100000@hkn.eecs.berkeley.edu>

> In this example the class instance is initiated by the following:
>
> object = module.klass()
>
> but, what will be change if i want to initiate a class instance like the
> following:
>
> object = module.klass(x,y,z)


The example that you have calls the class constructor here:

###
>   pargs  = Py_BuildValue("()");
>   pinst  = PyEval_CallObject(pclass, pargs);        /* call class() */
>   Py_DECREF(pclass);
>   Py_DECREF(pargs);
###

If you want to pass some objects like x, y, and z, we can build up that
pargs tuple to include those.  If x, y, and z are already PyObjects, we
can do something like:

    pargs = Py_BuildValue("(OOO)", x, y, z);


Hope this helps!




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 12 18:32:35 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Apr 2002 10:32:35 -0700 (PDT)
Subject: [Tutor] Unsubscribe
In-Reply-To: <000001c1e246$08b9b1a0$7584c8cb@HIM>
Message-ID: <Pine.LNX.4.44.0204121030300.8460-100000@hkn.eecs.berkeley.edu>


On Sun, 7 Apr 2002, H.S.Bajwa wrote:

> Please unsubscribe me from the mailing list because i am recieving too
> much mail.

You can unsubscribe yourself by visiting the web page you used to
subscribe to Tutor:

    http://mail.python.org/mailman/listinfo/tutor

Go down to the bottom of this page, and you should see a form about "Edit
Options".  You can unsubscribe and change the mailing list options from
there.


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 12 18:59:27 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Apr 2002 10:59:27 -0700 (PDT)
Subject: [Tutor] The Evil eval()
In-Reply-To: <003501c1e1aa$1dc193c0$1f01040a@centre.edu>
Message-ID: <Pine.LNX.4.44.0204121033200.8460-100000@hkn.eecs.berkeley.edu>


On Thu, 11 Apr 2002, Timothy M. Brauch wrote:

> I am getting ready to write a program that will read the contents of a file
> and then manipulate the data.  The file consists of a single list of lists
> all on  one line.  Something like:
>
> [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
>
> If I understand correctly, when I read the file in, I will get a string
> and to make it into a list of lists, I will have to use eval().


Not necessarily.  Here's a quick-and-dirty parser that you may be able to
use to turn that string of listed numbers into a real Python list:


###
import re

def parse(s):
    tokens = tokenize(s)
    return parseTokens(tokens)


def parseTokens(tokens):
    """This is an example of a "recursive descent" parser."""
    if tokens[0] == '[':       ## If this looks like a list...
        tokens.pop(0)          ## First, chew that leading brace.
        list_pieces = []
                               ## Let's accumulate the inner elements.
        while tokens[0] != ']':
            list_pieces.append(parseTokens(tokens))
        tokens.pop(0)          ## Chomp off the trailing brace.
        return list_pieces     ## and return our constructed list.
    else:                      ## Otherwise, assume it's a number
        return int(tokens.pop(0))



def tokenize(s):
    ## First, turn all commas into spaces just to simplify things
    s = s.replace(',', ' ')
    pattern = re.compile(r'''(
                                 [\[\]]    ## Literal braces
                                 |         ## or
                                 \s+       ## whitespace
                             )''', re.VERBOSE)
    pieces = pattern.split(s)
    return [p.strip() for p in pieces if p.strip()]


_test_string = "[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4,
8, 12, 16, 20]]"

if __name__ == '__main__':
    print repr(parse(_test_string))
###


This parser is written in a style called "recursive descent", and it's
recursive because if the parser senses that it's running across a list,
it'll recursively call itself to parse out the individual elements of this
list.  The recursion is necessarly because lists can contain sublists.
Here's an example of the parser in action:

###
>>> parse("[1, 2, [3, 4, [5]]]")
[1, 2, [3, 4, [5]]]
###


This parse doesn't do any error trapping, so you may want to fiddle with
it a bit to make it work more nicely.  Please feel free to ask questions
about this; parsing is a fun subject!



Best of wishes to you!




From c.bifulco@tin.it  Fri Apr 12 21:18:19 2002
From: c.bifulco@tin.it (Carlo Bifulco)
Date: Fri, 12 Apr 2002 22:18:19 +0200
Subject: [Tutor] ftp synch
Message-ID: <002401c1e25f$3049d4c0$3a03d33e@216.112.112.212.216.172.62>

Hi folks,
first of all thanks for the nice tutoring. Just hanging around has been very
instructive.
I have a question concerning the ftplib python module.
I wrote a small application which synchronizes a local and remote
directories through FTP (basically it uploads files absent on the server dir
but present in the local directory and downloads files present in the remote
directory and absent in the local dir). Unfortunately I haven't found a good
way to distinguish files looking at the modification time. I  would like
both directories to share the latest version of each file. I'm having a
problem witht the fact  that the 2 machines have different system clocks. Is
there an easy way to solve this ?
Thanks for any help,
Carlo Bifulco





From scottw@distek.com  Fri Apr 12 21:40:35 2002
From: scottw@distek.com (Scott Weston)
Date: Fri, 12 Apr 2002 15:40:35 -0500
Subject: [Tutor] ftp synch
Message-ID: <5A7559BCCBAD7241AB4CFBE57300D2A2076FE6@magistrate.distekcf>

You may want to synch both servers with an external time server. This =
would at least help you in determining file dates with more accuracy.

- Scott Weston -


-----Original Message-----
From: Carlo Bifulco [mailto:c.bifulco@tin.it]
Sent: Friday, April 12, 2002 3:18 PM
To: tutor@python.org
Subject: [Tutor] ftp synch


Hi folks,
first of all thanks for the nice tutoring. Just hanging around has been =
very
instructive.
I have a question concerning the ftplib python module.
I wrote a small application which synchronizes a local and remote
directories through FTP (basically it uploads files absent on the server =
dir
but present in the local directory and downloads files present in the =
remote
directory and absent in the local dir). Unfortunately I haven't found a =
good
way to distinguish files looking at the modification time. I  would like
both directories to share the latest version of each file. I'm having a
problem witht the fact  that the 2 machines have different system =
clocks. Is
there an easy way to solve this ?
Thanks for any help,
Carlo Bifulco




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



From dyoo@hkn.eecs.berkeley.edu  Fri Apr 12 21:46:32 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 12 Apr 2002 13:46:32 -0700 (PDT)
Subject: [Tutor] ftp synch
In-Reply-To: <002401c1e25f$3049d4c0$3a03d33e@216.112.112.212.216.172.62>
Message-ID: <Pine.LNX.4.44.0204121333130.13129-100000@hkn.eecs.berkeley.edu>


On Fri, 12 Apr 2002, Carlo Bifulco wrote:

> Hi folks,
> first of all thanks for the nice tutoring. Just hanging around has been very
> instructive.
> I have a question concerning the ftplib python module.
> I wrote a small application which synchronizes a local and remote
> directories through FTP (basically it uploads files absent on the server dir
> but present in the local directory and downloads files present in the remote
> directory and absent in the local dir). Unfortunately I haven't found a good
> way to distinguish files looking at the modification time. I  would like
> both directories to share the latest version of each file. I'm having a
> problem witht the fact  that the 2 machines have different system clocks. Is
> there an easy way to solve this ?
> Thanks for any help,
> Carlo Bifulco


Would it be possible to have a "checksum" file on your FTP server?
Python comes with a nice 'md5' function that you can use to quickly create
a numeric signature of a file.  For example:

###
>>> def digestFile(f):
...     m = md5.new()
...     while 1:
...         chunk = f.read(1024)
...         if not chunk: break
...         m.update(chunk)
...     return m.hexdigest()
...
>>> myfile = open("/usr/share/dict/words")
>>> digestFile(myfile)
'c649076690e43c051de2fd58f91eac3d'
###

This 'digest' is a signature of the contents of a file, and will radically
change if the contents of the words is different.


You can set up a scheduled cron job on your FTP server that will
periodically update the signatures of your files into a separate signature
file.  These signatures are very small, so they should be very easy to
download.  Later, when you're updating a file, you can see if the
signatures of your local file and the server file match up.  If their
signatures do match, it's very likely that nothing's changed.


For more information on these string-signature "hash" functions, you can
see:

    http://www.python.org/doc/lib/module-md5.html
    http://www.python.org/doc/lib/module-sha.html
    http://www.python.org/doc/lib/module-hmac.html


Good luck to you!




From lha2@columbia.edu  Fri Apr 12 23:32:04 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Fri, 12 Apr 2002 18:32:04 -0400
Subject: [Fwd: Re: [Tutor] The Evil eval()]
References: <3CB6A963.AFDFCC3F@mail.verizon.net>
Message-ID: <3CB76064.240025AC@mail.verizon.net>

and "-". Forgot "-". (if you have any negative numbers). And "." if you
have any  floats. Maybe the whole string.punctuation--I don't think
there's anything in there that can hurt you without letters.

> Alternatively, if you're in a hurry and don't mind being slow, you could
> run a for loop on your string and ensure that each character is in "[],
> 1234567890", or (more generously) in
> "[],"+string.whitespace+string.digits
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From ak@silmarill.org  Sat Apr 13 01:51:38 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 12 Apr 2002 20:51:38 -0400
Subject: [Tutor] ftp synch
In-Reply-To: <002401c1e25f$3049d4c0$3a03d33e@216.112.112.212.216.172.62>
References: <002401c1e25f$3049d4c0$3a03d33e@216.112.112.212.216.172.62>
Message-ID: <20020413005137.GA17661@ak.silmarill.org>

On Fri, Apr 12, 2002 at 10:18:19PM +0200, Carlo Bifulco wrote:
> Hi folks,
> first of all thanks for the nice tutoring. Just hanging around has been very
> instructive.
> I have a question concerning the ftplib python module.
> I wrote a small application which synchronizes a local and remote
> directories through FTP (basically it uploads files absent on the server dir
> but present in the local directory and downloads files present in the remote
> directory and absent in the local dir). Unfortunately I haven't found a good
> way to distinguish files looking at the modification time. I  would like
> both directories to share the latest version of each file. I'm having a
> problem witht the fact  that the 2 machines have different system clocks. Is
> there an easy way to solve this ?
> Thanks for any help,
> Carlo Bifulco
>
I think I looked at this before and found that there's a time signature
that does not change when a file is uploaded. IE let's say you type and
save a file at 5am EST and upload it to a server in different timezone
and one of its time signatures (i think last mod. time) is still going
to be 5am EST so you can tell it's unmodified file.


 - Andrei

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

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From tbrauch@tbrauch.com  Sat Apr 13 05:06:35 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Sat, 13 Apr 2002 00:06:35 -0400
Subject: [Tutor] The Evil eval()
References: <003501c1e1aa$1dc193c0$1f01040a@centre.edu> <003601c1e22a$a8aa6e50$1664a8c0@mega>
Message-ID: <000d01c1e2a0$9ad54f40$1f01040a@centre.edu>

> > I am getting ready to write a program that will read the contents of a
> file
> > and then manipulate the data.  The file consists of a single list of
lists
> > all on  one line.  Something like:
> >
> > [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16,
20]]
> >
> > If I understand correctly, when I read the file in, I will get a string
> and
> > to make it into a list of lists, I will have to use eval().  But, I also
> > know that is dangerous and if someone knew I used that for this program,
> > they could really mess
>
> If this list of lists is produced by a Python program (as some of the
> answers
> you got until now seem to assume): why not use pickle?

I wish it were only that easy.  I have no idea what language writes the data
files.  I think it is java, though.  All I get are these small data files
and I have to perform mindless computations on it.

> >>> import pickle
> >>> f = open("pickletest.data","w")
> >>> a = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12,
> 16, 20]]
> >>> pickle.dump(a,f)
> >>> f.close()
> >>> f = open("pickletest.data","r")
> >>> b = pickle.load(f)
> >>> b
> [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
> >>>
>
> Wouldn't this solve your problem?
>
> Gregor

I would use pickle as since learning about it, I have learned to love it.
But, I do not have that convience.

 - Tim

P.S.  My posts are getting through, just a slight four hour delay the last
few days.  Hopefully the mailservers of the world look kindly on this
message.  I am sending it at 13 April 2002 at 12:06am.





From idiot1@netzero.net  Sat Apr 13 05:08:30 2002
From: idiot1@netzero.net (kirk Bailey)
Date: Sat, 13 Apr 2002 00:08:30 -0400
Subject: [Tutor] tinylist mention on python.org
Message-ID: <3CB7AF3E.FE5E06D8@netzero.net>

How can I get a breif link to tinylist.org on the python website? I
wrote the webmaster but got no reply.

-- 
 
end
	    Respectfully,
			 Kirk D Bailey


+---------------------"Thou Art Free." -Eris----------------------+
| http://www.howlermonkey.net mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+  mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking---------------------+
                           +--------+

NOTE: By sending SPAM to this address you agree to pay me a service
fee of $100 for the service of receiving,  storing,  examining, and
deleting your piece of SPAM. I am a postmaster, and take a dim view
of such.



From imcmeans@shaw.ca  Sat Apr 13 05:42:27 2002
From: imcmeans@shaw.ca (Ian!)
Date: Fri, 12 Apr 2002 21:42:27 -0700
Subject: [Tutor] The Evil eval()
References: <20020413041201.26787.8039.Mailman@mail.python.org>
Message-ID: <002b01c1e2a5$9d3ac440$da494e18@cr536745a>

Well, the mailservers of the world must be smiling on you, because I got
your message almost 3 hours before you sent it! =)




From python@rcn.com  Sat Apr 13 07:31:53 2002
From: python@rcn.com (Raymond Hettinger)
Date: Sat, 13 Apr 2002 02:31:53 -0400
Subject: [Tutor] tinylist mention on python.org
References: <3CB7AF3E.FE5E06D8@netzero.net>
Message-ID: <001c01c1e2b4$e77cf000$96b53bd0@othello>

From: "kirk Bailey" <idiot1@netzero.net>
> How can I get a breif link to tinylist.org on the python website? I
> wrote the webmaster but got no reply.

I'm don't think www.python.org has an appropriate section
for listing your tool; however, someone else here may know otherwise.

May I suggest you add a link at The Vaults of Parnassus,
http://www.vex.net/parnassus/


Raymond Hettinger





From c.bifulco@tin.it  Sat Apr 13 09:28:01 2002
From: c.bifulco@tin.it (Carlo Bifulco)
Date: Sat, 13 Apr 2002 10:28:01 +0200
Subject: [Tutor] ftp synch
References: <Pine.LNX.4.44.0204121333130.13129-100000@hkn.eecs.berkeley.edu>
Message-ID: <000601c1e2c5$20741e00$3a03d33e@216.112.112.212.216.172.62>

Thanks Danny,
I like the idea.  I would never gotten there on my own :).
Carlo

----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Carlo Bifulco" <c.bifulco@tin.it>
Cc: <tutor@python.org>
Sent: Friday, April 12, 2002 10:46 PM
Subject: Re: [Tutor] ftp synch


>
>
> On Fri, 12 Apr 2002, Carlo Bifulco wrote:
>
> > Hi folks,
> > first of all thanks for the nice tutoring. Just hanging around has been
very
> > instructive.
> > I have a question concerning the ftplib python module.
> > I wrote a small application which synchronizes a local and remote
> > directories through FTP (basically it uploads files absent on the server
dir
> > but present in the local directory and downloads files present in the
remote
> > directory and absent in the local dir). Unfortunately I haven't found a
good
> > way to distinguish files looking at the modification time. I  would like
> > both directories to share the latest version of each file. I'm having a
> > problem witht the fact  that the 2 machines have different system
clocks. Is
> > there an easy way to solve this ?
> > Thanks for any help,
> > Carlo Bifulco
>
>
> Would it be possible to have a "checksum" file on your FTP server?
> Python comes with a nice 'md5' function that you can use to quickly create
> a numeric signature of a file.  For example:
>
> ###
> >>> def digestFile(f):
> ...     m = md5.new()
> ...     while 1:
> ...         chunk = f.read(1024)
> ...         if not chunk: break
> ...         m.update(chunk)
> ...     return m.hexdigest()
> ...
> >>> myfile = open("/usr/share/dict/words")
> >>> digestFile(myfile)
> 'c649076690e43c051de2fd58f91eac3d'
> ###
>
> This 'digest' is a signature of the contents of a file, and will radically
> change if the contents of the words is different.
>
>
> You can set up a scheduled cron job on your FTP server that will
> periodically update the signatures of your files into a separate signature
> file.  These signatures are very small, so they should be very easy to
> download.  Later, when you're updating a file, you can see if the
> signatures of your local file and the server file match up.  If their
> signatures do match, it's very likely that nothing's changed.
>
>
> For more information on these string-signature "hash" functions, you can
> see:
>
>     http://www.python.org/doc/lib/module-md5.html
>     http://www.python.org/doc/lib/module-sha.html
>     http://www.python.org/doc/lib/module-hmac.html
>
>
> Good luck to you!
>




From hsteiger@comcast.net  Sat Apr 13 14:23:31 2002
From: hsteiger@comcast.net (Henry Steigerwaldt)
Date: Sat, 13 Apr 2002 08:23:31 -0500
Subject: [Tutor] Two questions
Message-ID: <000a01c1e2ee$682f2ae0$0201a8c0@eagle>

This is a multi-part message in MIME format.

--Boundary_(ID_Bk+4r1YCDXhkwVOBJSpFfw)
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 7BIT

To Whom It May Concern:

The program I am about to describe is opened in Idle, and then run in
Idle. The code pieces below are all located in a function called Main().

The following piece of code works just fine:

   # read first line in a file to get URL
   site_url = fileobject.readline()
   print "site_url = ", url

In the above code, the URL read in first line of a file stores just fine 
into variable "site_url." However, when I try to store the URL into a  
list or tuple, I get an error. 

Below is the piece of code to store URL into a list:

   i = 0
   site_url[i] = fileobject.readline()
   print "site_url = ", site_url[i]

Here is the error that is output in Idle:

  Main()
  File "C:\python_pgms\misc_obs_pgm.py", line 37, in Main
    site_url[i] = fileobject.readline()
NameError: global name 'site_url' is not defined
_________________________________
Below is the piece of code to store URL into a tuple:

   i = 0
   site_url(i) = fileobject.readline()
   print "site_url = ", site_url(i)

Here is the error that is output in Idle:

 File "C:\python_pgms\misc_obs_pgm.py", line 37
    site_url(i) = fileobject.readline()
SyntaxError: can't assign to function call
______________________________________________

I do not understand why I am getting these errors. 

Actually what I want to do in this program is read the first
line of a file, which contains a number, say 4. The number tells
the program how many URLs will follow (one per line) in the file.
So after the first line of the file is read, the program then is 
supposed to read and then store the URLs in either a list or
a tuple. After that, I want to go to each site (URL) and grab
some information. 

Please be as least cryptic as possible in any response. I have
written some small programs in Tcl/Tk (and a couple of other 
languages in the past), but my programming experience is very
limited. 

Thanks for any help provided ! 

Henry Steigerwaldt
Hermitage, TN


--Boundary_(ID_Bk+4r1YCDXhkwVOBJSpFfw)
Content-type: text/html; charset=iso-8859-1
Content-transfer-encoding: 7BIT

<!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 6.00.2600.0" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=#ffffff>
<DIV><FONT face=Arial size=2>To Whom It May Concern:</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>The program I am about to describe is opened in 
Idle, and then run in</FONT></DIV>
<DIV><FONT face=Arial size=2>Idle. The code pieces below are all located in a 
function called Main().</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>The following piece of code&nbsp;works </FONT><FONT 
face=Arial size=2>just fine:</FONT></DIV>
<DIV><FONT size=2><FONT face=Arial></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>&nbsp;&nbsp; # read first line in a file to get 
URL</FONT></DIV>
<DIV><FONT face=Arial size=2>&nbsp;&nbsp; site_url = 
fileobject.readline()</FONT></DIV>
<DIV><FONT size=2><FONT face=Arial>&nbsp;&nbsp; print "site_url = ", 
url</FONT></DIV></FONT>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>In the above code, the URL&nbsp;read in first line 
of a file&nbsp;stores just fine </FONT></DIV>
<DIV><FONT face=Arial size=2>into&nbsp;variable "site_url." </FONT><FONT 
face=Arial size=2>However, when I try to store the URL&nbsp;into a&nbsp; 
</FONT></DIV>
<DIV><FONT face=Arial size=2>list or tuple, I get an error. </FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>Below is the piece of code to store&nbsp;URL into a 
list:</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>&nbsp;&nbsp; i = 0</FONT></DIV>
<DIV><FONT face=Arial size=2>&nbsp;&nbsp; site_url[i] = 
fileobject.readline()<BR>&nbsp;&nbsp; print "site_url = ", 
site_url[i]<BR></FONT><FONT face=Arial size=2></FONT></DIV>
<DIV><FONT face=Arial size=2>Here is the error that is output in 
Idle:</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>&nbsp; Main()<BR>&nbsp; File 
"C:\python_pgms\misc_obs_pgm.py", line 37, in Main<BR>&nbsp;&nbsp;&nbsp; 
site_url[i] = fileobject.readline()<BR>NameError: global name 'site_url' is not 
defined</FONT></DIV>
<DIV><FONT face=Arial size=2>_________________________________</FONT></DIV>
<DIV><FONT face=Arial size=2>Below&nbsp;is the piece of code to&nbsp;store URL 
into a tuple:</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>&nbsp;&nbsp; i = 0</FONT></DIV>
<DIV><FONT face=Arial size=2>&nbsp;&nbsp; site_url(i) = 
fileobject.readline()<BR>&nbsp;&nbsp; print "site_url = ", 
site_url(i)</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV>
<DIV><FONT face=Arial size=2>Here is the error that is output in 
Idle:</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>&nbsp;File "C:\python_pgms\misc_obs_pgm.py", line 
37<BR>&nbsp;&nbsp;&nbsp; site_url(i) = fileobject.readline()<BR>SyntaxError: 
can't assign to function 
call<BR>______________________________________________</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>I do not understand why I am getting these errors. 
</FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>
<DIV><FONT face=Arial size=2>Actually what I want to do in this program is read 
the first</FONT></DIV>
<DIV><FONT face=Arial size=2>line of a file, which contains a number, say 4. The 
number tells</FONT></DIV>
<DIV><FONT face=Arial size=2>the program how many URLs will follow (one per 
line) in the file.</FONT></DIV>
<DIV><FONT face=Arial size=2>So after&nbsp;the first </FONT><FONT face=Arial 
size=2>line of the file is read, the </FONT><FONT face=Arial size=2>program then 
is </FONT></DIV>
<DIV><FONT face=Arial size=2>supposed to read and then store </FONT><FONT 
face=Arial size=2>the URLs in either a list or</FONT></DIV>
<DIV><FONT face=Arial size=2>a tuple. After that, I want to go to each site 
(URL) and grab</FONT></DIV>
<DIV><FONT face=Arial size=2>some </FONT><FONT face=Arial><FONT 
size=2>information. <FONT size=+0></DIV></FONT></FONT></FONT></FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>Please be as least cryptic </FONT><FONT face=Arial 
size=2>as possible in any response. I have</FONT></DIV>
<DIV><FONT face=Arial size=2>written some small&nbsp;</FONT><FONT face=Arial 
size=2>programs in Tcl/Tk (and a couple of other </FONT></DIV>
<DIV><FONT face=Arial size=2>languages in </FONT><FONT face=Arial size=2>the 
past), but my programming experience is very</FONT></DIV>
<DIV><FONT face=Arial size=2>limited. </FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>Thanks for any help provided ! </FONT></DIV>
<DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial size=2>Henry Steigerwaldt</FONT></DIV>
<DIV><FONT face=Arial size=2>Hermitage, TN</FONT></DIV>
<DIV>&nbsp;</DIV></DIV></BODY></HTML>

--Boundary_(ID_Bk+4r1YCDXhkwVOBJSpFfw)--



From erikprice@mac.com  Sat Apr 13 14:52:59 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 13 Apr 2002 09:52:59 -0400
Subject: [Tutor] constructors
In-Reply-To: <E16vwQv-0001YJ-00@mail.python.org>
Message-ID: <C3B2CAFC-4EE5-11D6-B569-00039351FE6A@mac.com>

On Friday, April 12, 2002, at 04:29  AM, Prahlad Vaidyanathan wrote:

>> Since Python is loosely/weakly/dynamically typed, does initializing
>> really matter a great deal?  Or is it just to allow us to use
>> polymorphism in a later method (by not requiring that later method to
>
> Ok, taking the risk of sounding *very* duh,
>
>     What does polymorphism mean ?

I learned that word a few days ago from Alan Gauld's Tutor (this one: 
http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm) and from 
asking a few more questions on the list.  Check that page out, the 
"shape" example makes a lot of sense.

I have also found some good explanation of OOP in the first chapter of 
"Thinking in Java" by Bruce Eckel, which is available free at 
www.mindview.net

Not duh at all :)



Erik




From erikprice@mac.com  Sat Apr 13 15:01:58 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 13 Apr 2002 10:01:58 -0400
Subject: [Tutor] << operator ?  [left bitwise shifting]
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C545@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <053405D5-4EE7-11D6-B569-00039351FE6A@mac.com>

On Friday, April 12, 2002, at 06:43  AM, alan.gauld@bt.com wrote:

>> have you ever looked at the source code for Google pages?
>> Very little whitespace, no verbosity at all.  It's like
>> the opposite of XML
>
> Correct. Google is very popular because its fast. One
> reason its fast it they optimise the HTML they send
> so it doesn't hog bandwith sending unnecessary bytes.
>
> Its a trait I commend to web designers everywhere!

Oh, I don't know if I could agree to that!  (Of course, we can agree to 
disagree :)  I'm a firm believer in making sure that a web page is 
standards-compliant -- in the long run, it makes everyone happy.  If 
your pages take too long to download over 14k bps modem, then remove 
some Flash or some graphics, or consider chunking your content into 
separate pages.

Optimizing HTML has its place (for high-volume search engines like 
Google it is a necessity), but for most web pages, standards compliant 
code is perfectly fine and easier to read as well!  I believe it is a 
similar argument to the one made for writing clean and well-organized 
code.  (If browsers were more strict, then more web pages would be 
analogous to Python scripts -- properly nested tags, appropriately 
quoted attributes, etc.)

As far as XML is concerned, I am very interested but agree 
wholeheartedly that it's not really the best transmission format for Joe 
User (but for LANs it seems to be sufficient).  Of course, I'm no expert 
or anything.


Erik




From erikprice@mac.com  Sat Apr 13 15:01:55 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 13 Apr 2002 10:01:55 -0400
Subject: [Tutor] constructors
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C549@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <039A4420-4EE7-11D6-B569-00039351FE6A@mac.com>

On Friday, April 12, 2002, at 08:59  AM, alan.gauld@bt.com wrote:

> Apart from typing raise ERROR_1 instead of return ERROR_1
> the originating code isn't much doifferent either.
>
> The only snag is that sometimes you can lose context
> which makes it harder to recover from an exception
> that a return valued error. In that case you wind up
> with a lot of

I'm not sure I understand what you mean?  How can I avoid this snag (or 
rather, what is this snag)?





Erik




From pythontutor@venix.com  Sat Apr 13 15:04:25 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 13 Apr 2002 10:04:25 -0400
Subject: [Tutor] Two questions
References: <000a01c1e2ee$682f2ae0$0201a8c0@eagle>
Message-ID: <3CB83AE9.50506@venix.com>

You need to create a (possibly empty) list before you can stick
something into the list.  This should fix your problem:
i = 0
site_url = []	# create an empty list
site_url[i] = fileobject.readline()
print "site_url = ", site_url[i]

It is usually simpler to not track the positions when putting
things into the list.  Something like:

site_url = []
site_url.append( fileobject.readline())

simply adds the url to the end of the list.  You can NOT add
things to a tuple.  A tuple can NOT be changed.  If you want your
URLs to be in a tuple, create the list first.  Then use the
builtin tuple function.

tuple_site_url = tuple( site_url)	# makes tuple from list

Henry Steigerwaldt wrote:

> To Whom It May Concern:
> 
>  
> 
> The program I am about to describe is opened in Idle, and then run in
> 
> Idle. The code pieces below are all located in a function called Main().
> 
>  
> 
> The following piece of code works just fine:
> 
>  
> 
>    # read first line in a file to get URL
> 
>    site_url = fileobject.readline()
> 
>    print "site_url = ", url
> 
>  
> 
> In the above code, the URL read in first line of a file stores just fine
> 
> into variable "site_url." However, when I try to store the URL into a 
> 
> list or tuple, I get an error.
> 
>  
> 
> Below is the piece of code to store URL into a list:
> 
>  
> 
>    i = 0
> 
>    site_url[i] = fileobject.readline()
>    print "site_url = ", site_url[i]
> 
> Here is the error that is output in Idle:
> 
>  
> 
>   Main()
>   File "C:\python_pgms\misc_obs_pgm.py", line 37, in Main
>     site_url[i] = fileobject.readline()
> NameError: global name 'site_url' is not defined
> 
> _________________________________
> 
> Below is the piece of code to store URL into a tuple:
> 
>  
> 
>    i = 0
> 
>    site_url(i) = fileobject.readline()
>    print "site_url = ", site_url(i)
> 
>  
> 
> Here is the error that is output in Idle:
> 
>  
> 
>  File "C:\python_pgms\misc_obs_pgm.py", line 37
>     site_url(i) = fileobject.readline()
> SyntaxError: can't assign to function call
> ______________________________________________
> 
>  
> 
> I do not understand why I am getting these errors.
> 
>  
> 
> Actually what I want to do in this program is read the first
> 
> line of a file, which contains a number, say 4. The number tells
> 
> the program how many URLs will follow (one per line) in the file.
> 
> So after the first line of the file is read, the program then is
> 
> supposed to read and then store the URLs in either a list or
> 
> a tuple. After that, I want to go to each site (URL) and grab
> 
> some information.
> 
>  
> 
> Please be as least cryptic as possible in any response. I have
> 
> written some small programs in Tcl/Tk (and a couple of other
> 
> languages in the past), but my programming experience is very
> 
> limited.
> 
>  
> 
> Thanks for any help provided !
> 
>  
> 
> Henry Steigerwaldt
> 
> Hermitage, TN
> 
>  
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From ak@silmarill.org  Sat Apr 13 15:11:32 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sat, 13 Apr 2002 10:11:32 -0400
Subject: [Tutor] Two questions
In-Reply-To: <000a01c1e2ee$682f2ae0$0201a8c0@eagle>
References: <000a01c1e2ee$682f2ae0$0201a8c0@eagle>
Message-ID: <20020413141132.GA22474@ak.silmarill.org>

On Sat, Apr 13, 2002 at 08:23:31AM -0500, Henry Steigerwaldt wrote:
> To Whom It May Concern:
> 
> The program I am about to describe is opened in Idle, and then run in
> Idle. The code pieces below are all located in a function called Main().
> 
> The following piece of code works just fine:
> 
>    # read first line in a file to get URL
>    site_url = fileobject.readline()
>    print "site_url = ", url
> 
> In the above code, the URL read in first line of a file stores just fine 
> into variable "site_url." However, when I try to store the URL into a  
> list or tuple, I get an error. 
> 
> Below is the piece of code to store URL into a list:
> 
>    i = 0
>    site_url[i] = fileobject.readline()
>    print "site_url = ", site_url[i]
>
Here's how it's done:

site_url = [fileobject.readline()]

OR

line = fileobject.readline()
site_url = [line]

OR

site_url = []
site_url.append(fileobject.readline())

> 
> Here is the error that is output in Idle:
> 
>   Main()
>   File "C:\python_pgms\misc_obs_pgm.py", line 37, in Main
>     site_url[i] = fileobject.readline()
> NameError: global name 'site_url' is not defined
> _________________________________
> Below is the piece of code to store URL into a tuple:
> 
>    i = 0
>    site_url(i) = fileobject.readline()
>    print "site_url = ", site_url(i)
>
Although you probably don't want to do this at all:

site_url = (fileobject.readline(),)

> 
> Here is the error that is output in Idle:
> 
>  File "C:\python_pgms\misc_obs_pgm.py", line 37
>     site_url(i) = fileobject.readline()
> SyntaxError: can't assign to function call
> ______________________________________________
> 
> I do not understand why I am getting these errors. 
> 
> Actually what I want to do in this program is read the first
> line of a file, which contains a number, say 4. The number tells
> the program how many URLs will follow (one per line) in the file.
> So after the first line of the file is read, the program then is 
> supposed to read and then store the URLs in either a list or
> a tuple. After that, I want to go to each site (URL) and grab
> some information. 
>
You probably don't need the number, just read in the lines and if they
start with http or www, add them to URL list:

site_url = []
while 1:
    l = fileobject.readline()
    if l.startswith("http") or l.startswith("www"):
        site_url.append(l.strip())   # strip because I think it will
                                    # have \n at the end otherwise.

If you really need the number:

n = fileobject.readline()
num = int(n.strip())

> 
> Please be as least cryptic as possible in any response. I have
> written some small programs in Tcl/Tk (and a couple of other 
> languages in the past), but my programming experience is very
> limited. 
> 
> Thanks for any help provided ! 
> 
> Henry Steigerwaldt
> Hermitage, TN
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From pythontutor@venix.com  Sat Apr 13 15:23:24 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 13 Apr 2002 10:23:24 -0400
Subject: [Tutor] constructors
References: <039A4420-4EE7-11D6-B569-00039351FE6A@mac.com>
Message-ID: <3CB83F5C.8010905@venix.com>

I think Alan was talking about the gap between the piece of
code that raises an exception and the piece of code that
handles the exception.

The handler is usually close to the user interface.  The code
that raises the exception may in a database module, or sockets,
or most anywhere.  Somehow, the handler has to provide a
useful error message or automatically use an alternate procedure
to make things work.

If the lower levels of the program can figure out
how to respond, then they catch the exceptions and do the proper
response.

Erik Price wrote:

> 
> On Friday, April 12, 2002, at 08:59  AM, alan.gauld@bt.com wrote:
> 
>> Apart from typing raise ERROR_1 instead of return ERROR_1
>> the originating code isn't much doifferent either.
>>
>> The only snag is that sometimes you can lose context
>> which makes it harder to recover from an exception
>> that a return valued error. In that case you wind up
>> with a lot of
> 
> 
> I'm not sure I understand what you mean?  How can I avoid this snag (or 
> rather, what is this snag)?
> 
> 
> 
> 
> 
> Erik
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From lha2@columbia.edu  Sat Apr 13 16:00:32 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Sat, 13 Apr 2002 11:00:32 -0400
Subject: [Tutor] Two questions
References: <000a01c1e2ee$682f2ae0$0201a8c0@eagle>
Message-ID: <3CB84810.24DA7EC6@mail.verizon.net>

Other people have addressed mechanics; but a quick word on the
difference between a tuple and a list (as I understand it).

First, what your error means:
>  File "C:\python_pgms\misc_obs_pgm.py", line 37
>     site_url(i) = fileobject.readline()
> SyntaxError: can't assign to function call

when you use the notation "site_url[i]", you are saying, "the ith
element of list, tuple, or dictionary (in which case i is a key rather
than an index) of site_url". When you say "site_url(i)", you are
implying that site_url is a function, and that you want to send the
argument i to it. You can call a function on the right side of an
assignment (=), but it doesn't make sense to call a function on the left
side of an =. site_url(i) DOES NOT IMPLY THAT site_url IS A TUPLE (even
though lists are denoted by [] and tuples by ()).

Tuples are immutable. That means that the only way to modify a tuple is
by computing a new one, like the only way to modify an integer variable
is by computing a new one to overwrite the old one (e.g., 

myInt = 2
myInt = myInt + 4

but myInt has no methods for changing myInt without overwriting the old
one). Lists and dictionaries, though, do let you do all sorts of neat
stuff in place, including append, which is what I have a feeling you
want to do.

If you create a list named site_url

site_url = []

then you can add new elements to this list variable by using the command

site_url.append(fileobject.readline())

If your list has ten elements and you realize that you want to change
the 0th one, THEN you would use the construction

site_url[0] = fileobject.readline()

but if there is not already a 0th element, you're out of luck (and will
get an IndexError, "I can't overwrite a 0th element if one didn't
already exist").

Once there is an element with index 2,

print site_url[2]

will print that element WHETHER site_url IS A LIST OR A TUPLE. But I see
no reason for your code to use tuples. Tuples are cool for dictionary
keys, but I haven't seen any other instances where tuples are preferable
to lists. Lists are  much easier to play with.

> Henry Steigerwaldt wrote:
> 
> To Whom It May Concern:
> 
> The program I am about to describe is opened in Idle, and then run in
> Idle. The code pieces below are all located in a function called
> Main().
> 
> The following piece of code works just fine:
> 
>    # read first line in a file to get URL
>    site_url = fileobject.readline()
>    print "site_url = ", url
> 
> In the above code, the URL read in first line of a file stores just
> fine
> into variable "site_url." However, when I try to store the URL into a
> list or tuple, I get an error.
> 
> Below is the piece of code to store URL into a list:
> 
>    i = 0
>    site_url[i] = fileobject.readline()
>    print "site_url = ", site_url[i]
> Here is the error that is output in Idle:
> 
>   Main()
>   File "C:\python_pgms\misc_obs_pgm.py", line 37, in Main
>     site_url[i] = fileobject.readline()
> NameError: global name 'site_url' is not defined
> _________________________________
> Below is the piece of code to store URL into a tuple:
> 
>    i = 0
>    site_url(i) = fileobject.readline()
>    print "site_url = ", site_url(i)
> 
> Here is the error that is output in Idle:
> 
>  File "C:\python_pgms\misc_obs_pgm.py", line 37
>     site_url(i) = fileobject.readline()
> SyntaxError: can't assign to function call
> ______________________________________________
> 
> I do not understand why I am getting these errors.
> 
> Actually what I want to do in this program is read the first
> line of a file, which contains a number, say 4. The number tells
> the program how many URLs will follow (one per line) in the file.
> So after the first line of the file is read, the program then is
> supposed to read and then store the URLs in either a list or
> a tuple. After that, I want to go to each site (URL) and grab
> some information.
> 
> Please be as least cryptic as possible in any response. I have
> written some small programs in Tcl/Tk (and a couple of other
> languages in the past), but my programming experience is very
> limited.
> 
> Thanks for any help provided !
> 
> Henry Steigerwaldt
> Hermitage, TN
>



From erikprice@mac.com  Sat Apr 13 16:20:25 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 13 Apr 2002 11:20:25 -0400
Subject: [Tutor] Two questions
In-Reply-To: <3CB83AE9.50506@venix.com>
Message-ID: <FADD21F1-4EF1-11D6-8107-00039351FE6A@mac.com>

On Saturday, April 13, 2002, at 10:04  AM, Lloyd Kvam wrote:

> You need to create a (possibly empty) list before you can stick
> something into the list.

I thought that, being a dynamically typed language, you could just 
create list elements on the fly (in the way that henry steigerwaldt did 
in his original script).  I know/have heard that it's good practice to 
declare a variable first, like

site_url = []

but I thought that it was possible to just jump in and start assigning 
directly to elements in a list.  I can't -- even if I declare site_url 
as a list, the following doesn't work:

 >>> site_url=[]
 >>> site_url[0] = 'hi'
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
IndexError: list assignment index out of range

Why is that?  I thought dynamic typing was more flexible than this... ?

> i = 0
> site_url = []	# create an empty list
> site_url[i] = fileobject.readline()
> print "site_url = ", site_url[i]
>
> It is usually simpler to not track the positions when putting
> things into the list.  Something like:
>
> site_url = []
> site_url.append( fileobject.readline())
>
> simply adds the url to the end of the list.  You can NOT add
> things to a tuple.  A tuple can NOT be changed.  If you want your
> URLs to be in a tuple, create the list first.  Then use the
> builtin tuple function.

Then how come I can do:

tuple1 = (1, 2)
tuple2 = (3, 4)
tuple3 = tuple1 + tuple2
(1, 2, 3, 4)

or is that because I'm creating a new tuple?

Erik




From erikprice@mac.com  Sat Apr 13 16:26:33 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 13 Apr 2002 11:26:33 -0400
Subject: [Tutor] Two questions
In-Reply-To: <FADD21F1-4EF1-11D6-8107-00039351FE6A@mac.com>
Message-ID: <D6652D8D-4EF2-11D6-8107-00039351FE6A@mac.com>

Nevermind this whole email, Lloyd just explained it very well in a later 
email that I hadn't read yet.


Thank you,

Erik


On Saturday, April 13, 2002, at 11:20  AM, Erik Price wrote:

>
> On Saturday, April 13, 2002, at 10:04  AM, Lloyd Kvam wrote:
>
>> You need to create a (possibly empty) list before you can stick
>> something into the list.
>
> I thought that, being a dynamically typed language, you could just 
> create list elements on the fly (in the way that henry steigerwaldt did 
> in his original script).  I know/have heard that it's good practice to 
> declare a variable first, like
>
> site_url = []
>
> but I thought that it was possible to just jump in and start assigning 
> directly to elements in a list.  I can't -- even if I declare site_url 
> as a list, the following doesn't work:
>
> >>> site_url=[]
> >>> site_url[0] = 'hi'
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> IndexError: list assignment index out of range
>
> Why is that?  I thought dynamic typing was more flexible than this... ?
>
>> i = 0
>> site_url = []	# create an empty list
>> site_url[i] = fileobject.readline()
>> print "site_url = ", site_url[i]
>>
>> It is usually simpler to not track the positions when putting
>> things into the list.  Something like:
>>
>> site_url = []
>> site_url.append( fileobject.readline())
>>
>> simply adds the url to the end of the list.  You can NOT add
>> things to a tuple.  A tuple can NOT be changed.  If you want your
>> URLs to be in a tuple, create the list first.  Then use the
>> builtin tuple function.
>
> Then how come I can do:
>
> tuple1 = (1, 2)
> tuple2 = (3, 4)
> tuple3 = tuple1 + tuple2
> (1, 2, 3, 4)
>
> or is that because I'm creating a new tuple?
>
> Erik
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>




From pythontutor@venix.com  Sat Apr 13 17:42:43 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 13 Apr 2002 12:42:43 -0400
Subject: [Tutor] Two questions
References: <FADD21F1-4EF1-11D6-8107-00039351FE6A@mac.com>
Message-ID: <3CB86003.8070304@venix.com>

That will teach me to post without checking!

The list assignment does not let you assign beyond the existing
size of a list.  It prevents:
	alist = []
	alist[5] = 'hi'
What should Python do about the missing elements before [5]?
This works:
	alist = [1,2,3,4,5,6]
	alist[5] = 'hi'
because the slot 5 has been created.  (slot 5 == the sixth element)

Yes, Andrei's and Lloyd Allen's later posts cover this better...

Erik Price wrote:

> 
> On Saturday, April 13, 2002, at 10:04  AM, Lloyd Kvam wrote:
> 
>> You need to create a (possibly empty) list before you can stick
>> something into the list.
> 
> 
> I thought that, being a dynamically typed language, you could just 
> create list elements on the fly (in the way that henry steigerwaldt did 
> in his original script).  I know/have heard that it's good practice to 
> declare a variable first, like
> 
> site_url = []
> 
> but I thought that it was possible to just jump in and start assigning 
> directly to elements in a list.  I can't -- even if I declare site_url 
> as a list, the following doesn't work:
> 
>  >>> site_url=[]
>  >>> site_url[0] = 'hi'
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> IndexError: list assignment index out of range
> 
> Why is that?  I thought dynamic typing was more flexible than this... ?
> 
>> i = 0
>> site_url = []    # create an empty list
>> site_url[i] = fileobject.readline()
>> print "site_url = ", site_url[i]
>>
>> It is usually simpler to not track the positions when putting
>> things into the list.  Something like:
>>
>> site_url = []
>> site_url.append( fileobject.readline())
>>
>> simply adds the url to the end of the list.  You can NOT add
>> things to a tuple.  A tuple can NOT be changed.  If you want your
>> URLs to be in a tuple, create the list first.  Then use the
>> builtin tuple function.
> 
> 
> Then how come I can do:
> 
> tuple1 = (1, 2)
> tuple2 = (3, 4)
> tuple3 = tuple1 + tuple2
> (1, 2, 3, 4)
> 
> or is that because I'm creating a new tuple?
> 
> Erik
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From alex@gabuzomeu.net  Sat Apr 13 17:57:25 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Sat, 13 Apr 2002 18:57:25 +0200
Subject: [Tutor] Two questions
In-Reply-To: <20020413160005.12084.43402.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020413184535.00b798f0@pop3.norton.antivirus>

Hello,


At 12:00 13/04/2002 -0400, you wrote:
>Date: Sat, 13 Apr 2002 11:20:25 -0400
>Subject: Re: [Tutor] Two questions
>From: Erik Price <erikprice@mac.com>

>I know/have heard that it's good practice to
>declare a variable first, like
>
>site_url = []

For lists, dictionaries, tuples, it's more than good practice: it's 
necessary. It's also necessary for variables incremented in loops, for 
instance.

 >>> for n in range(10):
...     toto = toto + 1

Here you get a NameError if you don't initialise "toto" before running the 
loop:

toto = 0

>  >>> site_url=[]
>  >>> site_url[0] = 'hi'
>Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>IndexError: list assignment index out of range
>
>Why is that?  I thought dynamic typing was more flexible than this... ?

You need to use yourList.append() to create a list element. Then you can 
access it using its index value if needed.

>Then how come I can do:
>
>tuple1 = (1, 2)
>tuple2 = (3, 4)
>tuple3 = tuple1 + tuple2
>(1, 2, 3, 4)
>
>or is that because I'm creating a new tuple?

Yes, this operation returns a new tuple. Example:

 >>> toto = (1, 2)
 >>> print id(toto)
29829852
 >>> toto = toto * 2
 >>> print id(toto)
39910620
 >>> print toto
(1, 2, 1, 2)

id() returns a different unique id number because "toto" has been 
reassigned to a new object.


Cheers.

Alexandre




From VSOFTSMITH@aol.com  Sat Apr 13 18:16:42 2002
From: VSOFTSMITH@aol.com (VSOFTSMITH@aol.com)
Date: Sat, 13 Apr 2002 13:16:42 EDT
Subject: [Tutor] how to do "program chains"
Message-ID: <1a4.ad9500.29e9c1fa@aol.com>

i am used to working in an environment where the user signs on with a 
password and is presented with a menu of choices of independent things they 
might want to do, eg

       1. admit patient
       2. display patient
      3. production run

with each choice a new program is called and executed. when complete it 
returns to the menu from which it was called.

some program transfers like to "production run" above are other menus.
there may be 300 programs that are accessible this way.
each program is small and easily maintained independently of the others

how do i do this in python? example code somewhere?

thanks for any help



From ak@silmarill.org  Sat Apr 13 18:59:38 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sat, 13 Apr 2002 13:59:38 -0400
Subject: [Tutor] how to do "program chains"
In-Reply-To: <1a4.ad9500.29e9c1fa@aol.com>
References: <1a4.ad9500.29e9c1fa@aol.com>
Message-ID: <20020413175938.GA23941@ak.silmarill.org>

On Sat, Apr 13, 2002 at 01:16:42PM -0400, VSOFTSMITH@aol.com wrote:
> i am used to working in an environment where the user signs on with a 
> password and is presented with a menu of choices of independent things they 
> might want to do, eg
> 
>        1. admit patient
>        2. display patient
>       3. production run
> 
> with each choice a new program is called and executed. when complete it 
> returns to the menu from which it was called.
> 
> some program transfers like to "production run" above are other menus.
> there may be 300 programs that are accessible this way.
> each program is small and easily maintained independently of the others
> 
> how do i do this in python? example code somewhere?
>
def admit_patient():
    [...]

def display_patient():
    [...]

def production_run():
    [...]

use_dict = {
    1: admit_patient,
    2: display_patient,
    3: production_run,
}

while 1:
    answer = raw_input("""
    1. admit patient
    2. display patient
    3. production run

    Enter number: """)

    try:
        a = int(answer)
        use_dict[a]()   # run needed function.
    except (ValueError, IndexError):
        print "Illegal response"
        continue


Each function could actually be in a separate module for easier
maintainance (if they grow real big). The only hockey thing here is the
line use_dict[a](). What happens here is that use_dict[1] (for instance)
becomes admit_patient. admit_patient with added () becomes
admit_patient(), which runs the respective function.


 - Andrei


> 
> thanks for any help
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From paulsid@shaw.ca  Sat Apr 13 20:45:25 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sat, 13 Apr 2002 13:45:25 -0600
Subject: [Tutor] how to do "program chains"
References: <1a4.ad9500.29e9c1fa@aol.com>
Message-ID: <3CB88AD5.6BC273E8@shaw.ca>

VSOFTSMITH@aol.com wrote:

> with each choice a new program is called and executed. when complete it
> returns to the menu from which it was called.
> 
> some program transfers like to "production run" above are other menus.
> there may be 300 programs that are accessible this way.
> each program is small and easily maintained independently of the others

If I may, I would suggest you don't try to implement things this way
unless a significant number of menu options are already implemented as
standalone programs in another language.  I have always found this
design principle to be somewhat amateurish - kind of a holdover from
ancient BASICs where there was no concept of modularity.

If you're really intent on doing this I recommend using a shell script
to invoke the programs.  Heck, there are even things for DOS that will
let you write menu scripts like this.

Fortunately, with Python you can take a modular approach - one "program"
per module - and still code each module as if it were an independent
program.  Here's a simple menu front-end that will dynamically load and
execute the modules when commands are selected.  It assumes each module
has a function called main(), and executes the command by calling that
function.  This has no errorchecking!

cmddict = {'a': ("Add User", "adduser"),
           'b': ("Banking", "banking"),
           'c': ("Create Account", "createacct"),
           'd': ("Delete User", "deleteuser")}

while 1:
    # Could implement cmddict in a module and reload it here to allow
    # dynamic updating of commands.
    cmdkeys = cmddict.keys()
    cmdkeys.sort()
    print
    for k in cmdkeys:
        print "%c) %s" % (k, cmddict[k][0])
    print "0) Quit"
    print
    key = raw_input("Select---> ")
    if not key:
        continue
    if key == '0':
        break
    key = key[0]
    if cmddict.has_key(key):
        if cmddict[key][1]:
            cmdcode = __import__(cmddict[key][1])
            reload(cmdcode)
            cmdcode.main()
            del cmdcode
    else:
        print "Invalid command"

print

I have tested this and it works.  I tried using the add command,
modifying its code in another session, then using the add command again
and it executed the updated module the second time

Like I noted above, sticking the command dictionary in a module and
reloading it where the comments are would allow the actual command list
to be dynamically updated as well.

Of course adding errorchecking is a must and there may also be security
concerns, but it's a start.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From charlie@begeistert.org  Sat Apr 13 23:39:23 2002
From: charlie@begeistert.org (Charlie Clark)
Date: Sun, 14 Apr 2002 00:39:23 +0200
Subject: [Tutor] Re: Erik's questions
In-Reply-To: <20020413160005.12084.43402.Mailman@mail.python.org>
References: <20020413160005.12084.43402.Mailman@mail.python.org>
Message-ID: <20020414004126.3875.10@gormenghast.1018420652.fake>

On 2002-04-13 at 18:00:05 [+0200], tutor-request@python.org wrote:
> site_url = []
> 
> but I thought that it was possible to just jump in and start assigning 
> directly to elements in a list.  I can't -- even if I declare site_url as 
> a list, the following doesn't work:
> 
>  >>> site_url=[]
>  >>> site_url[0] = 'hi'
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> IndexError: list assignment index out of range
> 
> Why is that?  I thought dynamic typing was more flexible than this... ?
This is not a typing issue.
site_url exists but as it doesn't have any members (it's an empty list), site_url[0] returns an error and cannot be assigned: there is no one in the dinner queue to get the first tray.

Charlie



From wolf_binary@hotmail.com  Sun Apr 14 02:18:14 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sat, 13 Apr 2002 20:18:14 -0500
Subject: [Tutor] exceptions
Message-ID: <DAV4610wSgrOAvO8jrR000043e5@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01C1E328.572F5000
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi all,

How do you approach error trapping and use exceptions in Python to take =
care of it?  How do you for all the possible dumb user mistakes?  I mean =
give me the kind of thought process of how I should go about thinking =
this through in planning my program.

Thanks guys for your help,

Cameron Stoner

------=_NextPart_000_0005_01C1E328.572F5000
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>How do you approach error trapping and =
use=20
exceptions in Python to take care of it?&nbsp; How do you for all the =
possible=20
dumb user mistakes?&nbsp; I mean give me the kind of thought process of =
how I=20
should go about thinking this through in planning my =
program.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks guys for your help,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Cameron =
Stoner</FONT></DIV></BODY></HTML>

------=_NextPart_000_0005_01C1E328.572F5000--



From pythontutor@venix.com  Sun Apr 14 03:40:21 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Sat, 13 Apr 2002 22:40:21 -0400
Subject: [Tutor] exceptions
References: <DAV4610wSgrOAvO8jrR000043e5@hotmail.com>
Message-ID: <3CB8EC15.5010000@venix.com>

Here is the "check value" code for numeric input in my current project.
All values that are set from the user interface funnel through here.  I
pulled out the numeric part because I think it is a reasonably complete
example for catching errors.  Part of the process is to build a string
with useful information when something goes wrong to provide some context
in describing the error - as opposed to simply reporting "Invalid Value!"

def uicheckSet(self, fieldname, value):
	''' Raise an exception for invalid value for this fieldname
	'''	
	process = self.uigetProcess( fieldname)	# i keep dictionary of processing info for each fieldname
	...	# skipping to numeric section
	elif process in ['ui_integer', 'ui_money', 'ui_percent', 'ui_year']:
		if not value:		# value may not have come directly from user typing
			value = 0		# so we "rationalize" it
		value = str( value).strip()	
		if process == 'ui_money': regexp = '[-]?[0-9]*\.?[0-9]?[0-9]?'
		elif process == 'ui_percent': regexp = '[-]?[0]*[.][0-9]+'
		else: regexp = '[-]?[0-9]+'
		try:
			m = re.match( regexp, value)
			if not m:
				msg = "Invalid characters for field: %s.  Received: %s.  Valid set is: %s" % (fieldname,value,regexp)
				raise ValueError, msg
			elif m.group() != value:
				msg = "Invalid character %s.  Valid charaters: %s" % (value[m.end()],regexp)
				raise ValueError, msg
		except re.error, diag:
			raise ValueError, str(diag)
		else:
			if process == 'ui_integer': value = int(value)
			else: value = float(value)
			range = self.uigetInput( fieldname)		# here i get the valid range for this fieldname
			if not range[0] <= value <= range[1]:
				raise ValueError, '%s should be between %s and %s' % (fieldname, str(range[0]), str(range[1]))

After this, the fieldname will be set to the supplied value, and if all goes
well, stored in the database.

Cameron Stoner wrote:

> Hi all,
> 
>  
> 
> How do you approach error trapping and use exceptions in Python to take 
> care of it?  How do you for all the possible dumb user mistakes?  I mean 
> give me the kind of thought process of how I should go about thinking 
> this through in planning my program.
> 
>  
> 
> Thanks guys for your help,
> 
>  
> 
> Cameron Stoner
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From shalehperry@attbi.com  Sun Apr 14 03:47:39 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sat, 13 Apr 2002 19:47:39 -0700 (PDT)
Subject: [Tutor] exceptions
In-Reply-To: <DAV4610wSgrOAvO8jrR000043e5@hotmail.com>
Message-ID: <XFMail.20020413194739.shalehperry@attbi.com>

On 14-Apr-2002 Cameron Stoner wrote:
> Hi all,
> 
> How do you approach error trapping and use exceptions in Python to take care
> of it?  How do you for all the possible dumb user mistakes?  I mean give me
> the kind of thought process of how I should go about thinking this through in
> planning my program.
> 

I tend to write it through once clean without error checking (or minimal
checking).  Thne I use it and see what happens.  As I start to add code to
catch this I look at all the possible errors go from there.

A lot of working with exceptions is knowing where to put the handler.  This
just becomes intuitive as you get used to it.  The key is the error code should
not distract too much from the workings of the program.  If you find youself
reading more error code than actual application code you probably need to
rethink things.



From dyoo@hkn.eecs.berkeley.edu  Sun Apr 14 08:44:28 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 14 Apr 2002 00:44:28 -0700 (PDT)
Subject: [Tutor] << operator ?  [left bitwise shifting / Jon Bentley's
 Programming Pearls]
In-Reply-To: <E16vwQv-0001YI-00@mail.python.org>
Message-ID: <Pine.LNX.4.44.0204140038070.2466-100000@hkn.eecs.berkeley.edu>

> > And this is what we mean when we say that computers count in base-two
> > arithmetic --- they represent numbers by using on/off switches --- "bits".
> > On most systems that Python runs on, each integer is made up of 32 bits.
>
> Hmm .. is this the difference between the computers used popularly
> today, and the new IA-64 architecture ? If so, does a "2" on a 64-bit
> machine have 32 more zeroes in front of it, than a "2" on a 32-bit
> machine ?

Yes, I believe so.  On a 64 bit machine, integers should be represented in
64 bits.


> Ok. I think I've got a hang of what these operators do. Now to go find a
> binary file to play with in "pure" python .... :-)

If you ever get the chance, youy might be interested in the book
"Programming Pearls", by Jon Bentley.  If you browse through Column 1,
you'll see a great example of bits in action.  *grin*

    http://www.cs.bell-labs.com/cm/cs/pearls/cto.html


Best of wishes to you!




From dyoo@hkn.eecs.berkeley.edu  Sun Apr 14 09:16:09 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 14 Apr 2002 01:16:09 -0700 (PDT)
Subject: [Tutor] Two questions   [array out of bounds / lazylist /
 autovivification]
In-Reply-To: <3CB86003.8070304@venix.com>
Message-ID: <Pine.LNX.4.44.0204140053300.2466-100000@hkn.eecs.berkeley.edu>


On Sat, 13 Apr 2002, Lloyd Kvam wrote:

> That will teach me to post without checking!
>
> The list assignment does not let you assign beyond the existing
> size of a list.  It prevents:
> 	alist = []
> 	alist[5] = 'hi'

Yes; this is one difference between Python and Perl --- Python assumes
that if we index beyond the length of an array, we probably goofed, and
should be told about the error through an IndexError.  On the other hand,
Perl will automatically expand the array to the appropriate size.  In Perl
terms, it "autovivifies" array elements.


It is possible to write a "lazylist", that is, a list subclass that
supports autovivification.  Here's one way to do it:


###
class lazylist(list):
    def __getitem__(self, i):
        if not (type(i) is tuple):
            self.padExpand(i)
        return list.__getitem__(self, i)

    def __setitem__(self, i, obj):
        if not (type(i) is tuple):
            self.padExpand(i)
        return list.__setitem__(self, i, obj)

    def padExpand(self, i):
        """Make sure that this list contains n+1 elements by padding
        None at the end."""
        if i < 0: return
        if len(self) <= i:
            self.extend([None] * (i - len(self) + 1))
###


Let's take a look!

###
>>> l = lazylist([1, 2, 3])
>>> l
[1, 2, 3]
>>> l[10:]
[]
>>> l
[1, 2, 3]
>>> l[10]
>>> l
[1, 2, 3, None, None, None, None, None, None, None, None]
>>> l[20] = "twenty"
>>> l
[1, 2, 3, None, None, None, None, None, None, None, None, None, None,
 None, None, None, None, None, None, None, 'twenty']
###



As a caveat: I'm not sure if this is a good idea or not to use lazylist.
Autovivification has some really serious potential of hiding off-by-one
boundary errors, and that's a bad thing.  I think the intention of the
IndexError is to force programmers to really think about boundary cases,
instead of just shoving everything underneath the rug.


Hope this helps!




From urnerk@qwest.net  Sun Apr 14 13:32:54 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 14 Apr 2002 08:32:54 -0400
Subject: [Tutor] Two questions   [array out of bounds / lazylist / autovivification]
In-Reply-To: <Pine.LNX.4.44.0204140053300.2466-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0204140053300.2466-100000@hkn.eecs.berkeley.edu>
Message-ID: <E16wlw1-00086l-00@mail.python.org>

On Sunday 14 April 2002 04:16 am, Danny Yoo wrote:

> ###
> class lazylist(list):
>     def __getitem__(self, i):
>         if not (type(i) is tuple):
>             self.padExpand(i)
>         return list.__getitem__(self, i)

Hi Danny -- could you please explain why you are making sure
i is not a tuple here, and in __setitem__.

Also, I notice that asking for l[5] changes a 3-element list to have
5 elements, yet returns nothing, whereas l[5:6] returns the empty
list and does not change it.  This might seem inconsistent, but 
is perhaps intentional.

In any case, this was an instructive example of subclassing a
builtin.

Kirby



From dyoo@hkn.eecs.berkeley.edu  Sun Apr 14 19:47:07 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 14 Apr 2002 11:47:07 -0700 (PDT)
Subject: [Tutor] Two questions   [list subclassing / list.__getslice__]
In-Reply-To: <E16wlw1-00086l-00@mail.python.org>
Message-ID: <Pine.LNX.4.44.0204141105120.18390-100000@hkn.eecs.berkeley.edu>


On Sun, 14 Apr 2002, Kirby Urner wrote:

> On Sunday 14 April 2002 04:16 am, Danny Yoo wrote:
>
> > ###
> > class lazylist(list):
> >     def __getitem__(self, i):
> >         if not (type(i) is tuple):
> >             self.padExpand(i)
> >         return list.__getitem__(self, i)
>
> Hi Danny -- could you please explain why you are making sure
> i is not a tuple here, and in __setitem__.

According to the reference documentation, __getitem__() gets called if we
do tuple-slicing as well:

    http://python.org/doc/current/ref/sequence-types.html


For example:

###
>>> class Foo:
...     def __getitem__(self, i):
...         print "I see %s with the representation %s" % (type(i), i)
...
>>> f = Foo()
>>> f[3]
I see <type 'int'> with the representation 3
>>> f[3:10]
I see <type 'slice'> with the representation slice(3, 10, None)
>>> f[3:2:10]
I see <type 'slice'> with the representation slice(3, 2, 10)
>>> f[:10]
I see <type 'slice'> with the representation slice(0, 10, None)
>>> f[10:]
I see <type 'slice'> with the representation slice(10, 2147483647, None)
###

Oh!  Ok, I didn't realize that in the case of slices, we get back a "slice
object", and not a tuple.  lazylist needs to be amended to test for
slices, not tuples.  Sorry about that.  But the idea was not to do
autovivification if we're working with a tuple; I just wanted to change
access to single elements.



Hmmm... wait... ooops.  There's another problem here: lists don't appear
to use __getitem__() on list slices!

###
>>> class testlist(list):
...     def __getitem__(self, i):
...         print "Hello"
...
>>> t = testlist()
>>> t[3]
Hello
>>> t[3:4]
[]
###

and that's because lists have defined the deprecated "__getslice__()" and
__setslice__() methods:

###
>>> t.__getslice__
<method-wrapper object at 0x814c6e4>
>>> t.__setslice__
<method-wrapper object at 0x814e04c>
###

If __getslice__() exists, it takes precedence over __getitem__() on
slicing.



All these bugs were unexpected.  *grin* Well, at least it shows that even
code that looks like it's working shouldn't be completely trusted until
it's been looked over a few times.  Here's a corrected version of
lazylist:


######
class lazylist(list):
    def __getitem__(self, i):
        self.padExpand(i)
        return list.__getitem__(self, i)

    def __setitem__(self, i, obj):
        self.padExpand(i)
        return list.__setitem__(self, i, obj)

    def padExpand(self, i):
        """Make sure that this list contains i+1 elements by padding
        None at the end."""
        if i < 0: return
        if type(i) is slice: return    ## Be aware that, as of Python 2.2,
                                       ## this won't happen since lists
                                       ## still implement __getslice__().
                                       ## This is here just in case the
                                       ## status quo changes.
        if len(self) <= i:
            self.extend([None] * (i - len(self) + 1))
######



> Also, I notice that asking for l[5] changes a 3-element list to have 5
> elements, yet returns nothing, whereas l[5:6] returns the empty list and
> does not change it.  This might seem inconsistent, but is perhaps
> intentional.

Yes, slicing is a bit more relaxed than indicing.  I wanted to make sure
that something like:

###
>>> l = lazylist(range(10))
>>> print l[5:]
[5, 6, 7, 8, 9]
###

would still work.  It turns out that on "single sided" indices like "5:",
Python uses a honking big number for the right endpoint:

###
>>> class testslice:
...     def __getitem__(self, i):
...         print i
...
>>> testslice()[:]
slice(0, 2147483647, None)
###

so autovivification would not be a good idea for slices.  *grin*


Hope this helps!




From wolf_binary@hotmail.com  Sun Apr 14 21:21:56 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sun, 14 Apr 2002 15:21:56 -0500
Subject: [Tutor] where to start for beginners
Message-ID: <DAV42XePhVgvjDrzzyC00004a4e@hotmail.com>

This is a multi-part message in MIME format.

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

Hi all,

I am currently writing and teaching my brother how to program, cause he =
says he wants to make his own computer games.  Should I start teaching =
him about registers, and the ALU and things like that first, or should I =
teach him about flow charting and psuedo code?  I didn't really start at =
either one.  I started with the Python tutorials and that didn't go to =
far at first.  I am trying to help him get started in a more structured =
sort of way that won't make him get discouraged.  Do any of you have any =
suggestions?

Thanks for you help,

Cameron Stoner

------=_NextPart_000_0007_01C1E3C8.1D1D2C20
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I am currently writing and teaching my =
brother how=20
to program, cause he says he wants to make his own computer games.&nbsp; =
Should=20
I start teaching him about registers, and the ALU and things like that =
first, or=20
should I teach him about flow charting and psuedo code?</FONT><FONT =
face=3DArial=20
size=3D2>&nbsp; I didn't really start at either one.&nbsp; I started =
with the=20
Python tutorials and that didn't go to far at first.&nbsp; I am trying =
to help=20
him get started in a more structured sort of way that won't make him get =

discouraged.&nbsp; Do any of you have any suggestions?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks for you help,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Cameron =
Stoner</FONT></DIV></BODY></HTML>

------=_NextPart_000_0007_01C1E3C8.1D1D2C20--



From scarblac@pino.selwerd.nl  Sun Apr 14 21:29:24 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Sun, 14 Apr 2002 22:29:24 +0200
Subject: [Tutor] where to start for beginners
In-Reply-To: <DAV42XePhVgvjDrzzyC00004a4e@hotmail.com>; from wolf_binary@hotmail.com on Sun, Apr 14, 2002 at 03:21:56PM -0500
References: <DAV42XePhVgvjDrzzyC00004a4e@hotmail.com>
Message-ID: <20020414222924.A2902@pino.selwerd.nl>

On  0, Cameron Stoner <wolf_binary@hotmail.com> wrote:
> I am currently writing and teaching my brother how to program, cause he
> says he wants to make his own computer games.  Should I start teaching him
> about registers, and the ALU and things like that first, or should I teach
> him about flow charting and psuedo code?  I didn't really start at either
> one.  I started with the Python tutorials and that didn't go to far at
> first.  I am trying to help him get started in a more structured sort of way
> that won't make him get discouraged.  Do any of you have any suggestions?

I'd say, take some task, a very simple game of some sort, like hangman.

Then explain to him what sort of things the program has to do, and show it
how to do them.

Or start out with something even simpler - but just show him how to do
things, I'd say. Examples rule.

-- 
Remco Gerlich



From dark_cactus@hotmail.com  Sat Apr 13 17:01:07 2002
From: dark_cactus@hotmail.com (Ashley Fox)
Date: Sun, 14 Apr 2002 00:01:07 +0800
Subject: [Tutor] Help Needed
Message-ID: <DAV70fPVtVTwMEbb4pg0000408c@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_0005_01C1E347.7A666A80
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

hello, my name is Ashley and i m 12 years old. i would like to learn how =
to program. Could someone plz help me with all these stuff. i find it =
all a little confusing. i have necer programed anything before

------=_NextPart_000_0005_01C1E347.7A666A80
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2600.0" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#00ffff>
<DIV><FONT face=3DArial color=3D#000000 size=3D2>hello, my name is =
Ashley and i m 12=20
years old. i would like to learn how to program. Could someone plz help =
me with=20
all these stuff. i find it all a little confusing. i have necer =
programed=20
anything before</FONT></DIV></BODY></HTML>

------=_NextPart_000_0005_01C1E347.7A666A80--



From alan.gauld@bt.com  Sun Apr 14 22:28:00 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Sun, 14 Apr 2002 22:28:00 +0100
Subject: [Tutor] constructors
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C54D@mbtlipnt02.btlabs.bt.co.uk>

> On Friday, April 12, 2002, at 08:59  AM, alan.gauld@bt.com wrote:
> > The only snag is that sometimes you can lose context
> > which makes it harder to recover from an exception

> I'm not sure I understand what you mean?  How can I avoid 
> this snag (or rather, what is this snag)?

What I mean is that if the try/except encompasses many 
statements when an exception occurs you jump to the 
end of that block with no way back in (I've always thought 
a 'continue' for exception handlers would be nice!)

Thus if you are reading through a list or file and some
relatively unimportant error(divide by zero say) occurs 
throwing an exception you cannot just go back to reading 
your list/file. The context has been lost...

With explicit error testing on each call you only fail 
the one bit in the middle of the block, you can still 
go back to the start.

You can do this with exceptions too by using very small, 
tightly controlled try/excepts - down to each single 
statement if needed - but it then spoils the improved 
readability of the code. The trick is to make the 
enclosed block 'atomic', that is it only does one thing, 
with no unrelated bits of code. So in my example above:

try:
   for line in file.xreadlines():
      processData(line)
except DivideByZero: # want to just move on to next line but...
   continue          # can't do this, we lost the loop context!
except IOError:
   print 'File error'

So we have to do this;

try:    # enclose file handling bits, catching those exceptions
   for line in file.xreadlines():
      try:   # now enclose the data processing bits
          processData(line)
      except DivideByZero:
          continue   # still have the file/loop context  
except IOError:
   print 'File error'

Which looks less elegant but maintains context.

HTH,

Alan G



From michael.williams@st-annes.oxford.ac.uk  Sun Apr 14 11:10:18 2002
From: michael.williams@st-annes.oxford.ac.uk (Michael Williams)
Date: Sun, 14 Apr 2002 11:10:18 +0100
Subject: [Tutor] Help Needed
In-Reply-To: <DAV70fPVtVTwMEbb4pg0000408c@hotmail.com>
References: <DAV70fPVtVTwMEbb4pg0000408c@hotmail.com>
Message-ID: <20020414101018.GD263@st-annes.oxford.ac.uk>

On Sun, Apr 14, 2002 at 12:01:07AM +0800, Ashley Fox wrote:
> hello, my name is Ashley and i m 12 years old. i would like to learn
> how to program. Could someone plz help me with all these stuff. i find
> it all a little confusing. i have necer programed anything before

Hi Ashley,

Assuming you want to learn to program in Python (which is a really good
language to start off in), you should start off by installing Python.  You can
get the Windows version here:
<http://www.python.org/ftp/python/2.2.1/Python-2.2.1.exe>. Once that is done
you need a tutorial which will take you through the basics of Python and the
concepts of programming. I wouldn't recommend the official one by Guido (the
guy who wrote Python) for you as it is more for people who already know a
programming language other than Python.  Here are a couple for you that you
could read through.

Livewires: <http://livewires.org.uk/python/index.html> and Alan Gauld's "How to
Program": <http://www.freenetpages.co.uk/hp/alan.gauld/>.

Both of these can be downloaded for you to go through offline and if you pay
for your internet connection by the minute this might be good idea.  If you
need any more help don't hesitate to post to <tutor@python.org>.

One more bit of advice - pay attention in your maths classes! They're really
important for programming.  
-- 
Michael



From dyoo@hkn.eecs.berkeley.edu  Mon Apr 15 00:01:53 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 14 Apr 2002 16:01:53 -0700 (PDT)
Subject: [Tutor] constructors
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C54D@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.44.0204141541550.27107-100000@hkn.eecs.berkeley.edu>


On Sun, 14 Apr 2002 alan.gauld@bt.com wrote:

> You can do this with exceptions too by using very small,
> tightly controlled try/excepts - down to each single
> statement if needed - but it then spoils the improved
> readability of the code. The trick is to make the
> enclosed block 'atomic', that is it only does one thing,
> with no unrelated bits of code. So in my example above:
>
> try:
>    for line in file.xreadlines():
>       processData(line)
> except DivideByZero: # want to just move on to next line but...
>    continue          # can't do this, we lost the loop context!
> except IOError:
>    print 'File error'
>
> So we have to do this;
>
> try:    # enclose file handling bits, catching those exceptions
>    for line in file.xreadlines():
>       try:   # now enclose the data processing bits
>           processData(line)
>       except DivideByZero:
>           continue   # still have the file/loop context
> except IOError:
>    print 'File error'
>
> Which looks less elegant but maintains context.


It's possible to make the above look nicer if we tell Python to tell a
function to "ignore" certain exceptions.  Here's one way we could do this:

###
def ignoreZeroDivisionWrapper(function):
    def wrapped_function(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except ZeroDivisionError:
            return None
    return wrapped_function
###

This is another example of a function that returns a new function, and is
a fun technique to use.  The syntax above is in Python 2.2 style though,
so you may need to do a "from __future__ import nested_scopes" if you're
using 2.1.


This newly generated function will do pretty much the same thing as the
old function, except that it quietly hides exceptions from dividing by
zero.  Here's an example of it in action:

###
>>> def roots(a, b, c):
...     desc = math.sqrt(b**2 - 4*a*c)
...     two_a = 2 * a
...     return ((-b + desc)/two_a,
...             (-b - desc)/two_a)
...
>>> roots(3, 2, -1)
(0.33333333333333331, -1.0)
>>> roots(0, 2, -1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in roots
ZeroDivisionError: float division
>>>
>>>
>>> protected_roots = ignoreZeroDivisionWrapper(roots)
>>> protected_roots(3, 2, -1)
(0.33333333333333331, -1.0)
>>> protected_roots(0, 2, -1)
>>>
###



Once we have something like ignoreZeroDivisionWrapper(), we can use it
like this:

###
try:
    processData = ignoreZeroDivisionWrapper(processData)
    for line in file.xreadlines():
        processData(line)
except IOError:
###

And this doesn't look so bad.


Hope this helps!




From sfpetard@earthlink.net  Mon Apr 15 00:12:07 2002
From: sfpetard@earthlink.net (Bob Rea)
Date: Sun, 14 Apr 2002 16:12:07 -0700
Subject: [Tutor] Help Needed
In-Reply-To: <20020414101018.GD263@st-annes.oxford.ac.uk>
References: <DAV70fPVtVTwMEbb4pg0000408c@hotmail.com> <20020414101018.GD263@st-annes.oxford.ac.uk>
Message-ID: <E16wtA7-0002JP-00@gull.prod.itd.earthlink.net>

On Sunday 14 April 2002 03:10 am, Michael Williams wrote:
> One more bit of advice - pay attention in your maths
> classes! They're really important for programming.

I owuld second that strongly. I have been trying to learn 
to program my own self and the math involved is something I 
know nothing about
I had algebra and palne geometry in high school and thats 
it. 

an example: Chun, ch 5, exercise 15, "Determine the 
greatest common divisor and least common multiple of a pair 
of integers."

Oh, yeah, say what? I almost understand, but not enough.

Is there a site one can go to on the net for stuff like 
this?

-- 
Bob Rea

Give a man a fish, he owes you one fish.
Teach a man to fish, you give up your monopoly on fisheries.

sfpetard@earthlink.net      
http://home.earthlink.net/~sfpetard/



From paulsid@shaw.ca  Mon Apr 15 00:22:51 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sun, 14 Apr 2002 17:22:51 -0600
Subject: [Tutor] Help Needed
References: <DAV70fPVtVTwMEbb4pg0000408c@hotmail.com>
 <20020414101018.GD263@st-annes.oxford.ac.uk>
 <E16wtA7-0002JP-00@gull.prod.itd.earthlink.net>
Message-ID: <3CBA0F4B.A4595555@shaw.ca>

Bob Rea wrote:

> an example: Chun, ch 5, exercise 15, "Determine the
> greatest common divisor and least common multiple of a pair
> of integers."
> 
> Is there a site one can go to on the net for stuff like
> this?

Eric Weisstein's World of Mathematics is one of the most popular online
references:

http://mathworld.wolfram.com/

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From dyoo@hkn.eecs.berkeley.edu  Mon Apr 15 00:28:30 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 14 Apr 2002 16:28:30 -0700 (PDT)
Subject: [Tutor] Help Needed   [greatest common divisor]
In-Reply-To: <E16wtA7-0002JP-00@gull.prod.itd.earthlink.net>
Message-ID: <Pine.LNX.4.44.0204141615150.27107-100000@hkn.eecs.berkeley.edu>


On Sun, 14 Apr 2002, Bob Rea wrote:

> On Sunday 14 April 2002 03:10 am, Michael Williams wrote:
> > One more bit of advice - pay attention in your maths
> > classes! They're really important for programming.
>
> I owuld second that strongly. I have been trying to learn to program my
> own self and the math involved is something I know nothing about I had
> algebra and palne geometry in high school and thats it.
>
> an example: Chun, ch 5, exercise 15, "Determine the
> greatest common divisor and least common multiple of a pair
> of integers."

Let's say that we have a fraction that hasn't been reduced to lowest terms
yet.  Here's an example of such a fraction:

    42
    --
     8

A common divisor is some number D that we can use to divide a group of
numbers.  For example, if we have 42 and 8, a common divisor of those two
numbers could be 2, since 2 divides 42 and it also divides 8.

The "Greatest Common Divisor" is just the largest number we can use that
will divide two numbers neatly.  In the example with 42 and 8, we can
figure it out by successively checking numbers:

    Does 1 divide 42 and 8?
    Does 2 divide 42 and 8?
    ...

At some point, we should be able to figure out when there aren't any more
common divisors we can look for, so this search won't take forever.


This is one way of figuring out what the greatest common divisor is... but
it's not the only way!  This question is a classic one in computer
science; if you get the chance, look up in your library or favorite search
engin the topic of "Euclid's Algorithm", and you should see something
interesting.


Best of wishes to you!




From urnerk@qwest.net  Mon Apr 15 00:47:36 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 14 Apr 2002 16:47:36 -0700
Subject: [Tutor] referring to list elements
In-Reply-To: <fc.004c4b6b00943bf8004c4b6b00943bf8.943c03@blakeschool.org
 >
Message-ID: <4.2.0.58.20020414164500.00ae9450@pop3.norton.antivirus>

At 11:44 PM 4/11/2002 -0500, Christopher Smith wrote:
>Can someone educated in comp sci tell me whether you really
>refer to the elements of a list, when speaking, as zero-eth,
>one-eth, two-eth, etc..., as described in the How to Think book?
>What do you do when you get to the fifth element: do you call
>it the four-eth element?  If you refer to them in the natural
>linguistic sense as '1st', '2nd', etc..., are you always
>doing a little mental gymnastics to remember that the index
>is one less than the actual element position in the ordinal
>sense?
>
>['1st','2nd','3rd','4th','5th'] #indices [0,1,2,3,4]
>
>/c

Yeah, we say the index of the Nth element of a list in N-1.

It's correct to say the first element has index 0, just
as we say the length of a list of N elements -- as in
len(thelist) -- is N, not N-1.  But the indices of such
a list range from 0 to N-1.

And yes, you're always doing a little mental gymnastics
to remember that the index of the Nth element is N-1.
But that's not so bad, really.

Kirby




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




From alan.gauld@bt.com  Mon Apr 15 10:15:22 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 15 Apr 2002 10:15:22 +0100
Subject: [Tutor] how to do "program chains"
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C54F@mbtlipnt02.btlabs.bt.co.uk>

> i am used to working in an environment where the user signs on with a 
> password and is presented with a menu of choices of 
....
> with each choice a new program is called and executed. 

> how do i do this in python? example code somewhere?

There are various options.
Wholly Python:
1) write all the sub programs in separate modules.
2) write a module per menu and in each of these import 
   the required subprogram modules
[ You may like to use a dictionary to store the menu choice 
  to function lookups.... but its your choice]

Python menus only:
Write the menu handling code in Python then use the os.system() 
function to call external programs. When they complete they 
return to your python code.

Fancier Python:
Use the Python command module to implement a menu system 
which will be easy to move to a GUI framework in the future.

You can of course mix and match these approaches as you 
feel the need.

Oh and finally if you want to give the system a nice feel 
use the curses.getch() function(on Unix) or the msvcrt.getch() 
function(Windoze/DOS) to read the users menu selection 
- this means they don't have to hit ENTER after it and 
don't see the screen scroll up a line in the process. 
Looks much more professional. (If you are on Linux 
consider using the other curses stuff too)

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Mon Apr 15 10:22:58 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 15 Apr 2002 10:22:58 +0100
Subject: [Tutor] exceptions
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C550@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C1E45F.222683A0
Content-type: text/plain; charset="ISO-8859-1"

>  How do you approach error trapping and use exceptions in Python to  
>  take care of it?  How do you for all the possible dumb user mistakes?   
 
My tutor contains a page on this subject, plus we just had a thread on it.
 
>  I mean give me the kind of thought process of how I should go about  
>  thinking this through in planning my program. 
 
The main thing is just to think through what could 
go wrong and catch those exceptions at the last point 
that you can sensibly deal with them.
 
For production code I routinely put a try:/except/ 
handler around my entire program which just says 
"Oops something unexpected happened". But thats just 
to shield the gentle users from unsightly stack traces. 
I comment it out during development/testing.
 
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld
<http://www.freenetpages.co.uk/hp/alan.gauld>  

 


------_=_NextPart_001_01C1E45F.222683A0
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.50.4807.2300" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=#ffffff>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002><FONT 
face="Courier New" color=#0000ff>&gt; &nbsp;</FONT></SPAN>How do you approach 
error trapping and use exceptions in Python to&nbsp;<SPAN 
class=700342009-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002><FONT 
face="Courier New" color=#0000ff>&gt; </FONT>&nbsp;</SPAN>take care of it?&nbsp; 
How do you for all the possible dumb user mistakes?&nbsp;&nbsp;<SPAN 
class=700342009-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=700342009-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002>My tutor 
contains a page on this subject, plus we just had a thread on 
it.</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=700342009-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002>&gt; 
&nbsp;</SPAN>I mean give me the kind of thought process of how I should go 
about&nbsp;<SPAN class=700342009-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002><FONT 
face="Courier New" color=#0000ff>&gt; </FONT>&nbsp;</SPAN>thinking this through 
in planning my program.<SPAN class=700342009-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=700342009-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002><FONT 
face="Courier New" color=#0000ff>The main thing is just to think through what 
could </FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002><FONT 
face="Courier New" color=#0000ff>go wrong</FONT>&nbsp;<FONT face="Courier New" 
color=#0000ff>and catch those exceptions at the last point 
</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=700342009-15042002><FONT 
face="Courier New" color=#0000ff>that you can sensibly deal with 
them.</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002>For production code I routinely put a try:/except/ 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002>handler around my entire program which just says 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002>"Oops something unexpected happened". But thats just 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002>to shield the gentle users from unsightly stack traces. 
</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002>I comment it out during 
development/testing.</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=700342009-15042002>
<P><FONT size=2>Alan g.<BR>Author of the 'Learning to Program' web site<BR><A 
target=_blank 
href="http://www.freenetpages.co.uk/hp/alan.gauld">http://www.freenetpages.co.uk/hp/alan.gauld</A></FONT> 
</P></SPAN></FONT></FONT></DIV>
<BLOCKQUOTE dir=ltr 
style="PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #0000ff 2px solid; MARGIN-RIGHT: 0px">
  <DIV><FONT face=Arial size=2></FONT>&nbsp;</DIV></BLOCKQUOTE></BODY></HTML>

------_=_NextPart_001_01C1E45F.222683A0--



From alan.gauld@bt.com  Mon Apr 15 10:33:05 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 15 Apr 2002 10:33:05 +0100
Subject: [Tutor] where to start for beginners
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C551@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C1E460.8BA95BD0
Content-type: text/plain; charset="iso-8859-1"

>  I am currently writing and teaching my brother how to program, cause  
>  he says he wants to make his own computer games.  Should I start  
>  teaching him about registers, and the ALU and things like that first 
 
No, the value of Assembler nowadays is definitely questionable apart from a
few 
specialist areas - and games probably isn't one of them - especially not for
a beginner!
 
>  , or should I teach him about flow charting and psuedo code?   
 
Even thats not needed till things start to get more complex. IMHO of course
:-)
 
> I didn't really start at either one.  I started with the Python tutorials
and that  
> didn't go to far at first. 
 
But do you really think the above would have helped?!
Programming is challenging, the initial learning curve is steep.
 
 > Do any of you have any suggestions? 
 
Well of course I'm going to suggest my tutor since it is 
explicitly designed to teach programming rather than Python... 
:-) 
 
And, being serious, my book is even better because it has 
more introductory concepts explained, diagrams etc.
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld
<http://www.freenetpages.co.uk/hp/alan.gauld>  


------_=_NextPart_001_01C1E460.8BA95BD0
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.50.4807.2300" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=#ffffff>
<DIV><FONT size=2><FONT face=Arial><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>&gt; &nbsp;</FONT></SPAN>I am currently writing 
and teaching my brother how to program, cause&nbsp;<SPAN 
class=530132909-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>&gt; </FONT>&nbsp;</SPAN>he says he wants to 
make his own computer games.&nbsp; Should I start&nbsp;<SPAN 
class=530132909-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>&gt; </FONT>&nbsp;</SPAN>teaching him about 
registers, and the ALU and things like that first<SPAN 
class=530132909-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN class=530132909-15042002>No, the value 
of Assembler nowadays is definitely questionable apart from a few 
</SPAN></FONT></FONT></DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN class=530132909-15042002>specialist 
areas - and games probably isn't one of them - especially not for a 
beginner!</SPAN></FONT></FONT></DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN class=530132909-15042002>&gt; 
&nbsp;</SPAN>, or should I teach him about flow charting and psuedo 
code?</FONT><FONT face=Arial>&nbsp;&nbsp;<SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN class=530132909-15042002>Even thats not 
needed till things start to get more complex. IMHO of course 
:-)</SPAN></FONT></FONT></DIV>
<DIV><FONT size=2><FONT face=Arial><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=530132909-15042002>&gt;&nbsp;</SPAN>I didn't really start at either 
one.&nbsp; I started with the Python tutorials and that&nbsp;<SPAN 
class=530132909-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>&gt;</FONT>&nbsp;</SPAN>didn't go to far at 
first.<SPAN class=530132909-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=530132909-15042002>But do you 
really think the above would have helped?!</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=530132909-15042002>Programming is 
challenging, the initial learning curve is steep.</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>&nbsp;&gt;&nbsp;</FONT></SPAN>Do any of you 
have any suggestions?<SPAN class=530132909-15042002><FONT face="Courier New" 
color=#0000ff>&nbsp;</FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>Well of course I'm going to suggest my tutor 
since it is </FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>explicitly designed to teach programming rather 
than Python... </FONT></SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT size=2><SPAN class=530132909-15042002><FONT 
face="Courier New" color=#0000ff>:-)</FONT>&nbsp;</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=530132909-15042002></SPAN></FONT></FONT>&nbsp;</DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=530132909-15042002>And, being serious, my book is even better because it 
has </SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial><FONT face="Courier New" color=#0000ff size=2><SPAN 
class=530132909-15042002>more introductory concepts explained, diagrams 
etc.</SPAN></FONT></FONT></DIV>
<DIV><FONT face=Arial size=2>
<P><FONT size=2>Alan g.<BR>Author of the 'Learning to Program' web site<BR><A 
target=_blank 
href="http://www.freenetpages.co.uk/hp/alan.gauld">http://www.freenetpages.co.uk/hp/alan.gauld</A></FONT> 
</P></FONT></DIV></BODY></HTML>

------_=_NextPart_001_01C1E460.8BA95BD0--



From ACrane@computer2000.co.uk  Mon Apr 15 10:41:17 2002
From: ACrane@computer2000.co.uk (Crane, Adam)
Date: Mon, 15 Apr 2002 10:41:17 +0100
Subject: [Tutor] Looping
Message-ID: <0A45A5A5BE1BD6118C4100805FE64FF2466278@tdukbasmail01.computer2000.co.uk>

Ok, I'm a newbie to Python, so please forgive me if this sounds stupid :)
But I'm not really sure where to send this...

Is there a way to stop text from looping using while?  For example, if I
used this in a program, the indented text would loop:

password = raw_input("Password:")
while password != "password":
               print "Wrong Password"

I still having a lot of reading to do on Python, but this is really bugging
me.  This is probably really obvious, but any help would be appreciated.


Thanks,
Adam


The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.



From scarblac@pino.selwerd.nl  Mon Apr 15 10:55:12 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 15 Apr 2002 11:55:12 +0200
Subject: [Tutor] Looping
In-Reply-To: <0A45A5A5BE1BD6118C4100805FE64FF2466278@tdukbasmail01.computer2000.co.uk>; from ACrane@computer2000.co.uk on Mon, Apr 15, 2002 at 10:41:17AM +0100
References: <0A45A5A5BE1BD6118C4100805FE64FF2466278@tdukbasmail01.computer2000.co.uk>
Message-ID: <20020415115512.A6414@pino.selwerd.nl>

On  0, "Crane, Adam" <ACrane@computer2000.co.uk> wrote:
> Ok, I'm a newbie to Python, so please forgive me if this sounds stupid :)
> But I'm not really sure where to send this...
> 
> Is there a way to stop text from looping using while?  For example, if I
> used this in a program, the indented text would loop:
> 
> password = raw_input("Password:")
> while password != "password":
>                print "Wrong Password"
> 
> I still having a lot of reading to do on Python, but this is really bugging
> me.  This is probably really obvious, but any help would be appreciated.

Well, the while keeps doing whatever is inside its block, as long as
password isn't equal to "password". That's what while does. Maybe you were
looking for 'if'?

Since you don't change password inside the loop, it loops forever.

A solution is to ask for the password inside the loop again:

password = raw_input("Password:")
while password != "password":
   print "Wrong Password"
   password = raw_input("Password:")
   
This has the disadvantage that the same line is on two places, and if you
ever change one, you might forget about the other. A common way to spell
this in Python is like "do this forever: ask for the password, and if its
right, then stop." Which you write like this:

while 1:
   password = raw_input("Password:")
   if password == "password":
      break

This keeps repeating while '1' is true (it always is), but the 'break'
allows it to exit the loop.
-- 
Remco Gerlich



From lha2@columbia.edu  Mon Apr 15 10:54:14 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Mon, 15 Apr 2002 05:54:14 -0400
Subject: [Tutor] Looping
Message-ID: <3CBAA346.13322D89@mail.verizon.net>

The variable "password" is not updated inside the loop. Since password
never changes, you're stuck in an infinite loop.

You want something like

password = raw_input("Password:")
while password != "password"
               print "Wrong Password"
               password = raw_input("Password:")

"Crane, Adam" wrote:
> 
> Ok, I'm a newbie to Python, so please forgive me if this sounds stupid :)
> But I'm not really sure where to send this...
> 
> Is there a way to stop text from looping using while?  For example, if I
> used this in a program, the indented text would loop:
> 
> password = raw_input("Password:")
> while password != "password":
>                print "Wrong Password"
> 
> I still having a lot of reading to do on Python, but this is really bugging
> me.  This is probably really obvious, but any help would be appreciated.
> 
> Thanks,
> Adam
> 
> The contents of this e-mail are intended for the named addressee only. It
> contains information which may be confidential and which may also be
> privileged. Unless you are the named addressee (or authorised to receive for
> the addressee) you may not copy or use it, or disclose it to anyone else. If
> you received it in error please notify us immediately and then destroy it.
> The information, views and comments within this communication are those of
> the sender and not necessarily those of Computer 2000.
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From ACrane@computer2000.co.uk  Mon Apr 15 11:04:47 2002
From: ACrane@computer2000.co.uk (Crane, Adam)
Date: Mon, 15 Apr 2002 11:04:47 +0100
Subject: [Tutor] Looping
Message-ID: <0A45A5A5BE1BD6118C4100805FE64FF246627B@tdukbasmail01.computer2000.co.uk>

Thank you!  As I thought, it was obvious, but I just couldn't figure that
one out.  I think it must've been the lack of coffee :)

Thanks again,
Adam

-----Original Message-----
From: Remco Gerlich [mailto:scarblac@pino.selwerd.nl]
Sent: 15 April 2002 10:55
To: tutor@python.org
Subject: Re: [Tutor] Looping


On  0, "Crane, Adam" <ACrane@computer2000.co.uk> wrote:
> Ok, I'm a newbie to Python, so please forgive me if this sounds stupid :)
> But I'm not really sure where to send this...
> 
> Is there a way to stop text from looping using while?  For example, if I
> used this in a program, the indented text would loop:
> 
> password = raw_input("Password:")
> while password != "password":
>                print "Wrong Password"
> 
> I still having a lot of reading to do on Python, but this is really
bugging
> me.  This is probably really obvious, but any help would be appreciated.

Well, the while keeps doing whatever is inside its block, as long as
password isn't equal to "password". That's what while does. Maybe you were
looking for 'if'?

Since you don't change password inside the loop, it loops forever.

A solution is to ask for the password inside the loop again:

password = raw_input("Password:")
while password != "password":
   print "Wrong Password"
   password = raw_input("Password:")
   
This has the disadvantage that the same line is on two places, and if you
ever change one, you might forget about the other. A common way to spell
this in Python is like "do this forever: ask for the password, and if its
right, then stop." Which you write like this:

while 1:
   password = raw_input("Password:")
   if password == "password":
      break

This keeps repeating while '1' is true (it always is), but the 'break'
allows it to exit the loop.
-- 
Remco Gerlich


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.



From jay.jordan@eds.com  Mon Apr 15 17:03:56 2002
From: jay.jordan@eds.com (Jordan, Jay)
Date: Mon, 15 Apr 2002 11:03:56 -0500
Subject: [Tutor] Reduce?
Message-ID: <B6C890CB5E29D211A78B00A02461EDE91460AA4F@USPLM209>

Here is what I am aiming for. I have a sequence of numbers N. I have a
sequence of primes P. I want to multiply the primes each raised to the power
of the numbers such that

p1**n1*p1**n1*p3**n3...etc

I know reduce is supposed to allow one to apply calculations all the way
through a sequence but the documentation on the reduce finction is super
sketchy. can anyone point to a better way of doing this?



From scarblac@pino.selwerd.nl  Mon Apr 15 17:28:23 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Mon, 15 Apr 2002 18:28:23 +0200
Subject: [Tutor] Reduce?
In-Reply-To: <B6C890CB5E29D211A78B00A02461EDE91460AA4F@USPLM209>; from jay.jordan@eds.com on Mon, Apr 15, 2002 at 11:03:56AM -0500
References: <B6C890CB5E29D211A78B00A02461EDE91460AA4F@USPLM209>
Message-ID: <20020415182823.A8012@pino.selwerd.nl>

On  0, "Jordan, Jay" <jay.jordan@eds.com> wrote:
> Here is what I am aiming for. I have a sequence of numbers N. I have a
> sequence of primes P. I want to multiply the primes each raised to the power
> of the numbers such that
> 
> p1**n1*p1**n1*p3**n3...etc
> 
> I know reduce is supposed to allow one to apply calculations all the way
> through a sequence but the documentation on the reduce finction is super
> sketchy. can anyone point to a better way of doing this?

The way I would do it is:
- First make the list of p1**n1 pairs. You can make pairs of the two lists
  with zip(), and then use a list comprehension to make the powers list:
 
  pairs = zip(P,N)
  powers = [p**n for p, n in pairs]
  
- Then, multiply all elements of that list by using reduce():

  import operator
  total = reduce(operator.mul, powers, 1)

operator.mul is a function that multiplies two numbers; if powers is a list
of four numbers p1 to p4, reduce turns that into

((((1*p1)*p2)*p3)*p4)

The default of 1 is there in case the sequence is empty, multiplying by 1
has no effect otherwise.

You can write it all in one statement, but I wouldn't.

-- 
Remco Gerlich



From python@rcn.com  Mon Apr 15 20:13:35 2002
From: python@rcn.com (Raymond Hettinger)
Date: Mon, 15 Apr 2002 15:13:35 -0400
Subject: [Tutor] Reduce?
References: <B6C890CB5E29D211A78B00A02461EDE91460AA4F@USPLM209>
Message-ID: <000d01c1e4b1$a4f8d600$51b53bd0@othello>

From: "Jordan, Jay" <jay.jordan@eds.com>
> Here is what I am aiming for. I have a sequence of numbers N. I have a
> sequence of primes P. I want to multiply the primes each raised to the
power
> of the numbers such that
>
> p1**n1*p1**n1*p3**n3...etc
>
> I know reduce is supposed to allow one to apply calculations all the way
> through a sequence but the documentation on the reduce finction is super
> sketchy. can anyone point to a better way of doing this?

Try two steps:

>>> p = [2,3]
>>> n = [4,5]
>>> reduce(operator.mul, map(pow,p,n))
3888
>>> 2**4 * 3**5
3888


Raymond Hettinger






From lco@gofuse.com  Mon Apr 15 22:23:28 2002
From: lco@gofuse.com (lco)
Date: Mon, 15 Apr 2002 14:23:28 -0700
Subject: [Tutor] untar?
Message-ID: <EPEHIKODNBMDIJGGOEACKEKACIAA.lco@gofuse.com>

I'm running python 2.1c on windows 2000. What I would like to do is make a
script that can automatically fetch a tar file via ftp and then untar it to
a specified directory. I've already gotten the ftp function to work but
unable to find anything on untaring the file. Can someone post for me an
example of how this can be done? or point me toward the right direction? TIA

Leo




From csmith@blakeschool.org  Mon Apr 15 22:41:55 2002
From: csmith@blakeschool.org (Christopher Smith)
Date: Mon, 15 Apr 2002 16:41:55 -0500
Subject: [Tutor] recursive memory
Message-ID: <fc.004c4b6b0094ac72004c4b6b0094ac72.94ad9f@blakeschool.org>

I'm making a modification to the walk() function on the Mac so it avoids
getting caught in an alias loop between folders (i.e. walking a folder
which has an alias to another folder which has an alias of the first
folder).  The way I do this is store the file specs in a dictionary.  I
have two questions.

1)
Here's what I'm doing:

macpath module
--------------
def walk(t, f, a, visited={}):
	.
	.
	.
	for file in listOfFiles:
		.
		.
		.
		if visited.has_key(filespec): continue
		visited[filespec]=''
		t=join(t,file)
		walk(t, f, a, visited) # I pass the modified dictionary

#demo
walk(t, f, a) #no dictionary sent so it should start at {}

I need the dictionary to start at {} every time I first give the walk, but
then want it updated as I go deeper in the walk--so the main script call
leaves the dictionary off but recursive calls send the modified
dictionary.  Is this the right way to go about this?

2) 
I would also like to find out if an alias points to another (unmounted)
volume.  The only problem is that if the volume is unmounted, the
ResolveAliasFile routine (or other routines that will give file
information, like mac.stat()) will prompt me to insert the volume; I would
like to have the walk be unattended and so would like a way to override
the insert volume reaction and just know that the alias points to an
unmounted volume and just skip it.  Is there another way to detect this
condition without being asked to insert the missing volume?

/c





From pythontutor@venix.com  Mon Apr 15 23:54:29 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 15 Apr 2002 18:54:29 -0400
Subject: [Tutor] recursive memory (for Q 1)
References: <fc.004c4b6b0094ac72004c4b6b0094ac72.94ad9f@blakeschool.org>
Message-ID: <3CBB5A25.5050402@venix.com>

I have made this same mistake.
def walk(t, f, a, visited={}):
visited is given a clean dictionary only ONCE, when the function is
defined.  If you call walk a second time, without specifying visited,
you will simply default to using the same dictionary again.

One solution is:
def walk(t, f, a, visited=None):
	if visited is None: visited = {}

This provides a clean dictionary everytime walk is called without the
visited argument.

I can't help on Q2.

Christopher Smith wrote:

> I'm making a modification to the walk() function on the Mac so it avoids
> getting caught in an alias loop between folders (i.e. walking a folder
> which has an alias to another folder which has an alias of the first
> folder).  The way I do this is store the file specs in a dictionary.  I
> have two questions.
> 
> 1)
> Here's what I'm doing:
> 
> macpath module
> --------------
> def walk(t, f, a, visited={}):
> 	.
> 	.
> 	.
> 	for file in listOfFiles:
> 		.
> 		.
> 		.
> 		if visited.has_key(filespec): continue
> 		visited[filespec]=''
> 		t=join(t,file)
> 		walk(t, f, a, visited) # I pass the modified dictionary
> 
> #demo
> walk(t, f, a) #no dictionary sent so it should start at {}
> 
> I need the dictionary to start at {} every time I first give the walk, but
> then want it updated as I go deeper in the walk--so the main script call
> leaves the dictionary off but recursive calls send the modified
> dictionary.  Is this the right way to go about this?
> 
> 2) 
> I would also like to find out if an alias points to another (unmounted)
> volume.  The only problem is that if the volume is unmounted, the
> ResolveAliasFile routine (or other routines that will give file
> information, like mac.stat()) will prompt me to insert the volume; I would
> like to have the walk be unattended and so would like a way to override
> the insert volume reaction and just know that the alias points to an
> unmounted volume and just skip it.  Is there another way to detect this
> condition without being asked to insert the missing volume?
> 
> /c
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From dman@dman.ddts.net  Tue Apr 16 02:07:27 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 15 Apr 2002 20:07:27 -0500
Subject: [Tutor] constructors
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C54D@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C54D@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020416010727.GA20344@dman.ddts.net>

On Sun, Apr 14, 2002 at 10:28:00PM +0100, alan.gauld@bt.com wrote:
| > On Friday, April 12, 2002, at 08:59  AM, alan.gauld@bt.com wrote:
| > > The only snag is that sometimes you can lose context
| > > which makes it harder to recover from an exception
| 
| > I'm not sure I understand what you mean?  How can I avoid 
| > this snag (or rather, what is this snag)?
| 
| What I mean is that if the try/except encompasses many 
| statements when an exception occurs you jump to the 
| end of that block with no way back in (I've always thought 
| a 'continue' for exception handlers would be nice!)

Have you ever tried Eiffel?  It allows exception handlers to be
attached to functions (not arbitrary code segments), but includes a
'retry' keyword that will restart the function.

(not that I like Eiffel a lot, but it did get one or two things right)

-D

-- 

A man of many companions may come to ruin,
but there is a friend that sticks closer than a brother.
        Proverbs 18:24




From dman@dman.ddts.net  Tue Apr 16 02:12:08 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 15 Apr 2002 20:12:08 -0500
Subject: [Tutor] untar?
In-Reply-To: <EPEHIKODNBMDIJGGOEACKEKACIAA.lco@gofuse.com>
References: <EPEHIKODNBMDIJGGOEACKEKACIAA.lco@gofuse.com>
Message-ID: <20020416011208.GB20344@dman.ddts.net>

On Mon, Apr 15, 2002 at 02:23:28PM -0700, lco wrote:
| I'm running python 2.1c on windows 2000. What I would like to do is make a
| script that can automatically fetch a tar file via ftp and then untar it to
| a specified directory. I've already gotten the ftp function to work but
| unable to find anything on untaring the file. Can someone post for me an
| example of how this can be done? or point me toward the right direction? TIA

I don't know of any tar handlers for python, but if you install
cygwin, this shell script will do the same trick :

~~~~~~~~~~~
#!/bin/bash

URL=$1
if [ -z "$URL" ] ; then
    echo "You need to specify a URL"
    exit 1
fi

wget $URL
tar -zxvf `echo $URL | sed -e 's,http://.*/,,'`
~~~~~~~~~~~


If you think python is better suited for the job, you can use
os.system() to invoke tar, but you'll still have to install cygwin to
get tar.

(oh, yeah, wget supports http too, no extra work required :-))

HTH,
-D

-- 

Consider what God has done:
    Who can straighten what He has made crooked?
        Ecclesiastes 7:13




From dman@dman.ddts.net  Tue Apr 16 02:16:29 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 15 Apr 2002 20:16:29 -0500
Subject: [Tutor] exceptions
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C550@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C550@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <20020416011629.GC20344@dman.ddts.net>

On Mon, Apr 15, 2002 at 10:22:58AM +0100, alan.gauld@bt.com wrote:
| >  How do you approach error trapping and use exceptions in Python to  
| >  take care of it?  How do you for all the possible dumb user mistakes?   
|  
| My tutor contains a page on this subject, plus we just had a thread on it.
|  
| >  I mean give me the kind of thought process of how I should go about  
| >  thinking this through in planning my program. 

To echo Sean and Alan, I start out accepting only good input.  As I
see where I mess up I add rudimentary error handling and build it up
as I consider everything that can go wrong.  Often times it is just a
matter of seeing the list of exceptions a library method can raise and
doesn't necessarily require a full understanding of every possible
situation that can cause the method to fail.

| For production code I routinely put a try:/except/ 
| handler around my entire program which just says 
| "Oops something unexpected happened". But thats just 
| to shield the gentle users from unsightly stack traces. 
| I comment it out during development/testing.

I do the same thing, if the code is going to be production.  (that is,
if it will be more than a script that only I will use)  That is
especially important for a daemon that has no stdout for python to
dump a stack trace to.  Instead I must catch the exception and record
the error in the syslog so it can be tracked down later.

-D

-- 

A)bort, R)etry, D)o it right this time




From dman@dman.ddts.net  Tue Apr 16 02:20:03 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 15 Apr 2002 20:20:03 -0500
Subject: [Tutor] constructors
In-Reply-To: <BCCDBABC-4DC1-11D6-844F-00039351FE6A@mac.com>
References: <20020411191424.GA24388@dman.ddts.net> <BCCDBABC-4DC1-11D6-844F-00039351FE6A@mac.com>
Message-ID: <20020416012003.GD20344@dman.ddts.net>

On Thu, Apr 11, 2002 at 11:02:34PM -0400, Erik Price wrote:
| On Thursday, April 11, 2002, at 03:14  PM, dman wrote:
 
| >The do_something function doesn't need to do anything special (like
| >check a return value and propagate it by returning it) to not ignore
| >error conditions.  The module-level code doesn't need to interrupt the
| >flow of the code by checking a return value either, and can handle the
| >same type of error from both functions identically (if it wants to).
| 
| This is nice.  In PHP, I often do such code as:
| 
| if (!$connect = mysql_connect($connection_parameters)) {
|   die("Database connection failed");
| }
| 
| if (!$result = mysql_query($sql, $connection_handle)) {
|   die("SQL query failed");
| }
| 
| etc etc.
| It gets very repetitive, and makes the code look ugly.  But I hadn't 
| realized that this "interrupts the flow of code".

The flow of code is

$connect = mysql_connect($connection_parameters)
$result = mysql_query($sql, $connection_handle)

These two lines, all by them self, is the complete operation and is
quite easy to read.  The 7 lines you have above is much more
obfuscated, in comparision.  With exceptions you could rewrite it like

    try :
        $connect = mysql_connect($connection_parameters)
        $result = mysql_query($sql, $connection_handle)
    except db.Error , err :
        print "Whoa, what happened?"
        print err
        sys.exit( 1 )

Here the flow of code (the two lines between "try" and "except") is
uninterrupted.  The error handling code is written only once since you
do the same thing for both errors. 
 
| Exceptions are sweet -- I take it that they are another Python-centric 
| feature, that does not exist in C/C++/Java?

They don't exist in C, but they do exist in C++, Java, and Eiffel.
(this list is not exhaustive either :-))

-D

-- 

No harm befalls the righteous,
but the wicked have their fill of trouble.
        Proverbs 12:21




From tbrauch@tbrauch.com  Tue Apr 16 02:16:52 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Mon, 15 Apr 2002 21:16:52 -0400
Subject: [Tutor] Deep Copy
Message-ID: <001101c1e4e4$69439e00$1f01040a@centre.edu>

Is there a way to force Python to do a deep copy?  What I do not want is as
follows:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE Fork 0.8 -- press F1 for help
>>> t = [1, 2, 3]
>>> p = t
>>> id(t)
10717008
>>> id(p)
10717008
>>> p.append(4)
>>> p
[1, 2, 3, 4]
>>> t
[1, 2, 3, 4]

I know I could:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE Fork 0.8 -- press F1 for help
>>> t = [1, 2, 3]
>>> p=[]
>>> for i in t:
 p.append(i)


>>> p
[1, 2, 3]
>>> t
[1, 2, 3]
>>> p.append(4)
>>> p
[1, 2, 3, 4]
>>> t
[1, 2, 3]
>>> id(t)
10836352
>>> id(p)
10838048

But, I would prefer not doing that every time (I am doing this alot).

 - Tim




From tbrauch@tbrauch.com  Tue Apr 16 02:22:15 2002
From: tbrauch@tbrauch.com (Timothy M. Brauch)
Date: Mon, 15 Apr 2002 21:22:15 -0400
Subject: [Tutor] Deep Copy
References: <001101c1e4e4$69439e00$1f01040a@centre.edu>
Message-ID: <000d01c1e4e5$29b29e20$1f01040a@centre.edu>

I guess I should read the documentation before I send this things off.

I just read about copy.deepcopy.  That will solve my problems

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE Fork 0.8 -- press F1 for help
>>> import copy
>>> t = [1, 2, 3]
>>> p = copy.deepcopy(t)
>>> p.append(4)
>>> p
[1, 2, 3, 4]
>>> t
[1, 2, 3]
>>> id(t)
21712336
>>> id(p)
21740864

Yeah, that is what I need.

 - Tim

----- Original Message -----
From: "Timothy M. Brauch" <tbrauch@tbrauch.com>
To: <tutor@python.org>
Sent: Monday, April 15, 2002 9:16 PM
Subject: [Tutor] Deep Copy


> Is there a way to force Python to do a deep copy?  What I do not want is
as
> follows:
>
> Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE Fork 0.8 -- press F1 for help
> >>> t = [1, 2, 3]
> >>> p = t
> >>> id(t)
> 10717008
> >>> id(p)
> 10717008
> >>> p.append(4)
> >>> p
> [1, 2, 3, 4]
> >>> t
> [1, 2, 3, 4]
>
> I know I could:
>
> Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE Fork 0.8 -- press F1 for help
> >>> t = [1, 2, 3]
> >>> p=[]
> >>> for i in t:
>  p.append(i)
>
>
> >>> p
> [1, 2, 3]
> >>> t
> [1, 2, 3]
> >>> p.append(4)
> >>> p
> [1, 2, 3, 4]
> >>> t
> [1, 2, 3]
> >>> id(t)
> 10836352
> >>> id(p)
> 10838048
>
> But, I would prefer not doing that every time (I am doing this alot).
>
>  - Tim
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor




From faizal@umland.com.my  Tue Apr 16 02:19:59 2002
From: faizal@umland.com.my (Faizal)
Date: Tue, 16 Apr 2002 09:19:59 +0800
Subject: [Tutor] Need help
Message-ID: <01C1E527.E2A601A0@faizal>

Hi there...

I am still new(no exprience in programming)...&  need help from you guys...
Can u teach me how to learn programming (with example....)


Thank you 

Faizal 

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.325 / Virus Database: 182 - Release Date: 19/02/02
 





From sugarking666@hotmail.com  Tue Apr 16 02:41:07 2002
From: sugarking666@hotmail.com (Gus Tabares)
Date: Mon, 15 Apr 2002 21:41:07 -0400
Subject: [Tutor] Need help
Message-ID: <F305ZGUTwSIQK9VPRfL00009b57@hotmail.com>

Faizal,

  Although we cannot teach you to learn to program, something that is 
complex and time consumming, we can point you in the right direction. Try 
www.python.org for Guido's tutorial on Python or try a few links that have 
been mentioned here the past few days.

http://www.freenetpages.co.uk/hp/alan.gauld/
http://livewires.org.uk/python/index.html

Good luck...

Gus Tabares


>From: Faizal <faizal@umland.com.my>
>To: "'python'" <tutor@python.org>, "'python'" <python-list@python.org>
>Subject: [Tutor] Need help
>Date: Tue, 16 Apr 2002 09:19:59 +0800
>
>Hi there...
>
>I am still new(no exprience in programming)...&  need help from you guys...
>Can u teach me how to learn programming (with example....)
>
>
>Thank you
>
>Faizal
>
>---
>Outgoing mail is certified Virus Free.
>Checked by AVG anti-virus system (http://www.grisoft.com).
>Version: 6.0.325 / Virus Database: 182 - Release Date: 19/02/02
>
>
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor




_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From dyoo@hkn.eecs.berkeley.edu  Tue Apr 16 04:26:26 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 15 Apr 2002 20:26:26 -0700 (PDT)
Subject: [Tutor] Need help   [pointer to the Python for Newcomers page]
In-Reply-To: <01C1E527.E2A601A0@faizal>
Message-ID: <Pine.LNX.4.44.0204152022370.15855-100000@hkn.eecs.berkeley.edu>

On Tue, 16 Apr 2002, Faizal wrote:

> I am still new(no exprience in programming)...& need help from you
> guys... Can u teach me how to learn programming (with example....)

Hi Faizal,

Welcome aboard!  Sounds like you're starting from scratch.  *grin* Please
feel free to ask questions on Tutor; we'll be happy to talk with you.

You might find this page useful:

    http://python.org/doc/Newbies.html

This page collects all of the tutorials that are targeted for newcomers to
programming, and I think they're paced pretty well.  Try one of the
tutorials, and when things are a little unclear, you can always ask about
them here.


Again, feel free to ask questions.  Good luck to you!




From urnerk@qwest.net  Tue Apr 16 05:21:39 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 15 Apr 2002 21:21:39 -0700
Subject: [Tutor] untar?
In-Reply-To: <EPEHIKODNBMDIJGGOEACKEKACIAA.lco@gofuse.com>
Message-ID: <4.2.0.58.20020415211810.00cb5400@pop3.norton.antivirus>

At 02:23 PM 4/15/2002 -0700, lco wrote:
>I'm running python 2.1c on windows 2000. What I would like
>to do is make a script that can automatically fetch a tar
>file via ftp and then untar it to a specified directory.
>I've already gotten the ftp function to work but unable to
>find anything on untaring the file. Can someone post for me
>an example of how this can be done? or point me toward the
>right direction? TIA
>
>Leo

The winzip utility handles tar, tgz, gz etc. and there's
a beta add-on which allows controlling winzip from the
command line, i.e. from within Python:
http://www.winzip.com/beta.htm

I've used the command line from with another MSFT app to
control auto-zipping, but haven't tried to control
untaring to a specific directory.  I don't know for a
fact that the command line is rich enough to support this,
but it's worth a try.

Kirby




From urnerk@qwest.net  Tue Apr 16 05:30:37 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 15 Apr 2002 21:30:37 -0700
Subject: [Tutor] Deep Copy
In-Reply-To: <001101c1e4e4$69439e00$1f01040a@centre.edu>
Message-ID: <4.2.0.58.20020415212251.00cb9100@pop3.norton.antivirus>

>But, I would prefer not doing that every time (I am doing this alot).
>
>  - Tim

Fastest way to copy a list is:

newlist = oldlist[:]

That's a shallow copy, which is sufficient for the example
you gave, e.g. a list of integers or strings.

However, if oldlist contains objects and you want clones
of those objects as well, then you need the deepcopy
function in the copy module.

Here's some illustrative shell interaction:

  >>> class Foo:
         def __init__(self,var):
             self.value = var


  >>> o1 = Foo(2)
  >>> o2 = Foo(3)
  >>> oldlist = [o1,o2]
  >>> newlist = oldlist[:]
  >>> id(oldlist)
  11363440
  >>> id(newlist)  # ok, two distinct lists
  11371104
  >>> o1.value = 4
  >>> newlist[0].value  # oh oh, object o1 is same in both
  4

  >>> import copy       # copy to the rescue!
  >>> newlist = copy.deepcopy(oldlist)
  >>> o1.value = 44     # change o1's value property again
  >>> oldlist[0].value  # old list is effected
  44
  >>> newlist[0].value  # newlist has clone of o1, unchanged
  4
  >>> id(newlist[0])
  11406848
  >>> id(oldlist[0])    # confirming the difference
  11347248

Kirby




From urnerk@qwest.net  Tue Apr 16 05:32:26 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 15 Apr 2002 21:32:26 -0700
Subject: [Tutor] Need help
In-Reply-To: <01C1E527.E2A601A0@faizal>
Message-ID: <4.2.0.58.20020415213124.00cb7aa0@pop3.norton.antivirus>

At 09:19 AM 4/16/2002 +0800, Faizal wrote:
>Hi there...
>
>I am still new(no exprience in programming)...&  need
>help from you guys... Can u teach me how to learn
>programming (with example....)
>
>
>Thank you
>
>Faizal

Do you have Python installed and what operating system
are you using?  The best way to learn is use some tutorials
and follow along yourself, trying things.

Kirby




From ledirach@free.fr  Tue Apr 16 06:29:43 2002
From: ledirach@free.fr (ledirach@free.fr)
Date: Tue, 16 Apr 2002 07:29:43 +0200 (MEST)
Subject: [Tutor] untar ?
Message-ID: <1018934983.3cbbb6c73579a@imp.free.fr>

Hi.

You may wanna try the tarfile module at http://www.gustaebel.de/lars/tarfile/

Still experimental, but I use it to tar files (not untarring 'em yet), and it 
works well. Same commands and interface that the zipfile standard module.

BTW: hello to all list members. I've only been snooping around for a while, but 
it teach a lot already :-)

Pierre

>I'm running python 2.1c on windows 2000. What I would like to do is make a
>script that can automatically fetch a tar file via ftp and then untar it to
>a specified directory. I've already gotten the ftp function to work but
>unable to find anything on untaring the file. Can someone post for me an
>example of how this can be done? or point me toward the right direction? TIA
> 
>Leo



From csmith@blakeschool.org  Tue Apr 16 14:56:08 2002
From: csmith@blakeschool.org (Christopher Smith)
Date: Tue, 16 Apr 2002 08:56:08 -0500
Subject: [Tutor] Re: recursive memory
In-Reply-To: <D5CE9DD7-5118-11D6-9DE5-0030655234CE@cwi.nl>
References: <D5CE9DD7-5118-11D6-9DE5-0030655234CE@cwi.nl>
Message-ID: <fc.004c4b6b0094bc9b004c4b6b0094ac72.94bd9f@blakeschool.org>

This is a multi-part message in MIME format.

----=_--0094bd9f.0094bc9b.b8e197a8
Content-type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit

Jack.Jansen@cwi.nl writes:
>
>On Monday, April 15, 2002, at 11:41 , Christopher Smith wrote:
>
>> I'm making a modification to the walk() function on the Mac so it avoids
>> getting caught in an alias loop between folders (i.e. walking a folder
>> which has an alias to another folder which has an alias of the first
>> folder).  The way I do this is store the file specs in a dictionary.  I
>> have two questions.
>
>macpath.walk() (or actually os.path.walk) is explicitly define *not* to 
>do special things for symlinks or aliases. But still: the functionality 
>is nice, so maybe we should put it in a new function macostools.walk.

By "special things" you don't mean that walk() is suppose to skip over
aliases, do you?  Because as it is right now, aliases are walked.  And if
they are walked they can lead to two problems:

1) an infinite loop between two folders
2) bad pathnames being passed to the walkfunc (which is the issue that
resolve() was written to address).

If these undesirable behaviors were deemed bugs then the macpath.walk()
function could just be modified.  I have attached a version which has the
same behavior as the original but now has 3 optional arguments to handle
walking aliases, other volumes, and a dictionary to prevent walking
previously walked folders.

Also, I made the modification to islink() so it would return a 1 if a file
is an alias and 0 if it is not (or if it can't be resolved, perhaps
because someone else's walk gave it a path with multiple aliases in it, in
which case the resolve function that you have could be used by that person
to demangle the path first).

/c


----=_--0094bd9f.0094bc9b.b8e197a8
Content-Type: multipart/appledouble; boundary="--=_--b8e197a9.0d740840.0000008b";
 x-mac-type="54455854"; x-mac-creator="50797468"
Content-Disposition: attachment; filename="macpath_new.py"

----=_--b8e197a9.0d740840.0000008b
Content-Type: application/applefile; name="macpath_new.py"
Content-Transfer-Encoding: base64

AAUWBwACAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAADAAAASgAAAA4AAAAIAAAAWAAA
ABAAAAAJAAAAaAAAACAAAAACAAAAiAAAAhxtYWNwYXRoX25ldy5weQROnwUETqHP
CAAAAAgAAABURVhUUHl0aAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAHa
AAAA2gAAAEIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAADWe3MLAAAAcnVuX2FzX21haW5pAQAAAHMJAAAAc2VsZWN0aW9u
KAIAAABpxyEAAGnHIQAAcwcAAAB0YWJzaXplKAIAAABpCAAAAGkBAAAAcwwAAAB3
aW5kb3dib3VuZHMoBAAAAGkJAAAAaSsAAABpNwIAAGlOAgAAcwwAAABmb250c2V0
dGluZ3MoBAAAAHMGAAAAR2VuZXZhaQAAAABpCgAAACgDAAAAaQAAAABpAAAAAGkA
AAAAcxQAAABydW5fd2l0aF9pbnRlcnByZXRlcmkAAAAAMAAAAQAAAAHaAAAA2gAA
AEJTT1JUBbIAgAAcADIAAFB5V1MAAAAKAIAAAAAAAAAKRgGwD3dpbmRvdyBzZXR0
aW5ncw==

----=_--b8e197a9.0d740840.0000008b
Content-Type: text/plain; name="macpath_new.py"
Content-Transfer-Encoding: base64

IiIiUGF0aG5hbWUgYW5kIHBhdGgtcmVsYXRlZCBvcGVyYXRpb25zIGZvciB0aGUg
TWFjaW50b3NoLiIiIg0NaW1wb3J0IG9zDWZyb20gc3RhdCBpbXBvcnQgKg1pbXBv
cnQgbWFjZnMgI2Nwcw0NX19hbGxfXyA9IFsibm9ybWNhc2UiLCJpc2FicyIsImpv
aW4iLCJzcGxpdGRyaXZlIiwic3BsaXQiLCJzcGxpdGV4dCIsDSAgICAgICAgICAg
ImJhc2VuYW1lIiwiZGlybmFtZSIsImNvbW1vbnByZWZpeCIsImdldHNpemUiLCJn
ZXRtdGltZSIsDSAgICAgICAgICAgImdldGF0aW1lIiwiaXNsaW5rIiwiZXhpc3Rz
IiwiaXNkaXIiLCJpc2ZpbGUiLA0gICAgICAgICAgICJ3YWxrIiwiZXhwYW5kdXNl
ciIsImV4cGFuZHZhcnMiLCJub3JtcGF0aCIsImFic3BhdGgiXQ0NIyBOb3JtYWxp
emUgdGhlIGNhc2Ugb2YgYSBwYXRobmFtZS4gIER1bW15IGluIFBvc2l4LCBidXQg
PHM+Lmxvd2VyKCkgaGVyZS4NDWRlZiBub3JtY2FzZShwYXRoKToNICAgIHJldHVy
biBwYXRoLmxvd2VyKCkNDQ1kZWYgaXNhYnMocyk6DSAgICAiIiJSZXR1cm4gdHJ1
ZSBpZiBhIHBhdGggaXMgYWJzb2x1dGUuDSAgICBPbiB0aGUgTWFjLCByZWxhdGl2
ZSBwYXRocyBiZWdpbiB3aXRoIGEgY29sb24sDSAgICBidXQgYXMgYSBzcGVjaWFs
IGNhc2UsIHBhdGhzIHdpdGggbm8gY29sb25zIGF0IGFsbCBhcmUgYWxzbyByZWxh
dGl2ZS4NICAgIEFueXRoaW5nIGVsc2UgaXMgYWJzb2x1dGUgKHRoZSBzdHJpbmcg
dXAgdG8gdGhlIGZpcnN0IGNvbG9uIGlzIHRoZQ0gICAgdm9sdW1lIG5hbWUpLiIi
Ig0NICAgIHJldHVybiAnOicgaW4gcyBhbmQgc1swXSAhPSAnOicNDQ1kZWYgam9p
bihzLCAqcCk6DSAgICBwYXRoID0gcw0gICAgZm9yIHQgaW4gcDoNICAgICAgICBp
ZiAobm90IHMpIG9yIGlzYWJzKHQpOg0gICAgICAgICAgICBwYXRoID0gdA0gICAg
ICAgICAgICBjb250aW51ZQ0gICAgICAgIGlmIHRbOjFdID09ICc6JzoNICAgICAg
ICAgICAgdCA9IHRbMTpdDSAgICAgICAgaWYgJzonIG5vdCBpbiBwYXRoOg0gICAg
ICAgICAgICBwYXRoID0gJzonICsgcGF0aA0gICAgICAgIGlmIHBhdGhbLTE6XSAh
PSAnOic6DSAgICAgICAgICAgIHBhdGggPSBwYXRoICsgJzonDSAgICAgICAgcGF0
aCA9IHBhdGggKyB0DSAgICByZXR1cm4gcGF0aA0NDWRlZiBzcGxpdChzKToNICAg
ICIiIlNwbGl0IGEgcGF0aG5hbWUgaW50byB0d28gcGFydHM6IHRoZSBkaXJlY3Rv
cnkgbGVhZGluZyB1cCB0byB0aGUgZmluYWwNICAgIGJpdCwgYW5kIHRoZSBiYXNl
bmFtZSAodGhlIGZpbGVuYW1lLCB3aXRob3V0IGNvbG9ucywgaW4gdGhhdCBkaXJl
Y3RvcnkpLg0gICAgVGhlIHJlc3VsdCAocywgdCkgaXMgc3VjaCB0aGF0IGpvaW4o
cywgdCkgeWllbGRzIHRoZSBvcmlnaW5hbCBhcmd1bWVudC4iIiINDSAgICBpZiAn
Oicgbm90IGluIHM6IHJldHVybiAnJywgcw0gICAgY29sb24gPSAwDSAgICBmb3Ig
aSBpbiByYW5nZShsZW4ocykpOg0gICAgICAgIGlmIHNbaV0gPT0gJzonOiBjb2xv
biA9IGkgKyAxDSAgICBwYXRoLCBmaWxlID0gc1s6Y29sb24tMV0sIHNbY29sb246
XQ0gICAgaWYgcGF0aCBhbmQgbm90ICc6JyBpbiBwYXRoOg0gICAgICAgIHBhdGgg
PSBwYXRoICsgJzonDSAgICByZXR1cm4gcGF0aCwgZmlsZQ0NDWRlZiBzcGxpdGV4
dChwKToNICAgICIiIlNwbGl0IGEgcGF0aCBpbnRvIHJvb3QgYW5kIGV4dGVuc2lv
bi4NICAgIFRoZSBleHRlbnNpb24gaXMgZXZlcnl0aGluZyBzdGFydGluZyBhdCB0
aGUgbGFzdCBkb3QgaW4gdGhlIGxhc3QNICAgIHBhdGhuYW1lIGNvbXBvbmVudDsg
dGhlIHJvb3QgaXMgZXZlcnl0aGluZyBiZWZvcmUgdGhhdC4NICAgIEl0IGlzIGFs
d2F5cyB0cnVlIHRoYXQgcm9vdCArIGV4dCA9PSBwLiIiIg0NICAgIHJvb3QsIGV4
dCA9ICcnLCAnJw0gICAgZm9yIGMgaW4gcDoNICAgICAgICBpZiBjID09ICc6JzoN
ICAgICAgICAgICAgcm9vdCwgZXh0ID0gcm9vdCArIGV4dCArIGMsICcnDSAgICAg
ICAgZWxpZiBjID09ICcuJzoNICAgICAgICAgICAgaWYgZXh0Og0gICAgICAgICAg
ICAgICAgcm9vdCwgZXh0ID0gcm9vdCArIGV4dCwgYw0gICAgICAgICAgICBlbHNl
Og0gICAgICAgICAgICAgICAgZXh0ID0gYw0gICAgICAgIGVsaWYgZXh0Og0gICAg
ICAgICAgICBleHQgPSBleHQgKyBjDSAgICAgICAgZWxzZToNICAgICAgICAgICAg
cm9vdCA9IHJvb3QgKyBjDSAgICByZXR1cm4gcm9vdCwgZXh0DQ0NZGVmIHNwbGl0
ZHJpdmUocCk6DSAgICAiIiJTcGxpdCBhIHBhdGhuYW1lIGludG8gYSBkcml2ZSBz
cGVjaWZpY2F0aW9uIGFuZCB0aGUgcmVzdCBvZiB0aGUNICAgIHBhdGguICBVc2Vm
dWwgb24gRE9TL1dpbmRvd3MvTlQ7IG9uIHRoZSBNYWMsIHRoZSBkcml2ZSBpcyBh
bHdheXMNICAgIGVtcHR5IChkb24ndCB1c2UgdGhlIHZvbHVtZSBuYW1lIC0tIGl0
IGRvZXNuJ3QgaGF2ZSB0aGUgc2FtZQ0gICAgc3ludGFjdGljIGFuZCBzZW1hbnRp
YyBvZGRpdGllcyBhcyBET1MgZHJpdmUgbGV0dGVycywgc3VjaCBhcyB0aGVyZQ0g
ICAgYmVpbmcgYSBzZXBhcmF0ZSBjdXJyZW50IGRpcmVjdG9yeSBwZXIgZHJpdmUp
LiIiIg0NICAgIHJldHVybiAnJywgcA0NDSMgU2hvcnQgaW50ZXJmYWNlcyB0byBz
cGxpdCgpDQ1kZWYgZGlybmFtZShzKTogcmV0dXJuIHNwbGl0KHMpWzBdDWRlZiBi
YXNlbmFtZShzKTogcmV0dXJuIHNwbGl0KHMpWzFdDQ0NDWRlZiBpc2RpcihzKToN
ICAgICIiIlJldHVybiB0cnVlIGlmIHRoZSBwYXRobmFtZSByZWZlcnMgdG8gYW4g
ZXhpc3RpbmcgZGlyZWN0b3J5LiIiIg0NICAgIHRyeToNICAgICAgICBzdCA9IG9z
LnN0YXQocykNICAgIGV4Y2VwdCBvcy5lcnJvcjoNICAgICAgICByZXR1cm4gMA0g
ICAgcmV0dXJuIFNfSVNESVIoc3RbU1RfTU9ERV0pDQ0NIyBHZXQgc2l6ZSwgbXRp
bWUsIGF0aW1lIG9mIGZpbGVzLg0NZGVmIGdldHNpemUoZmlsZW5hbWUpOg0gICAg
IiIiUmV0dXJuIHRoZSBzaXplIG9mIGEgZmlsZSwgcmVwb3J0ZWQgYnkgb3Muc3Rh
dCgpLiIiIg0gICAgc3QgPSBvcy5zdGF0KGZpbGVuYW1lKQ0gICAgcmV0dXJuIHN0
W1NUX1NJWkVdDQ1kZWYgZ2V0bXRpbWUoZmlsZW5hbWUpOg0gICAgIiIiUmV0dXJu
IHRoZSBsYXN0IG1vZGlmaWNhdGlvbiB0aW1lIG9mIGEgZmlsZSwgcmVwb3J0ZWQg
Ynkgb3Muc3RhdCgpLiIiIg0gICAgc3QgPSBvcy5zdGF0KGZpbGVuYW1lKQ0gICAg
cmV0dXJuIHN0W1NUX01USU1FXQ0NZGVmIGdldGF0aW1lKGZpbGVuYW1lKToNICAg
ICIiIlJldHVybiB0aGUgbGFzdCBhY2Nlc3MgdGltZSBvZiBhIGZpbGUsIHJlcG9y
dGVkIGJ5IG9zLnN0YXQoKS4iIiINICAgIHN0ID0gb3Muc3RhdChmaWxlbmFtZSkN
ICAgIHJldHVybiBzdFtTVF9BVElNRV0NDWRlZiBpc2xpbmsocyk6DSAgICAiIiJS
ZXR1cm4gdHJ1ZSBpZiB0aGUgcGF0aG5hbWUgcmVmZXJzIHRvIGEgc3ltYm9saWMg
bGluay4NICAgIEFsd2F5cyBmYWxzZSBvbiB0aGUgTWFjLCB1bnRpbCB3ZSB1bmRl
cnN0YW5kIEFsaWFzZXMuKSIiIg0NICAgIHRyeToNICAgICAgICByZXR1cm4gbWFj
ZnMuUmVzb2x2ZUFsaWFzRmlsZShzKVsyXSAjdXNlIHRvIGJlIDAgYWxsIHRoZSB0
aW1lDSAgICBleGNlcHQ6DSAgICAgICAgcmV0dXJuIDANDWRlZiBpc2ZpbGUocyk6
DSAgICAiIiJSZXR1cm4gdHJ1ZSBpZiB0aGUgcGF0aG5hbWUgcmVmZXJzIHRvIGFu
IGV4aXN0aW5nIHJlZ3VsYXIgZmlsZS4iIiINDSAgICB0cnk6DSAgICAgICAgc3Qg
PSBvcy5zdGF0KHMpDSAgICBleGNlcHQgb3MuZXJyb3I6DSAgICAgICAgcmV0dXJu
IDANICAgIHJldHVybiBTX0lTUkVHKHN0W1NUX01PREVdKQ0NDWRlZiBleGlzdHMo
cyk6DSAgICAiIiJSZXR1cm4gdHJ1ZSBpZiB0aGUgcGF0aG5hbWUgcmVmZXJzIHRv
IGFuIGV4aXN0aW5nIGZpbGUgb3IgZGlyZWN0b3J5LiIiIg0NICAgIHRyeToNICAg
ICAgICBzdCA9IG9zLnN0YXQocykNICAgIGV4Y2VwdCBvcy5lcnJvcjoNICAgICAg
ICByZXR1cm4gMA0gICAgcmV0dXJuIDENDSMgUmV0dXJuIHRoZSBsb25nZXN0IHBy
ZWZpeCBvZiBhbGwgbGlzdCBlbGVtZW50cy4NDWRlZiBjb21tb25wcmVmaXgobSk6
DSAgICAiR2l2ZW4gYSBsaXN0IG9mIHBhdGhuYW1lcywgcmV0dXJucyB0aGUgbG9u
Z2VzdCBjb21tb24gbGVhZGluZyBjb21wb25lbnQiDSAgICBpZiBub3QgbTogcmV0
dXJuICcnDSAgICBwcmVmaXggPSBtWzBdDSAgICBmb3IgaXRlbSBpbiBtOg0gICAg
ICAgIGZvciBpIGluIHJhbmdlKGxlbihwcmVmaXgpKToNICAgICAgICAgICAgaWYg
cHJlZml4WzppKzFdICE9IGl0ZW1bOmkrMV06DSAgICAgICAgICAgICAgICBwcmVm
aXggPSBwcmVmaXhbOmldDSAgICAgICAgICAgICAgICBpZiBpID09IDA6IHJldHVy
biAnJw0gICAgICAgICAgICAgICAgYnJlYWsNICAgIHJldHVybiBwcmVmaXgNDWRl
ZiBleHBhbmR2YXJzKHBhdGgpOg0gICAgIiIiRHVtbXkgdG8gcmV0YWluIGludGVy
ZmFjZS1jb21wYXRpYmlsaXR5IHdpdGggb3RoZXIgb3BlcmF0aW5nIHN5c3RlbXMu
IiIiDSAgICByZXR1cm4gcGF0aA0NDWRlZiBleHBhbmR1c2VyKHBhdGgpOg0gICAg
IiIiRHVtbXkgdG8gcmV0YWluIGludGVyZmFjZS1jb21wYXRpYmlsaXR5IHdpdGgg
b3RoZXIgb3BlcmF0aW5nIHN5c3RlbXMuIiIiDSAgICByZXR1cm4gcGF0aA0Nbm9y
bV9lcnJvciA9ICdtYWNwYXRoLm5vcm1fZXJyb3I6IHBhdGggY2Fubm90IGJlIG5v
cm1hbGl6ZWQnDQ1kZWYgbm9ybXBhdGgocyk6DSAgICAiIiJOb3JtYWxpemUgYSBw
YXRobmFtZS4gIFdpbGwgcmV0dXJuIHRoZSBzYW1lIHJlc3VsdCBmb3INICAgIGVx
dWl2YWxlbnQgcGF0aHMuIiIiDQ0gICAgaWYgIjoiIG5vdCBpbiBzOg0gICAgICAg
IHJldHVybiAiOiIrcw0NICAgIGNvbXBzID0gcy5zcGxpdCgiOiIpDSAgICBpID0g
MQ0gICAgd2hpbGUgaSA8IGxlbihjb21wcyktMToNICAgICAgICBpZiBjb21wc1tp
XSA9PSAiIiBhbmQgY29tcHNbaS0xXSAhPSAiIjoNICAgICAgICAgICAgaWYgaSA+
IDE6DSAgICAgICAgICAgICAgICBkZWwgY29tcHNbaS0xOmkrMV0NICAgICAgICAg
ICAgICAgIGkgPSBpIC0gMQ0gICAgICAgICAgICBlbHNlOg0gICAgICAgICAgICAg
ICAgIyBiZXN0IHdheSB0byBoYW5kbGUgdGhpcyBpcyB0byByYWlzZSBhbiBleGNl
cHRpb24NICAgICAgICAgICAgICAgIHJhaXNlIG5vcm1fZXJyb3IsICdDYW5ub3Qg
dXNlIDo6IGltbWVkaWF0ZWx5IGFmdGVyIHZvbHVtZSBuYW1lJw0gICAgICAgIGVs
c2U6DSAgICAgICAgICAgIGkgPSBpICsgMQ0NICAgIHMgPSAiOiIuam9pbihjb21w
cykNDSAgICAjIHJlbW92ZSB0cmFpbGluZyAiOiIgZXhjZXB0IGZvciAiOiIgYW5k
ICJWb2x1bWU6Ig0gICAgaWYgc1stMV0gPT0gIjoiIGFuZCBsZW4oY29tcHMpID4g
MiBhbmQgcyAhPSAiOiIqbGVuKHMpOg0gICAgICAgIHMgPSBzWzotMV0NICAgIHJl
dHVybiBzDQ0NZGVmIHdhbGsodG9wLCBmdW5jLCBhcmcsd2Fsa0FsaWFzPTEsd2Fs
a090aGVyVm9sdW1lcz0xLHdhbGtlZD17fSk6DSAgICAiIiJEaXJlY3RvcnkgdHJl
ZSB3YWxrIHdpdGggY2FsbGJhY2sgZnVuY3Rpb24uDQ0gICAgRm9yIGVhY2ggZGly
ZWN0b3J5IGluIHRoZSBkaXJlY3RvcnkgdHJlZSByb290ZWQgYXQgdG9wIChpbmNs
dWRpbmcgdG9wDSAgICBpdHNlbGYsIGJ1dCBleGNsdWRpbmcgJy4nIGFuZCAnLi4n
KSwgY2FsbCBmdW5jKGFyZywgZGlybmFtZSwgZm5hbWVzKS4NICAgIGRpcm5hbWUg
aXMgdGhlIG5hbWUgb2YgdGhlIGRpcmVjdG9yeSwgYW5kIGZuYW1lcyBhIGxpc3Qg
b2YgdGhlIG5hbWVzIG9mDSAgICB0aGUgZmlsZXMgYW5kIHN1YmRpcmVjdG9yaWVz
IGluIGRpcm5hbWUgKGV4Y2x1ZGluZyAnLicgYW5kICcuLicpLiAgZnVuYw0gICAg
bWF5IG1vZGlmeSB0aGUgZm5hbWVzIGxpc3QgaW4tcGxhY2UgKGUuZy4gdmlhIGRl
bCBvciBzbGljZSBhc3NpZ25tZW50KSwNICAgIGFuZCB3YWxrIHdpbGwgb25seSBy
ZWN1cnNlIGludG8gdGhlIHN1YmRpcmVjdG9yaWVzIHdob3NlIG5hbWVzIHJlbWFp
biBpbg0gICAgZm5hbWVzOyB0aGlzIGNhbiBiZSB1c2VkIHRvIGltcGxlbWVudCBh
IGZpbHRlciwgb3IgdG8gaW1wb3NlIGEgc3BlY2lmaWMNICAgIG9yZGVyIG9mIHZp
c2l0aW5nLiAgTm8gc2VtYW50aWNzIGFyZSBkZWZpbmVkIGZvciwgb3IgcmVxdWly
ZWQgb2YsIGFyZywNICAgIGJleW9uZCB0aGF0IGFyZyBpcyBhbHdheXMgcGFzc2Vk
IHRvIGZ1bmMuICBJdCBjYW4gYmUgdXNlZCwgZS5nLiwgdG8gcGFzcw0gICAgYSBm
aWxlbmFtZSBwYXR0ZXJuLCBvciBhIG11dGFibGUgb2JqZWN0IGRlc2lnbmVkIHRv
IGFjY3VtdWxhdGUNICAgIHN0YXRpc3RpY3MuICBQYXNzaW5nIE5vbmUgZm9yIGFy
ZyBpcyBjb21tb24uDQ0gICAgaWYgd2Fsa0FsaWFzIGlzIDAsIG5vIGFsaWFzIGZv
bGRlcnMgd2lsbCBiZSBmb2xsb3dlZDsgZnVydGhlcm1vcmUsDSAgICBpZiB3YWxr
T3RoZXJWb2x1bWVzIGlzIDAgdGhlbiBvbmx5IGZvbGRlcnMgb24gdGhlIHNhbWUg
dm9sdW1lDSAgICBhcyB0aGUgaW5pdGlhbCBvbmUgd2lsbCBiZSB3YWxrZWQuICBU
aGUgZGljdGlvbmFyeSAid2Fsa2VkIiBpcyB1c2VkDSAgICB0byBrZWVwIHRyYWNr
IG9mIHRoZSBmc3MncyB0aGF0IGhhdmUgYmVlbiB3YWxrZWQgYWxyZWFkeSB0byBh
dm9pZCB3YWxraW5nDSAgICB0aHJvdWdoIGEgZm9sZGVyIHRoYXQgaGFzIGFscmVh
ZHkgYmVlbiB3YWxrZWQuDQ0gICAgQ2F1dGlvbjogIGlzIHlvdSB3YWxrIGFsaWFz
ZXMgYW5kIHlvdSBlbmNvdW50ZXIgYW4gYWxpYXMgdG8gYW4gdW5tb3VudGVkDSAg
ICB2b2x1bWUsIHlvdSB3aWxsIGJlIGFza2VkIHRvIG1vdW50IHRoZSB2b2x1bWUg
KGUuZyBpbnNlcnQgdGhlIG1pc3NpbmcgZGlzaykNICAgIHdoZXRoZXIgb3Igbm90
IHlvdSB3YW50IHRvIHdhbGsgb3RoZXIgdm9sdW1lcy4gIEkgZG9uJ3Qga25vdyBo
b3cgdG8gZGV0ZWN0DSAgICB0aGlzIGNvbmRpdGlvbiBiZWZvcmUgdGhlIHJlcXVl
c3QgdG8gaW5zZXJ0IHRoZSBkaXNrIGlzIG1hZGUuICBSaWdodCBub3cgdGhlIA0g
ICAgd2Fsa090aGVyVm9sdW1lcyBvcHRpb24gd2lsbCBhbGxvdyB5b3UgdG8ga2Vl
cCB5b3VyIHdhbGsgdG8gYSBzaW5nbGUgdm9sdW1lLiIiIg0NICAgIHRyeToNICAg
ICAgICBuYW1lcyA9IG9zLmxpc3RkaXIodG9wKQ0gICAgZXhjZXB0IG9zLmVycm9y
Og0gICAgICAgIHJldHVybg0gICAgZnVuYyhhcmcsIHRvcCwgbmFtZXMpDQ0jIGlu
aXRpYWxpemUgdGhlIHdhbGsgcmVjb3JkDSAgICBpZiB3YWxrQWxpYXM6DSAgICAg
ICAgZnNzLCBpc0RpciwgaXNBbGlhcz1tYWNmcy5SZXNvbHZlQWxpYXNGaWxlKHRv
cCkNICAgICAgICBrPWZzcy5hc190dXBsZSgpDSAgICAgICAgd2Fsa2VkW2tdPScn
DSAgICAgICAgaWYgbm90IHdhbGtlZC5oYXNfa2V5KCd0b3Bfdm9sdW1lJyk6DSAg
ICAgICAgICAgIHdhbGtlZFsndG9wX3ZvbHVtZSddPWtbMF0NDSMgd2FsayB0aGUg
c3ViLWl0ZW1zIGluIHRoaXMgZGlyZWN0b3J5IGlmIHRoZXkgYXJlIGRpcmVjdG9y
aWVzDSAgICBmb3IgbmFtZSBpbiBuYW1lczoNICAgICAgICBuYW1lID0gam9pbih0
b3AsIG5hbWUpDQ0gICAgICAgIHRyeTogCQkJCSNnZXQgdGhlIGluZm9ybWF0aW9u
IGFib3V0IHRoaXMgbmFtZQ0gICAgICAgICAgICBmc3MsIGlzRGlyLCBpc0FsaWFz
PW1hY2ZzLlJlc29sdmVBbGlhc0ZpbGUobmFtZSkNICAgICAgICBleGNlcHQ6DSAg
ICAgICAgICAgIGNvbnRpbnVlIAkJI2RpcmVjdG9yeSBkb2Vzbid0IGV4aXN0DQ0g
ICAgICAgIGlmIGlzRGlyOg0gICAgICAgICAgICBpZiBpc0FsaWFzIGFuZCBub3Qg
d2Fsa0FsaWFzOiBjb250aW51ZQ0gICAgICAgICAgICBpZiB3YWxrQWxpYXM6DSAg
ICAgICAgICAgICAgICBrPWZzcy5hc190dXBsZSgpDSAgICAgICAgICAgICAgICBp
ZiAobm90IHdhbGtPdGhlclZvbHVtZXMgYW5kIHdhbGtlZFsndG9wX3ZvbHVtZSdd
PD5rWzBdKSBvciB3YWxrZWQuaGFzX2tleShrKTogY29udGludWUgDSAgICAgICAg
ICAgICAgICB3YWxrZWRba109JycNICAgICAgICAgICAgICAgIGlmIGlzQWxpYXM6
CQkjcmVzb2x2ZSBub3cgb3IgZWxzZSBpdCB3b24ndCBiZSBlYXN5IGxhdGVyDSAg
ICAgICAgICAgICAgICAgICAgbmFtZT1mc3MuYXNfcGF0aG5hbWUoKQ0JICAgIHdh
bGsobmFtZSwgZnVuYywgYXJnLCB3YWxrQWxpYXMsIHdhbGtPdGhlclZvbHVtZXMs
IHdhbGtlZCkNDQ0NZGVmIGFic3BhdGgocGF0aCk6DSAgICAiIiJSZXR1cm4gYW4g
YWJzb2x1dGUgcGF0aC4iIiINICAgIGlmIG5vdCBpc2FicyhwYXRoKToNICAgICAg
ICBwYXRoID0gam9pbihvcy5nZXRjd2QoKSwgcGF0aCkNICAgIHJldHVybiBub3Jt
cGF0aChwYXRoKQ0NIyByZWFscGF0aCBpcyBhIG5vLW9wIG9uIHN5c3RlbXMgd2l0
aG91dCBpc2xpbmsgc3VwcG9ydA1yZWFscGF0aCA9IGFic3BhdGgNDWlmIF9fbmFt
ZV9fID09ICdfX21haW5fXyc6DQlpbXBvcnQgdGltZQ0JZGVmIHdhbGtmdW5jKGFy
ZywgZGlyLG5hbWVzKToNCQlmb3IgbmFtZSBpbiBuYW1lczoNCQkJcz1qb2luKGRp
cixuYW1lKQ0JCQlwcmludCBuYW1lDQ0JdG9wPW1hY2ZzLkdldERpcmVjdG9yeSgp
WzBdLmFzX3BhdGhuYW1lKCkNCXQ9dGltZS50aW1lKCkNCXByaW50DQlhcmc9W10N
CXdhbGtBbGlhc2VzPTANCXdhbGtPdGhlclZvbHVtZXM9MA0Jd2Fsayh0b3Asd2Fs
a2Z1bmMsYXJnLHdhbGtBbGlhc2VzLHdhbGtPdGhlclZvbHVtZXMpDQlwcmludCAi
U2Vjb25kcyB0YWtlbjoiLHRpbWUudGltZSgpLXQN

----=_--b8e197a9.0d740840.0000008b--

----=_--0094bd9f.0094bc9b.b8e197a8--



From camartin@snet.net  Tue Apr 16 16:25:05 2002
From: camartin@snet.net (Cliff Martin)
Date: Tue, 16 Apr 2002 11:25:05 -0400
Subject: [Tutor] Reading in data
Message-ID: <3CBC4251.498C2D5@snet.net>

I've noticed over the months that most of the posts are asking about
text or text manipulation for the web. I'm interested in simple data
manipulation of numbers.  In all the books I've read I've never seen one
example of how to read into a variable 1) two columns(or three if I'm
doing 3D) of numbers that represent an ordered pair(or set) without line
feeds and 2) a simple stream of data over multiple lines without the
line feeds.  Could I get some help here?  Also any references to using
Python as a data cruncher would be useful. NumPy, etc. is nice but most
of the work there is associated with modeling not analyzing data.
Thanks in advance.

Cliff




From ewmc@ncol.net  Mon Apr 15 15:46:19 2002
From: ewmc@ncol.net (Anonymous)
Date: Mon, 15 Apr 2002 09:46:19 -0500
Subject: [Tutor] help
Message-ID: <B8E051EA.BD%ewmc@ncol.net>

Hello there:

I am looking for help.

I would like to learn programming and Python on my Power Book G3 but I do
not know AMYTING about programming.

I just downloaded Python 2.2.1 complete; that's it.

I heard of compilers; it sounds as if you need them too but I do not know
more.
Unfortunately I do not like to learn from books.
I like direct teaching.

Can someone tell me what the next step must be? Just the next one.

I apologyse for these stupid questions and would greatly appreciate your
kindness and patience in answering them.

Thank you.

Best regards

Frank A.




From pythonhack@yahoo.com  Tue Apr 16 19:16:51 2002
From: pythonhack@yahoo.com (pythonhack@yahoo.com)
Date: Tue, 16 Apr 2002 11:16:51 -0700
Subject: [Tutor] help
In-Reply-To: <B8E051EA.BD%ewmc@ncol.net>
References: <B8E051EA.BD%ewmc@ncol.net>
Message-ID: <196354650820.20020416111651@yahoo.com>

Here you go:

http://www.python.org/doc/Newbies.html


A> Hello there:

A> I am looking for help.

A> I would like to learn programming and Python on my Power Book G3 but I do
A> not know AMYTING about programming.

A> I just downloaded Python 2.2.1 complete; that's it.

A> I heard of compilers; it sounds as if you need them too but I do not know
A> more.
A> Unfortunately I do not like to learn from books.
A> I like direct teaching.

A> Can someone tell me what the next step must be? Just the next one.

A> I apologyse for these stupid questions and would greatly appreciate your
A> kindness and patience in answering them.

A> Thank you.

A> Best regards

A> Frank A.



A> _______________________________________________
A> Tutor maillist  -  Tutor@python.org
A> http://mail.python.org/mailman/listinfo/tutor


_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com




From bobx@linuxmail.org  Tue Apr 16 19:27:49 2002
From: bobx@linuxmail.org (Bob X)
Date: Wed, 17 Apr 2002 02:27:49 +0800
Subject: [Tutor] Deleting Lines of text
Message-ID: <20020416182749.31760.qmail@linuxmail.org>

How do I delete a line of text in a file? I want to find the word "BobH" and delete the line it is on and then close the file.
-- 

Get your free email from www.linuxmail.org 


Powered by Outblaze



From kalle@gnupung.net  Tue Apr 16 19:41:50 2002
From: kalle@gnupung.net (Kalle Svensson)
Date: Tue, 16 Apr 2002 20:41:50 +0200
Subject: [Tutor] help
In-Reply-To: <B8E051EA.BD%ewmc@ncol.net>
References: <B8E051EA.BD%ewmc@ncol.net>
Message-ID: <20020416184150.GA1441@i92.ryd.student.liu.se>

[Anonymous]
> Hello there:
> 
> I am looking for help.
> 
> I would like to learn programming and Python on my Power Book G3 but I do
> not know AMYTING about programming.

Welcome!  You've come to the right place.  

> I just downloaded Python 2.2.1 complete; that's it.

Good!  You won't need anything else to get started, I think.

> I heard of compilers; it sounds as if you need them too but I do not
> know more.

Generally, a programming language can be interpreted, compiled or
both.  With an interpreted language, you run the program by feeding
the source code to a special program called the interpreter.  A
compiled program is run by first running the source through a compiler
and then taking the result and running that directly, without any help
from an interpreter.  Python is interpreted (almost), and the
interpreter is included in the installation.

Hope that made sense.

> Unfortunately I do not like to learn from books.
> I like direct teaching.
> 
> Can someone tell me what the next step must be? Just the next one.

The best way to get started with programming is by trying to solve a
problem.  Is there anything special you would like to sove by writing
a program?  Otherwise, there are some suggestions on the Useless
Python website (http://www.lowerstandard.com/python/).

Then you start by maybe looking at a tutorial, there are several
listed at http://www.python.org/doc/Newbies.html .  If there is
something you don't understand, ask on this list.

> I apologyse for these stupid questions and would greatly appreciate your
> kindness and patience in answering them.

On the tutor list, there are no stupid questions.  Don't worry, we've
all been beginners at one time.

Med utmärkt högaktning,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.



From pythonhack@yahoo.com  Tue Apr 16 19:47:30 2002
From: pythonhack@yahoo.com (pythonhack@yahoo.com)
Date: Tue, 16 Apr 2002 11:47:30 -0700
Subject: [Tutor] Deleting Lines of text
In-Reply-To: <20020416182749.31760.qmail@linuxmail.org>
References: <20020416182749.31760.qmail@linuxmail.org>
Message-ID: <23356490135.20020416114730@yahoo.com>

as far as i know, it's not possible to edit a file in place.  you'll
have to read the contents of the file into memory, make whatever
changes you want, then write it back to a different file. like this (assuming
test.txt is the one you want to edit:
newfile = open('test2.txt', 'w')
file = open('test.txt', 'r')
     lines = file.readlines()
     line = lines.split()
     for line in lines:
          if 'BobH' not in line:
              newfile.write(line):
     file.close()
     newfile.close()

**i didn't test this, so it might not be exact, but that's the idea...

brett
BX> How do I delete a line of text in a file? I want to find the word "BobH" and delete the line it is on and then close the file.


_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com




From jay.jordan@eds.com  Tue Apr 16 20:23:14 2002
From: jay.jordan@eds.com (Jordan, Jay)
Date: Tue, 16 Apr 2002 14:23:14 -0500
Subject: [Tutor] string to number
Message-ID: <B6C890CB5E29D211A78B00A02461EDE91460AA52@USPLM209>

I have a list containing multiple strings which are numbers. [209, 30, 50,
123, 40, ...etc]

I want to use my list but perform numerical operations on the contents but
it wont let me use INT and the ATOL function keeps comming up as undefined
even though I have IMPORT STRING at the top of my project. Is there another
better way to take a string and make it a number?



From urnerk@qwest.net  Tue Apr 16 20:28:52 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 16 Apr 2002 12:28:52 -0700
Subject: [Tutor] Reading in data
In-Reply-To: <3CBC4251.498C2D5@snet.net>
Message-ID: <4.2.0.58.20020416122705.01b8bcf0@pop3.norton.antivirus>

At 11:25 AM 4/16/2002 -0400, Cliff Martin wrote:
>I've noticed over the months that most of the posts are asking about
>text or text manipulation for the web. I'm interested in simple data
>manipulation of numbers.  In all the books I've read I've never seen one
>example of how to read into a variable 1) two columns(or three if I'm
>doing 3D) of numbers that represent an ordered pair(or set) without line
>feeds and 2) a simple stream of data over multiple lines without the
>line feeds.  Could I get some help here?  Also any references to using
>Python as a data cruncher would be useful. NumPy, etc. is nice but most
>of the work there is associated with modeling not analyzing data.
>Thanks in advance.
>
>Cliff



  >>> f = open("test.dat",'w')
  >>> f.writelines(
  """
  3.0  4.5  3.1
  1.4  2.1  4.5
  """)
  >>> f.close()
  >>> f = open("test.dat",'r')
  >>> for i in f.readlines(): print i,


  3.0  4.5  3.1
  1.4  2.1  4.5

  >>> def getdata(filename):
          f = open(filename,'r')
          xyz = []  # empty list
          for i in f.readlines():
             if len(i.strip())>0:  # skip blank lines
                 xyz.append([float(x) for x in i.split()]) # str->floats
          return xyz

  >>> getdata("test.dat")
  [[3.0, 4.5, 3.1000000000000001], [1.3999999999999999,
  2.1000000000000001, 4.5]]


Kirby




From shalehperry@attbi.com  Tue Apr 16 20:34:15 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 16 Apr 2002 12:34:15 -0700 (PDT)
Subject: [Tutor] string to number
In-Reply-To: <B6C890CB5E29D211A78B00A02461EDE91460AA52@USPLM209>
Message-ID: <XFMail.20020416123415.shalehperry@attbi.com>

On 16-Apr-2002 Jordan, Jay wrote:
> I have a list containing multiple strings which are numbers. [209, 30, 50,
> 123, 40, ...etc]
> 
> I want to use my list but perform numerical operations on the contents but
> it wont let me use INT and the ATOL function keeps comming up as undefined
> even though I have IMPORT STRING at the top of my project. Is there another
> better way to take a string and make it a number?
> 

num = int(str) # easy enough (-:



From ak@silmarill.org  Tue Apr 16 22:51:22 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Tue, 16 Apr 2002 17:51:22 -0400
Subject: [Tutor] string to number
In-Reply-To: <B6C890CB5E29D211A78B00A02461EDE91460AA52@USPLM209>
References: <B6C890CB5E29D211A78B00A02461EDE91460AA52@USPLM209>
Message-ID: <20020416215122.GA20796@ak.silmarill.org>

On Tue, Apr 16, 2002 at 02:23:14PM -0500, Jordan, Jay wrote:
> I have a list containing multiple strings which are numbers. [209, 30, 50,
> 123, 40, ...etc]
> 
> I want to use my list but perform numerical operations on the contents but
> it wont let me use INT and the ATOL function keeps comming up as undefined
> even though I have IMPORT STRING at the top of my project. Is there another
> better way to take a string and make it a number?
>

Python 2.1.1 (#1, Apr  6 2002, 13:34:31) 
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> l = ["209", "30", "50"]
>>> l = [int(x) for x in l]
>>> l
[209, 30, 50]

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

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From dyoo@hkn.eecs.berkeley.edu  Tue Apr 16 22:57:50 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Apr 2002 14:57:50 -0700 (PDT)
Subject: [Tutor] string to number
In-Reply-To: <B6C890CB5E29D211A78B00A02461EDE91460AA52@USPLM209>
Message-ID: <Pine.LNX.4.44.0204161453280.10332-100000@hkn.eecs.berkeley.edu>


On Tue, 16 Apr 2002, Jordan, Jay wrote:

> I have a list containing multiple strings which are numbers. [209, 30, 50,
> 123, 40, ...etc]
>
> I want to use my list but perform numerical operations on the contents
> but it wont let me use INT and the ATOL function keeps comming up as
> undefined even though I have IMPORT STRING at the top of my project. Is
> there another better way to take a string and make it a number?

Can you show us the code that you're using?  It sounds like you have a
list of strings, and if so, you can use the int() function to make them
numerical.  For example:

###
>>> mylist = ["209", "30", "50", "123"]
>>> mylist
['209', '30', '50', '123']
>>> type(mylist[0])
<type 'string'>
>>> mylist[0] + mylist[1] + mylist[2] + mylist[3]
'2093050123'
###


Here, we have a list of strings.  Even though they might look like
numbers, Python won't automatically do numeric manipulations with them
until we make them integers.  We can use the built-in int() function for
this:

###
>>> numbers = map(int, mylist)
>>> type(numbers[0])
<type 'int'>
>>> numbers
[209, 30, 50, 123]
>>> numbers[0] + numbers[1] + numbers[2] + numbers[3]
412
###


Is this what you're looking for?  If you have more questions, please feel
free to ask.  Good luck!




From erikprice@mac.com  Wed Apr 17 01:42:01 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 16 Apr 2002 20:42:01 -0400
Subject: [Tutor] Python with readline
Message-ID: <EE9621EC-519B-11D6-AF03-00039351FE6A@mac.com>

A few weeks back I asked about how I could get some of the emacs-style 
functionality (command history, emacs navigation keybindings) into my 
Python 2.2 interactive interpreter.  Someone (I forget) said that this 
is GNU Readline, and that I should look into recompiling with readline.

Well, I've tried a few different iterations of it -- by slightly 
changing the Modules/Setup file in the source tree from my Python 2.2 
tarball.  Unfortunately, I can't seem to get the right combination of 
flags.  Here is the text of the section where I'm supposed to turn it on:

<snip>
# GNU readline.  Unlike previous Python incarnations, GNU readline is
# now incorporated in an optional module, configured in the Setup file
# instead of by a configure script switch.  You may have to insert a
# -L option pointing to the directory where libreadline.* lives,
# and you may have to change -ltermcap to -ltermlib or perhaps remove
# it, depending on your system -- see the GNU readline instructions.
# It's okay for this to be a shared library, too.

#readline readline.c -lreadline -ltermcap
</snip>

I've tried simply uncommenting the line, adding the -L option in various 
places on the line, specifying a path to my readline library, etc, but I 
haven't had success -- either the ./configure has failed, the make has 
failed, or I've ended up with a Python with no readline ability -- 
exactly what I have now.

Does anyone have any familiarity with setting Python up for this?  I'm 
using Mac OS X 10.1.3, but I can't imagine that the procedure is much 
different than for Linux or any other Unix.  I'm not really clear on 
what readline does, I imagine it's some kind of library, but my lack of 
familiarity with C and the whole "make" business is probably making this 
difficult for me to grasp.

I've asked about this on comp.lang.python, but not persistently.  Before 
I pester them again, I thought I'd ask here.  It's not an emergency -- I 
can get by without it -- but now that emacs-style keybindings work in 
almost every Mac OS X app, I find myself constantly hitting Ctrl-F or 
Ctrl-P, and in the interactive interpreter this just gives me garbage 
escape characters.

Thanks in advance,


Erik




From jar@mminternet.com  Wed Apr 17 03:10:35 2002
From: jar@mminternet.com (James A Roush)
Date: Tue, 16 Apr 2002 19:10:35 -0700
Subject: [Tutor] How do you make a module
In-Reply-To: <XFMail.20020410222118.shalehperry@attbi.com>
Message-ID: <000001c1e5b5$0f793ed0$0300000a@thor>


> -----Original Message-----
> From: Sean Perry [mailto:shaleh@one.local]On Behalf Of Sean 'Shaleh'
> Perry
> Sent: Wednesday, April 10, 2002 10:21 PM
> To: James A Roush
> Cc: Python Tutot List
> Subject: Re: [Tutor] How do you make a module
>
>
>
> On 11-Apr-2002 James A Roush wrote:
> > I have several functions that I've written and use in multiple
> programs.  I
> > would like to put them in a module for easier maintainability.  Could
> > somebody point me to a tutorial that will explain how?
> >
> > Once it's made, what directory does it go in?
>
> you make a module every time you create a .py file.  When you
> want to import it
> you use the filename without the '.py' extension.  So 'foo.py'
> becomes 'import
> foo'.
>
> If you have a directory like:
>
> this/
>      foo.py
>      bar.py
>      this.py
>
> this.py could be:
>
> #!/usr/bin/python
>
> import foo, bar
>
> bar.command()
> x = foo.variable
> print x + 2
>
> python looks in the current directory first.  If you have a
> module of nifty
> python code you have written and want all of your programs to use
> it then the
> answer depends on your OS.
>
> Under linux (bsd, unix, whatever) you can either make a ~/python
> directory and
> add that to PYTHONPATH (see the docs for more info) or more
> easily just drop it
> in /usr/local/lib/site-python and python should see it
> automatically without
> further work.
>
> My preference is to include small modules with any project that
> needs them and
> to install bigger ones in the system directory.
>
> Hope that helps.
>

Thanks.  I didn't realize that even the program calling other modules was in
fact a module itself.




From jar@mminternet.com  Wed Apr 17 03:31:55 2002
From: jar@mminternet.com (James A Roush)
Date: Tue, 16 Apr 2002 19:31:55 -0700
Subject: [Tutor] How do you make a module
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C544@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <000101c1e5b8$0a32d050$0300000a@thor>


> -----Original Message-----
> From: alan.gauld@bt.com [mailto:alan.gauld@bt.com]
> Sent: Friday, April 12, 2002 3:36 AM
> To: jar@mminternet.com; tutor@python.org
> Subject: RE: [Tutor] How do you make a module
>
>
> > I have several functions that I've written and use in
> > multiple programs.  I
> > would like to put them in a module for easier maintainability.  Could
> > somebody point me to a tutorial that will explain how?
>
> Try the modules chaprter of my tutor(see sig)
>
> > Once it's made, what directory does it go in?
>
> Anywhere thats in your PYTHONPATH value.
> Or anywhere and add that place to your PYTHONPATH....
>
> Alan g.
> Author of the 'Learning to Program' web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>

Thanks Alen.  That's what I needed.  It's nice to know your website is still
online.  I lost track of it when the URL changed.

I'm stumped about how to handle a namespace issue.

In the __main__ program I open a file for output like this:

    DEBUGOUT = open('f:/source/linkextr2/debug_rr.txt', 'w')

and the functions that __main__ calls output logging data to it.  Now that
those functions have been moved to their own module (crawler.py), the
functions have no idea of DEBUGOUT's existence.  My first thought would be
to pass DEBUGOUT to crawl_site(), but crawl_site calls other functions
within the same module and those functions also need to access the DEBUGOUT
file.

Is there a way to make DEBUGOUT created in __main__ available to the other
module (crawler.py)?





From shalehperry@attbi.com  Wed Apr 17 05:35:45 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Tue, 16 Apr 2002 21:35:45 -0700 (PDT)
Subject: [Tutor] How do you make a module
In-Reply-To: <000001c1e5b5$0f793ed0$0300000a@thor>
Message-ID: <XFMail.20020416213545.shalehperry@attbi.com>

> 
> Thanks.  I didn't realize that even the program calling other modules was in
> fact a module itself.
> 

when used as a module the value of __name__ is the name of the module file,
when ran by the interpreter it is '__main__'.  This is why you see code like
this:

foo.py:

def foo():
  do stuff

if __name__ == '__main__':
  # test foo out
#end

if I then do:

import foo

foo.foo() it is happy.  If I do python foo.py it will run the tests.



From alan.gauld@bt.com  Wed Apr 17 11:38:01 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 17 Apr 2002 11:38:01 +0100
Subject: [Tutor] How do you make a module
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C557@mbtlipnt02.btlabs.bt.co.uk>

> I'm stumped about how to handle a namespace issue.
> 
> In the __main__ program I open a file for output like this:
> 
>     DEBUGOUT = open('f:/source/linkextr2/debug_rr.txt', 'w')
> 
> and the functions that __main__ calls output logging data to 
> it.  Now that those functions have been moved to their own 
> module (crawler.py), the functions have no idea of DEBUGOUT's 
> existence.  

from crawler import DEBUGOUT

should make it available. Alternatively set a local variable 
to it via the module:

dbgout = crawler.DEBUGOUT

> to pass DEBUGOUT to crawl_site(), but crawl_site calls other functions
> within the same module and those functions also need to 
> access the DEBUGOUT file.

That means they are using the name as a global variable which is 
bad practice from a purist point of view. Better to have all 
functions that use it take it as an argument. However that 
may be a big edit job so use the techniques above to fake the 
global...

> Is there a way to make DEBUGOUT created in __main__ available 
> to the other module (crawler.py)?

Ah, I see, its the other way arround.

OK, In that case modify crawl_site() to take the DEBUGOUT as 
an argument and at the begginning set a module level variable 
in crawler.py to the log file

Like so:

if __name__ == "__main__":
    DBGOUT = open(....)
    crawl_site(DBGOUT,....)

And in crawler.py

DEBUGOUT = None  # initialise the module level variable

def crawl_site(dbgfile,....):
   global DEBUGOUT
   DEBUGOUT = dbgfile # now set variable with value from __main__ 
   .....as before....

def crawl_another():
   # blah blah
   DEBUGOUT.write("OOPS, An error happened\n")

etc etc...


HTH,

Alan g.



From ACrane@computer2000.co.uk  Wed Apr 17 12:27:34 2002
From: ACrane@computer2000.co.uk (Crane, Adam)
Date: Wed, 17 Apr 2002 12:27:34 +0100
Subject: [Tutor] Storing Info
Message-ID: <0A45A5A5BE1BD6118C4100805FE64FF2466295@tdukbasmail01.computer2000.co.uk>

I'm attempting to write a program that stores/remembers a users input when
it is run.  It's a Notes/Reminder program.

So far I have this code (not tried or tested):

print "Notes Program."
print "Type in "null" if you do not wish to add a note."

notes = raw_input("Enter a note/Reminder:")
while notes <= "":
	print "That's a rather short note!"
	notes = raw_input("Enter a note/Reminder:")
if notes == "null"
	break

So what I need to do is store the users input for future reference.  I'm
starting to think I'm in way over my head.  I was thinking maybe I'd have to
import the info, or something similar (I have no idea)

Any help would be great.

Thanks,
Adam
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.



From AMoore4437@aol.com  Wed Apr 17 15:28:32 2002
From: AMoore4437@aol.com (AMoore4437@aol.com)
Date: Wed, 17 Apr 2002 10:28:32 EDT
Subject: [Tutor] Fwd: FW: Sign the England World Cup flag, NOW
Message-ID: <7f.24a032fd.29eee090@aol.com>

--part1_7f.24a032fd.29eee090_boundary
Content-Type: text/plain; charset="US-ASCII"
Content-Transfer-Encoding: 7bit

 

--part1_7f.24a032fd.29eee090_boundary
Content-Type: message/rfc822
Content-Disposition: inline

Return-Path: <Richard.Sroka@swedbank.com>
Received: from  rly-xi02.mx.aol.com (rly-xi02.mail.aol.com [172.20.116.7]) by air-xi02.mail.aol.com (v84.14) with ESMTP id MAILINXI23-0417095947; Wed, 17 Apr 2002 09:59:47 -0400
Received: from  mail.foreningssparbanken.se (mail.sparbanken.se [164.10.32.65]) by rly-xi02.mx.aol.com (v84.15) with ESMTP id MAILRELAYINXI26-0417095934; Wed, 17 Apr 2002 09:59:34 -0400
Received: (from smap@localhost)
        by mail.foreningssparbanken.se (MAIL_RELAY_HOST) id PAA26381;
        Wed, 17 Apr 2002 15:32:22 +0200 (MET DST)
From: Richard.Sroka@swedbank.com
X-Authentication-Warning: mail.foreningssparbanken.se: smap set sender to <Richard.Sroka@swedbank.com> using -f
Received: from fwweb5(164.10.32.66) by webmail via smap (V2.1+anti-relay+anti-spam)
	id xma026022; Wed, 17 Apr 02 15:31:09 +0200
Received: from mailgw ([10.90.1.149]) by fwweb1.; Wed, 17 Apr 2002 15:44:45 +0000 (MET)
Received: from fsbs02x01.swedbank.foreningssparbanken.se by foreningssparbanken.se (8.8.8+Sun/SMI-SVR4-memo-ForeningsSparbanken-20000111-V8.8.8)
	id PAA07170; Wed, 17 Apr 2002 15:49:04 +0200 (MET DST)
Received: by fsbs02x01.swedbank.foreningssparbanken.se with Internet Mail Service (5.5.2653.19)
	id <236784CW>; Wed, 17 Apr 2002 15:57:16 +0200
Message-ID: <61D65BC701E4D111ACF20008C724C6BD41F659@FSBS02X03>
To: craig.winters@rp-rorer.co.uk, gary@gwac.fsnet.co.uk,
        jane.wright@uk.abnamro.com, john.cavalli@abraxas.co.uk,
        msyme@bankofny.com, neil.oddy@nomura.co.uk,
        Stephen_Lord@notes.ntrs.com, Stuart.Clapson@swedbank.com,
        amoore4437@aol.com
Subject: FW: Sign the England World Cup flag, NOW
Date: Wed, 17 Apr 2002 15:57:13 +0200
MIME-Version: 1.0
X-Mailer: Internet Mail Service (5.5.2653.19)
Content-Type: text/plain;
	charset="iso-8859-1"

Calling all England fans: we need your support. 

Come and sign the OFFICIAL ENGLAND WORLD CUP FLAG now.

One of your mates has signed the flag to show their support, and has sent
you this email because they think you'll want to do the same. 

Only a few thousand fans will go to Japan and cheer on the team but there
will be millions of you watching from home. So we've teamed up with
Nationwide, the Official England Team Sponsor, to produce the Worlds biggest
fans flag, complete with one million supporters names printed on it, to show
the boys we're right there behind them. 

Just visit http://flag.TheFA.com/ 

All you'll need to give us your email address and your first and second
name, and your support for the team will go all the way to the World Cup.

Plus, everyone who signs will be automatically entered into a draw with the
chance to win a once-in-a-lifetime opportunity for two lucky fans to go to
Japan. You'll meet the team, visit the team camp and present the flag for
the whole country. There's also loads of England stuff to be won from signed
balls to the brand new kit.

You can also:
-   search for your mates names and famous names, who've signed the flag
-   view your own name on the Flag
-   get your mates to 'Sign the Flag' 

So, get signing, and let your friends know - there's not much time to fill
the flag!

Visit http://flag.TheFA.com/, sign the flag, and one way or another - you'll
be at the World Cup giving England your support.

Come on England!



--part1_7f.24a032fd.29eee090_boundary--



From dman@dman.ddts.net  Wed Apr 17 16:20:33 2002
From: dman@dman.ddts.net (dman)
Date: Wed, 17 Apr 2002 10:20:33 -0500
Subject: [Tutor] Python with readline
In-Reply-To: <EE9621EC-519B-11D6-AF03-00039351FE6A@mac.com>
References: <EE9621EC-519B-11D6-AF03-00039351FE6A@mac.com>
Message-ID: <20020417152033.GA4413@dman.ddts.net>

On Tue, Apr 16, 2002 at 08:42:01PM -0400, Erik Price wrote:
| A few weeks back I asked about how I could get some of the emacs-style 
| functionality (command history, emacs navigation keybindings) into my 
| Python 2.2 interactive interpreter.  Someone (I forget) said that this 
| is GNU Readline, and that I should look into recompiling with readline.
| 
| Well, I've tried a few different iterations of it -- by slightly 
| changing the Modules/Setup file in the source tree from my Python 2.2 
| tarball.  Unfortunately, I can't seem to get the right combination of 
| flags.  Here is the text of the section where I'm supposed to turn it on:
| 
| <snip>
| # GNU readline.  Unlike previous Python incarnations, GNU readline is
| # now incorporated in an optional module, configured in the Setup file
| # instead of by a configure script switch.  You may have to insert a
| # -L option pointing to the directory where libreadline.* lives,
| # and you may have to change -ltermcap to -ltermlib or perhaps remove
| # it, depending on your system -- see the GNU readline instructions.
| # It's okay for this to be a shared library, too.
| 
| #readline readline.c -lreadline -ltermcap
| </snip>
| 
| I've tried simply uncommenting the line, adding the -L option in various 
| places on the line, specifying a path to my readline library, etc, but I 
| haven't had success -- either the ./configure has failed, the make has 
| failed, or I've ended up with a Python with no readline ability -- 
| exactly what I have now.
| 
| Does anyone have any familiarity with setting Python up for this?  I'm 
| using Mac OS X 10.1.3, but I can't imagine that the procedure is much 
| different than for Linux or any other Unix.  I'm not really clear on 
| what readline does, I imagine it's some kind of library, but my lack of 
| familiarity with C and the whole "make" business is probably making this 
| difficult for me to grasp.

Yeah, understanding the C compilation environment really does help in
these situations.

Where are your readline and termcap libraries installed?  What is the
error message the build process gives you?

Do you have sshd running on your system?  (if so you can give someone
else shell access and they can work with the system to get it built)

-D

-- 

Python is executable pseudocode. Perl is executable line noise.




From ACrane@computer2000.co.uk  Wed Apr 17 16:24:28 2002
From: ACrane@computer2000.co.uk (Crane, Adam)
Date: Wed, 17 Apr 2002 16:24:28 +0100
Subject: [Tutor] Storing Info
Message-ID: <0A45A5A5BE1BD6118C4100805FE64FF246629C@tdukbasmail01.computer2000.co.uk>

I guess I'm in over my head :P

-----Original Message-----
From: Crane, Adam 
Sent: 17 April 2002 12:28
To: tutor@python.org
Subject: [Tutor] Storing Info


I'm attempting to write a program that stores/remembers a users input when
it is run.  It's a Notes/Reminder program.

So far I have this code (not tried or tested):

print "Notes Program."
print "Type in "null" if you do not wish to add a note."

notes = raw_input("Enter a note/Reminder:")
while notes <= "":
	print "That's a rather short note!"
	notes = raw_input("Enter a note/Reminder:")
if notes == "null"
	break

So what I need to do is store the users input for future reference.  I'm
starting to think I'm in way over my head.  I was thinking maybe I'd have to
import the info, or something similar (I have no idea)

Any help would be great.

Thanks,
Adam
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.



From israel@lith.com  Wed Apr 17 16:26:50 2002
From: israel@lith.com (Israel Evans)
Date: Wed, 17 Apr 2002 08:26:50 -0700
Subject: [Tutor] working with data in a database...
Message-ID: <AF020C5FC551DD43A4958A679EA16A15028E2398@abbott.lith.com>

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_01C1E624.4D6FCECE
Content-Type: text/plain

 
I'm currently trying to work with a small to middling amount of data ( about
a thousand rows or so ),  and I'm wondering about the best approach.
It seems that to analyze, compare, and otherwise play around with the data,
it would be easier just to extract it all out of the database and manipulate
a couple of instances of various classes.  Playing with strings, tuples,
lists and dicts makes a lot of sense to me right now and my SQL skills leave
something to be desired.  Though I realize that I could take a definite
performance hit were my data set to grow by any substantial amount and that
by going around the database, I'm neglecting a very valuable tool.  I'm just
new enough at this that I don't really see how best to proceed.
 
Are there any resources you database masters out there cherish and wouldn't
leave the house without?  How you chosen to deal with data housed in
databases?  What are your favorite methods?  Any hints, suggestions or
random musings are welcome...
 
Thanks,
 
 
 
~Israel~
 

------_=_NextPart_001_01C1E624.4D6FCECE
Content-Type: text/html
Content-Transfer-Encoding: quoted-printable

<html xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Dus-ascii">


<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 10">
<meta name=3DOriginator content=3D"Microsoft Word 10">
<link rel=3DFile-List href=3D"cid:filelist.xml@01C1E5E9.9EA293C0">
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"country-region"/>
<o:SmartTagType =
namespaceuri=3D"urn:schemas-microsoft-com:office:smarttags"
 name=3D"place"/>
<!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:DoNotRelyOnCSS/>
 </o:OfficeDocumentSettings>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:DocumentKind>DocumentEmail</w:DocumentKind>
  <w:EnvelopeVis/>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
   <w:UseFELayout/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
 </w:WordDocument>
</xml><![endif]--><!--[if !mso]>
<style>
st1\:*{behavior:url(#default#ieooui) }
</style>
<![endif]-->
<style>
<!--
 /* Font Definitions */
 @font-face
	{font-family:PMingLiU;
	panose-1:2 2 3 0 0 0 0 0 0 0;
	mso-font-alt:\65B0\7D30\660E\9AD4;
	mso-font-charset:136;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:3 137232384 22 0 1048577 0;}
@font-face
	{font-family:"\@PMingLiU";
	panose-1:2 2 3 0 0 0 0 0 0 0;
	mso-font-charset:136;
	mso-generic-font-family:roman;
	mso-font-pitch:variable;
	mso-font-signature:3 137232384 22 0 1048577 0;}
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-parent:"";
	margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:PMingLiU;}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;
	text-underline:single;}
p.MsoAutoSig, li.MsoAutoSig, div.MsoAutoSig
	{margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";
	mso-fareast-language:EN-US;}
span.EmailStyle17
	{mso-style-type:personal-compose;
	mso-style-noshow:yes;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;
	font-family:Arial;
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:windowtext;}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.25in 1.0in 1.25in;
	mso-header-margin:.5in;
	mso-footer-margin:.5in;
	mso-paper-source:0;}
div.Section1
	{page:Section1;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */=20
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-parent:"";
	mso-padding-alt:0in 5.4pt 0in 5.4pt;
	mso-para-margin:0in;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman";}
</style>
<![endif]-->
</head>

<body lang=3DEN-US link=3Dblue vlink=3Dpurple =
style=3D'tab-interval:.5in'>

<div class=3DSection1>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>I'm currently trying to work with a small to =
middling
amount of data <span class=3DGramE>( about</span> a thousand rows or so =
),<span
style=3D'mso-spacerun:yes'>&nbsp; </span>and I'm wondering about the =
best
approach.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>It seems that to analyze, compare, and otherwise =
play around
with the data, it would be easier just to extract it all out of the =
database
and manipulate a couple of instances of various classes.<span
style=3D'mso-spacerun:yes'>&nbsp; </span>Playing with strings, <span
class=3DSpellE>tuples</span>, lists and <span =
class=3DSpellE>dicts</span> makes a
lot of sense to me right now and my SQL skills leave something to be =
desired. <span
style=3D'mso-spacerun:yes'>&nbsp;</span>Though I realize that I could =
take a
definite performance hit were my data set to grow by any substantial =
amount and
that by going around the database, I'm neglecting a very valuable tool. =
<span
style=3D'mso-spacerun:yes'>&nbsp;</span>I'm just new enough at this =
that I
don't really see how best to proceed.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Are there any resources you database masters out =
there
cherish and wouldn't leave the house without?<span
style=3D'mso-spacerun:yes'>&nbsp; </span>How you chosen to deal with =
data housed
in databases?<span style=3D'mso-spacerun:yes'>&nbsp; </span>What are =
your
favorite methods?<span style=3D'mso-spacerun:yes'>&nbsp; </span>Any =
hints, suggestions
or random musings are welcome...<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'>Thanks,<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;
font-family:Arial'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt;mso-no-proof:yes'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoAutoSig><font size=3D2 face=3D"Courier New"><span =
style=3D'font-size:
10.0pt;font-family:"Courier =
New";mso-no-proof:yes'>~</span></font><st1:country-region><st1:place><fo=
nt
  size=3D2 face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
  =
mso-no-proof:yes'>Israel</span></font></st1:place></st1:country-region><=
font
size=3D2 face=3D"Courier New"><span =
style=3D'font-size:10.0pt;font-family:"Courier New";
mso-no-proof:yes'>~<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D3 face=3D"Times New Roman"><span =
style=3D'font-size:
12.0pt'><o:p>&nbsp;</o:p></span></font></p>

</div>

</body>

</html>

------_=_NextPart_001_01C1E624.4D6FCECE--



From michael.williams@st-annes.oxford.ac.uk  Wed Apr 17 16:36:18 2002
From: michael.williams@st-annes.oxford.ac.uk (Michael Williams)
Date: Wed, 17 Apr 2002 16:36:18 +0100
Subject: [Tutor] Storing Info
In-Reply-To: <0A45A5A5BE1BD6118C4100805FE64FF246629C@tdukbasmail01.computer2000.co.uk>
References: <0A45A5A5BE1BD6118C4100805FE64FF246629C@tdukbasmail01.computer2000.co.uk>
Message-ID: <20020417153617.GA1659@st-annes.oxford.ac.uk>

On Wed, Apr 17, 2002 at 04:24:28PM +0100, Crane, Adam wrote:
> I'm attempting to write a program that stores/remembers a users input when
> it is run.  It's a Notes/Reminder program.
> 
> So far I have this code (not tried or tested):
> 
> print "Notes Program."
> print "Type in "null" if you do not wish to add a note."
> 
> notes = raw_input("Enter a note/Reminder:")
> while notes <= "":
> 	print "That's a rather short note!"
> 	notes = raw_input("Enter a note/Reminder:")
> if notes == "null"
> 	break
> 
> So what I need to do is store the users input for future reference.  I'm
> starting to think I'm in way over my head.  I was thinking maybe I'd have to
> import the info, or something similar (I have no idea)
> 
> Any help would be great.

How you handle this depends largely on whether the program is going to
be running permenantly in the background, or is going to be stopped and
started. If the latter you need to store the notes' text in files for
later access. Take a look at the file tutorial in the official Python
tutorial

<http://www.python.org/doc/current/tut/node9.html>

Similar guides can be found on the other online tutorials. You will
probably need to do some string manipulation too:

<http://www.python.org/doc/current/lib/module-string.html>

-- 
Michael



From tim@johnsons-web.com  Wed Apr 17 17:30:13 2002
From: tim@johnsons-web.com (Tim Johnson)
Date: Wed, 17 Apr 2002 08:30:13 -0800
Subject: [Tutor] URL for searchable Archives
Message-ID: <20020417163013.GZ32331@johnsons-web.com>

Hello All:
    Are there searchable archives for this mailing
    lists, and if so, where is the location?
    TIA
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com
      http://www.johnsons-web.com



From michael.williams@st-annes.oxford.ac.uk  Wed Apr 17 17:53:01 2002
From: michael.williams@st-annes.oxford.ac.uk (Michael Williams)
Date: Wed, 17 Apr 2002 17:53:01 +0100
Subject: [Tutor] Getting range to produce float lists
Message-ID: <20020417165301.GB1659@st-annes.oxford.ac.uk>

I'm writing a tutorial introducing scientific programming to first year
Physics undergraduates and have got to the bit where I explain for loops
and, by implication range(). It is a common requirement to want to step
the loop in fractional increments, e.g.

[0.0, 0.1, 0.2, 0.3, 0.4]

I would like to do this by doing range(0, 0.5, 0.1) but of course range
only produces integer lists and will round all the arguments (making the
step = 0 if required). Is there a way to do this easily with core
Python or should I hack up a quick function for my students to use?
-- 
Michael



From alan.gauld@bt.com  Wed Apr 17 17:40:01 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 17 Apr 2002 17:40:01 +0100
Subject: [Tutor] constructors
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C55C@mbtlipnt02.btlabs.bt.co.uk>

> | statements when an exception occurs you jump to the 
> | end of that block with no way back in (I've always thought 
> | a 'continue' for exception handlers would be nice!)
> 
> Have you ever tried Eiffel?  ... includes a
> 'retry' keyword that will restart the function.

Yes, I've played with the free ISE Eiffel edition.
I like a lot of it, but unfortunately some of the libraries 
were a bit buggy at the time and it seemed a bit verbose 
for many things. However the concepts were very sound.

> (not that I like Eiffel a lot, but it did get one or two things right)

I thought it got more right than wrong. The biggest failing 
was not getting market share, and that was  largely down to 
being, in effect, a proprietary language with a single source 
of supply. 

If it achieves nothing else Eiffel will have produced one of 
the best OO texts ever written...

Alan G.



From dyoo@hkn.eecs.berkeley.edu  Wed Apr 17 18:27:25 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 17 Apr 2002 10:27:25 -0700 (PDT)
Subject: [Tutor] URL for searchable Archives
In-Reply-To: <20020417163013.GZ32331@johnsons-web.com>
Message-ID: <Pine.LNX.4.44.0204171024150.4585-100000@hkn.eecs.berkeley.edu>


On Wed, 17 Apr 2002, Tim Johnson wrote:

> Hello All:
>     Are there searchable archives for this mailing
>     lists, and if so, where is the location?

Hi Tim,

Activestate hosts a nice search interface for the Tutor mailing list here:

    http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor


Hope this helps!




From alan.gauld@bt.com  Wed Apr 17 18:12:37 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 17 Apr 2002 18:12:37 +0100
Subject: [Tutor] Storing Info
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C55E@mbtlipnt02.btlabs.bt.co.uk>

> print "Notes Program."
> print "Type in "null" if you do not wish to add a note."

You have embeddeed quotes within quotes. 
You need to use single quotes on the outside...

> 
> notes = raw_input("Enter a note/Reminder:")
> while notes <= "":

Are you sure you mean <= ie less than or equal?
I suspect that should be == for equals.

> 	print "That's a rather short note!"
> 	notes = raw_input("Enter a note/Reminder:")
> if notes == "null"
> 	break

The if claess needs to be indented to the same level 
as the notes= line, otherwise its seen by python as 
being outside the loop.

> starting to think I'm in way over my head.  

No, you are pretty close.

> I was thinking maybe I'd have to import the info, 
> or something similar (I have no idea)

No you are reading it from the user.
Of course in the real world you probably want to store 
the notes in a file or something but that can wait till 
later ;-)

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Wed Apr 17 17:51:03 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 17 Apr 2002 17:51:03 +0100
Subject: [Tutor] string to number
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C55D@mbtlipnt02.btlabs.bt.co.uk>

> it wont let me use INT and the ATOL function keeps comming up 
> as undefined

Python is case sensitive.

try using atol or int instead.

Also you need to use parens as in 

>>> int('57')
57

Alan G



From paulsid@shaw.ca  Wed Apr 17 18:38:46 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Wed, 17 Apr 2002 11:38:46 -0600
Subject: [Tutor] Getting range to produce float lists
References: <20020417165301.GB1659@st-annes.oxford.ac.uk>
Message-ID: <3CBDB326.AFC3CDAA@shaw.ca>

Michael Williams wrote:

> I'm writing a tutorial introducing scientific programming to first year
> Physics undergraduates and have got to the bit where I explain for loops
> and, by implication range(). It is a common requirement to want to step
> the loop in fractional increments, e.g.
> 
> [0.0, 0.1, 0.2, 0.3, 0.4]
> 
> I would like to do this by doing range(0, 0.5, 0.1) but of course range
> only produces integer lists and will round all the arguments (making the
> step = 0 if required). Is there a way to do this easily with core
> Python or should I hack up a quick function for my students to use?

List comprehensions are probably the most straightforward:

for x in [i*0.1 for i in range(5)]:
    print x

For first year non-CS, though, I'd suggest just writing a function for
them.

Of course you could just tell them that range() only works with integers
and that they will have to do things the long way:  build a list using a
for or while loop and then use "for x in newlist:".  However, this would
mean exposing your students to more of the nasty details of programming,
which I suspect isn't what you would want to do in a sci-prog course.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From nicole.seitz@urz.uni-hd.de  Wed Apr 17 18:54:15 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Wed, 17 Apr 2002 19:54:15 +0200
Subject: [Tutor] Cheating?No, not me:-)
In-Reply-To: <20020405213822.GA1114@dman.ddts.net>
References: <20020324210443.GC10420@dman.ddts.net> <02040522425802.00703@utopia> <20020405213822.GA1114@dman.ddts.net>
Message-ID: <02041719541502.00705@utopia>

Am Freitag,  5. April 2002 23:38 schrieb dman:
> On Fri, Apr 05, 2002 at 10:42:58PM +0200, Nicole Seitz wrote:
> | Am Sonntag, 24. M=E4rz 2002 23:01 schrieb dman:
> | > | For people who are interested: here's a similar problem: "Given a
> | > | text file and an integer K, you are to print the K most common wo=
rds
> | > | in the file (and the number of their occurences) in decreasing
> | > | frequency."
> | >
> | > <cheater's hint>
> | > Search the tutor archives.  With only a couple minor modifications =
the
> | > answer is already there.
> | > </cheater's hint>
> |
> | Some hint WHERE in the archives I could find the answer?Month?Year?
>
> I don't remember, but try googling for :
>     python tutor word count slow perl
>
> which yields this as the second result :
>     http://mail.python.org/pipermail/tutor/2001-February/003403.html
>
> apparently it was February 1, 2001.
>
> Enjoy :-).

Thanks!
My program now runs almost perfectly. And I solved the problem how to pri=
nt=20
the K most common words. Maybe there's an easier way to determine the mos=
t=20
common words, I don't know.
Here's the little function that deals with the most common words.What do =
you=20
think of it?

Note: occ is the dictionary where I store the words and their occurences,=
e.g.=20
occ =3D { "hello":3,"you":123,"fool":23}
-------------------------------------------------------------------------=
------
def MostCommonWords(occ,K):=20
    dict =3D{}


    for key in occ.keys():
        if dict.has_key(occ[key]):
            dict[occ[key]].append(key)
        else:
            dict[occ[key]] =3D [key]

    key_list =3D dict.keys()
    key_list.sort()
    key_list.reverse()
    print "Most common word(s): "
    for i in range(int(K)):
        for word in dict[key_list[i]]:
            print "%-8s" % word, "\t",
            #print dict[key_list[ i]],
            print" (occurences: %2i) " % key_list[i]


-------------------------------------------------------------------------=
-------------

Last but not least, I've got some questions on regexes and other stuff wh=
ich=20
you use in your script.

# remove leading and trailing whitespace
        line =3D string.strip(line)

Why that?

       # split the string into a list of words
       # a word is delimited by whitespace or punctuation
        for word in re.split(
         "[" + string.whitespace + string.punctuation + "]+",
         line):

DOn't understand this regex.Could you explain,please?I guess=20
string.punctuation is [.,;:?!].But what's the meaning of [" + bla + bla +=
"] =20
???

# check to make sure the string is considered a word
            if re.match("^[" + string.lowercase + "]+$", word):

Is it necessary to do this.Can't I be sure that thestring is considered a=
=20
word?

Many thanks for your help.


Nicole
>
> -D



From nicole.seitz@urz.uni-hd.de  Wed Apr 17 19:24:38 2002
From: nicole.seitz@urz.uni-hd.de (Nicole Seitz)
Date: Wed, 17 Apr 2002 20:24:38 +0200
Subject: [Tutor] A style question
Message-ID: <02041720243803.00705@utopia>

Hi there!

I wrote these lines to write some stuff to a file.
Is there a way to reduce the number of lines needed here?There are so many 
uses of 'output.write'.

output.write("Number of lines: %s\n" % str(linecount))
    output.write("Total word count: %s\n" % str(wordcount))
    output.write("Total character count: %s\n\n"% str(charcount))
    for word in keyList:
        output.write("word: ")
        output.write(word)
        output.write(",    occurences:")
        output.write((str(occurences[word])))
        output.write("\n")

Thanks for your help!


Nicole



From kalle@gnupung.net  Wed Apr 17 19:34:38 2002
From: kalle@gnupung.net (Kalle Svensson)
Date: Wed, 17 Apr 2002 20:34:38 +0200
Subject: [Tutor] A style question
In-Reply-To: <02041720243803.00705@utopia>
References: <02041720243803.00705@utopia>
Message-ID: <20020417183438.GA534@i92.ryd.student.liu.se>

[Nicole Seitz]
> I wrote these lines to write some stuff to a file.
> Is there a way to reduce the number of lines needed here?There are so many 
> uses of 'output.write'.
[...]
>         output.write("word: ")
>         output.write(word)
>         output.write(",    occurences:")
>         output.write((str(occurences[word])))
>         output.write("\n")

could be written as

      output.write("word: %s,    occurences:%s\n" % (word,
                                                     occurences[word]))

Otherwise, I don't see anything obvious.

Med utmärkt högaktning,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.



From printers@sendme.cz  Wed Apr 17 20:23:00 2002
From: printers@sendme.cz (A)
Date: Wed, 17 Apr 2002 21:23:00 +0200
Subject: [Tutor] What webhosting
Message-ID: <3CBDE7B4.3348.4EB76@localhost>

Hi,
Does anybody know about a webhosting provider ( with Python and 
Telnet access) that does not remove a user's account if the user 
sends occasionally some unsolicited emails?
Thanks for reply
Ladislav





From shalehperry@attbi.com  Wed Apr 17 20:42:59 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 17 Apr 2002 12:42:59 -0700 (PDT)
Subject: [Tutor] Cheating?No, not me:-)
In-Reply-To: <02041719541502.00705@utopia>
Message-ID: <XFMail.20020417124259.shalehperry@attbi.com>

> 
> Thanks!
> My program now runs almost perfectly. And I solved the problem how to print 
> the K most common words. Maybe there's an easier way to determine the most 
> common words, I don't know.
> Here's the little function that deals with the most common words.What do you 
> think of it?
> 
> Note: occ is the dictionary where I store the words and their occurences,e.g.
> occ = { "hello":3,"you":123,"fool":23}

try this:

$ python
>>> def value_sort(a,b):
...     if a[1] == b[1]: return 0
...     elif a[1] < b[1]: return -1
...     else: return 1
... 
>>> occ = {"hello":3, "name":23, "bob":15, "jane":10}
>>> values = zip(occ.keys(), occ.values())
>>> values
[('hello', 3), ('name', 23), ('bob', 15), ('jane', 10)]
>>> values.sort(value_sort)
>>> values
[('hello', 3), ('jane', 10), ('bob', 15), ('name', 23)]

Getting the first K items in that list should be easy enough.

zip() takes two lists and makes a list of tuples.  the sort method of a list
takes an optional function which defines how to sort.  This function returns -1
when the first is less than the second, 0 when they are equal and 1 when the
first is greater than the second.





From israel@lith.com  Wed Apr 17 20:59:51 2002
From: israel@lith.com (Israel Evans)
Date: Wed, 17 Apr 2002 12:59:51 -0700
Subject: [Tutor] Cheating?No, not me:-)
Message-ID: <AF020C5FC551DD43A4958A679EA16A15028E23D6@abbott.lith.com>

I just ran across something like this that used list comprehensions to do
this...

As far as I can remember it went like this:


>>> occ = {"hello":3, "name":23, "bob":15, "jane":10}

	# switch the keys for the values
>>> pairs = [(v, k) for (k, v) in occ.items()]  

>>> pairs
[(10, 'jane'), (15, 'bob'), (3, 'hello'), (23, 'name')]

>>> pairs.sort()

	# reverse list so that most occurrences are at the front.
>>> pairs.reverse()

	# switch back the keys and values.
>>> pairs = [(k, v) for (v, k) in pairs]

>>> pairs
[('name', 23), ('bob', 15), ('jane', 10), ('hello', 3)]



~Israel~


-----Original Message-----
From: Sean 'Shaleh' Perry [mailto:shalehperry@attbi.com] 
Sent: 17 April 2002 12:43 PM
To: Nicole Seitz
Cc: tutor@python.org
Subject: Re: [Tutor] Cheating?No, not me:-)

> 
> Thanks!
> My program now runs almost perfectly. And I solved the problem how to
print 
> the K most common words. Maybe there's an easier way to determine the most

> common words, I don't know.
> Here's the little function that deals with the most common words.What do
you 
> think of it?
> 
> Note: occ is the dictionary where I store the words and their
occurences,e.g.
> occ = { "hello":3,"you":123,"fool":23}

try this:

$ python
>>> def value_sort(a,b):
...     if a[1] == b[1]: return 0
...     elif a[1] < b[1]: return -1
...     else: return 1
... 
>>> occ = {"hello":3, "name":23, "bob":15, "jane":10}
>>> values = zip(occ.keys(), occ.values())
>>> values
[('hello', 3), ('name', 23), ('bob', 15), ('jane', 10)]
>>> values.sort(value_sort)
>>> values
[('hello', 3), ('jane', 10), ('bob', 15), ('name', 23)]

Getting the first K items in that list should be easy enough.

zip() takes two lists and makes a list of tuples.  the sort method of a list
takes an optional function which defines how to sort.  This function returns
-1
when the first is less than the second, 0 when they are equal and 1 when the
first is greater than the second.




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



From Jack.Jansen@cwi.nl  Tue Apr 16 10:03:36 2002
From: Jack.Jansen@cwi.nl (Jack Jansen)
Date: Tue, 16 Apr 2002 11:03:36 +0200
Subject: [Tutor] Re: [Pythonmac-SIG] recursive memory
In-Reply-To: <fc.004c4b6b0094ac72004c4b6b0094ac72.94ad9f@blakeschool.org>
Message-ID: <D5CE9DD7-5118-11D6-9DE5-0030655234CE@cwi.nl>

On Monday, April 15, 2002, at 11:41 , Christopher Smith wrote:

> I'm making a modification to the walk() function on the Mac so it avoids
> getting caught in an alias loop between folders (i.e. walking a folder
> which has an alias to another folder which has an alias of the first
> folder).  The way I do this is store the file specs in a dictionary.  I
> have two questions.

macpath.walk() (or actually os.path.walk) is explicitly define *not* to 
do special things for symlinks or aliases. But still: the functionality 
is nice, so maybe we should put it in a new function macostools.walk.


> walk(t, f, a) #no dictionary sent so it should start at {}
>
> I need the dictionary to start at {} every time I first give the walk, 
> but
> then want it updated as I go deeper in the walk--so the main script call
> leaves the dictionary off but recursive calls send the modified
> dictionary.  Is this the right way to go about this?

Yes, don't pass visited={}, because it's going to be the visited 
*object* that is modified, so the next call will use the last value of 
visited (as you've undoubtedly noticed:-).

The idiom is to do
def walk(..., visited=None):
	if visited is None:
		visited = {}

> 2)
> I would also like to find out if an alias points to another (unmounted)
> volume.  The only problem is that if the volume is unmounted, the
> ResolveAliasFile routine (or other routines that will give file
> information, like mac.stat()) will prompt me to insert the volume; I 
> would
> like to have the walk be unattended and so would like a way to override
> the insert volume reaction and just know that the alias points to an
> unmounted volume and just skip it.  Is there another way to detect this
> condition without being asked to insert the missing volume?

I can't find anything, also not in the lower level alias handling 
routines (i.e. what is partially exposed via macfs.Alias methods).
--
- Jack Jansen        <Jack.Jansen@oratrix.com>        
http://www.cwi.nl/~jack -
- If I can't dance I don't want to be part of your revolution -- Emma 
Goldman -




From Jack.Jansen@cwi.nl  Tue Apr 16 10:03:47 2002
From: Jack.Jansen@cwi.nl (Jack Jansen)
Date: Tue, 16 Apr 2002 11:03:47 +0200
Subject: [Tutor] Re: [Pythonmac-SIG] recursive memory
In-Reply-To: <fc.004c4b6b0094ac72004c4b6b0094ac72.94ad9f@blakeschool.org>
Message-ID: <DCA960BC-5118-11D6-9DE5-0030655234CE@cwi.nl>

On Monday, April 15, 2002, at 11:41 , Christopher Smith wrote:

> I'm making a modification to the walk() function on the Mac so it avoids
> getting caught in an alias loop between folders (i.e. walking a folder
> which has an alias to another folder which has an alias of the first
> folder).  The way I do this is store the file specs in a dictionary.  I
> have two questions.

macpath.walk() (or actually os.path.walk) is explicitly define *not* to 
do special things for symlinks or aliases. But still: the functionality 
is nice, so maybe we should put it in a new function macostools.walk.


> walk(t, f, a) #no dictionary sent so it should start at {}
>
> I need the dictionary to start at {} every time I first give the walk, 
> but
> then want it updated as I go deeper in the walk--so the main script call
> leaves the dictionary off but recursive calls send the modified
> dictionary.  Is this the right way to go about this?

Yes, don't pass visited={}, because it's going to be the visited 
*object* that is modified, so the next call will use the last value of 
visited (as you've undoubtedly noticed:-).

The idiom is to do
def walk(..., visited=None):
	if visited is None:
		visited = {}

> 2)
> I would also like to find out if an alias points to another (unmounted)
> volume.  The only problem is that if the volume is unmounted, the
> ResolveAliasFile routine (or other routines that will give file
> information, like mac.stat()) will prompt me to insert the volume; I 
> would
> like to have the walk be unattended and so would like a way to override
> the insert volume reaction and just know that the alias points to an
> unmounted volume and just skip it.  Is there another way to detect this
> condition without being asked to insert the missing volume?

I can't find anything, also not in the lower level alias handling 
routines (i.e. what is partially exposed via macfs.Alias methods).
--
- Jack Jansen        <Jack.Jansen@oratrix.com>        
http://www.cwi.nl/~jack -
- If I can't dance I don't want to be part of your revolution -- Emma 
Goldman -




From Jack.Jansen@cwi.nl  Wed Apr 17 09:54:56 2002
From: Jack.Jansen@cwi.nl (Jack Jansen)
Date: Wed, 17 Apr 2002 10:54:56 +0200
Subject: [Tutor] Re: recursive memory
In-Reply-To: <fc.004c4b6b0094bc9b004c4b6b0094ac72.94bd9f@blakeschool.org>
Message-ID: <CAA1A8C1-51E0-11D6-BA96-0030655234CE@cwi.nl>

On Tuesday, April 16, 2002, at 03:56 , Christopher Smith wrote:

>> macpath.walk() (or actually os.path.walk) is explicitly define *not* to
>> do special things for symlinks or aliases. But still: the functionality
>> is nice, so maybe we should put it in a new function macostools.walk.
>
> By "special things" you don't mean that walk() is suppose to skip over
> aliases, do you?

Yes, that's what I mean. Do I understand from your comment that it walks 
aliases? That would be a bug, please file it at sourceforge.

(Look at posixpath, for instance: it doesn't do a straight isdir() 
because that would return true for a symlink pointing to a directory. It 
does an explicit lstat() and looks at the mode bits).
> --
- Jack Jansen        <Jack.Jansen@oratrix.com>        
http://www.cwi.nl/~jack -
- If I can't dance I don't want to be part of your revolution -- Emma 
Goldman -




From Jack.Jansen@cwi.nl  Wed Apr 17 09:57:42 2002
From: Jack.Jansen@cwi.nl (Jack Jansen)
Date: Wed, 17 Apr 2002 10:57:42 +0200
Subject: [Tutor] Re: [Pythonmac-SIG] Re: recursive memory
In-Reply-To: <fc.004c4b6b0094bc9b004c4b6b0094ac72.94bd9f@blakeschool.org>
Message-ID: <2D72D39E-51E1-11D6-BA96-0030655234CE@cwi.nl>

Sorry, hit send too quickly.

On Tuesday, April 16, 2002, at 03:56 , Christopher Smith wrote:
> If these undesirable behaviors were deemed bugs then the macpath.walk()
> function could just be modified.  I have attached a version which has 
> the
> same behavior as the original but now has 3 optional arguments to handle
> walking aliases, other volumes, and a dictionary to prevent walking
> previously walked folders.

Hmm. I don't think this is a good idea, because macpath == os.path. And 
the API of all the os.path modules (macpath, winpath, posixpath) is kept 
the same (with some historic exceptions:-).

I will pick up the islink() mod, though.
--
- Jack Jansen        <Jack.Jansen@oratrix.com>        
http://www.cwi.nl/~jack -
- If I can't dance I don't want to be part of your revolution -- Emma 
Goldman -




From WILLIAM.GRIFFIN@asu.edu  Wed Apr 17 23:23:09 2002
From: WILLIAM.GRIFFIN@asu.edu (William Griffin)
Date: Wed, 17 Apr 2002 15:23:09 -0700
Subject: [Tutor] Getting range to produce float lists
Message-ID: <8093ABAD9B81D211878200A0C9B406BA14B65A2C@mainex3.asu.edu>

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.

--Boundary_(ID_2sQTZWMWgVFWyHn5T2DnkA)
Content-type: text/plain;	charset="iso-8859-1"

It is possible to use Numeric's arange; for example:
(after importing Numeric *)
>>> for i in arange(0.1,0.8,0.1):
... 	print i
... 	
0.1
0.2
0.3
0.4
0.5
0.6
0.7
>>> 
 or in your case ---

>>> for i in arange(0, 0.5, 0.1):
... 	print i
... 	
0.0
0.1
0.2
0.3
0.4
>>> 

Hope this helps.
Bill

-----Original Message-----
From: Michael Williams [mailto:michael.williams@st-annes.oxford.ac.uk]
Sent: Wednesday, April 17, 2002 9:53 AM
To: tutor@python.org
Subject: [Tutor] Getting range to produce float lists


I'm writing a tutorial introducing scientific programming to first year
Physics undergraduates and have got to the bit where I explain for loops
and, by implication range(). It is a common requirement to want to step
the loop in fractional increments, e.g.

[0.0, 0.1, 0.2, 0.3, 0.4]

I would like to do this by doing range(0, 0.5, 0.1) but of course range
only produces integer lists and will round all the arguments (making the
step = 0 if required). Is there a way to do this easily with core
Python or should I hack up a quick function for my students to use?
-- 
Michael


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

--Boundary_(ID_2sQTZWMWgVFWyHn5T2DnkA)
Content-type: text/html;	charset="iso-8859-1"
Content-transfer-encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Diso-8859-1">
<META NAME=3D"Generator" CONTENT=3D"MS Exchange Server version =
5.5.2655.35">
<TITLE>RE: [Tutor] Getting range to produce float lists</TITLE>
</HEAD>
<BODY>

<P><FONT SIZE=3D2>It is possible to use Numeric's arange; for =
example:</FONT>
<BR><FONT SIZE=3D2>(after importing Numeric *)</FONT>
<BR><FONT SIZE=3D2>&gt;&gt;&gt; for i in arange(0.1,0.8,0.1):</FONT>
<BR><FONT SIZE=3D2>... &nbsp;&nbsp;&nbsp; print i</FONT>
<BR><FONT SIZE=3D2>... &nbsp;&nbsp;&nbsp; </FONT>
<BR><FONT SIZE=3D2>0.1</FONT>
<BR><FONT SIZE=3D2>0.2</FONT>
<BR><FONT SIZE=3D2>0.3</FONT>
<BR><FONT SIZE=3D2>0.4</FONT>
<BR><FONT SIZE=3D2>0.5</FONT>
<BR><FONT SIZE=3D2>0.6</FONT>
<BR><FONT SIZE=3D2>0.7</FONT>
<BR><FONT SIZE=3D2>&gt;&gt;&gt; </FONT>
<BR><FONT SIZE=3D2>&nbsp;or in your case ---</FONT>
</P>

<P><FONT SIZE=3D2>&gt;&gt;&gt; for i in arange(0, 0.5, 0.1):</FONT>
<BR><FONT SIZE=3D2>... &nbsp;&nbsp;&nbsp; print i</FONT>
<BR><FONT SIZE=3D2>... &nbsp;&nbsp;&nbsp; </FONT>
<BR><FONT SIZE=3D2>0.0</FONT>
<BR><FONT SIZE=3D2>0.1</FONT>
<BR><FONT SIZE=3D2>0.2</FONT>
<BR><FONT SIZE=3D2>0.3</FONT>
<BR><FONT SIZE=3D2>0.4</FONT>
<BR><FONT SIZE=3D2>&gt;&gt;&gt; </FONT>
</P>

<P><FONT SIZE=3D2>Hope this helps.</FONT>
<BR><FONT SIZE=3D2>Bill</FONT>
</P>

<P><FONT SIZE=3D2>-----Original Message-----</FONT>
<BR><FONT SIZE=3D2>From: Michael Williams [<A =
HREF=3D"mailto:michael.williams@st-annes.oxford.ac.uk">mailto:michael.wi=
lliams@st-annes.oxford.ac.uk</A>]</FONT>
<BR><FONT SIZE=3D2>Sent: Wednesday, April 17, 2002 9:53 AM</FONT>
<BR><FONT SIZE=3D2>To: tutor@python.org</FONT>
<BR><FONT SIZE=3D2>Subject: [Tutor] Getting range to produce float =
lists</FONT>
</P>
<BR>

<P><FONT SIZE=3D2>I'm writing a tutorial introducing scientific =
programming to first year</FONT>
<BR><FONT SIZE=3D2>Physics undergraduates and have got to the bit where =
I explain for loops</FONT>
<BR><FONT SIZE=3D2>and, by implication range(). It is a common =
requirement to want to step</FONT>
<BR><FONT SIZE=3D2>the loop in fractional increments, e.g.</FONT>
</P>

<P><FONT SIZE=3D2>[0.0, 0.1, 0.2, 0.3, 0.4]</FONT>
</P>

<P><FONT SIZE=3D2>I would like to do this by doing range(0, 0.5, 0.1) =
but of course range</FONT>
<BR><FONT SIZE=3D2>only produces integer lists and will round all the =
arguments (making the</FONT>
<BR><FONT SIZE=3D2>step =3D 0 if required). Is there a way to do this =
easily with core</FONT>
<BR><FONT SIZE=3D2>Python or should I hack up a quick function for my =
students to use?</FONT>
<BR><FONT SIZE=3D2>-- </FONT>
<BR><FONT SIZE=3D2>Michael</FONT>
</P>
<BR>

<P><FONT =
SIZE=3D2>_______________________________________________</FONT>
<BR><FONT SIZE=3D2>Tutor maillist&nbsp; -&nbsp; Tutor@python.org</FONT>
<BR><FONT SIZE=3D2><A =
HREF=3D"http://mail.python.org/mailman/listinfo/tutor" =
TARGET=3D"_blank">http://mail.python.org/mailman/listinfo/tutor</A></FON=
T>
</P>

</BODY>
</HTML>=

--Boundary_(ID_2sQTZWMWgVFWyHn5T2DnkA)--



From alex@gabuzomeu.net  Thu Apr 18 00:14:46 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Thu, 18 Apr 2002 01:14:46 +0200
Subject: [Tutor] Storing Info
In-Reply-To: <20020417112902.8321.67189.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020418010101.00dece30@pop3.norton.antivirus>

Hi Adam,


At 07:29 17/04/2002 -0400, you wrote:
>From: "Crane, Adam" <ACrane@computer2000.co.uk>
>Date: Wed, 17 Apr 2002 12:27:34 +0100
>Subject: [Tutor] Storing Info
>
>I'm attempting to write a program that stores/remembers a users input when 
>it is run.  It's a Notes/Reminder program.

(...)

>So what I need to do is store the users input for future reference.

To store data, take a look at the "pickle" and "cPickle" modules. They 
allow to store Python objects to the disk and load them back very easily.


Cheers.

Alexandre




From alex@gabuzomeu.net  Thu Apr 18 00:29:11 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Thu, 18 Apr 2002 01:29:11 +0200
Subject: [Tutor] Re: Tutor] A style question
In-Reply-To: <20020417210519.4743.42847.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020418010832.00d25340@pop3.norton.antivirus>

Hi Nicole,


At 17:05 17/04/2002 -0400, you wrote:
>From: Nicole Seitz <nicole.seitz@urz.uni-hd.de>
>Date: Wed, 17 Apr 2002 20:24:38 +0200
>Subject: [Tutor] A style question

>I wrote these lines to write some stuff to a file.
>Is there a way to reduce the number of lines needed here?There are so 
>many  uses of 'output.write'.
>
>output.write("Number of lines: %s\n" % str(linecount))
>     output.write("Total word count: %s\n" % str(wordcount))
>     output.write("Total character count: %s\n\n"% str(charcount))
>     for word in keyList:
>         output.write("word: ")
>         output.write(word)
>         output.write(",    occurences:")
>         output.write((str(occurences[word])))
>         output.write("\n")

You could use longer string templates to write larger chunks at a time:

header = """Number of lines: %i\n
Total word count: %i\n
Total character count: %i\n\n"""

body = """word: %s,   occurences: %i\n"""

Then use:

output.write(header % (linecount, wordcount, charcount))
for word in keyList:
     output.write(body % (word, occurences[word]))


Cheers.

Alexandre




From erikprice@mac.com  Thu Apr 18 02:54:17 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 17 Apr 2002 21:54:17 -0400
Subject: [Tutor] What webhosting
In-Reply-To: <3CBDE7B4.3348.4EB76@localhost>
Message-ID: <3103FA71-526F-11D6-9A67-00039351FE6A@mac.com>

On Wednesday, April 17, 2002, at 03:23  PM, A wrote:

> Hi,
> Does anybody know about a webhosting provider ( with Python and
> Telnet access) that does not remove a user's account if the user
> sends occasionally some unsolicited emails?
> Thanks for reply
> Ladislav

Everyone gets occasional unsolicited emails.  For instance, your email 
that I'm responding to right now, which has nothing to do with Python 
and yet was cross-posted to four different Python-specific mailing 
lists, was extremely unsolicited -- a cross-posted email illustrates its 
own lack of relevance to the subject matter of the mailing lists to 
which it was posted.

If you are referring to unsolicited advertisements sent by email, 
however, I certainly hope there are no webhosting providers that do not 
remove a user's account.  It's referred to as spam, and you probably 
won't find many people who respond favorably to it on these lists.


Erik




From python@rcn.com  Thu Apr 18 03:36:34 2002
From: python@rcn.com (Raymond Hettinger)
Date: Wed, 17 Apr 2002 22:36:34 -0400
Subject: [Tutor] What webhosting
References: <3103FA71-526F-11D6-9A67-00039351FE6A@mac.com>
Message-ID: <000f01c1e681$dbc0cd60$2fe97ad1@othello>

> > Hi,
> > Does anybody know about a webhosting provider ( with Python and
> > Telnet access) that does not remove a user's account if the user
> > sends occasionally some unsolicited emails?

It's not too late to turn you efforts away from the dark side and try to
accomplish something useful.

there-are-better-ways-to-make-money-ly yours,

Raymond




From erikprice@mac.com  Thu Apr 18 03:51:05 2002
From: erikprice@mac.com (Erik Price)
Date: Wed, 17 Apr 2002 22:51:05 -0400
Subject: [Tutor] Python with readline
In-Reply-To: <20020417152033.GA4413@dman.ddts.net>
Message-ID: <206C39EB-5277-11D6-9A67-00039351FE6A@mac.com>

On Wednesday, April 17, 2002, at 11:20  AM, dman wrote:

> Yeah, understanding the C compilation environment really does help in
> these situations.


> Where are your readline and termcap libraries installed?  What is the
> error message the build process gives you?

Well, I have the following files with the word "termcap" on my system 
(not including man pages):

/sw/include/termcap.h
/System/Library/Perl/termcap.pl
/usr/share/emacs/20.7/etc/termcap.src
/usr/share/misc/termcap
/usr/share/misc/termcap.db

As to be expected, the man page assumes a priori knowledge of whatever 
"termcap" is, so it's not very helpful.

And I believe my readline library is /sw/include/readline (if the /sw/ 
dir looks unfamiliar, it's the equivalent of /usr/local/ used by Fink, 
the Unix ported package management app for Mac OS X).

> Do you have sshd running on your system?  (if so you can give someone
> else shell access and they can work with the system to get it built)

Well... one can't be too paranoid when it comes to their system can 
they... I don't normally run this or many other services, and to be 
honest, while I'd like to get readline up and running, I'm note quite 
desperate enough to do it this way... :)


Erik




From dman@dman.ddts.net  Thu Apr 18 04:53:30 2002
From: dman@dman.ddts.net (dman)
Date: Wed, 17 Apr 2002 22:53:30 -0500
Subject: [Tutor] Python with readline
In-Reply-To: <206C39EB-5277-11D6-9A67-00039351FE6A@mac.com>
References: <20020417152033.GA4413@dman.ddts.net> <206C39EB-5277-11D6-9A67-00039351FE6A@mac.com>
Message-ID: <20020418035330.GA15806@dman.ddts.net>

On Wed, Apr 17, 2002 at 10:51:05PM -0400, Erik Price wrote:
| 
| On Wednesday, April 17, 2002, at 11:20  AM, dman wrote:
| 
| >Yeah, understanding the C compilation environment really does help in
| >these situations.
| 
| 
| >Where are your readline and termcap libraries installed?  What is the
| >error message the build process gives you?
| 
| Well, I have the following files with the word "termcap" on my system 
| (not including man pages):
| 
| /sw/include/termcap.h
| /System/Library/Perl/termcap.pl
| /usr/share/emacs/20.7/etc/termcap.src
| /usr/share/misc/termcap
| /usr/share/misc/termcap.db

No .so files?  They are always named libfoo.so, where 'foo' is the name
of the library.

| As to be expected, the man page assumes a priori knowledge of whatever 
| "termcap" is, so it's not very helpful.

termcap is the "TERMinal CAPability" database.  It lists the
capabilities and control characters for a variety of terminals.
(n)curses and readline (among others) use this to sanely handle the
wide variety of terminals and terminal emulators out there.  The
termcap db tells the app what characters/bytes to send to the terminal
to make the cursor and screen behave the way it wants.

| And I believe my readline library is /sw/include/readline (if the /sw/ 
| dir looks unfamiliar, it's the equivalent of /usr/local/ used by Fink, 
| the Unix ported package management app for Mac OS X).

The .h is the "include" file.  It is C source that is required for
compiling anything that uses the library.  The .so file is the "shared
library" file.  It is the already-compiled implementation of the
library.  The app (python in your case) will be dynamically linked
against that .so when it runs.

Stuff in /usr/share is typically just arbitrary data the app/lib uses
as it runs.

| >Do you have sshd running on your system?  (if so you can give someone
| >else shell access and they can work with the system to get it built)
| 
| Well... one can't be too paranoid when it comes to their system can 
| they... 

Not usually :-).

| I don't normally run this or many other services, and to be honest,
| while I'd like to get readline up and running, I'm note quite
| desperate enough to do it this way... :)

HTH,
-D

-- 

The teaching of the wise is a fountain of life,
turning a man from the snares of death.
        Proverbs 13:14




From ACrane@computer2000.co.uk  Thu Apr 18 09:18:56 2002
From: ACrane@computer2000.co.uk (Crane, Adam)
Date: Thu, 18 Apr 2002 09:18:56 +0100
Subject: [Tutor] Storing Info
Message-ID: <0A45A5A5BE1BD6118C4100805FE64FF24662A1@tdukbasmail01.computer2000.co.uk>

You're right :)  I wrote this code pretty quickly.  When I got home and got
a chance to look over it again I made a few minor changes.


print "Notes Program."
print "Type in null if you do not wish to add a note."

notes = raw_input("Enter a note/Reminder:")
while notes == "":
	print "That's a rather short note!"
	notes = raw_input("Enter a note/Reminder:")
while notes == "null":
	print "No note has been added"
	break

Thanks to all that helped, but I'll probably be putting this project on hold
for the moment.  It's a little to advanced for someone who's only been using
Python for a week :)  Ah well, back to my lovely math programs....

Adam

-----Original Message-----
From: alan.gauld@bt.com [mailto:alan.gauld@bt.com]
Sent: 17 April 2002 18:13
To: Crane, Adam; tutor@python.org
Subject: RE: [Tutor] Storing Info


> print "Notes Program."
> print "Type in "null" if you do not wish to add a note."

You have embeddeed quotes within quotes. 
You need to use single quotes on the outside...

> 
> notes = raw_input("Enter a note/Reminder:")
> while notes <= "":

Are you sure you mean <= ie less than or equal?
I suspect that should be == for equals.

> 	print "That's a rather short note!"
> 	notes = raw_input("Enter a note/Reminder:")
> if notes == "null"
> 	break

The if claess needs to be indented to the same level 
as the notes= line, otherwise its seen by python as 
being outside the loop.

> starting to think I'm in way over my head.  

No, you are pretty close.

> I was thinking maybe I'd have to import the info, 
> or something similar (I have no idea)

No you are reading it from the user.
Of course in the real world you probably want to store 
the notes in a file or something but that can wait till 
later ;-)

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.



From pythontutor@venix.com  Thu Apr 18 13:29:25 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Thu, 18 Apr 2002 08:29:25 -0400
Subject: [Tutor] working with data in a database...
References: <AF020C5FC551DD43A4958A679EA16A15028E2398@abbott.lith.com>
Message-ID: <3CBEBC25.7070201@venix.com>

(Ideas here were lifted from Hammon & Robinson as well as Norvig)
After executing a cursor:
	self._datanames = [info[0] for info in cursor.description]
	self._datarows = list(cursor.fetchall())
	self._datacols = zip(*self._datarows)
Assuming that your thousand row fits easily into memory, this gives you
access to your data by row and by column.  It is easy to find the
sum, max, min or whatever for any column.  Any ancillary routines for
your needs should be easy to write.

Israel Evans wrote:

>  
> 
> I'm currently trying to work with a small to middling amount of data ( 
> about a thousand rows or so ),  and I'm wondering about the best approach.
> 
> It seems that to analyze, compare, and otherwise play around with the 
> data, it would be easier just to extract it all out of the database and 
> manipulate a couple of instances of various classes.  Playing with 
> strings, tuples, lists and dicts makes a lot of sense to me right now 
> and my SQL skills leave something to be desired.  Though I realize that 
> I could take a definite performance hit were my data set to grow by any 
> substantial amount and that by going around the database, I'm neglecting 
> a very valuable tool.  I'm just new enough at this that I don't really 
> see how best to proceed.
> 
>  
> 
> Are there any resources you database masters out there cherish and 
> wouldn't leave the house without?  How you chosen to deal with data 
> housed in databases?  What are your favorite methods?  Any hints, 
> suggestions or random musings are welcome...
> 
>  
> 
> Thanks,
> 
>  
> 
>  
> 
>  
> 
> ~Israel~
> 
>  
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From alan.gauld@bt.com  Thu Apr 18 17:30:17 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 18 Apr 2002 17:30:17 +0100
Subject: [Tutor] A style question
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C561@mbtlipnt02.btlabs.bt.co.uk>

> Is there a way to reduce the number of lines needed 

> output.write("Number of lines: %s\n" % str(linecount))
>     output.write("Total word count: %s\n" % str(wordcount))
>     output.write("Total character count: %s\n\n"% str(charcount))
>     for word in keyList:
          strOut = "word: %15s,\toccurences: %d\n" % (word,occurences[word])
          output.write(strOut)

Notes: 
%15s -> a string occupying 15 spaces(makes it all line up)
\t -> tab
%d prints a number, no need for str()

Any better?

Alan G.



From python@rcn.com  Thu Apr 18 18:09:54 2002
From: python@rcn.com (Raymond Hettinger)
Date: Thu, 18 Apr 2002 13:09:54 -0400
Subject: [Tutor] A style question
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C561@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <001e01c1e6fb$dcfe07e0$1af8a4d8@othello>

> > Is there a way to reduce the number of lines needed
>
> > output.write("Number of lines: %s\n" % str(linecount))
> >     output.write("Total word count: %s\n" % str(wordcount))
> >     output.write("Total character count: %s\n\n"% str(charcount))

The lines can be combined and the str() conversion isn't necessary if you
use %d instead of %s:

output.write( 'Number of lines: %d\nTotal word count: %d\n Total character
count: %d\n\n' % (linecount, wordcount, charcount) )


> >     for word in keyList:
>           strOut = "word: %15s,\toccurences: %d\n" %
(word,occurences[word])
>           output.write(strOut)

Looping over .items() lets you get the word and the count in one lookup and
the tuple can be used to feed the formatting operator:

for wordcountpair in occurences.items():
     output.write( 'word: %15s,\t occurences: %d\n' % wordcountpair )


Using a list comprehension lets you do the output with writelines:

output.writelines(['word: %15s,\t occurences: %d' % pair for pair in
occurences.items()]

>
> Notes:
> %15s -> a string occupying 15 spaces(makes it all line up)
> \t -> tab
> %d prints a number, no need for str()
>
> Any better?

Removing the 15s and \t makes it longer and, in my book, not as clear.


BTW,  run a spell-check on 'occurences' ;)


Raymond Hettinger




From pythontutor@venix.com  Thu Apr 18 19:09:15 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Thu, 18 Apr 2002 14:09:15 -0400
Subject: [Tutor] Python Programming Patterns by Thomas Christopher
Message-ID: <3CBF0BCB.8010104@venix.com>

I have been looking up more topics in this book lately and am impressed
with the code examples and general level of discussion.  Issues are
covered concisely, but with enough depth.  The code examples are
very good.

The book is targeted at experienced programmers.
-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From kalle@gnupung.net  Thu Apr 18 19:38:03 2002
From: kalle@gnupung.net (Kalle Svensson)
Date: Thu, 18 Apr 2002 20:38:03 +0200
Subject: [Tutor] A style question
In-Reply-To: <001e01c1e6fb$dcfe07e0$1af8a4d8@othello>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C561@mbtlipnt02.btlabs.bt.co.uk> <001e01c1e6fb$dcfe07e0$1af8a4d8@othello>
Message-ID: <20020418183802.GA3758@i92.ryd.student.liu.se>

[Raymond Hettinger]
> The lines can be combined and the str() conversion isn't necessary
> if you use %d instead of %s:

You can use %s as well:
>>> "%s %d" % (5,5)
'5 5'

Med utmärkt högaktning,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.



From alex@gabuzomeu.net  Thu Apr 18 23:19:59 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 19 Apr 2002 00:19:59 +0200
Subject: [Tutor] Word-by-word diff in Python
Message-ID: <4.3.2.7.2.20020418234651.00c5b940@pop3.norton.antivirus>

Hello,


I'm looking for a word-by-word diff module / class in Python. I came across 
this Perl script; this is basically what I mean:

Main page: http://mike-labs.com/wd2h/
Perl script: http://mike-labs.com/wd2h/wd2h.html
Example output: http://mike-labs.com/wd2h/diff.htm

I found a diff2html utility (written in Python, 
http://diff2html.tuxfamily.org/), but it's line-based and it uses the diff 
utility. I rather use a pure-python, 2.0 compatible solution if possible:

Any idea?


Thanks.

Alexandre




From phthenry@earthlink.net  Thu Apr 18 23:42:46 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Thu, 18 Apr 2002 18:42:46 -0400
Subject: [Tutor] interacting with shell
Message-ID: <20020418184245.B11174@localhost.localdomain>

I am wondering how (of if) you interact with shell commands in
python. For example, in perl you can assign a variable to the
output from a command line. (I am using linux.)

$date = `date`

The string between the backslashes gets passed to the shell.

In python, I see you can use the command

os.system('date')

But can you assign this to a variable? 

Here is another example. I have written a small script in perl to
backup my files. I use perl code to determine what type of backup
I want to do, and store this value in the $backup variable. I
can then pass this to the shell with a command like this. 

`find /bin -ctime -$backup \! -type d`

Perl knows to change the variable $backup to the value stored in
it and then passes it to the shell.

I am hoping you can do this in python. If not, then I can see
where I would be somewhat limited in python.

Thanks!

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From dyoo@hkn.eecs.berkeley.edu  Fri Apr 19 04:29:38 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 18 Apr 2002 20:29:38 -0700 (PDT)
Subject: [Tutor] Word-by-word diff in Python
In-Reply-To: <4.3.2.7.2.20020418234651.00c5b940@pop3.norton.antivirus>
Message-ID: <Pine.LNX.4.44.0204182013570.24717-100000@hkn.eecs.berkeley.edu>


> I'm looking for a word-by-word diff module / class in Python. I came
> across this Perl script; this is basically what I mean:
>
> Main page: http://mike-labs.com/wd2h/
> Perl script: http://mike-labs.com/wd2h/wd2h.html
> Example output: http://mike-labs.com/wd2h/diff.htm

Interesting!  Hmmm... if the indentation or formatting is significant, we
could transform a line-by-line diff utility into a word-by-word by turning
the newlines into some sort of sentinel "NEWLINE"  character.

We could then apply a string.split() to break the lines into individual
words.  Python comes with a standard library module called "difflib":

    http://www.python.org/doc/current/lib/module-difflib.html

that can be used to find differences between two texts.  Here's an
example:


###
>>> revision_1 = """Today, a generation raised in the shadows of the Cold
... War assumes new responsibilities in a world warmed by the sunshine of
... freedom""".split()
>>> revision_2 = """Today, a person raised in the shadows of the Cold War
... assumes new responsibilities in a world warmed by the sunshine of
... freedom""".split()
>>> difflib.ndiff(revision_1, revision_2)
<generator object at 0x81641b8>
>>> diff = difflib.ndiff(revision_1, revision_2)
>>> diff.next()
'  Today,'
>>> diff.next()
'  a'
>>> diff.next()
'- generation'
###

Note that what gets returned is an generator, which is a Python 2.2 style
iterator that allows us to pull things from it one at a time if we use its
"next()" method.  Useful if we want to conserve memory, but not quite so
useful if we want it all at once.


To grab the whole diff at once, let's convince Python to give it to us as
a list:

###
>>> results = list(difflib.ndiff(revision_1, revision_2))
>>> results
['  Today,', '  a', '- generation', '+ person', '  raised', '  in', '
the', '  shadows', '  of', '  the', '  Cold', '  War', '  assumes', '
new', '  responsibilities', '  in', '  a', '  world', '  warmed', '  by',
'  the', '  sunshine', '  of', '  freedom']
###


And the output here can be modified to look like a nice HTML formatted
text with strikeouts and everything.  *grin*


Hope this helps!




From imcmeans@shaw.ca  Fri Apr 19 04:34:36 2002
From: imcmeans@shaw.ca (Ian!)
Date: Thu, 18 Apr 2002 20:34:36 -0700
Subject: [Tutor] is vs. ==
References: <20020418160003.31818.22465.Mailman@mail.python.org>
Message-ID: <000701c1e753$2164cac0$da494e18@cr536745a>

What's the difference between "is" and "=="? I always assumed they were the
same.

>>> __name__ == '__main__'
1
>>> __name__ is '__main__'
0
>>>




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 19 04:41:32 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 18 Apr 2002 20:41:32 -0700 (PDT)
Subject: [Tutor] interacting with shell
In-Reply-To: <20020418184245.B11174@localhost.localdomain>
Message-ID: <Pine.LNX.4.44.0204182030050.24717-100000@hkn.eecs.berkeley.edu>


On Thu, 18 Apr 2002, Paul Tremblay wrote:

> I am wondering how (of if) you interact with shell commands in
> python. For example, in perl you can assign a variable to the
> output from a command line. (I am using linux.)
>
> $date = `date`
>
> The string between the backslashes gets passed to the shell.
>
> In python, I see you can use the command
>
> os.system('date')
>
> But can you assign this to a variable?


Hi Paul,

Not in the way we'd expect, since os.system() returns the "errorlevel" or
exit code of the command we execute.  However, there's a separate
process-spawning function called os.popen()  that's more like what you're
looking for:

###
myfile = os.popen('date')
###


What it returns back is a file-like-object, so you can either pass it off
to some other function, or just suck all the string out of it with a
read():

###
print os.popen('date').read()
###


os.popen() returns a file because it's possible that the shell command
could give us a huge huge string, so the file interface allows us to read
chunks in at a time to conserve memory if we wanted to.

There's more information on os.popen() here:

    http://www.python.org/doc/lib/os-newstreams.html




> Here is another example. I have written a small script in perl to
> backup my files. I use perl code to determine what type of backup
> I want to do, and store this value in the $backup variable. I
> can then pass this to the shell with a command like this.
>
> `find /bin -ctime -$backup \! -type d`
>
> Perl knows to change the variable $backup to the value stored in
> it and then passes it to the shell.
>
> I am hoping you can do this in python. If not, then I can see where I
> would be somewhat limited in python.

We can do it similarly, but it takes just a wee bit more to get Perl-style
"string interpolation" to fire off.  Here's a quick translation of the
above Perl code to Python:

###
>>> backup = "some backup file"
>>> command = "find /bin -ctime -%(backup)s \! -type d" % vars()
>>> command
'find /bin -ctime -some backup file \\! -type d'
###

Python names this concept "String Formatting", and there's more
information about it here:

    http://www.python.org/doc/current/lib/typesseq-strings.html

It's more explicit in that we're explicitely using the string formatting
operator '%'.  Python's string formatting is also a bit more flexible
because it takes in a dictionary ("hashtable") for its source of data, so
we could potentially feed it something other than our list of accessible
var()iables:

###
>>> command = "find /bin -ctime -%(backup)s \! -type d"
>>> command % {'backup' : 'on tape'}
'find /bin -ctime -on tape \\! -type d'
>>> command % {'backup' : 'time'}
'find /bin -ctime -time \\! -type d'
###



If you have more questions, please feel free to ask.  And welcome aboard!




From shalehperry@attbi.com  Fri Apr 19 04:43:12 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 18 Apr 2002 20:43:12 -0700 (PDT)
Subject: [Tutor] is vs. ==
In-Reply-To: <000701c1e753$2164cac0$da494e18@cr536745a>
Message-ID: <XFMail.20020418204312.shalehperry@attbi.com>

On 19-Apr-2002 Ian! wrote:
> What's the difference between "is" and "=="? I always assumed they were the
> same.
> 
>>>> __name__ == '__main__'
> 1
>>>> __name__ is '__main__'
> 0
>>>>


'==' asks 'is this value equivalent to this other one'
'is' asks 'is this item the same item as this other one'




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 19 04:54:43 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 18 Apr 2002 20:54:43 -0700 (PDT)
Subject: [Tutor] is vs. ==
In-Reply-To: <000701c1e753$2164cac0$da494e18@cr536745a>
Message-ID: <Pine.LNX.4.44.0204182044000.24717-100000@hkn.eecs.berkeley.edu>


On Thu, 18 Apr 2002, Ian! wrote:

> What's the difference between "is" and "=="? I always assumed they were
> the same.
>
> >>> __name__ == '__main__'
> 1
> >>> __name__ is '__main__'
> 0

Slightly different.


'==' can be thought of as "value equality", that is, if two things look
the same, == should return a true value.  (For those with a Java
background, Python's == is actually doing something akin to an equals()
method.)


'is' can be thought of as 'object identity', that is, if the two things
actually are the same object.


The concept is a little subtle, so let's use an example:

###
>>> my_name = "danny"
>>> your_name = "ian"
>>> my_name == your_name
0
###


My name and your name are different.  But what about this?

###
>>> my_name[1:3] == your_name[1:3]
1
###

Our names share something in common.  *grin* We'd say that my_name[1:3]
looks the same as your_name[1:3], so they're "equal" in some sense that's
captured by the idea of '=='.  However, the sources of those strings are
different, and we can see this when we check against object identity:

###
>>> my_name[1:3] is your_name[1:3]
0
###

'is' allows us to make the distinction if the system is keeping track of
two things that just look alike, or are actually the same thing.  Why this
is useful isn't too obvious for strings; it's more of an issue when one is
dealing with classes or mutable data structures like lists.

For now, you probably want to use '==' when you want to compare two things
for equality.  When you learn about data structures, then 'is' will seem
more relevant.


Please feel free to ask more questions!  Good luck.




From GREGDRENNAN778@msn.com  Fri Apr 19 06:48:33 2002
From: GREGDRENNAN778@msn.com (GREGORY DRENNAN)
Date: Fri, 19 Apr 2002 01:48:33 -0400
Subject: [Tutor] Re: Interpreter
Message-ID: <OE117Faatao8KK8ZtP000029a04@hotmail.com>

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

I have been out of circulation for a few years, and was wondering where d=
o I start? Do I need a interactive interpreter, and if I do where can I g=
et one?

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

<HTML><BODY STYLE=3D"font:10pt verdana; border:none;"><DIV>I have been ou=
t of circulation for a few years, and was wondering where do I start? Do =
I need a interactive interpreter, and if I do where can I get one?<BR><BR=
></DIV></BODY></HTML>

------=_NextPart_001_0003_01C1E744.50721250--



From urnerk@qwest.net  Fri Apr 19 05:05:59 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 19 Apr 2002 00:05:59 -0400
Subject: [Tutor] interacting with shell
In-Reply-To: <20020418184245.B11174@localhost.localdomain>
References: <20020418184245.B11174@localhost.localdomain>
Message-ID: <E16ySOm-0000Dy-00@mail.python.org>

On Thursday 18 April 2002 06:42 pm, Paul Tremblay wrote:
> I am wondering how (of if) you interact with shell commands in
> python. 

You can definitely do this.  Probably the easiest thing is
to construct the final form of the command using string
substitution Python's way, and write this to the shell.
The popen command returns the shell's output as if from
a file.  Example:

 Python 2.2 (#1, Feb 24 2002, 16:21:58)
 [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux-i386
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import os
 >>> f = os.popen("echo $PATH")
 >>> f.readlines() 
 ['/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/usr/games:/home/kirby/bin:
 /usr/java/j2re1.4.0/bin:.\n']
 >>> f.close()

Another example:

 >>> f=os.popen('date; ls *.sh')
 >>> f.readlines()
 ['Fri Apr 19 00:00:31 EDT 2002\n', 'repl.sh\n', 'testfermat.sh\n']
 >>> f.close()

And one more:

 >>> f = os.popen("joe=`expr 2 + 2`; echo $joe")  # using back tics
 >>> f.readlines()  # echoes joe
 ['4\n']  
 >>> f.close()

Anyway, I think you get the idea.  

Kirby



From urnerk@qwest.net  Fri Apr 19 05:19:46 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 19 Apr 2002 00:19:46 -0400
Subject: [Tutor] Re: Interpreter
In-Reply-To: <OE117Faatao8KK8ZtP000029a04@hotmail.com>
References: <OE117Faatao8KK8ZtP000029a04@hotmail.com>
Message-ID: <E16ySc7-0001fX-00@mail.python.org>

On Friday 19 April 2002 01:48 am, GREGORY DRENNAN wrote:
> I have been out of circulation for a few years, and was wondering where do
> I start? Do I need a interactive interpreter, and if I do where can I get
> one?

If you've downloaded and installed Python, you already have
an interactive interpreter -- Python is interactive out of the box.

If you're on Windows, open a DOS box, cd to the python 
directory, and enter python.  You'll get a >>> (prompt) and 
there can enter 2 + 2 and get back 4.  You're on your way!

If you're on Linux (or Mac OSX?), open a term window and do
the same thing (probably python is in /usr/bin which is part of
your path, so you don't have to monkey with your PATH just
now).

Now, if you want a GUI front end (vs. a DOS box or tty-like window),
then you've got IDLE right out of the box (part of the standard 
Python download from www.python.org).  This requires installing Tk, 
which is part of what the Windows installer does for ya.  I think
with Linux you may have to dig /idle out of a tools subdirectory
and stick it in /usr/lib/python2.2/site-packages or wherever your
Python library lives (that's if you compile your own).

IDLE is nice because it gives you a text editor with syntax coloring,
and call tips when you start to enter a function (it tells you about
what arguments it expects).  If you're on Windows, then the 
ActiveState download of Python is worth looking into.  You get
another IDE (interactive development environment) called PythonWin.

A lot of people on *nix (Unix or Linux) use vi (vim, gvim) or emacs
as a text editor, and the regular Python shell in an X-window or
tty session.  You can run gvim (a graphical VI) in Windows too, 
but the DOS box Python shell is less workable in some ways --
I recommend starting with the GUI (IDLE in particular, since it 
comes with plain vanilla Python).  PyCrust is another IDE (check
SourceForge for most recent).  By all means use the Python shell
-- that's a great way to experiment with syntax, write short 
programs (you can do it right at the command line) and get 
immediate feedback.

How to get IDLE working on a Mac I'm not so sure, even though I
did it once (didn't have syntax coloring).  That was on a pre OSX
iMac though.  I also got it running in BeOS once, for kicks (using
the free BeOS that runs in a Windows subdirectory).

Kirby



From GREGDRENNAN778@msn.com  Fri Apr 19 06:22:35 2002
From: GREGDRENNAN778@msn.com (GREGORY DRENNAN)
Date: Fri, 19 Apr 2002 01:22:35 -0400
Subject: [Tutor] Interactive interpreter
Message-ID: <OE6clNhgoFKnQBrkyTw0002a9be@hotmail.com>

------=_NextPart_001_0001_01C1E740.B0002FD0
Content-Type: text/plain; charset="iso-8859-1"

I was wondering where I could find an interperter?
------=_NextPart_001_0001_01C1E740.B0002FD0
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<HTML><BODY STYLE=3D"font:10pt verdana; border:none;"><DIV>I was wonderin=
g where I could find an interperter?<BR><BR></DIV></BODY></HTML>

------=_NextPart_001_0001_01C1E740.B0002FD0--



From ACrane@computer2000.co.uk  Fri Apr 19 09:17:42 2002
From: ACrane@computer2000.co.uk (Crane, Adam)
Date: Fri, 19 Apr 2002 09:17:42 +0100
Subject: [Tutor] A question about input/raw_input
Message-ID: <0A45A5A5BE1BD6118C4100805FE64FF24662B3@tdukbasmail01.computer2000.co.uk>

I was just wondering, what is the difference between the two?  I know that
'input' is specifically for numbers, while 'raw_input' is for words and
numbers (well that's what I've come to understand).

But, if 'raw_input' can be used for words and numbers, then why is there an
'input' in the first place?  When writing programs, I often find myself
using 'raw_input' for numbers, because if I use input, and enter a word, the
program brings up an error message.  So I find it a lot easier to just use
'raw_input'.

I'm confused....more than usual I mean...

Adam
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.



From glingl@aon.at  Fri Apr 19 09:48:06 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Apr 2002 10:48:06 +0200
Subject: [Tutor] A question about input/raw_input
References: <0A45A5A5BE1BD6118C4100805FE64FF24662B3@tdukbasmail01.computer2000.co.uk>
Message-ID: <001001c1e77e$ed1b2800$1664a8c0@mega>

From: "Crane, Adam" <ACrane@computer2000.co.uk>
To: <tutor@python.org>


> I was just wondering, what is the difference between the two?  I know that
> 'input' is specifically for numbers, while 'raw_input' is for words and
> numbers (well that's what I've come to understand).
>

That's only half of the truth. In fact raw_input() accepts only strings as
input.
If you need numbers, for instance for some computations to perform with
them,
you have to convert the strings into numbers using the int(), float()
or similar functions.

On the other hand, input() accepts numbers, but not only numbers.
input() accepts every legal Python expression ( and mere numbers are
legal Python exprssions ).

>>> a = input('gimme an expression: ')
gimme an expression: 3
>>> input('gimme an expression: ')
gimme an expression: 3
3
>>> input('gimme an expression: ')
gimme an expression: 3+4
7
>>> input('gimme an expression: ')
gimme an expression: 'Wow!'         # Remark: you need the quotation marks!
'Wow!'
>>> var = input('gimme an expression: ')  # store the result of input()
gimme an expression: 'ok!'
>>> input('gimme an expression: ')
gimme an expression: var                  # !! A variable is also a legal
Python expression
'ok!'
>>> input('gimme an expression: ')
gimme an expression: nonVarName           # but a name without quotation
marks is not
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in ?
    input('gimme an expression: ')
  File "<string>", line 0, in ?
NameError: name 'nonVarName' is not defined      # Sorry!
>>> input('gimme an expression: ')        # Some more examples
gimme an expression: 'Wow' + ' or not Wow!'
'Wow or not Wow!'
>>> 'Wow' * 5
'WowWowWowWowWow'
>>> input('gimme an expression: ')
gimme an expression: [1,2]*3
[1, 2, 1, 2, 1, 2]
>>>

So, shortly, input() is for people who know Python and
who know what they ar going to do.

> But, if 'raw_input' can be used for words and numbers, then why is there
an
> 'input' in the first place?  When writing programs, I often find myself
> using 'raw_input' for numbers, because if I use input, and enter a word,
the
> program brings up an error message.  So I find it a lot easier to just use
> 'raw_input'.

Consequently this is - in my opinion - normally a good strategy.

>
> I'm confused....more than usual I mean...
>

I hope no more ...

Gregor




From glingl@aon.at  Fri Apr 19 09:53:44 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Apr 2002 10:53:44 +0200
Subject: [Tutor] A question about input/raw_input
References: <0A45A5A5BE1BD6118C4100805FE64FF24662B3@tdukbasmail01.computer2000.co.uk>
Message-ID: <001c01c1e77f$b6574500$1664a8c0@mega>

Forgot to mention someting like:

     input = eval + raw_input

I mean:

>>> def my_input(x):
 return eval(raw_input(x))

>>> my_input('What? ')
What? 3+4
7
>>>

Gregor 




From ACrane@computer2000.co.uk  Fri Apr 19 09:57:58 2002
From: ACrane@computer2000.co.uk (Crane, Adam)
Date: Fri, 19 Apr 2002 09:57:58 +0100
Subject: [Tutor] A question about input/raw_input
Message-ID: <0A45A5A5BE1BD6118C4100805FE64FF24662B7@tdukbasmail01.computer2000.co.uk>

Ahh, I see.  Thanks for clearing that up.  I didn't know input was so
useful.  

One more question.  How do I stop python bringing up an error message if a
word is entered to input without quotes?

Thanks again for explaining this to me.

Adam
-----Original Message-----
From: Gregor Lingl [mailto:glingl@aon.at]
Sent: 19 April 2002 09:48
To: Crane, Adam; tutor@python.org
Subject: Re: [Tutor] A question about input/raw_input


From: "Crane, Adam" <ACrane@computer2000.co.uk>
To: <tutor@python.org>


> I was just wondering, what is the difference between the two?  I know that
> 'input' is specifically for numbers, while 'raw_input' is for words and
> numbers (well that's what I've come to understand).
>

That's only half of the truth. In fact raw_input() accepts only strings as
input.
If you need numbers, for instance for some computations to perform with
them,
you have to convert the strings into numbers using the int(), float()
or similar functions.

On the other hand, input() accepts numbers, but not only numbers.
input() accepts every legal Python expression ( and mere numbers are
legal Python exprssions ).

>>> a = input('gimme an expression: ')
gimme an expression: 3
>>> input('gimme an expression: ')
gimme an expression: 3
3
>>> input('gimme an expression: ')
gimme an expression: 3+4
7
>>> input('gimme an expression: ')
gimme an expression: 'Wow!'         # Remark: you need the quotation marks!
'Wow!'
>>> var = input('gimme an expression: ')  # store the result of input()
gimme an expression: 'ok!'
>>> input('gimme an expression: ')
gimme an expression: var                  # !! A variable is also a legal
Python expression
'ok!'
>>> input('gimme an expression: ')
gimme an expression: nonVarName           # but a name without quotation
marks is not
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in ?
    input('gimme an expression: ')
  File "<string>", line 0, in ?
NameError: name 'nonVarName' is not defined      # Sorry!
>>> input('gimme an expression: ')        # Some more examples
gimme an expression: 'Wow' + ' or not Wow!'
'Wow or not Wow!'
>>> 'Wow' * 5
'WowWowWowWowWow'
>>> input('gimme an expression: ')
gimme an expression: [1,2]*3
[1, 2, 1, 2, 1, 2]
>>>

So, shortly, input() is for people who know Python and
who know what they ar going to do.

> But, if 'raw_input' can be used for words and numbers, then why is there
an
> 'input' in the first place?  When writing programs, I often find myself
> using 'raw_input' for numbers, because if I use input, and enter a word,
the
> program brings up an error message.  So I find it a lot easier to just use
> 'raw_input'.

Consequently this is - in my opinion - normally a good strategy.

>
> I'm confused....more than usual I mean...
>

I hope no more ...

Gregor
The contents of this e-mail are intended for the named addressee only. It
contains information which may be confidential and which may also be
privileged. Unless you are the named addressee (or authorised to receive for
the addressee) you may not copy or use it, or disclose it to anyone else. If
you received it in error please notify us immediately and then destroy it.
The information, views and comments within this communication are those of
the sender and not necessarily those of Computer 2000.



From lha2@columbia.edu  Fri Apr 19 10:25:51 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Fri, 19 Apr 2002 05:25:51 -0400
Subject: [Tutor] is vs. ==
References: <20020418160003.31818.22465.Mailman@mail.python.org> <000701c1e753$2164cac0$da494e18@cr536745a>
Message-ID: <3CBFE29F.D85E4FE6@mail.verizon.net>

"Ian!" wrote:
> 
> What's the difference between "is" and "=="? I always assumed they were the
> same.
> 
> >>> __name__ == '__main__'
> 1
> >>> __name__ is '__main__'
> 0
> >>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

One last thing that I don't think has been addressed yet--one item "is"
another iff they have the same id #. Two integers less than 100, or two
strings (probably subject to some restriction), are likely to have the
same identity and so "is" each other. But for an example of two items
that are distinct but of equal value,

>>> thing1 = ['c','a','t']
>>> thing2 = ['c','a','t']
>>> id(thing1)
11119696
>>> id(thing2)
11121936
>>> thing1 == thing2
1
>>> thing1 is thing2
0

however, if you

>>> thing2 = thing1

then

>>> thing2 is thing1
1

and using list methods to modify will end up also modifying the other
(since they are the same object, with the same identity).



From lha2@columbia.edu  Fri Apr 19 10:28:06 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Fri, 19 Apr 2002 05:28:06 -0400
Subject: [Tutor] Interactive interpreter
References: <OE6clNhgoFKnQBrkyTw0002a9be@hotmail.com>
Message-ID: <3CBFE326.5030A6F6@mail.verizon.net>

>I was wondering where I could find an interperter?

http://www.python.org/download/



From alex@gabuzomeu.net  Fri Apr 19 10:27:41 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Fri, 19 Apr 2002 11:27:41 +0200
Subject: [Tutor] Word-by-word diff in Python
In-Reply-To: <Pine.LNX.4.44.0204182013570.24717-100000@hkn.eecs.berkeley
 .edu>
References: <4.3.2.7.2.20020418234651.00c5b940@pop3.norton.antivirus>
Message-ID: <4.3.2.7.2.20020419103915.00bb8100@pop3.norton.antivirus>

Hi Danny,


At 20:29 18/04/2002 -0700, Danny Yoo wrote:
>Interesting!  Hmmm... if the indentation or formatting is significant, we
>could transform a line-by-line diff utility into a word-by-word by turning
>the newlines into some sort of sentinel "NEWLINE"  character.

Yes, thanks; that's the key idea. I had toyed with difflib but I fed it two 
strings instead of word lists; hence it spat back a character-based diff.

>We could then apply a string.split() to break the lines into individual
>words.  Python comes with a standard library module called "difflib":
>
>     http://www.python.org/doc/current/lib/module-difflib.html

One problem I had with this module is that it was added to the standard 
library in 2.1 and 2.2, whereas I try to make my app compatible with Python 
2.0.

I found a partial backported version in ViewCVS; it features the 
SequenceMatcher class, but the ndiff class is not included.

> >>> difflib.ndiff(revision_1, revision_2)
><generator object at 0x81641b8>
> >>> diff = difflib.ndiff(revision_1, revision_2)

>To grab the whole diff at once, let's convince Python to give it to us as
>a list:

> >>> results = list(difflib.ndiff(revision_1, revision_2))

>And the output here can be modified to look like a nice HTML formatted
>text with strikeouts and everything.  *grin*

Yes, that's good. I found an example that used the SequenceMatcher class 
directly, though it's lower-level. Here is a test implementation:

##
from difflib import SequenceMatcher

class TextDiff:
     """Create diffs of text snippets."""

     def __init__(self, source, target):
         """source = source text - target = target text"""
         self.nl = "<NL>"
         self.delTag = "<span class='deleted'>%s</span>"
         self.insTag = "<span class='inserted'>%s</span>"
         self.source = source.replace("\n", "\n%s" % self.nl).split()
         self.target = target.replace("\n", "\n%s" % self.nl).split()
         self.deleteCount, self.insertCount, self.replaceCount = 0, 0, 0
         self.diffText = None
         self.cruncher = SequenceMatcher(None, self.source,
                                         self.target)
         self._buildDiff()

     def _buildDiff(self):
         """Create a tagged diff."""
         outputList = []
         for tag, alo, ahi, blo, bhi in self.cruncher.get_opcodes():
             if tag == 'replace':
                 # Text replaced = deletion + insertion
                 outputList.append(self.delTag % " 
".join(self.source[alo:ahi]))
                 outputList.append(self.insTag % " 
".join(self.target[blo:bhi]))
                 self.replaceCount += 1
             elif tag == 'delete':
                 # Text deleted
                 outputList.append(self.delTag % " 
".join(self.source[alo:ahi]))
                 self.deleteCount += 1
             elif tag == 'insert':
                 # Text inserted
                 outputList.append(self.insTag % " 
".join(self.target[blo:bhi]))
                 self.insertCount += 1
             elif tag == 'equal':
                 # No change
                 outputList.append(" ".join(self.source[alo:ahi]))
         diffText = " ".join(outputList)
         diffText = " ".join(diffText.split())
         self.diffText = diffText.replace(self.nl, "\n")

     def getStats(self):
         "Return a tuple of stat values."
         return (self.insertCount, self.deleteCount, self.replaceCount)

     def getDiff(self):
         "Return the diff text."
         return self.diffText

if __name__ == "__main__":
     ch1 = """Today, a generation raised in the shadows of the Cold
     War assumes new responsibilities in a world warmed by the sunshine of
     freedom"""

     ch2 = """Today, pythonistas raised in the shadows of the Cold
     War assumes responsibilities in a world warmed by the sunshine of
     spam and freedom"""

     differ = TextDiff(ch1, ch2)

     print "%i insertion(s), %i deletion(s), %i replacement(s)" % 
differ.getStats()
     print differ.getDiff()

1 insertion(s), 1 deletion(s), 1 replacement(s)
Today, a <span class='deleted'>generation</span> <span 
class='inserted'>pythonista</span> raised in the shadows of the Cold
  War assumes <span class='deleted'>new</span> responsibilities in a world 
warmed by the sunshine of
  <span class='inserted'>spam and</span> freedom
##


Cheers.

Alexandre




From glingl@aon.at  Fri Apr 19 12:03:07 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 19 Apr 2002 13:03:07 +0200
Subject: [Tutor] A question about input/raw_input
References: <0A45A5A5BE1BD6118C4100805FE64FF24662B7@tdukbasmail01.computer2000.co.uk>
Message-ID: <3CBFF96B.4298626B@rg16.asn-wien.ac.at>



> Ahh, I see.  Thanks for clearing that up.  I didn't know input was so
> useful.
>
> One more question.  How do I stop python bringing up an error message if a
> word is entered to input without quotes?
>

Try:

>>> try:
       print input("Gimme a cake: ")
except:
       print "Something is going wrong an you don't know what it ihihis!"


Gimme a cake: cake
Something is going wrong an you don't know what it ihihis!
>>>

Sorry for not having time for more explanations (during a lesson here at my
school)

Gregor

"Crane, Adam" schrieb:



>
> Thanks again for explaining this to me.
>
> Adam
> -----Original Message-----
> From: Gregor Lingl [mailto:glingl@aon.at]
> Sent: 19 April 2002 09:48
> To: Crane, Adam; tutor@python.org
> Subject: Re: [Tutor] A question about input/raw_input
>
> From: "Crane, Adam" <ACrane@computer2000.co.uk>
> To: <tutor@python.org>
>
> > I was just wondering, what is the difference between the two?  I know that
> > 'input' is specifically for numbers, while 'raw_input' is for words and
> > numbers (well that's what I've come to understand).
> >
>
> That's only half of the truth. In fact raw_input() accepts only strings as
> input.
> If you need numbers, for instance for some computations to perform with
> them,
> you have to convert the strings into numbers using the int(), float()
> or similar functions.
>
> On the other hand, input() accepts numbers, but not only numbers.
> input() accepts every legal Python expression ( and mere numbers are
> legal Python exprssions ).
>
> >>> a = input('gimme an expression: ')
> gimme an expression: 3
> >>> input('gimme an expression: ')
> gimme an expression: 3
> 3
> >>> input('gimme an expression: ')
> gimme an expression: 3+4
> 7
> >>> input('gimme an expression: ')
> gimme an expression: 'Wow!'         # Remark: you need the quotation marks!
> 'Wow!'
> >>> var = input('gimme an expression: ')  # store the result of input()
> gimme an expression: 'ok!'
> >>> input('gimme an expression: ')
> gimme an expression: var                  # !! A variable is also a legal
> Python expression
> 'ok!'
> >>> input('gimme an expression: ')
> gimme an expression: nonVarName           # but a name without quotation
> marks is not
> Traceback (most recent call last):
>   File "<pyshell#10>", line 1, in ?
>     input('gimme an expression: ')
>   File "<string>", line 0, in ?
> NameError: name 'nonVarName' is not defined      # Sorry!
> >>> input('gimme an expression: ')        # Some more examples
> gimme an expression: 'Wow' + ' or not Wow!'
> 'Wow or not Wow!'
> >>> 'Wow' * 5
> 'WowWowWowWowWow'
> >>> input('gimme an expression: ')
> gimme an expression: [1,2]*3
> [1, 2, 1, 2, 1, 2]
> >>>
>
> So, shortly, input() is for people who know Python and
> who know what they ar going to do.
>
> > But, if 'raw_input' can be used for words and numbers, then why is there
> an
> > 'input' in the first place?  When writing programs, I often find myself
> > using 'raw_input' for numbers, because if I use input, and enter a word,
> the
> > program brings up an error message.  So I find it a lot easier to just use
> > 'raw_input'.
>
> Consequently this is - in my opinion - normally a good strategy.
>
> >
> > I'm confused....more than usual I mean...
> >
>
> I hope no more ...
>
> Gregor
> The contents of this e-mail are intended for the named addressee only. It
> contains information which may be confidential and which may also be
> privileged. Unless you are the named addressee (or authorised to receive for
> the addressee) you may not copy or use it, or disclose it to anyone else. If
> you received it in error please notify us immediately and then destroy it.
> The information, views and comments within this communication are those of
> the sender and not necessarily those of Computer 2000.




From amitsoni@softhome.net  Fri Apr 19 04:46:01 2002
From: amitsoni@softhome.net (amit soni)
Date: Fri, 19 Apr 2002 09:16:01 +0530
Subject: [Tutor] MCQs in Python
Message-ID: <00c701c1e754$bd43f0a0$010811ac@soni>

This is a multi-part message in MIME format.

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

Dear sir,

I require a set of multiple choice question test papers for my company. =
I searched a lot but could not find any.

These tests are preliminary tests for new recruitments in our company.

I require atmost 30 questions.

Could you help with me this...like any website you know that has such =
stuff.

regards,
Amit.


------=_NextPart_000_00C4_01C1E782.D33F72C0
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=3DArial size=3D2>
<DIV><FONT face=3DArial size=3D2>Dear sir,</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I require a set of multiple choice =
question test=20
papers for my company. I searched a lot but could not find =
any.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>These tests are preliminary tests for =
new=20
recruitments in our company.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I require atmost 30 =
questions.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Could you help with me this...like any =
website you=20
know that has such stuff.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>regards,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Amit.</FONT></DIV>
<DIV>&nbsp;</DIV></FONT></DIV></BODY></HTML>

------=_NextPart_000_00C4_01C1E782.D33F72C0--




From jeff@ccvcorp.com  Fri Apr 19 18:24:55 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 19 Apr 2002 10:24:55 -0700
Subject: [Tutor] A question about input/raw_input
References: <20020419160004.10032.47681.Mailman@mail.python.org>
Message-ID: <3CC052E7.9778F94E@ccvcorp.com>

>  "Crane, Adam" <ACrane@computer2000.co.uk> wrote:
>
> Ahh, I see.  Thanks for clearing that up.  I didn't know input was so
> useful.

But be *very* careful!  Python actually evaluates whatever is typed in to
input().  Which means that if the user types in a string such as, say...

    "import os; os.system('rm -s /')"

you could be in a really ugly situation.  The text given to input() is run as if
it were actual Python code in your program.  This is *very* risky -- even if
you're not worried about malicious users, there's a lot of potential to
accidentally stomp on your programs variables, or other sorts of accidental
mischief.  So don't use input() unless you *really* know what you're doing.

If you just want to have a number entered, it is *much* safer to simply use

    number = int( raw_input("Enter a number: ") )

There's currently talk on comp.lang.python about deprecating input(), and possibly
even removing it from the language, because it *looks* nice and useful, but leads
to problems as often as not.  (And if someone *really* needs that functionality,
they could still get it by using eval(raw_input()), but that makes the risks a
little bit more apparent.)

Jeff Shannon
Technician/Programmer
Credit International





From ak@silmarill.org  Fri Apr 19 19:34:05 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 19 Apr 2002 14:34:05 -0400
Subject: [Tutor] interacting with shell
In-Reply-To: <20020418184245.B11174@localhost.localdomain>
References: <20020418184245.B11174@localhost.localdomain>
Message-ID: <20020419183404.GA24853@ak.silmarill.org>

On Thu, Apr 18, 2002 at 06:42:46PM -0400, Paul Tremblay wrote:
> I am wondering how (of if) you interact with shell commands in
> python. For example, in perl you can assign a variable to the
> output from a command line. (I am using linux.)
> 
> $date = `date`
> 
> The string between the backslashes gets passed to the shell.
> 
> In python, I see you can use the command
> 
> os.system('date')
> 
> But can you assign this to a variable? 
> 
> Here is another example. I have written a small script in perl to
> backup my files. I use perl code to determine what type of backup
> I want to do, and store this value in the $backup variable. I
> can then pass this to the shell with a command like this. 
> 
> `find /bin -ctime -$backup \! -type d`
> 
> Perl knows to change the variable $backup to the value stored in
> it and then passes it to the shell.
>
os.popen("find /bin -ctime -%s \! -type d" % backup)
# %s gets replaces with value of backup variable

> 
> I am hoping you can do this in python. If not, then I can see
> where I would be somewhat limited in python.
> 
> Thanks!
> 
> Paul
> 
> -- 
> 
> ************************
> *Paul Tremblay         *
> *phthenry@earthlink.net*
> ************************
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From ak@silmarill.org  Fri Apr 19 19:43:58 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Fri, 19 Apr 2002 14:43:58 -0400
Subject: [Tutor] A question about input/raw_input
In-Reply-To: <0A45A5A5BE1BD6118C4100805FE64FF24662B7@tdukbasmail01.computer2000.co.uk>
References: <0A45A5A5BE1BD6118C4100805FE64FF24662B7@tdukbasmail01.computer2000.co.uk>
Message-ID: <20020419184358.GB24853@ak.silmarill.org>

On Fri, Apr 19, 2002 at 09:57:58AM +0100, Crane, Adam wrote:
> Ahh, I see.  Thanks for clearing that up.  I didn't know input was so
> useful.  
>
It's dangerous, too. If user makes a mistake he may delete data, or
crash the program. If you use raw_input you can check that entered data
is "valid". You can say "give me a yes or no" and then check that input
was indeed either yes or no, and if not, print error and ask again.

I think input() and raw_input() are not well named. raw_input would
be best called input() or getline(), and input should be hidden
somewhere deep in libraries, like maybe os.unprocessed_input(). It's
a fairly common thing for new users to get confused by these two
functions.

If you plan to distribute your program to users, use raw_input. In fact,
you can't go wrong by using it everywhere.


 - Andrei

[snip]

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From phthenry@earthlink.net  Fri Apr 19 20:57:37 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Fri, 19 Apr 2002 15:57:37 -0400
Subject: [Tutor] interacting with shell
In-Reply-To: <Pine.LNX.4.44.0204182030050.24717-100000@hkn.eecs.berkeley.edu>
References: <20020418184245.B11174@localhost.localdomain> <Pine.LNX.4.44.0204182030050.24717-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020419155736.E11174@localhost.localdomain>

On Thu, Apr 18, 2002 at 08:41:32PM -0700, Danny Yoo wrote:

> 
> Not in the way we'd expect, since os.system() returns the "errorlevel" or
> exit code of the command we execute.  However, there's a separate
> process-spawning function called os.popen()  that's more like what you're
> looking for:
> 

[snip]


Thanks everyone! I don't care that it takes a few more lines of code. I
need to re-write this backup script, and rather than use perl, I
figure I should use python, which I am just learning. 

I have checked out a book called *The Quick Python book* from the
library, and for some reason it didn't give very much information
on interacting with the shell. 

So far, I am really bowled over with python. It is easier to
understand than perl, it is cleaner, and it is object oriented.
This means my code will be easier to maintain. I want to parse
xml and have looked at several tutorials on doing it in perl,
and still can't quite figure it out. I have also looked at
several tutorials on python, and even though I know hardly any
python, I could pretty much understand them right off.

I'm not trying to bash perl; it is a very powerful language.
However, it seems at this point that if I had just one language
to learn, it would be python.

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From erikprice@mac.com  Fri Apr 19 22:43:58 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 19 Apr 2002 17:43:58 -0400
Subject: [Tutor] A question about input/raw_input
In-Reply-To: <3CC052E7.9778F94E@ccvcorp.com>
Message-ID: <8DCFD4ED-53DE-11D6-A27E-00039351FE6A@mac.com>

On Friday, April 19, 2002, at 01:24  PM, Jeff Shannon wrote:

> There's currently talk on comp.lang.python about deprecating input(), 
> and possibly
> even removing it from the language, because it *looks* nice and useful, 
> but leads
> to problems as often as not.  (And if someone *really* needs that 
> functionality,
> they could still get it by using eval(raw_input()), but that makes the 
> risks a
> little bit more apparent.)

So is input() really just a shortcut for eval(raw_input()) ?  There's 
really no difference between them?

In that case, it sounds like a good idea to deprecate input().  Apart 
from the danger of using it without realizing its strength (which 
doesn't seem that big a deal to me -- you should always validate input), 
it doesn't seem like this is one of those cases where it's good to have 
two different ways to do something.  eval(raw_input()) is perfectly easy 
to type -- why would anyone really even use input() ?

Thanks for the thoughts Jeff.


Erik




From gman_95@hotmail.com  Sat Apr 20 01:23:30 2002
From: gman_95@hotmail.com (Daryl Gallatin)
Date: Sat, 20 Apr 2002 00:23:30 +0000
Subject: [Tutor] HTMLParser question
Message-ID: <F1619NLX2Al4QKLLlrr00006dad@hotmail.com>

Hi, is there a good example somewhere on how to use the HTMLParser class
I would like to create a simple HTML web browser, but the simple example 
provided in the documentation doesn't give me much to work on

I have a text browser, but I want to be able to view at least Simple HTML 
pages

Is there an example someplace that I could build on.
I've looked at Grail source code, but its to complicated
I found reference to something called Dancer, but its link is bad now


Thanks

_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From ncoulter@es.com  Sat Apr 20 02:54:53 2002
From: ncoulter@es.com (ncoulter@es.com)
Date: Fri, 19 Apr 2002 19:54:53 -0600
Subject: [Tutor] Where does python look for import files
Message-ID: <1D0833CB3B1D7244B617A0DC8399C27E0EC69E@vega>

I apologize if this is documented in some obvious place, but I have =
spent all day looking for this information, and have yet to find it:

What procedure/variables does python use to search for files in import =
commands?  I see that sys.path contains a list of paths, but am not sure =
how to modify it.  My goal right now is to set up a folder =
(c:\python22\scripts) where I can create a folder tree python will =
search when it encounters an import command.

This is my approach to installing third-party scripts.  Maybe that's not =
the way to do it.

Would somebody mind pointing me to some info on how best to organize =
python files in the windows file system?

Poor Yorick
python.tutor[at]pooryorick.com



From erikprice@mac.com  Sat Apr 20 03:59:41 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 19 Apr 2002 22:59:41 -0400
Subject: [Tutor] Where does python look for import files
In-Reply-To: <1D0833CB3B1D7244B617A0DC8399C27E0EC69E@vega>
Message-ID: <A8BA4D88-540A-11D6-A27E-00039351FE6A@mac.com>

On Friday, April 19, 2002, at 09:54  PM, <ncoulter@es.com> wrote:

> I apologize if this is documented in some obvious place, but I have 
> spent all day looking for this information, and have yet to find it:
>
> What procedure/variables does python use to search for files in import 
> commands?  I see that sys.path contains a list of paths, but am not 
> sure how to modify it.  My goal right now is to set up a folder 
> (c:\python22\scripts) where I can create a folder tree python will 
> search when it encounters an import command.
>
> This is my approach to installing third-party scripts.  Maybe that's 
> not the way to do it.
>
> Would somebody mind pointing me to some info on how best to organize 
> python files in the windows file system?

I really don't know much about Windows, but in Unix you should have an 
environment variable called PYTHONPATH.  Perhaps the same is true of 
Windows.

PYTHONPATH defines the directories searched when importing a module 
using the import statement.

One of the directories in PYTHONPATH is . so you should be able to 
import any modules that are in the current working directory from whence 
you called Python (or the script if it is standalone).

Although everything I've described applies to Unix, I would be surprised 
if it was very different in Windows -- somewhere there should be a 
script which sets the PYTHONPATH environment variable when you launch 
Python, just modify this script.

Hopefully?


Erik




From erikprice@mac.com  Sat Apr 20 03:59:55 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 19 Apr 2002 22:59:55 -0400
Subject: [Tutor] Re: Interpreter
In-Reply-To: <E16ySc7-0001fX-00@mail.python.org>
Message-ID: <B14ACF80-540A-11D6-A27E-00039351FE6A@mac.com>

On Friday, April 19, 2002, at 12:19  AM, Kirby Urner wrote:

> How to get IDLE working on a Mac I'm not so sure, even though I
> did it once (didn't have syntax coloring).  That was on a pre OSX
> iMac though.  I also got it running in BeOS once, for kicks (using
> the free BeOS that runs in a Windows subdirectory).

To the best of my knowledge, you will need to install X11, since that 
provides Tk libraries.

Erik




From urnerk@qwest.net  Sat Apr 20 01:54:27 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 19 Apr 2002 20:54:27 -0400
Subject: [Tutor] Where does python look for import files
In-Reply-To: <1D0833CB3B1D7244B617A0DC8399C27E0EC69E@vega>
References: <1D0833CB3B1D7244B617A0DC8399C27E0EC69E@vega>
Message-ID: <E16ylsx-0007F8-00@mail.python.org>

On Friday 19 April 2002 09:54 pm, ncoulter@es.com wrote:
> I apologize if this is documented in some obvious place, but I have spent
> all day looking for this information, and have yet to find it:
>
> What procedure/variables does python use to search for files in import
> commands?  I see that sys.path contains a list of paths, but am not sure
> how to modify it.  My goal right now is to set up a folder
> (c:\python22\scripts) where I can create a folder tree python will search
> when it encounters an import command.

You should find c:\python22\lib\site-packages in your windows 
tree.   That's a better place to put your 3rd party stuff.

But if you want to augment the standard tree with other locations,
in WIndows you have the option to create .pth files, e.g. init.pth,
where you can list additional paths, e.g. if you have a subdirectory
of \python22 names scripts, just create init.pth with the one word
scripts in it, and nothing more.

Kirby



From urnerk@qwest.net  Sat Apr 20 03:54:25 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 19 Apr 2002 22:54:25 -0400
Subject: [Tutor] HTMLParser question
In-Reply-To: <F1619NLX2Al4QKLLlrr00006dad@hotmail.com>
References: <F1619NLX2Al4QKLLlrr00006dad@hotmail.com>
Message-ID: <E16ynl3-0001n2-00@mail.python.org>

On Friday 19 April 2002 08:23 pm, Daryl Gallatin wrote:
> Hi, is there a good example somewhere on how to use the HTMLParser class
> I would like to create a simple HTML web browser, but the simple example
> provided in the documentation doesn't give me much to work on
>
> I have a text browser, but I want to be able to view at least Simple HTML
> pages

If you're saying you want a GUI-based rendering of HTML that 
pays attention to a reduced tag set (e.g. <p> and some formatting),
that's a non-trivial application.  

As a learning exercise it might be fun, but the practical solution is 
to just use a browser you've already got.

HTMLParser class is good for stripping information from a web 
page, like maybe you just want what's between <pre> </pre> tags.

Below is a program you can run from the OS command line, to harvest
polyhedron data in OFF format (a text format used in computational 
geometry) from a specific website.  Parameters might be cube.html 
or icosa.html (these get appended to a base URL that's hardwired into 
the program).  

Following Lundh's advice, I just use the SGMLParser, and find I need 
to capture <pre> and </pre> tags by overwriting the unknown_starttag 
and unknown_endtag methods:

#!/usr/bin/python
"""
Thanks to example in Puthon Standard Library, Lundh (O'Reilly)

Excerpts data from http://www.scienceu.com/geometry/facts/solids/
which just happens to be saved between <pre> </pre> tags, which
are unique and/or first on each page.
"""

import urllib,sys
import sgmllib

class FoundPre(Exception):
    pass

class ExtractPre(sgmllib.SGMLParser):

    def __init__(self,verbose=0):
        sgmllib.SGMLParser.__init__(self,verbose)
        self.pretag = self.data = None

    def handle_data(self,data):
        if self.data is not None: # skips adding unless <pre> found
            self.data.append(data)

    def unknown_starttag(self, tag, attrs):
        if tag=="pre":
           self.start_pre(attrs)

    def unknown_endtag(self, tag):
        if tag=="pre":
           self.end_pre(attrs)

    def start_pre(self,attrs):
        print "Yes!!!"  # found my <pre> tag
        self.data = []

    def end_pre(self):
        self.pretag = self.data
        raise FoundPre # done parsing

def getwebdata(wp):
    p  = ExtractPre()
    n = 0
    try:  # clever use of exception to terminate
        while 1:
            s = wp.read(512)
            if not s:
                break
            p.feed(s)
        p.close()
    except FoundPre:
        return p.pretag
    return None

if __name__ == '__main__':
    webpage = sys.argv[1]
    baseurl = "http://www.scienceu.com/geometry/facts/solids/coords/"
    fp = urllib.urlopen(baseurl + webpage)
    output = open("data.txt","w")
    results = getwebdata(fp)
    fp.close()

    if results:
        for i in results:
            output.write(i)
    output.close()

Example usage:

[kirby@grunch bin]$ scipoly.py cube.html
Yes!!!
[kirby@grunch bin]$ cat data.txt


  OFF
     8    6    0
    -0.469     0.000    -0.664
     0.469     0.000     0.664
    -0.469     0.664     0.000
    -0.469    -0.664     0.000
     0.469     0.664     0.000
    -0.469     0.000     0.664
     0.469     0.000    -0.664
     0.469    -0.664     0.000

  4   3 7 1 5     153  51 204
  4   1 7 6 4     153  51 204
  4   4 1 5 2     153  51 204
  4   5 2 0 3     153  51 204
  4   6 0 3 7     153  51 204
  4   4 6 0 2     153  51 204

I have another Python script to read in the above file and convert
it to Povray for rendering.  Unfortunately, the data is to only 3 
significant figures, and this means some facets aren't coplanar 
enough for Povray's tastes (qhull likewise sometimes gets different
facets, when parsing the same vertices -- I need a better source
of coordinate data I guess).

Kirby



From urnerk@qwest.net  Sat Apr 20 05:39:11 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 20 Apr 2002 00:39:11 -0400
Subject: [Tutor] Getting range to produce float lists
In-Reply-To: <8093ABAD9B81D211878200A0C9B406BA14B65A2C@mainex3.asu.edu>
References: <8093ABAD9B81D211878200A0C9B406BA14B65A2C@mainex3.asu.edu>
Message-ID: <E16ypOS-0004CC-00@mail.python.org>

On Wednesday 17 April 2002 06:23 pm, William Griffin wrote:

> I would like to do this by doing range(0, 0.5, 0.1) but of course range
> only produces integer lists and will round all the arguments (making the
> step = 0 if required). Is there a way to do this easily with core
> Python or should I hack up a quick function for my students to use?

Maybe your students'd like to do a quick hack.  One option is 
to pass a,b,d where d = denominator, a,b are regular range 
arguments. 

 >>> from __future__ import division  # to get floating point answers

 >>> def frange(a,b,d):
         return [i/d for i in range(a,b)]

 >>> frange(1,5,10)
 [0.10000000000000001, 0.20000000000000001, 0.29999999999999999,  
 0.40000000000000002]

Could have optional 3rd skip value, and a default denominator of 1,
e.g. frange(a,b,d=1,skip=1) -- stuff like that.  Make it be a 
generator function too if you wanna be fancy.

Another option is to think of a,b as integers and f as a function.

 >>> def frange(a,b,f):
         return [f(i) for i in range(a,b)]

Then you could define f independently as in:

 >>> def f(x):  return x/100.0

Anyway, it's a fun little challenge to help with learning Python.

Kirby



Kirby



From urnerk@qwest.net  Sat Apr 20 14:43:34 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 20 Apr 2002 09:43:34 -0400
Subject: [Tutor] HTMLParser question
In-Reply-To: <F419iJCAgn5yIVqVWrx0000232a@hotmail.com>
References: <F419iJCAgn5yIVqVWrx0000232a@hotmail.com>
Message-ID: <E16yxtF-0007xl-00@mail.python.org>

On Saturday 20 April 2002 09:44 am, Daryl Gallatin wrote:
> Hi, Thanks
> Yes, a gui based program that renders HTML is what I am looking to create.
> say, a python example of an early html browser

OK, that's a fine project to learn from.  I've never done much like
this myself.

> non-trivial application? You mean it would actually be simple to do?

Non-trivial means not trivial, where trivial means really easy.

> The text browser example I have is from deitel and deitel's book and is
> something that I want to expand on and create my own at least simple html
> browser to at least see how it works.
>

I'll hand you off to someone better at GUI-based stuff.  You'd have
to pick a GUI library like Tkinter, and figure out how to translate
HTML tags into formatting instructions for whatever text window
widget.

Kirby



From phthenry@earthlink.net  Sun Apr 21 04:24:47 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Sat, 20 Apr 2002 23:24:47 -0400
Subject: [Tutor] setting path
Message-ID: <20020420232447.A29513@localhost.localdomain>

I would like to set up a library in my home file for my own
modules. I want to set the path of the Python, but am not able
to do so. I am running Mandrake 8.1. 

>From bash, I type:

ehco $PYTHONPATH

I get nothing.

>From a python script, I type

import sys
print sys.path

I get:

['/home/paul/paultemp', '/usr/lib/python2.1',
 '/usr/lib/python2.1/plat-linux-i386',
 '/usr/lib/python2.1/lib-tk', '/usr/lib/python2.1/lib-dynload',
 '/usr/lib/python2.1/site-packages']

I don't believe I can simply type 

PYTHONPATH=/home/paul/python_lib
export $PYTHONPATH

since $PYTHONPATH is not set up.

Thanks!

Paul


-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From urnerk@qwest.net  Sun Apr 21 04:12:48 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 20 Apr 2002 23:12:48 -0400
Subject: [Tutor] setting path
In-Reply-To: <20020420232447.A29513@localhost.localdomain>
References: <20020420232447.A29513@localhost.localdomain>
Message-ID: <E16zAWM-0001dr-00@mail.python.org>

What you *can* do in the shell is go:

  >>> import sys
  >>> sys.path.append('/home/paul/python_lib')

and you'll be able to import modules from that directory
*for this session only*.  That's not what you're after, 
I realize, but sometimes useful to know.

> since $PYTHONPATH is not set up.
>

If you want to set up PYTHONPATH, consider adding something
like this to your .bash_profile or .bashrc

PYTHONPATH=/home/paul/python_lib
export PYTHONPATH

After making this change, going 

bash --login 

at the $ prompt should reinitialize your environment without 
necessitating logging out and back in again.  As a check,
now try 

echo $PYTHONPATH

Inside Python, the sys.path should remain the same (i.e. won't 
show the addition), but now you should be able to import modules 
from ~/python_lib as well.

Kirby



From dyoo@hkn.eecs.berkeley.edu  Sun Apr 21 07:36:37 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Apr 2002 23:36:37 -0700 (PDT)
Subject: [Tutor] Case study: writing an Python extension type in C [C extensions /
 priority queues / PyHeap]
Message-ID: <Pine.LNX.4.44.0204202320050.6675-100000@hkn.eecs.berkeley.edu>

[note: you may want to skip this message if you haven't programmed in C]


Hi everyone,

I got off my lazy behind and typed up a preliminary example of an C
extension.  I've chosen to do an implementation of a "priority queue"
using the "heap" data structure.


A "priority queue" is something that keeps track of items and their
priorities, and makes it relatively fast to grab the most "important"
element at any given time.  A simple way of implementing this in Python
would be to use a sorted list:

###
class PriorityQueue:
    """This is a simple implementation of a priority queue."""

    def __init__(self, cmp=cmp):
        self.cmp = cmp
        self.items = []

    def push(self, obj):
        self.items.append(obj)
        self.items.sort(cmp)

    def pop(self):
        return self.items.pop()
###


No sweat.  *grin* And this works well enough:

###
>>> pq = PriorityQueue()
>>> pq.push( (1, "eat") )
>>> pq.push( (2, "sleep") )
>>> pq.push( (3, "have life") )
>>> pq.pop()
(3, 'have life')
>>> pq.push( (42, "program") )
>>> pq.pop()
(42, 'program')
>>> pq.pop()
(2, 'sleep')
>>> pq.pop()
(1, 'eat')
>>> pq.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/tmp/python-539-9L", line 13, in pop
IndexError: pop from empty list
###

The only problem here is that inserting into this priority queue costs
quite a bit: it requires us to resort the list whenever we add a new task
to the list.  Heaps are a data structure that allow us to do insertions
and max-grabbing at a fairly low cost.


I've written the code to do this with heaps.  I'll start writing an HTML
page to present this stuff more leisurely, and perhaps this will interest
people who want to see how Python extensions work.

And now an apology: I lost the email of the people who contacted me about
writing this tutorial!  please forgive me for not responding!  For people
who haven't been insulted by my unresponsiveness, the code can be found
here:

    http://hkn.eecs.berkeley.edu/~dyoo/python/pyheap/PyHeap-0.1.tar.gz

Any suggestions would be greatly appreciated.  I promise I won't ignore
the emails this time.  *grin*



Hope this helps!




From rbrito@ime.usp.br  Sat Apr 20 13:04:01 2002
From: rbrito@ime.usp.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Sat, 20 Apr 2002 09:04:01 -0300
Subject: [Tutor] Re: Interpreter
In-Reply-To: <B14ACF80-540A-11D6-A27E-00039351FE6A@mac.com>
References: <E16ySc7-0001fX-00@mail.python.org> <B14ACF80-540A-11D6-A27E-00039351FE6A@mac.com>
Message-ID: <20020420120401.GA664@ime.usp.br>

On Apr 19 2002, Erik Price wrote:
> To the best of my knowledge, you will need to install X11, since
> that provides Tk libraries.

	Aren't there Carbonized versions of Tcl/Tk? I'd love to be
	able to use Tkinter under MacOS X, without an Xserver. Is this
	possible?


	[]s, Roger...

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



From gman_95@hotmail.com  Sat Apr 20 14:44:44 2002
From: gman_95@hotmail.com (Daryl Gallatin)
Date: Sat, 20 Apr 2002 13:44:44 +0000
Subject: [Tutor] HTMLParser question
Message-ID: <F419iJCAgn5yIVqVWrx0000232a@hotmail.com>

Hi, Thanks
Yes, a gui based program that renders HTML is what I am looking to create. 
say, a python example of an early html browser

non-trivial application? You mean it would actually be simple to do?

The text browser example I have is from deitel and deitel's book and is 
something that I want to expand on and create my own at least simple html 
browser to at least see how it works.

Thanks!







>From: Kirby Urner <urnerk@qwest.net>
>To: "Daryl Gallatin" <gman_95@hotmail.com>, tutor@python.org
>Subject: Re: [Tutor] HTMLParser question
>Date: Fri, 19 Apr 2002 22:54:25 -0400
>
>On Friday 19 April 2002 08:23 pm, Daryl Gallatin wrote:
> > Hi, is there a good example somewhere on how to use the HTMLParser class
> > I would like to create a simple HTML web browser, but the simple example
> > provided in the documentation doesn't give me much to work on
> >
> > I have a text browser, but I want to be able to view at least Simple 
>HTML
> > pages
>
>If you're saying you want a GUI-based rendering of HTML that
>pays attention to a reduced tag set (e.g. <p> and some formatting),
>that's a non-trivial application.
>
>As a learning exercise it might be fun, but the practical solution is
>to just use a browser you've already got.
>
>HTMLParser class is good for stripping information from a web
>page, like maybe you just want what's between <pre> </pre> tags.
>
>Below is a program you can run from the OS command line, to harvest
>polyhedron data in OFF format (a text format used in computational
>geometry) from a specific website.  Parameters might be cube.html
>or icosa.html (these get appended to a base URL that's hardwired into
>the program).
>
>Following Lundh's advice, I just use the SGMLParser, and find I need
>to capture <pre> and </pre> tags by overwriting the unknown_starttag
>and unknown_endtag methods:
>
>#!/usr/bin/python
>"""
>Thanks to example in Puthon Standard Library, Lundh (O'Reilly)
>
>Excerpts data from http://www.scienceu.com/geometry/facts/solids/
>which just happens to be saved between <pre> </pre> tags, which
>are unique and/or first on each page.
>"""
>
>import urllib,sys
>import sgmllib
>
>class FoundPre(Exception):
>     pass
>
>class ExtractPre(sgmllib.SGMLParser):
>
>     def __init__(self,verbose=0):
>         sgmllib.SGMLParser.__init__(self,verbose)
>         self.pretag = self.data = None
>
>     def handle_data(self,data):
>         if self.data is not None: # skips adding unless <pre> found
>             self.data.append(data)
>
>     def unknown_starttag(self, tag, attrs):
>         if tag=="pre":
>            self.start_pre(attrs)
>
>     def unknown_endtag(self, tag):
>         if tag=="pre":
>            self.end_pre(attrs)
>
>     def start_pre(self,attrs):
>         print "Yes!!!"  # found my <pre> tag
>         self.data = []
>
>     def end_pre(self):
>         self.pretag = self.data
>         raise FoundPre # done parsing
>
>def getwebdata(wp):
>     p  = ExtractPre()
>     n = 0
>     try:  # clever use of exception to terminate
>         while 1:
>             s = wp.read(512)
>             if not s:
>                 break
>             p.feed(s)
>         p.close()
>     except FoundPre:
>         return p.pretag
>     return None
>
>if __name__ == '__main__':
>     webpage = sys.argv[1]
>     baseurl = "http://www.scienceu.com/geometry/facts/solids/coords/"
>     fp = urllib.urlopen(baseurl + webpage)
>     output = open("data.txt","w")
>     results = getwebdata(fp)
>     fp.close()
>
>     if results:
>         for i in results:
>             output.write(i)
>     output.close()
>
>Example usage:
>
>[kirby@grunch bin]$ scipoly.py cube.html
>Yes!!!
>[kirby@grunch bin]$ cat data.txt
>
>
>   OFF
>      8    6    0
>     -0.469     0.000    -0.664
>      0.469     0.000     0.664
>     -0.469     0.664     0.000
>     -0.469    -0.664     0.000
>      0.469     0.664     0.000
>     -0.469     0.000     0.664
>      0.469     0.000    -0.664
>      0.469    -0.664     0.000
>
>   4   3 7 1 5     153  51 204
>   4   1 7 6 4     153  51 204
>   4   4 1 5 2     153  51 204
>   4   5 2 0 3     153  51 204
>   4   6 0 3 7     153  51 204
>   4   4 6 0 2     153  51 204
>
>I have another Python script to read in the above file and convert
>it to Povray for rendering.  Unfortunately, the data is to only 3
>significant figures, and this means some facets aren't coplanar
>enough for Povray's tastes (qhull likewise sometimes gets different
>facets, when parsing the same vertices -- I need a better source
>of coordinate data I guess).
>
>Kirby




_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From dyoo@hkn.eecs.berkeley.edu  Sun Apr 21 07:53:16 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 20 Apr 2002 23:53:16 -0700 (PDT)
Subject: [Tutor] Re: Case study: writing an Python extension type in C [C extensions
 / priority queues / PyHeap]
In-Reply-To: <Pine.LNX.4.44.0204202320050.6675-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0204202350070.6675-100000@hkn.eecs.berkeley.edu>

> ###
> class PriorityQueue:
>     """This is a simple implementation of a priority queue."""
>
>     def __init__(self, cmp=cmp):
>         self.cmp = cmp
>         self.items = []
>
>     def push(self, obj):
>         self.items.append(obj)
>         self.items.sort(cmp)
>
>     def pop(self):
>         return self.items.pop()
> ###
>
>
> No sweat.  *grin* And this works well enough:


Doh.  I hate hubris; I spoke too soon again.  There's a bug in push():

>     def push(self, obj):
>         self.items.append(obj)
>         self.items.sort(cmp)
                          ^^^

I meant to write:

     def push(self, obj):
         self.items.append(obj)
         self.items.sort(self.cmp)



Sorry about that.  Here's the correction version of a sort-based
PriorityQueue class:

###
class PriorityQueue:
    """This is a simple implementation of a priority queue."""

    def __init__(self, cmp=cmp):
        self.cmp = cmp
        self.items = []

    def push(self, obj):
        self.items.append(obj)
        self.items.sort(self.cmp)

    def pop(self):
        return self.items.pop()
###




From kent@springfed.com  Sun Apr 21 13:37:38 2002
From: kent@springfed.com (kent@springfed.com)
Date: Sun, 21 Apr 2002 07:37:38 -0500
Subject: [Tutor] editing scripts with Vim
Message-ID: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>

Howdy,

Vim looks like a good free cross platform
editor for editing Python.

I seem to recall that Vim provided for 
highlighting a line of code and sending it
to the interpreter, I can't find the reference.

I would appreciate any hints and tips on 
setting up Vim for efficient programming.

Thanks,
Kent





From gus.tabares@verizon.net  Sun Apr 21 15:49:02 2002
From: gus.tabares@verizon.net (Gus Tabares)
Date: Sun, 21 Apr 2002 10:49:02 -0400
Subject: [Tutor] Getting started on programming
Message-ID: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>

Hello,

   I have a substantial knowledge of the basics in Python. But I think the
best way to get use to the language and know it better is to use it. What
did all of you start writing in Python when you first started out? I'm
thinking of something semi-challenging (i.e., not something that computes
2+2;) that will help me better understand Python and further my knowledge.
Thanks


Gus Tabares




From sigurd@12move.de  Sun Apr 21 17:33:22 2002
From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sun, 21 Apr 2002 18:33:22 +0200
Subject: [Tutor] setting path
In-Reply-To: <20020420232447.A29513@localhost.localdomain> (Paul Tremblay's
 message of "Sat, 20 Apr 2002 23:24:47 -0400")
References: <20020420232447.A29513@localhost.localdomain>
Message-ID: <m3u1q5ggjt.fsf@hamster.pflaesterer.de>

On Sat, 20 Apr 2002, Paul Tremblay <- phthenry@earthlink.net wrote:
> I would like to set up a library in my home file for my own
> modules. I want to set the path of the Python, but am not able
> to do so. I am running Mandrake 8.1.=20

> From bash, I type:

> ehco $PYTHONPATH

> I get nothing.

> From a python script, I type

> import sys
> print sys.path

> I don't believe I can simply type=20

> PYTHONPATH=3D/home/paul/python_lib
> export $PYTHONPATH

You could but you would have to type export PYTHONPATH not $PYTHONPATH

> since $PYTHONPATH is not set up.

Python looks if your shell has a variable namend PYTHONPATH. If not
python uses the builtin defaults. If it finds such a variable it adds
its value to the search path.

,----[ man python ]
|  PYTHONPATH
|               Augments  the default search path for module files.
|               The format is the same as the shell's $PATH: one or
|               more directory pathnames separated by colons.  Non-
|               existant directories  are  silently  ignored.   The
|               default  search path is installation dependent, but
|               generally begins with ${prefix}/lib/python<version>
|               (see PYTHONHOME above).  The default search path is
|               always appended to $PYTHONPATH.  If a script  argu-
|               ment  is given, the directory containing the script
|               is inserted in the path in  front  of  $PYTHONPATH.
|               The  search  path  can be manipulated from within a
|               Python program as the variable sys.path .
`----

You could also set the variable PYTHONSTARTUP in your bash (for me it is
~/.pythonrc). All commands in this file are executed at startup of your
python-interpreter. Here you could use your commands:
import sys
sys.path.append('YOUR_PATH')

Don't use the name ~/.pythonrc.py for that file. It is the name of the
file that python reads if you import the user module.


bye
   Karl
--=20
M=E4nner der Wissenschaft! Man sagt ihr viele nach,=20
aber die meisten mit Unrecht.=20=20
                             Karl Kraus 'Aphorismen'




From e.kotyk@shaw.ca  Sun Apr 21 13:07:14 2002
From: e.kotyk@shaw.ca (Eve Kotyk)
Date: Sun, 21 Apr 2002 12:07:14 +0000
Subject: [Tutor] Difficulties installing pygame
Message-ID: <20020421120714.35a7a133.e.kotyk@shaw.ca>

--=.)B)rv(CJwOz,'b
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 7bit


Hello,

I run RedHat 7.2 and Python 2.2.  I am attempting to install
pygame-python22-1.4-1.i386.rpm.  I ran into some dependency problems and
solved most of them.  However, I'm hung up on the following: rpm -ihv
pygame-python22-1.4-1.i386.rpm error: failed dependencies:
        libSDL_ttf-1.2.so.0   is needed by pygame-1.4-1

libSDL_ttf-1.2.so.0 in turn needs freetype1

 rpm -ihv SDL_ttf-1.2.2-4.i586.rpm
error: failed dependencies:
        freetype1   is needed by SDL_ttf-1.2.2-4

If I try to install freetype1 I get:

 rpm -ihv freetype1-1.3.1-4.i386.rpm
Preparing...                ###########################################
[100%] file /usr/share/locale/cs/LC_MESSAGES/freetype.mo from install of
freetype1-1.3.1-4 conflicts with file from package freetype-2.0.3-7 file
/usr/share/locale/de/LC_MESSAGES/freetype.mo from install of
freetype1-1.3.1-4 conflicts with file from package freetype-2.0.3-7 file
/usr/share/locale/es/LC_MESSAGES/freetype.mo from install of
freetype1-1.3.1-4 conflicts with file from package freetype-2.0.3-7 file
/usr/share/locale/fr/LC_MESSAGES/freetype.mo from install of
freetype1-1.3.1-4 conflicts with file from package freetype-2.0.3-7 file
/usr/share/locale/nl/LC_MESSAGES/freetype.mo from install of
freetype1-1.3.1-4 conflicts with file from package freetype-2.0.3-7

I'm at a loss as to where to go from here.  Does anyone have any
recommendations?

Eve
-- 

ekotyk

http://members.shaw.ca/e.kotyk/virtualstudio.htm

--=.)B)rv(CJwOz,'b
Content-Type: application/pgp-signature

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)

iD8DBQE8wqt2yxm8dPG0oMIRAq9xAKDKAhXQ7YhiOMHErMfNSjNeuhl8kgCeJsn7
pwmHtoKucIEXX+19ugOq2+c=
=qdE+
-----END PGP SIGNATURE-----

--=.)B)rv(CJwOz,'b--




From ak@silmarill.org  Sun Apr 21 19:15:38 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 21 Apr 2002 14:15:38 -0400
Subject: [Tutor] Getting started on programming
In-Reply-To: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>
References: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>
Message-ID: <20020421181538.GA18914@ak.silmarill.org>

On Sun, Apr 21, 2002 at 10:49:02AM -0400, Gus Tabares wrote:
> Hello,
> 
>    I have a substantial knowledge of the basics in Python. But I think the
> best way to get use to the language and know it better is to use it. What
> did all of you start writing in Python when you first started out? I'm
> thinking of something semi-challenging (i.e., not something that computes
> 2+2;) that will help me better understand Python and further my knowledge.
> Thanks
>
I started with small 1-page shell scripts, then wrote a few page
frontend to cdrecord and mkisofs.

> 
> 
> Gus Tabares
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From ak@silmarill.org  Sun Apr 21 19:21:53 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Sun, 21 Apr 2002 14:21:53 -0400
Subject: [Tutor] editing scripts with Vim
In-Reply-To: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
References: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
Message-ID: <20020421182153.GB18914@ak.silmarill.org>

On Sun, Apr 21, 2002 at 07:37:38AM -0500, kent@springfed.com wrote:
> Howdy,
> 
> Vim looks like a good free cross platform
> editor for editing Python.
> 
> I seem to recall that Vim provided for
> highlighting a line of code and sending it
> to the interpreter, I can't find the reference.
>
You could make a mapping for that, untested:

map ,p yy:!python -c "^R"<bs>"<cr>

where ^R is ctrl-V, ctrl-R

I also have a small python script to be used from console or gui vim to
print a colored list of def's and classes in current file:

http://silmarill.org/py_scripts/print_defs.py

> 
> I would appreciate any hints and tips on
> setting up Vim for efficient programming.
> 
> Thanks,
> Kent
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From paulsid@shaw.ca  Sun Apr 21 19:28:10 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Sun, 21 Apr 2002 12:28:10 -0600
Subject: [Tutor] Getting started on programming
References: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>
Message-ID: <3CC304BA.81F367AC@shaw.ca>

Gus Tabares wrote:

>    I have a substantial knowledge of the basics in Python. But I think the
> best way to get use to the language and know it better is to use it. What
> did all of you start writing in Python when you first started out? I'm
> thinking of something semi-challenging (i.e., not something that computes
> 2+2;) that will help me better understand Python and further my knowledge.

You might find the suggestions at the bottom of this post helpful:

http://mail.python.org/pipermail/tutor/2002-January/011003.html

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From linuxconsult@yahoo.com.br  Sun Apr 21 20:01:07 2002
From: linuxconsult@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Sun, 21 Apr 2002 16:01:07 -0300
Subject: [Tutor] Getting started on programming
In-Reply-To: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>
References: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>
Message-ID: <20020421190107.GB1510@ime.usp.br>

On Apr 21 2002, Gus Tabares wrote:
>    I have a substantial knowledge of the basics in Python. But I
> think the best way to get use to the language and know it better is
> to use it. What did all of you start writing in Python when you
> first started out?

	Well, I'm a newbie in Python yet, but some general advices
	would be to try to get a book on data structures (say,
	Cormen's or Knuth's) and try to get the pseudo-code converted
	to Python programs. Trying to get a reasonable implementation
	as classes should be a good excercise, since, IMO, classes are
	a perfect implementation model for data structes.

	Also, writing scripts for automatization (sp?) of tasks you
	usually do is a nice way to learn.

	Writing one-liners was a good way for me to learn Perl.
	Unfortunately, it seems that in Python, this is not so easy to
	do, since Python doesn't have braces to limit the body of
	loops or of conditional statements ("if's").

	Doing some programs for text-processing (say, using as a CGI
	script) would be yet another good way to use Python, I'd say.

	Well, the list can be extended ad infinitum, but I hope that
	this helps.


	[]s, Roger...

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



From budgester@budgester.com  Sun Apr 21 20:18:39 2002
From: budgester@budgester.com (Martin Stevens)
Date: Sun, 21 Apr 2002 20:18:39 +0100
Subject: [Tutor] editing scripts with Vim
In-Reply-To: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
References: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
Message-ID: <20020421191839.GA10266@akira.budgenet>

try 

:syntax on

or 

:syntax off

Then put that in your vimrc file, and it should then auto syntax
for whatever type of file you use.

I know it's not strictly python but i found this usefull :-)

On Sun, Apr 21, 2002 at 07:37:38AM -0500, kent@springfed.com wrote:
> Howdy,
> 
> Vim looks like a good free cross platform
> editor for editing Python.
> 
> I seem to recall that Vim provided for 
> highlighting a line of code and sending it
> to the interpreter, I can't find the reference.
> 
> I would appreciate any hints and tips on 
> setting up Vim for efficient programming.
> 
> Thanks,
> Kent
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Budgester Technologies Ltd
Office : 01992 718568
Mobile : 07815 982380
mailto:martin@budgester.com
http://www.budgester.com



From yduppen@xs4all.nl  Sun Apr 21 20:19:18 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Sun, 21 Apr 2002 21:19:18 +0200
Subject: [Tutor] Getting started on programming
In-Reply-To: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>
References: <ODEIKMAHBLFLGHJPOKDNGEACCAAA.gus.tabares@verizon.net>
Message-ID: <200204211919.g3LJJLmV027264@smtpzilla2.xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> [...] What
> did all of you start writing in Python when you first started out? I'm
> thinking of something semi-challenging (i.e., not something that computes
> 2+2;) that will help me better understand Python and further my knowledge.

Some spanish university has a huge collection of assignments for the ACM 
Programming Competition; while they don't accept Python programs for 
automatic judging, the problems are _great_ for learning the expressiveness 
of basic Python. (At least, they were for me)

Of course, once you get a grasp of expressing complex algorithms in Python, 
these assignments are no longer useful; they never force you to delve into 
the Python libraries, for example. Once you reach that stage, the suggestions 
made by others (games, shell scripts) will help you further

You can find the Problem Archive over here:

http://acm.uva.es/problemset/

(Useless Python contains some solutions in python)

YDD
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8wxC5LsKMuCf5EdwRAmwYAJ0RBqN1Bx7Oz9ldwqnOXvjQGpTlPACfcYsg
9QtFUShOVIQRwrNOZNJNhT4=
=vdXu
-----END PGP SIGNATURE-----



From dyoo@hkn.eecs.berkeley.edu  Sun Apr 21 21:07:42 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 21 Apr 2002 13:07:42 -0700 (PDT)
Subject: [Tutor] Getting started on programming
In-Reply-To: <200204211919.g3LJJLmV027264@smtpzilla2.xs4all.nl>
Message-ID: <Pine.LNX.4.44.0204211304460.19719-100000@hkn.eecs.berkeley.edu>


On Sun, 21 Apr 2002, Yigal Duppen wrote:

> Python, these assignments are no longer useful; they never force you to
> delve into the Python libraries, for example. Once you reach that stage,
> the suggestions made by others (games, shell scripts) will help you
> further
>
> You can find the Problem Archive over here:
>
> http://acm.uva.es/problemset/
>
> (Useless Python contains some solutions in python)

By the way, Useless Python is located here:

    http://www.lowerstandard.com/python/

It has a separate section of "Challenges" that you can try out:

    http://www.lowerstandard.com/python/pythonchallenge.html
    http://www.lowerstandard.com/python/acmcontest.html

that will allow you to apply what you've learned toward some interesting
programs!


Good luck to you.




From csmith@blakeschool.org  Sun Apr 21 22:21:55 2002
From: csmith@blakeschool.org (Christopher Smith)
Date: Sun, 21 Apr 2002 16:21:55 -0500
Subject: [Tutor] Re: A Demolished Function
Message-ID: <fc.004c4b6b009583d6004c4b6b009583d6.9583f6@blakeschool.org>

>Danny Yoo wrote:
>>After writing this function, though, I still feel tense and
>apprehensive. 
>>Does anyone see any improvements one could make to make the function 
>>easier to read?  Any criticism or dissension would be great.  Thanks! 
>
Kirby replied:
>Some inconsequential coding changes -- not necessarily easier
>to read:
>
>def conservativeSplit(regex, stuff):
>     """Split 'stuff' along 'regex' seams."""
>     fragments = []
>     while 1:
>         match = regex.search(stuff)
>         if not match: break
>         begin, end = match.span()
>         if not begin == 0:
>             fragments.append(stuff[0 : begin])
>         fragments.append(stuff[begin : end])
>         stuff = stuff[end :]
>     if stuff: fragments.append(stuff)
>     return fragments
>
>Kirby

I was revisting string splitting and the sorting titles that contain
numbers and I realized that the "conservative split" is already a
regex option:  just enclose your pattern in parentheses and the 
match will be retained in the split:

>>> import re
>>> t="five sir four sir three sir two sir one sir"
>>> sir=re.compile(r'(sir)')
>>> sir.split(t)
['five ', 'sir', ' four ', 'sir', ' three ', 'sir', ' two ', 'sir', ' one
', 'sir', '']

Another way to sort titles containing numbers is to split out (and retain)
the numbers, convert the numbers to integers, and then sort the split-up
titles.  This will cause the numbers to be treated as numbers instead of
strings.  Joining the split titles back together again brings you back to
the original title.

Here's a demo using Danny's original data:

def sortTitles(b):
    """The strings in list b are split apart on numbers (integer runs)
    before they are sorted so the strings get sorted according to 
    numerical values when they occur (rather than text values) so
    2 will follow 1, for example, rather than 11."""

    # the () around the pattern preserves the pattern in the split
    integer=re.compile(r'(\d+)') 
    for j in range(len(b)):
        title=integer.split(b[j])
        #
        # Every *other* element will be an integer which was found; 
        # convert it to a int
        #
        for i in range(1,len(title),2):
                title[i]=int(title[i])
        b[j]=title[:]
    #
    # Now sort and rejoin the elements of the title
    #
    b.sort()
    for i in range(len(b)):
        for j in range(1,len(b[i]),2):
                b[i][j]=str(b[i][j])
        b[i]=''.join(b[i])

if __name__ == '__main__':
    book_titles = ['The 10th Annual Python Proceedings',
                   'The 9th Annual Python Proceedings',
                   'The 40th Annual Python Proceedings',
                   '3.1415... A Beautiful Number',
                   '3.14... The Complexity of Infinity',
                   'TAOCP Volume 3: Sorting and Searching',
                   'TAOCP Volume 2: Seminumerical Algorithms',
                   'The Hitchhiker\'s Guide to the Galaxy']

    print "Here are a list of my books, in sorted order:"
    sortTitles(book_titles)
    print book_titles

/c




From wolf_binary@hotmail.com  Mon Apr 22 00:10:07 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Sun, 21 Apr 2002 18:10:07 -0500
Subject: [Tutor] slearing the screen
Message-ID: <DAV633vSAMfKQu1bCdU0000a622@hotmail.com>

This is a multi-part message in MIME format.

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

Hi all,

How do you clear the screen?  Is there a command like in C++ to clear =
the screen in Python?  Also is there a function for turning numbers and =
letters into ASCII?  I have been going through the modules without much =
luck.

Thanks for any help,
Cameron Stoner

------=_NextPart_000_0009_01C1E95F.C4AFB920
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>How do you clear the screen?&nbsp; Is =
there a=20
command like in C++ to clear the screen in Python?&nbsp; Also is there a =

function for turning numbers and letters into ASCII?&nbsp; I have been =
going=20
through the modules without much luck.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks for any help,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Cameron =
Stoner</FONT></DIV></BODY></HTML>

------=_NextPart_000_0009_01C1E95F.C4AFB920--



From erikprice@mac.com  Mon Apr 22 00:30:40 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 21 Apr 2002 19:30:40 -0400
Subject: [Tutor] Re: Interpreter
In-Reply-To: <20020420120401.GA664@ime.usp.br>
Message-ID: <CAD9B831-557F-11D6-AAEE-00039351FE6A@mac.com>

On Saturday, April 20, 2002, at 08:04  AM, Rog=E9rio Brito wrote:

> On Apr 19 2002, Erik Price wrote:
>> To the best of my knowledge, you will need to install X11, since
>> that provides Tk libraries.
>
> 	Aren't there Carbonized versions of Tcl/Tk? I'd love to be
> 	able to use Tkinter under MacOS X, without an Xserver. Is this
> 	possible?

I had heard that there were... in fact, at one time someone on this list=20=

passed me a screenshot of Tk running on OS X.  Apple recently announced=20=

(in ADC) that the Tk libraries are indeed carbonized.  But I'm not=20
familiar with any package that sets it up easily for you -- perhaps if=20=

you are willing to do the legwork.

I did find this

http://www.apple.com/scitech/news/

which mentions that you can use Fink to install Tcl/Tk.  But I haven't=20=

done it myself.

There's more info here

http://www.maths.mq.edu.au/~steffen/tcltk/darwin.xhtml


Good luck


Erik




From jgoerz@cfl.rr.com  Mon Apr 22 01:59:20 2002
From: jgoerz@cfl.rr.com (Jesse Goerz)
Date: 21 Apr 2002 20:59:20 -0400
Subject: [Tutor] slearing the screen
In-Reply-To: <DAV633vSAMfKQu1bCdU0000a622@hotmail.com>
References: <DAV633vSAMfKQu1bCdU0000a622@hotmail.com>
Message-ID: <1019437160.947.290.camel@reign.home>

On Sun, 2002-04-21 at 19:10, Cameron Stoner wrote:
> Hi all,
> 
> How do you clear the screen?  Is there a command like in C++ to clear the screen in Python?  Also is there a function for turning numbers and letters into ASCII?  I have been going through the modules without much luck.
> 
> Thanks for any help,
> Cameron Stoner

I'm pretty sure you can do it like this:

import os

os.system('clear')




From garber@centralcatholic.org  Mon Apr 22 02:47:57 2002
From: garber@centralcatholic.org (Robert Garber)
Date: Sun, 21 Apr 2002 21:47:57 -0400
Subject: [Tutor] Visual Basic AND Python, is there a way to...
Message-ID: <200204212147.AA113050226@centralcatholic.org>

OK hear goes an off the wall question. I started with python and loved it...came very easy to me. I moved on to visual basic. I like the way you can set up the GUI first and the methods used in doing so...seems very intuitive. i like the dea of writing code for each part of the form and object in it...is there a way to use VB6.0 and ptyhon together... set up the GUi and use python to write the code for each event in the app?or is there an IDE out ther that wroks like VB 6.0 for setting up and writting GUI apps? I have to admit I never messed with tkinter, but i know it sets up the GUI with code instead  the 'drag and drop' methods in VB6.0...i like writting code with python..it is the first language i have learned and would like to find a way to use both together if possible.\


Thanks for any input,
Robert




From j.ezequiel@spitech.com  Mon Apr 22 02:59:31 2002
From: j.ezequiel@spitech.com (Ezequiel, Justin)
Date: Mon, 22 Apr 2002 09:59:31 +0800
Subject: [Tutor] reading dBase IV files (.DBF)
Message-ID: <0F757892D113D611BD2E0002559C1FF472CF29@EMAIL>

Is it possible?
Can somebody point me to samples/tutorials/resources/etc.?
BTW, the said .DBF file I need to read would have 500,000+ records.



From dyoo@hkn.eecs.berkeley.edu  Mon Apr 22 08:21:33 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 22 Apr 2002 00:21:33 -0700 (PDT)
Subject: [Tutor] Re: A Demolished Function
In-Reply-To: <fc.004c4b6b009583d6004c4b6b009583d6.9583f6@blakeschool.org>
Message-ID: <Pine.LNX.4.44.0204220001460.8277-100000@hkn.eecs.berkeley.edu>


> I was revisting string splitting and the sorting titles that contain
> numbers and I realized that the "conservative split" is already a regex
> option:  just enclose your pattern in parentheses and the match will be
> retained in the split:
>
> >>> import re
> >>> t="five sir four sir three sir two sir one sir"
> >>> sir=re.compile(r'(sir)')
> >>> sir.split(t)
> ['five ', 'sir', ' four ', 'sir', ' three ', 'sir', ' two ', 'sir', ' one
> ', 'sir', '']


I hadn't known about how groups with re.split() had worked when I wrote
conservativeSplit().  Thanks for pointing this out; I like your approach
much better.



>     integer=re.compile(r'(\d+)')
>     for j in range(len(b)):
>         title=integer.split(b[j])
>         #
>         # Every *other* element will be an integer which was found;
>         # convert it to a int
>         #
>         for i in range(1,len(title),2):
>                 title[i]=int(title[i])
>         b[j] = title[:]


Instead of replacing b[j] altogether, we can "decorate" each b[j]:

###
b[j] = (title, b[j])
###

The advantage of decorating the b[j]'s is that we can pull out the
original b[j]'s after the sorting's done:

###
b.sort()                        ## Sort the decorated elements.
for i in range(len(b)):
    b[i] = b[i][1]              ## Remove the decorations.
###


Good night!




From wolf_binary@hotmail.com  Mon Apr 22 14:58:47 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Mon, 22 Apr 2002 08:58:47 -0500
Subject: [Tutor] binary was slearing meant to be clearing
Message-ID: <DAV23UKEwpNzdwcZnOH0000afbf@hotmail.com>

This is a multi-part message in MIME format.

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

I guess what I meant was to change it into the 0s and 1s of every key on =
the keyboard.

Right now I have a dictionary that holds all the values, but I would =
like to remove the need for it if possible.  ei: dict =3D =
{'A':'01000001','B':'01000010','C':'01000011','D':'01000100'}  This is =
the machine lanuage or what ever the proper term is.  I am not sure.  I =
was calling it binary.

Thanks,
Cameron


------=_NextPart_000_000F_01C1E9DB.E9B44660
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>I guess what I meant was to change it =
into the 0s=20
and 1s of every key on the keyboard.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Right now I have a dictionary that =
holds all the=20
values, but I would like to remove the need for it if possible.&nbsp; =
ei: dict =3D=20
{'A':'01000001','B':'01000010','C':'01000011','D':'01000100'}&nbsp; This =
is the=20
machine lanuage or what ever the proper term is.&nbsp; I am not =
sure.&nbsp; I=20
was calling it binary.</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Cameron</FONT></DIV>
<DIV>&nbsp;</DIV></BODY></HTML>

------=_NextPart_000_000F_01C1E9DB.E9B44660--



From pythontutor@venix.com  Mon Apr 22 15:43:26 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 22 Apr 2002 10:43:26 -0400
Subject: [Tutor] binary was slearing meant to be clearing
References: <DAV23UKEwpNzdwcZnOH0000afbf@hotmail.com>
Message-ID: <3CC4218E.2010500@venix.com>

 >>> ord('A')
65
 >>> chr(65)
'A'
 >>> "%x" % ord('A')
'41'
 >>>
I am not sure of the best way to turn an integer into a base2 string.  Format
supports octal (base8) and hex(base16).  Possibly, you didn't really need the
base2 string, but simply the value that the ord function provides.

Cameron Stoner wrote:

> I guess what I meant was to change it into the 0s and 1s of every key on 
> the keyboard.
> 
>  
> 
> Right now I have a dictionary that holds all the values, but I would 
> like to remove the need for it if possible.  ei: dict = 
> {'A':'01000001','B':'01000010','C':'01000011','D':'01000100'}  This is 
> the machine lanuage or what ever the proper term is.  I am not sure.  I 
> was calling it binary.
> 
>  
> 
> Thanks,
> 
> Cameron
> 
>  
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From pythontutor@venix.com  Mon Apr 22 16:06:59 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 22 Apr 2002 11:06:59 -0400
Subject: [Tutor] program to count keys with timer display and clock display
Message-ID: <3CC42713.6060609@venix.com>

My son (age 18) is looking to write a program that would count keypresses while
displaying a 15 minute countdown timer and the current time.  He wants this to
run under Linux and Windows.  He wants to be able to distinguish keys at a relatively
low level e.g. RightShift-a, LeftShift-a.

I (of course) recommended learning some Python to do this, but then started checking.
The curses module would work for Linux, but not Windows.
The WConio module would work for Windows, but is fairly different from curses.
PyGame seems to support timers and keypresses, but looks to be more complex.

My inclination is to recommend writing two programss, one based on WConio and the other
based on curses.

Any suggestions??

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From stuart_clemons@us.ibm.com  Mon Apr 22 15:50:36 2002
From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com)
Date: Mon, 22 Apr 2002 10:50:36 -0400
Subject: [Tutor] Newbie with question about text file processing
Message-ID: <OFF59A4AF0.F4BE89DA-ON85256BA3.004F75BC@lotus.com>

--0__=0ABBE130DFDCF32C8f9e8a93df938690918c0ABBE130DFDCF32C
Content-type: text/plain; charset=US-ASCII

Hi all:

I have an NT admin type of task that I'd like to try to do using Python,
which I'm just starting to learn.

Here's a simplied version of what I'm trying to do.

I have two text files, a master.txt and a newfile.txt.   The master.txt
file has two fields, WINS and DNS.  The newfile.txt has numerous fields,
including the WINS and DNS fields.

I would like to compare the values of the WINS and DNS fields in the
newfile.txt against the WINS and DNS values in the master.txt file to be
sure they match.  I would like to write the results of the comparison to a
file, results.txt.

Here's the contents of master.txt:

      WINS Server : 9.99.99.1
      DNS Servers : 9.99.99.2
                  : 9.99.99.3

Here's the contents of newfile.txt

      IP Address  : 9.99.99.10
      Gateway     : 9.99.99.20
      WINS Server : 9.88.88.88
      Subnet            : 255.255.255.0
      DNS Servers:      : 9.99.99.2
                  : 9.99.99.3
      DHCP Server : 9.99.99.4

Any help will be greatly appreciated.

- Stuart
--0__=0ABBE130DFDCF32C8f9e8a93df938690918c0ABBE130DFDCF32C
Content-type: text/html; charset=US-ASCII
Content-Disposition: inline

<html><body>
<p>Hi all:<br>
<br>
I have an NT admin type of task that I'd like to try to do using Python, which I'm just starting to learn.<br>
<br>
Here's a simplied version of what I'm trying to do.<br>
<br>
I have two text files, a master.txt and a newfile.txt.   The master.txt file has two fields, WINS and DNS.  The newfile.txt has numerous fields, including the WINS and DNS fields.<br>
<br>
I would like to compare the values of the WINS and DNS fields in the newfile.txt against the WINS and DNS values in the master.txt file to be sure they match.  I would like to write the results of the comparison to a file, results.txt.<br>
<br>
Here's the contents of master.txt:<br>
<br>
	WINS Server	: 9.99.99.1<br>
	DNS Servers	: 9.99.99.2<br>
			: 9.99.99.3<br>
<br>
Here's the contents of newfile.txt<br>
<br>
	IP Address	: 9.99.99.10<br>
	Gateway	: 9.99.99.20<br>
	WINS Server	: 9.88.88.88<br>
	Subnet		: 255.255.255.0<br>
	DNS Servers:	: 9.99.99.2<br>
			: 9.99.99.3<br>
	DHCP Server	: 9.99.99.4<br>
<br>
Any help will be greatly appreciated. <br>
<br>
- Stuart</body></html>
--0__=0ABBE130DFDCF32C8f9e8a93df938690918c0ABBE130DFDCF32C--




From urnerk@qwest.net  Mon Apr 22 13:23:08 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 22 Apr 2002 08:23:08 -0400
Subject: [Tutor] ASCII to binary
In-Reply-To: <DAV23UKEwpNzdwcZnOH0000afbf@hotmail.com>
References: <DAV23UKEwpNzdwcZnOH0000afbf@hotmail.com>
Message-ID: <E16zfaS-0003UF-00@mail.python.org>

> Right now I have a dictionary that holds all the values, but I would like
> to remove the need for it if possible.  ei: dict =
> {'A':'01000001','B':'01000010','C':'01000011','D':'01000100'}  This is the
> machine lanuage or what ever the proper term is.  I am not sure.  I was
> calling it binary.
>
> Thanks,
> Cameron

Not so long ago, people were passing around a function that
used a dictionary only for the binary strings 0000 thru 1111.

If you get the hex byte of a character and break it into 
two half-bytes, you can read out the binary string with a
much shorter dictionary.  bitdict only maps the 16 hex 
digits, 0...9,a-f.  Any byte is a pair of these.

Example:

   def byte2bit(thechar):
	bitdict = {'0':'0000','1':'0001','2':'0010','3':'0011','4':'0100',
		   '5':'0101','6':'0110','7':'0111','8':'1000','9':'1001',
		   'a':'1010','b':'1011','c':'1100','d':'1101','e':'1110',
		   'f':'1111'}
        hexdigits = hex(ord(thechar))
        return bitdict[hexdigits[2]] + bitdict[hexdigits[3]]

 >>> byte2bit('Z')
 '01011010'
 >>> byte2bit('z')
 '01111010'

Note that ASCII codes, rendered as bits or whatever, a different from 
keyboard scan codes, which covers key combos like Alt+C and Ctrl+V,
the function keys and so on.  

Also, lots of software has moved away from ASCII to Unicode (Java being
an example), which matches ASCII to start, but then goes on to cover 
Chinese etc., using twice the bits (or even more if need be).

Kirby



From urnerk@qwest.net  Mon Apr 22 13:35:08 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 22 Apr 2002 08:35:08 -0400
Subject: [Tutor] Newbie with question about text file processing
In-Reply-To: <OFF59A4AF0.F4BE89DA-ON85256BA3.004F75BC@lotus.com>
References: <OFF59A4AF0.F4BE89DA-ON85256BA3.004F75BC@lotus.com>
Message-ID: <E16zfm3-0004rO-00@mail.python.org>

> Any help will be greatly appreciated.
> 
> - Stuart

Python can read these files into lists of strings.
If the lines you care about all have a colon, you
can skip lines that don't have one:

f = open("newfile.txt")
data = [i for i in f.readlines() if ":" in i]

then you can strip out what's to the left and right
of the colon:

valdict = {}
for d in data:
   colon = d.index(":")
   left,right = d[:colon].strip(), d[colon+1:].strip()
   valdict[left] = right

Now you can lookup values you care about using this 
dictionary, e.g. valdict['DNS'] will be '99.99.91' or
whatever.  Parse in both files like this, and compare
newvalues['DNS'] with oldvalues['DNS'] -- stuff like
that.

Put these pieces together and you've got at least one 
way of doing it.

Kirby




From paulsid@shaw.ca  Mon Apr 22 17:35:47 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Mon, 22 Apr 2002 10:35:47 -0600
Subject: [Tutor] program to count keys with timer display and clock display
References: <3CC42713.6060609@venix.com>
Message-ID: <3CC43BE3.EA619305@shaw.ca>

Lloyd Kvam wrote:

> My son (age 18) is looking to write a program that would count keypresses while
> displaying a 15 minute countdown timer and the current time.  He wants this to
> run under Linux and Windows.  He wants to be able to distinguish keys at a relatively
> low level e.g. RightShift-a, LeftShift-a.

> I (of course) recommended learning some Python to do this, but then started checking.
> The curses module would work for Linux, but not Windows.
> The WConio module would work for Windows, but is fairly different from curses.
> PyGame seems to support timers and keypresses, but looks to be more complex.

I think pygame would be a much better solution than writing two
programs.  It's not anywhere near as hard as it looks.  In fact it might
even be easier to use than the other two.  

Here's a very small, very simple, _working_ pygame program that shows
how to handle keypresses:

*****

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((300, 300), 0, 16)

while 1:
    event = pygame.event.poll()
    if event.type == QUIT:
        break
    if event.type == KEYDOWN:
        if event.key == K_ESCAPE:
            break
        if event.key == K_RETURN:
            screen.fill((255, 255, 255))
            pygame.display.update()
        if event.key == K_SPACE:
            screen.fill((0, 0, 0))
            pygame.display.update()

*****

Not bad for under 20 lines, eh?  Another benefit is he could use
pygame's graphics stuff to dress up the countdown timer, like displaying
it in a nice big font or something.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From paulsid@shaw.ca  Mon Apr 22 17:50:24 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Mon, 22 Apr 2002 10:50:24 -0600
Subject: [Tutor] Newbie with question about text file processing
References: <OFF59A4AF0.F4BE89DA-ON85256BA3.004F75BC@lotus.com>
Message-ID: <3CC43F50.3E85ABD@shaw.ca>

stuart_clemons@us.ibm.com wrote:

> I would like to compare the values of the WINS and DNS fields in the
> newfile.txt against the WINS and DNS values in the master.txt file to
> be sure they match. I would like to write the results of the
> comparison to a file, results.txt.

Please ignore if you really do want a Python solution, but if you just
want to get the task done quickly then the following should work in a
command line window:

fc newfile.txt master.txt > results.txt

Assuming NT still has this command it'll do the job for you.  I know
WinME has it.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From dyoo@hkn.eecs.berkeley.edu  Mon Apr 22 18:12:53 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 22 Apr 2002 10:12:53 -0700 (PDT)
Subject: [Tutor] Visual Basic AND Python, is there a way to...
In-Reply-To: <200204212147.AA113050226@centralcatholic.org>
Message-ID: <Pine.LNX.4.44.0204221003310.19772-100000@hkn.eecs.berkeley.edu>


On Sun, 21 Apr 2002, Robert Garber wrote:

> OK hear goes an off the wall question. I started with python and loved
> it...came very easy to me. I moved on to visual basic. I like the way
> you can set up the GUI first and the methods used in doing so...seems
> very intuitive. i like the dea of writing code for each part of the form
> and object in it...is there a way to use VB6.0 and ptyhon together...
> set up the GUi and use python to write the code for each event in the
> app?or is there an IDE out ther that wroks like VB 6.0 for setting up
> and writting GUI apps? I have to admit I never messed with tkinter, but
> i know it sets up the GUI with code instead the 'drag and drop' methods
> in VB6.0...i like writting code with python..it is the first language i
> have learned and would like to find a way to use both together if
> possible.\

It's possible; I'm not too familiar with the details, but Mark Hammond's
'win32' packages allow you to write Python code and have it accessible
from VB.

    http://www.python.org/windows/win32/
    http://starship.python.net/crew/mhammond/win32/


Hmmmm... I'm doing some quick searches on Google.  Here's a link that
might be useful:

    http://www.hps1.demon.co.uk/users/andy/pyvb/

Looks like a small example of VB driven with Python.  It might be enough
to get you started!  You may also want to check Mark's book, "Python and
Win32 Programming":

    http://www.oreilly.com/catalog/pythonwin32/

Chapter 7 on "Building a GUI with COM" might be very useful for you.


Finally, you might also want to talk with the Python-win32 folks:

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

They have a separate mailing list dedicated for Windows-specific stuff,
and the people there may be able to give more concrete examples of
VB-Python integration.


Best of wishes!




From jeff@ccvcorp.com  Mon Apr 22 18:16:59 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Mon, 22 Apr 2002 10:16:59 -0700
Subject: [Tutor] Visual Basic AND Python, is there a way to...
References: <20020422014901.21913.94861.Mailman@mail.python.org>
Message-ID: <3CC4458A.71981F28@ccvcorp.com>

> "Robert Garber" <garber@centralcatholic.org> wrote:
>
> OK hear goes an off the wall question. I started with python and loved it...came very easy to me. I moved on to visual basic. I like the way you can set up the GUI first and the methods used in doing so...seems very intuitive. i like the dea of writing code for each part of the form and object in it...is there a way to use VB6.0 and ptyhon together... set up the GUi and use python to write the code for each event in the app?or is there an IDE out ther that wroks like VB 6.0 for setting up and writting GUI apps? I have to admit I never messed with tkinter, but i know it sets up the GUI with code instead  the 'drag and drop' methods in VB6.0...i like writting code with python..it is the first language i have learned and would like to find a way to use both together if possible.\

Yes, you can use them together, though it's not quite as trivial as you might be thinking.  The best way would probably be to use Python to create COM objects which expose methods that do whatever event processing you want, and use VB to create the GUI.  You'll need to have stub event handlers in VB, whose purpose is to call the Python COM methods and then display the results in whatever way is appropriate.  The Python COM framework is part of Mark Hammond's Win32 extensions, available as a win32all package from www.python.org, or bundled with ActiveState's ActivePython distribution.  If you want to go this route, I strongly recommend picking up the book "Python Programming on Win32", by Mark Hammond and Andy Robinson.  It includes a lengthy example of doing exactly what you're
asking about.

Another option is to check out Boa Constructor (http://boa-constructor.sourceforge.net), which is a GUI builder for Python and the wxPython GUI framework.  I haven't tried it myself, but I gather that the intent, at least, is similar to VB's IDE.

Jeff Shannon
Technician/Programmer
Credit International





From garber@centralcatholic.org  Mon Apr 22 19:47:58 2002
From: garber@centralcatholic.org (Robert Garber)
Date: Mon, 22 Apr 2002 14:47:58 -0400
Subject: [Tutor] Visual Basic AND Python, is there a way to...
Message-ID: <200204221447.AA82969234@centralcatholic.org>

thanks for your help, i am hot on the trail, of as much Info as I can find on this subject.

The people on tutor have taught me a great deal.
Thanks,
Robert

---------- Original Message ----------------------------------
From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Date: Mon, 22 Apr 2002 10:12:53 -0700 (PDT)

>
>
>On Sun, 21 Apr 2002, Robert Garber wrote:
>
>> OK hear goes an off the wall question. I started with python and loved
>> it...came very easy to me. I moved on to visual basic. I like the way
>> you can set up the GUI first and the methods used in doing so...seems
>> very intuitive. i like the dea of writing code for each part of the form
>> and object in it...is there a way to use VB6.0 and ptyhon together...
>> set up the GUi and use python to write the code for each event in the
>> app?or is there an IDE out ther that wroks like VB 6.0 for setting up
>> and writting GUI apps? I have to admit I never messed with tkinter, but
>> i know it sets up the GUI with code instead the 'drag and drop' methods
>> in VB6.0...i like writting code with python..it is the first language i
>> have learned and would like to find a way to use both together if
>> possible.\
>
>It's possible; I'm not too familiar with the details, but Mark Hammond's
>'win32' packages allow you to write Python code and have it accessible
>from VB.
>
>    http://www.python.org/windows/win32/
>    http://starship.python.net/crew/mhammond/win32/
>
>
>Hmmmm... I'm doing some quick searches on Google.  Here's a link that
>might be useful:
>
>    http://www.hps1.demon.co.uk/users/andy/pyvb/
>
>Looks like a small example of VB driven with Python.  It might be enough
>to get you started!  You may also want to check Mark's book, "Python and
>Win32 Programming":
>
>    http://www.oreilly.com/catalog/pythonwin32/
>
>Chapter 7 on "Building a GUI with COM" might be very useful for you.
>
>
>Finally, you might also want to talk with the Python-win32 folks:
>
>    http://mail.python.org/mailman/listinfo/python-win32
>
>They have a separate mailing list dedicated for Windows-specific stuff,
>and the people there may be able to give more concrete examples of
>VB-Python integration.
>
>
>Best of wishes!
>
>



From rob@jam.rr.com  Mon Apr 22 19:50:39 2002
From: rob@jam.rr.com (Rob Andrews)
Date: Mon, 22 Apr 2002 11:50:39 -0700 (PDT)
Subject: [Tutor] "batch" printing
Message-ID: <20020422185039.70714.qmail@web14203.mail.yahoo.com>

I have several files to print on a Windows 2000 PC.
They can't be pasted together into one large document
for various reasons. I need to be able to print them
in a particular order, but in a "batch" of fifty or
so, printed in the correct order each of the 50 times.
In the case that brings this question to mind, all the
files are in the same folder and happen (dumb luck) to
be in the desired alphanumerical order by filename.

Is there a simple way to do this in Python?

-Hoopy

__________________________________________________
Do You Yahoo!?
Yahoo! Games - play chess, backgammon, pool and more
http://games.yahoo.com/



From urnerk@qwest.net  Mon Apr 22 17:15:32 2002
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 22 Apr 2002 12:15:32 -0400
Subject: [Tutor] "batch" printing
In-Reply-To: <20020422185039.70714.qmail@web14203.mail.yahoo.com>
References: <20020422185039.70714.qmail@web14203.mail.yahoo.com>
Message-ID: <E16zjIM-0007Cc-00@mail.python.org>

On Monday 22 April 2002 02:50 pm, Rob Andrews wrote:
> I have several files to print on a Windows 2000 PC.
> They can't be pasted together into one large document
> for various reasons. I need to be able to print them
> in a particular order, but in a "batch" of fifty or
> so, printed in the correct order each of the 50 times.
> In the case that brings this question to mind, all the
> files are in the same folder and happen (dumb luck) to
> be in the desired alphanumerical order by filename.
>
> Is there a simple way to do this in Python?
>
> -Hoopy

You don't say what kind of files.  If they're like Word
documents or Excel spreadsheets, then it makes more sense
to write a VBA macro to handle the job.  Python has to
work too hard.  If it's something you could do manually
in DOS by sending files to lpt1, as in C:> myfile > lpt1,
then Python could do this for you.  It'll read subdirectories
and execute your DOS commands.

Kirby



From rob@jam.rr.com  Mon Apr 22 20:36:50 2002
From: rob@jam.rr.com (Rob Andrews)
Date: Mon, 22 Apr 2002 14:36:50 -0500
Subject: [Tutor] "batch" printing
References: <20020422185039.70714.qmail@web14203.mail.yahoo.com> <E16zjIM-0007Cc-00@mail.python.org>
Message-ID: <3CC46652.4050205@jam.rr.com>

Sorry about that incomplete message of mine. Accidentally hit *send 
message* so the list got my "notes to self" part. My ISP doesn't let me 
send out email in the normal way when I'm not at home, so I had to use 
the ol' Yahoo! account until I could make it back. (One more good reason 
to set up uselesspython.org and get my hands on a few good POP mail 
accounts.)

The files are Word documents, but the guy I call for VBA macros is just 
a dabbler and doesn't know how to go about it.

Hoopy

Kirby Urner wrote:

> 
> You don't say what kind of files.  If they're like Word
> documents or Excel spreadsheets, then it makes more sense
> to write a VBA macro to handle the job.  Python has to
> work too hard.  If it's something you could do manually
> in DOS by sending files to lpt1, as in C:> myfile > lpt1,
> then Python could do this for you.  It'll read subdirectories
> and execute your DOS commands.
> 
> Kirby





From paulsid@shaw.ca  Mon Apr 22 20:43:26 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Mon, 22 Apr 2002 13:43:26 -0600
Subject: [Tutor] "batch" printing
References: <20020422185039.70714.qmail@web14203.mail.yahoo.com>
 <E16zjIM-0007Cc-00@mail.python.org>
Message-ID: <3CC467DE.52BA0EF5@shaw.ca>

Kirby Urner wrote:

> If it's something you could do manually
> in DOS by sending files to lpt1, as in C:> myfile > lpt1,
> then Python could do this for you.  It'll read subdirectories
> and execute your DOS commands.

Actually if they're printable from DOS, then DOS can do it for you. 
Switch to the directory with the files and enter this command:

for %x in (*.*) do copy %x LPT1

Of course you can change *.* as you see fit, e.g. *.TXT.

For Windows-based files, if the program (Word or whatever) has a command
line option (say -p) to print a file directly, then this would also
work:

for %x in (*.*) do c:\msword\word.exe -p %x

Sad to say it, but it looks like using DOS commands is truly becoming a
lost art...

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From pythontutor@venix.com  Mon Apr 22 20:58:17 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Mon, 22 Apr 2002 15:58:17 -0400
Subject: [Tutor] "batch" printing
References: <20020422185039.70714.qmail@web14203.mail.yahoo.com> <E16zjIM-0007Cc-00@mail.python.org> <3CC46652.4050205@jam.rr.com>
Message-ID: <3CC46B59.4000202@venix.com>

You'll need to spiff this up a bit but:

import win32com.client
wordApp = win32com.client.Dispatch('Word.Application')
wordDoc = wordApp.Documents.Open(r"c:\mydocs\myfile.doc")
wordDoc.PrintOut()

You may also have to watch out for the spooler shuffling the order of files.  I am
not sure if Windows does that to you.

Rob Andrews wrote:

> Sorry about that incomplete message of mine. Accidentally hit *send 
> message* so the list got my "notes to self" part. My ISP doesn't let me 
> send out email in the normal way when I'm not at home, so I had to use 
> the ol' Yahoo! account until I could make it back. (One more good reason 
> to set up uselesspython.org and get my hands on a few good POP mail 
> accounts.)
> 
> The files are Word documents, but the guy I call for VBA macros is just 
> a dabbler and doesn't know how to go about it.
> 
> Hoopy
> 
> Kirby Urner wrote:
> 
>>
>> You don't say what kind of files.  If they're like Word
>> documents or Excel spreadsheets, then it makes more sense
>> to write a VBA macro to handle the job.  Python has to
>> work too hard.  If it's something you could do manually
>> in DOS by sending files to lpt1, as in C:> myfile > lpt1,
>> then Python could do this for you.  It'll read subdirectories
>> and execute your DOS commands.
>>
>> Kirby
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From gman_95@hotmail.com  Mon Apr 22 19:50:04 2002
From: gman_95@hotmail.com (Daryl G)
Date: Mon, 22 Apr 2002 18:50:04 +0000
Subject: [Tutor] HTMLParser question
Message-ID: <F147c91Fi7Ct3kEoGkS000055ce@hotmail.com>



>From: Kirby Urner <urnerk@qwest.net>
>To: "Daryl Gallatin" <gman_95@hotmail.com>, tutor@python.org
>Subject: Re: [Tutor] HTMLParser question
>Date: Sat, 20 Apr 2002 09:43:34 -0400
>
>On Saturday 20 April 2002 09:44 am, Daryl Gallatin wrote:
> > Hi, Thanks
> > Yes, a gui based program that renders HTML is what I am looking to 
>create.
> > say, a python example of an early html browser
>
>OK, that's a fine project to learn from.  I've never done much like
>this myself.


> > non-trivial application? You mean it would actually be simple to do?
>
>Non-trivial means not trivial, where trivial means really easy.

Doh!  :)

I didn't think it would be particularly easy, but hopefully not too hard to 
do a simple HTML browser



> > The text browser example I have is from deitel and deitel's book and is
> > something that I want to expand on and create my own at least simple 
>html
> > browser to at least see how it works.
> >
>
>I'll hand you off to someone better at GUI-based stuff.  You'd have
>to pick a GUI library like Tkinter, and figure out how to translate
>HTML tags into formatting instructions for whatever text window
>widget.
>
>Kirby



Yeah, I figured I'd have to use Tk
And translating the tags is the part that I can't think of  how to do right 
now

Thanks You!


_________________________________________________________________
MSN Photos is the easiest way to share and print your photos: 
http://photos.msn.com/support/worldwide.aspx




From lkvam@venix.com  Mon Apr 22 21:06:58 2002
From: lkvam@venix.com (Lloyd Kvam)
Date: Mon, 22 Apr 2002 16:06:58 -0400
Subject: [Tutor] "batch" printing
References: <20020422185039.70714.qmail@web14203.mail.yahoo.com> <E16zjIM-0007Cc-00@mail.python.org> <3CC467DE.52BA0EF5@shaw.ca>
Message-ID: <3CC46D62.1050807@venix.com>

I hadn't realized that the Windows for...do would sort the filelist correctly.
This does seem simpler.

Paul Sidorsky wrote:

> Kirby Urner wrote:
> 
> 
>>If it's something you could do manually
>>in DOS by sending files to lpt1, as in C:> myfile > lpt1,
>>then Python could do this for you.  It'll read subdirectories
>>and execute your DOS commands.
>>
> 
> Actually if they're printable from DOS, then DOS can do it for you. 
> Switch to the directory with the files and enter this command:
> 
> for %x in (*.*) do copy %x LPT1
> 
> Of course you can change *.* as you see fit, e.g. *.TXT.
> 
> For Windows-based files, if the program (Word or whatever) has a command
> line option (say -p) to print a file directly, then this would also
> work:
> 
> for %x in (*.*) do c:\msword\word.exe -p %x
> 
> Sad to say it, but it looks like using DOS commands is truly becoming a
> lost art...
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From imcmeans@shaw.ca  Tue Apr 23 12:02:56 2002
From: imcmeans@shaw.ca (Ian!)
Date: Tue, 23 Apr 2002 04:02:56 -0700
Subject: [Tutor] copy / paste
References: <20020422160004.1970.76624.Mailman@mail.python.org>
Message-ID: <00db01c1eab6$6c70be00$da494e18@cr536745a>

How can I copy and paste to the windows clipboard from a python script? I
wasn't able to find anything about this in the library reference.




From imcmeans@shaw.ca  Tue Apr 23 12:04:13 2002
From: imcmeans@shaw.ca (Ian!)
Date: Tue, 23 Apr 2002 04:04:13 -0700
Subject: [Tutor] copy / paste
Message-ID: <00e701c1eab6$9a500f10$da494e18@cr536745a>

(oops, I sent the message without the [Tutor] tag. Sorry to whomever gets
that accidentally)

So, here's the question: How can I copy and paste to the windows clipboard
from a python script? I wasn't able to find anything about this in the
library reference.





From erikprice@mac.com  Tue Apr 23 12:41:46 2002
From: erikprice@mac.com (Erik Price)
Date: Tue, 23 Apr 2002 07:41:46 -0400
Subject: [Tutor] Python with readline
In-Reply-To: <20020418035330.GA15806@dman.ddts.net>
Message-ID: <178BB710-56AF-11D6-864B-00039351FE6A@mac.com>

On Wednesday, April 17, 2002, at 11:53  PM, dman wrote:

> No .so files?  They are always named libfoo.so, where 'foo' is the name
> of the library.

Not any that I could see.

> | And I believe my readline library is /sw/include/readline (if the /sw/
> | dir looks unfamiliar, it's the equivalent of /usr/local/ used by Fink,
> | the Unix ported package management app for Mac OS X).
>
> The .h is the "include" file.  It is C source that is required for
> compiling anything that uses the library.  The .so file is the "shared
> library" file.  It is the already-compiled implementation of the
> library.  The app (python in your case) will be dynamically linked
> against that .so when it runs.

Useful knowledge.  Why does it need to be source code -- couldn't this 
information just be placed into the shared library (.so) file?

> Stuff in /usr/share is typically just arbitrary data the app/lib uses
> as it runs.

Someone told me that the "setup.py" script automatically checks for the 
presence of GNU Readline.  I didn't even know about this script, I 
assumed that all you do is ./configure; make; make install.  So I looked 
at it, and then I looked at the ./configure script.  Nope, setup.py does 
not appear to be called by ./configure (although I would have assumed it 
was).  So I need to run setup.py myself.  This is interesting for two 
reasons --

1) setup.py is not an executable.  No reason it should be, but then, 
doesn't that assume that I have a working version of Python on my 
system?  Otherwise this "setup" script wouldn't work.  Fortunately I do, 
but if this was my first time building Python... well, it just seems 
strange.

2) the interface is not readily apparent.  Although running "python 
setup.py --help" does display a list of options, it does not display a 
list of COMMANDS that need to be given (as arguments?) with the setup.py 
script.  I didn't actually get a chance to look at the source code yet, 
to see if I can figure out what I'm supposed to do, but perhaps someone 
on this list is more familiar with setup.py and can tell me what I 
should be doing.

TIA,


Erik




From m_konermann@gmx.de  Tue Apr 23 16:56:12 2002
From: m_konermann@gmx.de (Marcus)
Date: Tue, 23 Apr 2002 17:56:12 +0200
Subject: [Tutor] memory allocation error
Message-ID: <3CC5841C.1050509@gmx.de>

Hello !

I've got Problems with memory allocation errors after wrapping C++ code. 
I want to create a few instances (sap_h1, sap_h2) from the class 
simanneal_parameter(), exsisting in a module named simannealfile.py. 
simannealfile.py is a python shadow class created with SWIG. And now, 
after running a script, consist of the following instances, i get a 
memory allocation error under WindowsXP and also under Windows 98. I 
tried different systems to check, if my hardware was ok.

sap_h1=simannealfile.simanneal_parameter()
sap_h2=simannealfile.simanneal_parameterPtr(sap_h1)    

The allocation error will also be there, if i build up a few more 
different instances of one class. And perhaps some time, if i declare 
the same instances a little bit later in my dummy file, there were´nt 
any allocation errors at all . I absolutly don´t know if it´s a problem 
of SWIG (C++  -> Python) or of Python.
Perhaps anyone has got an idea ?

Thanks for your help
greetings
Marcus




From jgregorio@ultrasw.com  Tue Apr 23 18:20:37 2002
From: jgregorio@ultrasw.com (Josh Gregorio)
Date: Tue, 23 Apr 2002 10:20:37 -0700
Subject: [Tutor] lists
Message-ID: <000a01c1eaeb$45d537a0$abf1b542@computer>

This is a multi-part message in MIME format.

------=_NextPart_000_0007_01C1EAB0.8311A580
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

What are linked lists and do you need them in Python?=20

Thanks,=20
Josh

------=_NextPart_000_0007_01C1EAB0.8311A580
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>What are linked lists and do you need =
them in=20
Python? </FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>Thanks, </FONT></DIV>
<DIV><FONT face=3DArial>Josh</FONT></DIV></BODY></HTML>

------=_NextPart_000_0007_01C1EAB0.8311A580--




From bryce@bembry.org  Tue Apr 23 18:31:47 2002
From: bryce@bembry.org (Bryce Embry)
Date: Tue, 23 Apr 2002 12:31:47 -0500
Subject: [Tutor] py2exe and Tkinter
Message-ID: <5.1.0.14.0.20020423122509.02e4dee0@www.bembry.org>

I've got a small script I wrote in Tkinter.  I want to make the script an 
executable in Windows, which is not to hard to do with py2exe or 
installer.  What's driving me crazy is that whenever I run the executable, 
a big, ugly DOS window opens up behind the GUI.  Is there any way to get 
rid of this ugly box and have just my GUI showing?

Here's the script.  it works fine in Python, just need to get rid of that 
ugly DOS screen, if it's possible.  The script is just a random number 
generator for use in a business that has to randomly pick truck drivers to 
screen.:


# num_gen.py
from Tkinter import *
from random import randrange
root = Tk()
root.title("Phyllis's Random Numbers")
# row 1 ------------------------------------------
Label(root, text="How many numbers do you need?").grid(row=1, column=0)
num_of_nums = Entry(root, width = 5)
num_of_nums.grid(row=1, column = 1)

# row 2 ------------------------------------------
Label(root, text = "Largest number to choose: ").grid(row=2, column=0)
max_num = Entry(root, width=5)
max_num.grid(row=2, column =1)


# Define random number generator function
def num_generator():
     total = int(num_of_nums.get())
     maxnum = int(max_num.get())
     output = []
     for i in range(total):
         newnum = randrange(0, maxnum)
         if newnum not in output:
             output.append(newnum)
         else:
             pass
     output.sort()
     output_text = ""

     for item in output:
         output_text += str(item) + "\n"

     root2 = Toplevel(root)
     Message(root2, text = output_text).grid()

#row 3---------------------------------------------
Button(root, text= "Get Numbers", command = num_generator).grid(row=3, 
columnspan=2)

root.mainloop()

---------------------------------------------------------------------------------------------------
Thanks


Bryce Embry
Geek-Of-All-Trades / Master-Of-None

www.bembry.org
--------------------------------------------------------------------------------------------------------------------------------------------------------
Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 
38117 ^ (901)682-2409
--------------------------------------------------------------------------------------------------------------------------------------------------------




From scot@possum.in-berlin.de  Tue Apr 23 15:53:36 2002
From: scot@possum.in-berlin.de (Scot Stevenson)
Date: Tue, 23 Apr 2002 16:53:36 +0200
Subject: [Tutor] editing scripts with Vim
References: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
Message-ID: <200204222204.g3MM4JR10066@possum.cozen.org>

Unfortunately, on Tuesday 23 April 2002 16:44, I wrote:

> and "filetype indent on",
> which makes vim color your text according to the filetype. 

Oh, of course it doesn't do that. It does what the name says it does, 
makes vim /indent/ your text according to the filetype. 

Now, doesn't this make you feel good to know I don't work in a nuclear 
power plant?

Y, Scot



From scot@possum.in-berlin.de  Tue Apr 23 15:44:31 2002
From: scot@possum.in-berlin.de (Scot Stevenson)
Date: Tue, 23 Apr 2002 16:44:31 +0200
Subject: [Tutor] editing scripts with Vim
In-Reply-To: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
References: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
Message-ID: <200204222155.g3MLtER10029@possum.cozen.org>

Hello Kent, ,

> Vim looks like a good free cross platform
> editor for editing Python.

If you can type with all ten fingers, there is no other way to fly. My 
.vimrc file looks like this: 

===========================================

" We use a vim
set nocompatible
"
" Colo(u)red or not colo(u)red
" If you want color you should set this to true
"
let color = "true"
"
if has("syntax")
    if color == "true"
	" This will switch colors ON
	so ${VIMRUNTIME}/syntax/syntax.vim
    else
	" this switches colors OFF
	syntax off
	set t_Co=0
    endif
endif
set textwidth=75
set autoindent
set tabstop=8
set expandtab
set shiftwidth=4
filetype indent on
" ~/.vimrc ends here

============================================

This is bascially the way SuSE ships it, my additions are the "set 
shiftwidth=4" (for Python, this lets you do a CNTRL-T to get a Python 
indent while keeping the tapstop at eight), and "filetype indent on", 
which makes vim color your text according to the filetype. If I remember 
correctly, SuSE has "let color = "false" as default, but I am not sure 
anymore. 

I have no idea what this would look like in a Windows environment. 

Y, Scot



From tjenkins@devis.com  Tue Apr 23 18:32:31 2002
From: tjenkins@devis.com (Tom Jenkins)
Date: 23 Apr 2002 13:32:31 -0400
Subject: [Tutor] py2exe and Tkinter
In-Reply-To: <5.1.0.14.0.20020423122509.02e4dee0@www.bembry.org>
References: <5.1.0.14.0.20020423122509.02e4dee0@www.bembry.org>
Message-ID: <1019583152.12197.10.camel@asimov>

On Tue, 2002-04-23 at 13:31, Bryce Embry wrote:
> I've got a small script I wrote in Tkinter.  I want to make the script an 
> executable in Windows, which is not to hard to do with py2exe or 
> installer.  What's driving me crazy is that whenever I run the executable, 
> a big, ugly DOS window opens up behind the GUI.  Is there any way to get 
> rid of this ugly box and have just my GUI showing?
> 

Try running py2exe with the -w flag (or --windows flag):
python setup.py py2exe -w

http://starship.python.net/crew/theller/py2exe/
-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com





From bryce@bembry.org  Tue Apr 23 18:43:28 2002
From: bryce@bembry.org (Bryce Embry)
Date: Tue, 23 Apr 2002 12:43:28 -0500
Subject: [Tutor] py2exe and Tkinter
In-Reply-To: <1019583152.12197.10.camel@asimov>
References: <5.1.0.14.0.20020423122509.02e4dee0@www.bembry.org>
 <5.1.0.14.0.20020423122509.02e4dee0@www.bembry.org>
Message-ID: <5.1.0.14.0.20020423124254.02e5c118@www.bembry.org>

Wow, that was easy enough.  I feel kind of foolish now.  Thanks for the help.

Bryce

At 12:32 PM 4/23/2002, you wrote:
>On Tue, 2002-04-23 at 13:31, Bryce Embry wrote:
> > I've got a small script I wrote in Tkinter.  I want to make the script an
> > executable in Windows, which is not to hard to do with py2exe or
> > installer.  What's driving me crazy is that whenever I run the executable,
> > a big, ugly DOS window opens up behind the GUI.  Is there any way to get
> > rid of this ugly box and have just my GUI showing?
> >
>
>Try running py2exe with the -w flag (or --windows flag):
>python setup.py py2exe -w
>
>http://starship.python.net/crew/theller/py2exe/
>--
>
>Tom Jenkins
>Development InfoStructure
>http://www.devis.com


Bryce Embry
Geek-Of-All-Trades / Master-Of-None

www.bembry.org
--------------------------------------------------------------------------------------------------------------------------------------------------------
Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 
38117 ^ (901)682-2409
--------------------------------------------------------------------------------------------------------------------------------------------------------




From dyoo@hkn.eecs.berkeley.edu  Tue Apr 23 18:58:24 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Apr 2002 10:58:24 -0700 (PDT)
Subject: [Tutor] lists
In-Reply-To: <000a01c1eaeb$45d537a0$abf1b542@computer>
Message-ID: <Pine.LNX.4.44.0204231044160.28766-100000@hkn.eecs.berkeley.edu>


On Tue, 23 Apr 2002, Josh Gregorio wrote:

> What are linked lists and do you need them in Python?

Hi Josh,

The "How To Think Like a Computer Scientist" tutorial has a nice section
on linked lists here:

    http://www.ibiblio.org/obp/thinkCSpy/chap17.htm


A linked list is a data structure that allows us to string together bits
of data into a long chain.

But let's first compare this with what you know already, a regular Python
list.  A Python list is a blocky container:

-----------------
|   |   |   |   |
|   |   |   |   |
-----------------

and we can use it to store multiple values in one place.


A linked list does the same sort of thing --- they're used to keep objects
--- but instead of all the blocks being arranged right next to each other,
we string them together with "references":

-----            -----
|   |----------->|   |-------+
|   |            |   |       |
-----            -----       |
                             V
                            -----
                            |   |
                            |   |
                            -----
                              |
                              |         -----
                              +-------->|   |
                                        |   |
                                        -----

One advantage of stringing the blocks is that it's efficient to insert a
new block right in the middle of the chain: all we need to do is reroute a
link or two, and that's it.  In contrast, in a regular Python list,
insertion usually involves bumping off all the neighbors to the right so
that we have the room to do the insertion.


As you're browsing through that chapter, please feel free to bring your
questions here; we'll be happy to talk about linked lists.

Good luck!






From vcardon@siue.edu  Tue Apr 23 13:00:47 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Tue, 23 Apr 2002 07:00:47 -0500
Subject: [Tutor] lists
In-Reply-To: <000a01c1eaeb$45d537a0$abf1b542@computer>
References: <000a01c1eaeb$45d537a0$abf1b542@computer>
Message-ID: <20020423120047.GA9495@spastic.siue.edu>

--LZvS9be/3tNcYl/X
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Apr 23, 2002 at 10:20:37AM -0700, Josh Gregorio wrote:
> What are linked lists and do you need them in Python?=20

A linked list is a data structure where each item in the list is
considered a node, and each node points to either the following node,
the preceeding node, or both. If it points to both the following node
and the preceeding node, then it is called a doubly linked list.

Linked lists are created using pointers in lanquages like C and C++.
Nodes are accessed in a linear fashion. However, the design makes the
removal or insertion of nodes very efficient.

You do not need linked lists in Python. In fact it would be very
difficult to create (if not impossible), because Python does not have
pointers. A standard list in Python should give you the functionality of
a linked list, and is much easier to create :-)

HTH,
Victor


--LZvS9be/3tNcYl/X
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8xUzvZU/bSegbOhwRAvkIAJwK83HR5+2UlPkYv6n7DomhhhTUbQCggykm
ILV9A4UT0OeiSWOYUVbwSTs=
=lv3M
-----END PGP SIGNATURE-----

--LZvS9be/3tNcYl/X--



From dman@dman.ddts.net  Tue Apr 23 20:25:40 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 23 Apr 2002 14:25:40 -0500
Subject: [Tutor] editing scripts with Vim
In-Reply-To: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
References: <200204211244.g3LCifP6025069@bucky.airstreamcomm.net>
Message-ID: <20020423192540.GA24222@dman.ddts.net>

On Sun, Apr 21, 2002 at 07:37:38AM -0500, kent@springfed.com wrote:
| Howdy,
|=20
| Vim looks like a good free cross platform
| editor for editing Python.

It is!

| I seem to recall that Vim provided for
| highlighting a line of code and sending it
| to the interpreter, I can't find the reference.
|=20
| I would appreciate any hints and tips on
| setting up Vim for efficient programming.

In my .vimrc I have (amongst other stuff) :


~~~~~~~~~~~~~~~~~~~~~~
highlight Normal guibg=3Dblack guifg=3Dgrey90
set background=3Ddark     " makes syntax highlighing lighter
syntax on

set autoindent
set tabstop=3D8                   " Tabs are always 8 characters!!!
set softtabstop=3D4 shiftwidth=3D4  " default character indentation level
set expandtab                   " use spaces instead of tabs for indentation

set ruler           " show cursor postion
set esckeys         " allow cursor keys in insert mode
set showcmd         " Show (partial) command in status line.
"set hlsearch        " Highlight all matches of the last search pattern (so=
metimes annoying, good for code)
set showmatch       " show matching parens/brackets
set backspace=3D2     " allows for backspace beyond current insert session
set joinspaces      " insert 2 spaces after a period when joining lines
set fileformat=3Dunix " The Right Way(tm)
" Don't be noisy, don't flash the screen
set noerrorbells visualbell
" note : this only works for the console!  it is reset when gvim starts
set t_vb=3D

set guioptions-=3DT   " no toolbar, I don't use it anyways!

" enable the new filetype and indent plugins
filetype on
filetype plugin on
filetype indent on

set lcs=3Dtab:>-
set list

" this takes effect when the syntax file is loaded
let python_highlight_all=3D1

augroup Python
    au!
    au BufNewFile *.py 0read ~/util/templates/Python.py
    " see also :help smartindent , cinwords
    au FileType python set sts=3D4 sw=3D4 et tw=3D80 fo=3Dcroq2 hls fenc=3D=
utf-8
    au FileType python set comments=3Db:#=20

    " turn off the C preprocessor indenting
    " (allow comments to be indented properly)
    au FileType python inoremap # X=08#

    au FileType python set foldmethod=3Dindent
    " do I want everything collapsed when I open the file?
    "au FileType python set foldenable
    au FileType python set nofoldenable
augroup END
~~~~~~~~~~~~~~~~~~~~~~

(note between the 'X' and the '#' in the "inoremap" command is a
literal ^H (backspace) character, you type it by pressing ^V^H)

Once you've got this configuration, all you need to do is learn how to
use vim :-).

HTH,
-D

--=20

A wise servant will rule over a disgraceful son,
and will share the inheritance as one of the brothers.
        Proverbs 17:2




From dyoo@hkn.eecs.berkeley.edu  Tue Apr 23 21:52:26 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Apr 2002 13:52:26 -0700 (PDT)
Subject: [Tutor] lists    [Linked lists]
In-Reply-To: <20020423120047.GA9495@spastic.siue.edu>
Message-ID: <Pine.LNX.4.44.0204231333590.2516-100000@hkn.eecs.berkeley.edu>


On Tue, 23 Apr 2002, Victor R. Cardona wrote:

> Linked lists are created using pointers in lanquages like C and C++.
> Nodes are accessed in a linear fashion. However, the design makes the
> removal or insertion of nodes very efficient.
>
> You do not need linked lists in Python. In fact it would be very
> difficult to create (if not impossible), because Python does not have
> pointers. A standard list in Python should give you the functionality of
> a linked list, and is much easier to create :-)

Actually, it's not so hard.


###
class Cons:
    def __init__(self, head, tail):
        self.head, self.tail = head, tail

NULL_LIST = None
###

Done.  *grin*



Here's how we can work with them:

###
>>> mylist = Cons(1, Cons(2, Cons(3, NULL_LIST)))
>>> mylist
<__main__.Cons instance at 0x81156ec>
###

'mylist' is now a list of three elements.  We can get at the value of the
head of our list by doing a elements when we yank on the "head" of our
list.

###
>>> mylist.head
1
###

And to get to the other elements in a linked list, we just start dragging
it by its tail!

###
>>> mylist.tail
<__main__.Cons instance at 0x8112b2c>
>>> mylist.tail.head
2
>>> mylist.tail.tail.head
3
###

We stop pulling at the tail when there's no more tail to yank.

###
>>> mylist.tail.tail.tail
>>> mylist.tail.tail.tail.head
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'None' object has no attribute 'head'
###

Linked lists are nice because they're conceptually simple once you see a
picture of them.  Think LEGO, and how the pieces fit together, and that's
a good idea of how linked lists work.  *grin*



Please feel free to ask more questions about this.  Hope this helps!




From phthenry@earthlink.net  Tue Apr 23 21:54:57 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Tue, 23 Apr 2002 16:54:57 -0400
Subject: [Tutor] using class methods (security)
Message-ID: <20020423165457.B29513@localhost.localdomain>

I am wondering if there is a good way to create class methods in
python.

I have included a simple script below to illustrate what I mean.

There seems to be no way to call on a class object directly in
python. Both methods I know of seem seem awkward:

(1)Modify the variable directly. For example, in the class below I
created a counter, called counter, which keeps track of many
Circle ojbects I have created. When I want to find out what the
counter is, I simply request the value for Circle.counter. But I
have been told you should never access a class variable directly.

(2)Use an object to access a class variable. For example, I
created a second counter called __counter. This counter is
private. In order to access it, I simply used an object method:

myCircleObject.numOfCircles()

It somehow seems wrong to access a class variable by using an
object, though I guess this second method should work, and seems
more secure and preferable to the first. 

Thanks!

Paul


#!/usr/bin/python

class Circle:
	__pi = 3.14159
	counter = 0
	__counter = 0 # desired method
     
	def __init__(self,radius=1):
		self.__radius=radius
		Circle.counter = Circle.counter +1
		Circle.__counter = Circle.__counter + 1 #desired method
          
	def area(self):
		return self.__radius * self.__radius * Circle.__pi
          
	def numOfCircles(self):
		print Circle.__counter
                
     
# This function gives simple accesses the class variable
# Circle.counter

def numCircles():
	total = 0
	print Circle.counter

myCircleObject = Circle(5)
print myCircleObject.area()
myCircle2Object = Circle()
print myCircleObject2.area()
numCircles() # access a class variable directly
Circle.counter = 100 # You can create a bogus number. Yikes!
numCircles() # prints out a bogus number
myCircleObject.numOfCircles() #object method to access class
						#variable


-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From dyoo@hkn.eecs.berkeley.edu  Tue Apr 23 21:57:21 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Apr 2002 13:57:21 -0700 (PDT)
Subject: [Tutor] lists    [Linked lists]
In-Reply-To: <Pine.LNX.4.44.0204231333590.2516-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0204231353400.2516-100000@hkn.eecs.berkeley.edu>


> Here's how we can work with them:
>
> ###
> >>> mylist = Cons(1, Cons(2, Cons(3, NULL_LIST)))
> >>> mylist
> <__main__.Cons instance at 0x81156ec>
> ###
>
> 'mylist' is now a list of three elements.  We can get at the value of the
> head of our list by doing a elements when we yank on the "head" of our
> list.

??!  Sorry about the unreadability of that last sentence.  It used to be
two sentences, but I merged the sentences together... but didn't merge it
correctly. I meant to say:

"""
We can grab at the very first value in our list by yanking at the "head"
of our list.
"""




From paulsid@shaw.ca  Tue Apr 23 22:29:51 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Tue, 23 Apr 2002 15:29:51 -0600
Subject: [Tutor] using class methods (security)
References: <20020423165457.B29513@localhost.localdomain>
Message-ID: <3CC5D24F.58091B70@shaw.ca>

Paul Tremblay wrote:

> It somehow seems wrong to access a class variable by using an
> object, though I guess this second method should work, and seems
> more secure and preferable to the first.

>         def numOfCircles(self):
>                 print Circle.__counter

I was about to recommend simply removing "self" from the parameter list
and calling this as Circle.numOfCircles() when I discovered it doesn't
work!  It seems like such a natural solution that I very nearly didn't
even bother to verify it.

Naturally I got curious about why it doesn't work so I went to find the
answer.  Luckily I didn't have to look too far:  there's an explanation
in the FAQ, question 6.24, along with some recommendations.

I think it's kind of a pity this doesn't work in the "obvious" way.  On
the other hand, I've never found class variables and methods to be all
that useful so it doesn't bother me that they aren't supported all that
well.  I expect one could research the debate in the c.l.py archives if
one wanted to, though.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From kalle@gnupung.net  Wed Apr 24 01:32:33 2002
From: kalle@gnupung.net (Kalle Svensson)
Date: Wed, 24 Apr 2002 02:32:33 +0200
Subject: [Tutor] using class methods (security)
In-Reply-To: <20020423165457.B29513@localhost.localdomain>
References: <20020423165457.B29513@localhost.localdomain>
Message-ID: <20020424003233.GA10199@i92.ryd.student.liu.se>

[Paul Tremblay]
> I am wondering if there is a good way to create class methods in
> python.

If you're using Python 2.2 or later, you already have them.  They seem
to be poorly documented, but there is some information and an example
in A.M. Kuchling's _What's New in Python 2.2_
(http://amk.ca/python/2.2/).

Med utmärkt högaktning,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.



From dyoo@hkn.eecs.berkeley.edu  Wed Apr 24 02:18:14 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Apr 2002 18:18:14 -0700 (PDT)
Subject: [Tutor] copy / paste
In-Reply-To: <00e701c1eab6$9a500f10$da494e18@cr536745a>
Message-ID: <Pine.LNX.4.44.0204231815010.12261-100000@hkn.eecs.berkeley.edu>


On Tue, 23 Apr 2002, Ian! wrote:

> (oops, I sent the message without the [Tutor] tag. Sorry to whomever gets
> that accidentally)

No problem.


> So, here's the question: How can I copy and paste to the windows
> clipboard from a python script? I wasn't able to find anything about
> this in the library reference.

Here you go:

    http://margaretmorgan.com/wesley/python/clipboard.py



Good luck!




From dyoo@hkn.eecs.berkeley.edu  Wed Apr 24 02:23:06 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 23 Apr 2002 18:23:06 -0700 (PDT)
Subject: [Tutor] copy / paste    [win32clipboard]
In-Reply-To: <Pine.LNX.4.44.0204231815010.12261-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0204231820420.12261-100000@hkn.eecs.berkeley.edu>


On Tue, 23 Apr 2002, Danny Yoo wrote:

> > So, here's the question: How can I copy and paste to the windows
> > clipboard from a python script? I wasn't able to find anything about
> > this in the library reference.
>
> Here you go:
>
>     http://margaretmorgan.com/wesley/python/clipboard.py

Actualy, there may be a better module than this.  The win32 extensions by
Mark Hammond has a 'win32clipboard' module that sounds perfect for you:

http://aspn.activestate.com/ASPN/Reference/Products/ActivePython/PythonWin32Extensions/win32clipboard.html

If you're using vanilla Python, you may need to download the win32
extensions here:

    http://starship.python.net/crew/mhammond/win32/Downloads.html


Good luck to you!




From Karthik_Gurumurthy@i2.com  Wed Apr 24 06:22:58 2002
From: Karthik_Gurumurthy@i2.com (Karthik_Gurumurthy@i2.com)
Date: Wed, 24 Apr 2002 10:52:58 +0530
Subject: [Tutor] using class methods (security)
Message-ID: <OF620FAEAA.A361AF81-ON65256BA5.001D62D9@i2.com>

This is a multipart message in MIME format.
--=_alternative 001D917565256BA5_=
Content-Type: text/plain; charset="us-ascii"

> I am wondering if there is a good way to create class methods in
> python.

python2.2 has  a way to specify static methods. There is somethign called 
class method as well which is different from static methods which you are 
referring to.

class test(object):
    __count = 0
    def __init__(self):
        test.__count+=1
        print test.__count
 
    def func(self):
        pass
 
    def get_count():
        return test.__count
 
    def __del__(self):
        test.__count-=1
 
    get_count = staticmethod(get_count)

if __name__ == '__main__':
    t1 = test()
    print test.get_count()





--=_alternative 001D917565256BA5_=
Content-Type: text/html; charset="us-ascii"

<br>
<br><font size=2 face="Courier New">&gt; I am wondering if there is a good way to create class methods in<br>
&gt; python.</font>
<br>
<br><font size=2 face="sans-serif">python2.2 has &nbsp;a way to specify static methods. There is somethign called class method as well which is different from static methods which you are referring to.</font>
<br>
<br><font size=2 face="sans-serif">class test(object):</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; __count = 0</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; def __init__(self):</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; test.__count+=1</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; print test.__count</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; </font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; def func(self):</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; pass</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; </font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; def get_count():</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; return test.__count</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; </font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; def __del__(self):</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; test.__count-=1</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; &nbsp; &nbsp; </font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; get_count = staticmethod(get_count)</font>
<br>
<br><font size=2 face="sans-serif">if __name__ == '__main__':</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; t1 = test()</font>
<br><font size=2 face="sans-serif">&nbsp; &nbsp; print test.get_count()</font>
<br><font size=2 face="Courier New"><br>
<br>
</font>
<br>
<br>
--=_alternative 001D917565256BA5_=--



From apython101@yahoo.com  Wed Apr 24 13:52:41 2002
From: apython101@yahoo.com (john public)
Date: Wed, 24 Apr 2002 05:52:41 -0700 (PDT)
Subject: [Tutor] integers from strings
Message-ID: <20020424125241.35417.qmail@web21109.mail.yahoo.com>

--0-113823897-1019652761=:35375
Content-Type: text/plain; charset=us-ascii


 

this code works for two people to play tic tac toe using x and o for responses to raw input "who gets the square?"

a,b,c,d,e,f,g,h,i = 1,2,3,4,5,6,7,8,9 


sq = ['a','b','c','d','e','f','g','h','i',]

for p in range(9):
    print sq[0],sq[1],sq[2]
    print sq[3],sq[4],sq[5]
    print sq[6],sq[7],sq[8]
    n = input('which square?')
    s = raw_input("who gets the square?")
    sq[ n-1] = s
    

 I tried writing code so the machine would say "x (or o) wins" if some one won before the ninth draw. my problem in doing so was that raw_input was a string so I could not assign x and o to an integer and use an if loop to  print "x wins" if f sq[0] +sq[1]+sq[2] = 3x, ect.

Dropping the ' ' marks as so, sq = [a,b,c]  opens possiblitities except that it writes 1,2,3 instead of a,b,c on the tic tac toe board.-  One way I have thought of solving the problem is by having two lists sq=['a','b','c','d','e','f','g','h','i'] and ad=[a,b,c,d,e,f,g,h,i]  but I would need to generate x the string and x the variable assigned to an integer from raw_input. int() does not work. int will change the string'55' to the integer 55 but it won't turn the string 'x' into the variable x that is assigned to an integer even if x=55 is written in the program before raw_input is used.

 one thing that is confusing me greatly is that I assigned x to 11 at one point x=11, and now even thought I have erased x=11 x is still equal to 11 no matter what I do? I am completely baffled by this. evne if I shut off my computer x=11 still remains. I am doing this in IDLE 2.1 All comments appreciated.



---------------------------------
Do You Yahoo!?
Yahoo! Games - play chess, backgammon, pool and more
--0-113823897-1019652761=:35375
Content-Type: text/html; charset=us-ascii

<P>&nbsp;</P>
<P>this code works for two people to play tic tac toe using x and o for responses to raw input "who gets the square?"</P>
<P>a,b,c,d,e,f,g,h,i = 1,2,3,4,5,6,7,8,9 <BR><BR><BR>sq = ['a','b','c','d','e','f','g','h','i',]<BR><BR>for p in range(9):<BR>&nbsp;&nbsp;&nbsp; print sq[0],sq[1],sq[2]<BR>&nbsp;&nbsp;&nbsp; print sq[3],sq[4],sq[5]<BR>&nbsp;&nbsp;&nbsp; print sq[6],sq[7],sq[8]<BR>&nbsp;&nbsp;&nbsp; n = input('which square?')<BR>&nbsp;&nbsp;&nbsp; s = raw_input("who gets the square?")<BR>&nbsp;&nbsp;&nbsp; sq[ n-1] = s<BR>&nbsp;&nbsp;&nbsp; </P>
<P>&nbsp;I tried writing code so the machine would say "x (or o) wins" if some one won before the ninth draw. my problem in doing so was that raw_input was a string so I could not assign x and o to an integer and use an if loop to&nbsp; print "x wins" if f sq[0] +sq[1]+sq[2] = 3x, ect.</P>
<P>Dropping the ' ' marks as so, sq = [a,b,c]&nbsp; opens possiblitities except that it writes 1,2,3 instead of a,b,c on the tic tac toe board.-&nbsp; One way I have thought of solving the problem is by having two lists sq=['a','b','c','d','e','f','g','h','i'] and ad=[a,b,c,d,e,f,g,h,i]&nbsp; but I would need to generate x the string and x the variable assigned to an integer from raw_input. int() does not work. int will change the string'55' to the integer 55 but it won't turn the string 'x' into the variable x that is assigned to an integer even if x=55 is written in the program before raw_input is used.</P>
<P>&nbsp;one thing that is confusing me greatly is that I assigned x to 11 at one point x=11, and now even thought I have erased x=11 x is still equal to 11 no matter what I do? I am completely baffled by this. evne if I shut off my computer x=11 still remains. I am doing this in IDLE 2.1 All comments appreciated.</P><p><br><hr size=1><b>Do You Yahoo!?</b><br>
<a href="http://rd.yahoo.com/welcome/*http://games.yahoo.com">Yahoo! Games</a> - play chess, backgammon, pool and more
--0-113823897-1019652761=:35375--



From pythontutor@venix.com  Wed Apr 24 16:40:45 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Wed, 24 Apr 2002 11:40:45 -0400
Subject: [Tutor] reading dBase IV files (.DBF)
References: <0F757892D113D611BD2E0002559C1FF472CF29@EMAIL>
Message-ID: <3CC6D1FD.5020307@venix.com>

There is some code in the Vaults of Parnassus
http://www.kw.igs.net/~jimbag/

I found the DataHandler clumsy to use.  The method setData
in class DBFCursor (DBFcursor.py) handles the DBF file structure
to determine the fields in the file and the file layout.

I suspect that you can build from that to get what you really need.

Ezequiel, Justin wrote:

> Is it possible?
> Can somebody point me to samples/tutorials/resources/etc.?
> BTW, the said .DBF file I need to read would have 500,000+ records.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From jgregorio@ultrasw.com  Wed Apr 24 17:37:38 2002
From: jgregorio@ultrasw.com (Josh Gregorio)
Date: Wed, 24 Apr 2002 09:37:38 -0700
Subject: [Tutor] lists
References: <000a01c1eaeb$45d537a0$abf1b542@computer>
Message-ID: <001e01c1ebae$5c0123e0$a6f1b542@computer>

This is a multi-part message in MIME format.

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

Thanks! I'm going to go through that whole "Think Like a Computer =
Scientist" tutorial. It's got a lot of stuff not covered in my other =
materials.=20

Josh
  ----- Original Message -----=20
  From: Josh Gregorio=20
  To: tutor@python.org=20
  Sent: Tuesday, April 23, 2002 10:20 AM
  Subject: [Tutor] lists


  What are linked lists and do you need them in Python?=20

  Thanks,=20
  Josh

------=_NextPart_000_001B_01C1EB73.AC3363E0
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>Thanks! I'm going to go through that =
whole "Think=20
Like a Computer Scientist" tutorial. It's got a lot of stuff not covered =
in my=20
other materials. </FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>Josh</FONT></DIV>
<BLOCKQUOTE=20
style=3D"BORDER-LEFT: #000000 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: =
0px; PADDING-LEFT: 5px; PADDING-RIGHT: 0px">
  <DIV style=3D"FONT: 10pt arial">----- Original Message ----- </DIV>
  <DIV=20
  style=3D"BACKGROUND: #e4e4e4; FONT: 10pt arial; font-color: =
black"><B>From:</B>=20
  <A href=3D"mailto:jgregorio@ultrasw.com" =
title=3Djgregorio@ultrasw.com>Josh=20
  Gregorio</A> </DIV>
  <DIV style=3D"FONT: 10pt arial"><B>To:</B> <A =
href=3D"mailto:tutor@python.org"=20
  title=3Dtutor@python.org>tutor@python.org</A> </DIV>
  <DIV style=3D"FONT: 10pt arial"><B>Sent:</B> Tuesday, April 23, 2002 =
10:20=20
  AM</DIV>
  <DIV style=3D"FONT: 10pt arial"><B>Subject:</B> [Tutor] lists</DIV>
  <DIV><BR></DIV>
  <DIV><FONT face=3DArial size=3D2>What are linked lists and do you need =
them in=20
  Python? </FONT></DIV>
  <DIV>&nbsp;</DIV>
  <DIV><FONT face=3DArial>Thanks, </FONT></DIV>
  <DIV><FONT face=3DArial>Josh</FONT></DIV></BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_001B_01C1EB73.AC3363E0--




From israel@lith.com  Wed Apr 24 17:40:52 2002
From: israel@lith.com (Israel Evans)
Date: Wed, 24 Apr 2002 09:40:52 -0700
Subject: [Tutor] counting occurrences of pairings
Message-ID: <AF020C5FC551DD43A4958A679EA16A15028E2558@abbott.lith.com>

Hello there, I'm attempting to keep track of the number of times items are
occur together.
I really have very little experience with statistics and the like, so this
is my lame and currently broken attempt at figuring out a couple of things.



### --Here I'm setting up my tuples of data...
>>> atupe = ('a', 'b', 'c', 'd', 'e')
>>> btupe = ('a', 'f', 'g', 'd', 'h')
>>> ctupe = ('a', 'i', 'j', 'f', 'd')

### --Now I'm collecting them all together in another tuple.
>>> alltupe = (atupe, btupe, ctupe)

### --Here I'm setting up the base dictionary so that when I...
>>> basedict = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h':
0, 'i': 0, 'j': 0}

### --...define this dict...
>>> griddict = {'a': basedict, 'b': basedict, 'c': basedict, 'd': basedict,
'e': basedict, 'f': basedict, 'g': basedict, 'h': basedict, 'i': basedict,
'j': basedict}

### --...I can refer to the occurrences of the pairing of these two
characters like so:
>>> griddict['a']['b']
0

### -- Now I'll try it out and count all the pairings
>>> for tupe in alltupe:
	for char in tupe:
		for otherchar in tupe:
			griddict[char][otherchar] =
griddict[char][otherchar] + 1

### --I print this stuff out to see what's going on, and everything is
multiplied by five!  Apparently the for loop counted occurrences and added
them for as many items as there were in the list.  This isn't what I
expected!  Oh the Mathematical inadequacies!  
>>> for item in griddict.items():
	print item

('a', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('c', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('b', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('e', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('d', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('g', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('f', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('i', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('h', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})
('j', {'a': 15, 'c': 5, 'b': 5, 'e': 5, 'd': 15, 'g': 5, 'f': 10, 'i': 5,
'h': 5, 'j': 5})


### -- To see what was going on I decided to do a print thingy and the
results, look like I would imagine they should, but something is up and I
haven't been able to figure it out just yet.  It's probably simple and I've
just overlooked it so I beg of you to help the blind to see!  Lead me to the
country of light and knowledge!
Does anyone have any ideas on what I'm doing wrong, and what I might do
about it?  Also If any of you have any links to references on how other
people have done similar things, I would be most appreciative.  

Thanks a bundle!

>>> for tupe in alltupe:
	for char in tupe:
		print char
		for otherchar in tupe:
			print '\t', otherchar
			
a
	a
	b
	c
	d
	e
b
	a
	b
	c
	d
	e
c
	a
	b
	c
	d
	e
d
	a
	b
	c
	d
	e
e
	a
	b
	c
	d
	e
a
	a
	f
	g
	d
	h
f
	a
	f
	g
	d
	h
g
	a
	f
	g
	d
	h
d
	a
	f
	g
	d
	h
h
	a
	f
	g
	d
	h
a
	a
	i
	j
	f
	d
i
	a
	i
	j
	f
	d
j
	a
	i
	j
	f
	d
f
	a
	i
	j
	f
	d
d
	a
	i
	j
	f
	d



~Israel~





From shalehperry@attbi.com  Wed Apr 24 18:27:21 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 24 Apr 2002 10:27:21 -0700 (PDT)
Subject: [Tutor] counting occurrences of pairings
In-Reply-To: <AF020C5FC551DD43A4958A679EA16A15028E2558@abbott.lith.com>
Message-ID: <XFMail.20020424102721.shalehperry@attbi.com>

>>> dict1 = {'sean': 0, 'isreal': 0}
>>> dict2 = dict1
>>> dict2['sean'] = 2
>>> print dict2
{'isreal': 0, 'sean': 2}
>>> print dict1
{'isreal': 0, 'sean': 2}

Is what is happening.  When you put basedict into the other dictionary you are
not making a copy you are just storing a reference to basedict.  So every time
you write to the dictionary your changes are reflected in every other reference.

Same thing happens with lists.



From ncoulter@es.com  Tue Apr 23 18:33:31 2002
From: ncoulter@es.com (ncoulter@es.com)
Date: Tue, 23 Apr 2002 11:33:31 -0600
Subject: [Tutor] Where does python look for import files
Message-ID: <1D0833CB3B1D7244B617A0DC8399C27E0EC6A1@vega>

Your reply was quite helpful.  Thank you.  I installed Win32 extensions =
for Python today, and noticed that c:\python22\lib\site-packages\win32 =
is now in the Python Path Browser.  This path is not in init.pth, so =
where is it coming from?

-----Original Message-----
From: Kirby Urner [mailto:urnerk@qwest.net]
Sent: Friday, April 19, 2002 6:54 PM
To: Nathan Coulter; tutor@python.org
Subject: Re: [Tutor] Where does python look for import files


On Friday 19 April 2002 09:54 pm, ncoulter@es.com wrote:
> I apologize if this is documented in some obvious place, but I have =
spent
> all day looking for this information, and have yet to find it:
>
> What procedure/variables does python use to search for files in import
> commands?  I see that sys.path contains a list of paths, but am not =
sure
> how to modify it.  My goal right now is to set up a folder
> (c:\python22\scripts) where I can create a folder tree python will =
search
> when it encounters an import command.

You should find c:\python22\lib\site-packages in your windows=20
tree.   That's a better place to put your 3rd party stuff.

But if you want to augment the standard tree with other locations,
in WIndows you have the option to create .pth files, e.g. init.pth,
where you can list additional paths, e.g. if you have a subdirectory
of \python22 names scripts, just create init.pth with the one word
scripts in it, and nothing more.

Kirby


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



From jgregorio@ultrasw.com  Wed Apr 24 19:10:46 2002
From: jgregorio@ultrasw.com (Josh Gregorio)
Date: Wed, 24 Apr 2002 11:10:46 -0700
Subject: [Tutor] slearing the screen
References: <DAV633vSAMfKQu1bCdU0000a622@hotmail.com>
Message-ID: <000f01c1ebbb$5c325a20$a6f1b542@computer>

This is a multi-part message in MIME format.

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

I think you can use chr() and ord() to switch between ascii characters =
and their numbers.
>>>chr(35)
'#'
>>>ord('#')
35
>>>chr(33)
'!'
>>>ord('!')
33


Josh

  ----- Original Message -----=20
  From: Cameron Stoner=20
  To: python tutor=20
  Sent: Sunday, April 21, 2002 4:10 PM
  Subject: [Tutor] slearing the screen


  Hi all,
  =20
  How do you clear the screen?  Is there a command like in C++ to clear =
the screen in Python?  Also is there a function for turning numbers and =
letters into ASCII?  I have been going through the modules without much =
luck.
  =20
  Thanks for any help,
  Cameron Stoner

------=_NextPart_000_000C_01C1EB80.AEFAD560
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 think you can use chr() and ord() to =
switch=20
between ascii characters and their&nbsp;numbers.</FONT></DIV>
<DIV><FONT face=3DArial>&gt;&gt;&gt;chr(35)</FONT></DIV>
<DIV><FONT face=3DArial>'#'</FONT></DIV>
<DIV><FONT face=3DArial>&gt;&gt;&gt;ord('#')</FONT></DIV>
<DIV><FONT face=3DArial>35</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt;chr(33)</FONT></DIV>
<DIV><FONT face=3DArial>'!'</FONT></DIV>
<DIV><FONT face=3DArial>&gt;&gt;&gt;ord('!')</FONT></DIV>
<DIV><FONT face=3DArial>33</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial>Josh</FONT></DIV>
<DIV>&nbsp;</DIV>
<BLOCKQUOTE=20
style=3D"BORDER-LEFT: #000000 2px solid; MARGIN-LEFT: 5px; MARGIN-RIGHT: =
0px; PADDING-LEFT: 5px; PADDING-RIGHT: 0px">
  <DIV style=3D"FONT: 10pt arial">----- Original Message ----- </DIV>
  <DIV=20
  style=3D"BACKGROUND: #e4e4e4; FONT: 10pt arial; font-color: =
black"><B>From:</B>=20
  <A href=3D"mailto:wolf_binary@hotmail.com" =
title=3Dwolf_binary@hotmail.com>Cameron=20
  Stoner</A> </DIV>
  <DIV style=3D"FONT: 10pt arial"><B>To:</B> <A =
href=3D"mailto:tutor@python.org"=20
  title=3Dtutor@python.org>python tutor</A> </DIV>
  <DIV style=3D"FONT: 10pt arial"><B>Sent:</B> Sunday, April 21, 2002 =
4:10=20
PM</DIV>
  <DIV style=3D"FONT: 10pt arial"><B>Subject:</B> [Tutor] slearing the=20
screen</DIV>
  <DIV><BR></DIV>
  <DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
  <DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
  <DIV><FONT face=3DArial size=3D2>How do you clear the screen?&nbsp; Is =
there a=20
  command like in C++ to clear the screen in Python?&nbsp; Also is there =
a=20
  function for turning numbers and letters into ASCII?&nbsp; I have been =
going=20
  through the modules without much luck.</FONT></DIV>
  <DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
  <DIV><FONT face=3DArial size=3D2>Thanks for any help,</FONT></DIV>
  <DIV><FONT face=3DArial size=3D2>Cameron=20
Stoner</FONT></DIV></BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_000C_01C1EB80.AEFAD560--




From israel@lith.com  Wed Apr 24 19:31:25 2002
From: israel@lith.com (Israel Evans)
Date: Wed, 24 Apr 2002 11:31:25 -0700
Subject: [Tutor] counting occurrences of pairings
Message-ID: <AF020C5FC551DD43A4958A679EA16A15028E2562@abbott.lith.com>

Aha...  I think I've got at least part of it now...

I found that I had to create the spaces before I started assigning values to
them in a different way than I was.  This was because I was using a
reference to a dict for every value in the mix.  This way every time I
updated the values of one, All the values got updated! So this is what I
ended up doing...


>>> atupe = ('a', 'b', 'c', 'd', 'e')
>>> btupe = ('a', 'f', 'g', 'd', 'h')
>>> ctupe = ('a', 'i', 'j', 'f', 'd')
>>> alltupe = (atupe, btupe, ctupe)
>>> alldict = {}

>>> for tupe in alltupe:
	for char in tupe:
		alldict[char] = {}

>>> for tupe in alltupe:
	for char in tupe:
		for otherchar in tupe:
			alldict[char][otherchar] = 0

>>> for tupe in alltupe:
	for char in tupe:
		for otherchar in tupe:
			alldict[char][otherchar] = alldict[char][otherchar]
+ 1

>>> for item in alldict.items():
	print item
	
('a', {'a': 3, 'c': 1, 'b': 1, 'e': 1, 'd': 3, 'g': 1, 'f': 2, 'i': 1, 'h':
1, 'j': 1})
('c', {'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1})
('b', {'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1})
('e', {'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1})
('d', {'a': 3, 'c': 1, 'b': 1, 'e': 1, 'd': 3, 'g': 1, 'f': 2, 'i': 1, 'h':
1, 'j': 1})
('g', {'a': 1, 'h': 1, 'd': 1, 'g': 1, 'f': 1})
('f', {'a': 2, 'd': 2, 'g': 1, 'f': 2, 'i': 1, 'h': 1, 'j': 1})
('i', {'a': 1, 'i': 1, 'j': 1, 'd': 1, 'f': 1})
('h', {'a': 1, 'h': 1, 'd': 1, 'g': 1, 'f': 1})
('j', {'a': 1, 'i': 1, 'j': 1, 'd': 1, 'f': 1})

Thanks Sean!


~Israel~


-----Original Message-----
From: Sean 'Shaleh' Perry [mailto:shalehperry@attbi.com] 
Sent: 24 April 2002 10:27 AM
To: Israel Evans
Cc: tutor@python.org
Subject: Re: [Tutor] counting occurrences of pairings

>>> dict1 = {'sean': 0, 'isreal': 0}
>>> dict2 = dict1
>>> dict2['sean'] = 2
>>> print dict2
{'isreal': 0, 'sean': 2}
>>> print dict1
{'isreal': 0, 'sean': 2}

Is what is happening.  When you put basedict into the other dictionary you
are
not making a copy you are just storing a reference to basedict.  So every
time
you write to the dictionary your changes are reflected in every other
reference.

Same thing happens with lists.



From shalehperry@attbi.com  Wed Apr 24 19:39:37 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 24 Apr 2002 11:39:37 -0700 (PDT)
Subject: [Tutor] counting occurrences of pairings
In-Reply-To: <AF020C5FC551DD43A4958A679EA16A15028E2562@abbott.lith.com>
Message-ID: <XFMail.20020424113937.shalehperry@attbi.com>

> 
> Thanks Sean!
> 
> 
> ~Israel~
> 

This is a very common newbie question.  It even bites us old timers sometimes
(-:

Just remember in the future if your actions seem to be getting mirrored, look
for copies that are not copying.



From rob@jam.rr.com  Wed Apr 24 20:12:23 2002
From: rob@jam.rr.com (Rob Andrews)
Date: Wed, 24 Apr 2002 14:12:23 -0500
Subject: [Tutor] uselesspython.com.... no, really!
Message-ID: <3CC70397.5090002@jam.rr.com>

I'm giving it a few more days for the domain name to populate the 
world's DNS servers while I work on the long-promised site upgrade, but 
Useless Python has a new host/home in http://uselesspython.com or 
http://www.uselesspython.com (either works just fine from where I'm 
sitting).

In addition to uploading all the new source code (and deleting one or 
two things that people don't want to be remembered for), I'm working on 
a hopefully sleeker user experience. One of the python-friendly web 
hosting services mentioned on Useless has volunteered to donate a 
special treat to some randomly-chosen Useless Python contributor, and 
it's not too late to send in that *hello world* you've been hanging onto 
if you haven't sent in anything yet. The new site also supports Python 
CGI, and I'll find out from the host soon which version of Python they 
have running.

We could use a few more Python-related quotes, programming challenges, 
pythonic graphics, python-friendly web hosts, etc. Of course, new links, 
dead link reports, and that sort of thing, are always appreciated as well.

A few people have also suggested that we mention a few situations in 
which some of this stuff has been put to use.

Please pardon if it seems to take me too long to respond to emails these 
days, since I'm constantly mobile. Getting this site update together is 
my primary task over the next several days.

Thanks, especially if you read this far down,
Rob




From max_ig@yahoo.com  Wed Apr 24 20:15:40 2002
From: max_ig@yahoo.com (Maximiliano Ichazo)
Date: Wed, 24 Apr 2002 12:15:40 -0700 (PDT)
Subject: [Tutor] working with buttons in Tkinter
Message-ID: <20020424191540.64805.qmail@web11306.mail.yahoo.com>

I'm working out a program using Tkinter that has many buttons that call
for other dialogs with many button that call for other dialogs....

My code is looking like spaghetti (even though I don't have GO TO).

I'm looking for, praying, begging, searching ideas about a good aproach
to this kind of programs (not the crappy one I used).


Thanx,


Max

PS: It has no relation with my problem, but Python and MySQL is just marvellous.

__________________________________________________
Do You Yahoo!?
Yahoo! Games - play chess, backgammon, pool and more
http://games.yahoo.com/



From rob@jam.rr.com  Wed Apr 24 21:56:42 2002
From: rob@jam.rr.com (Rob Andrews)
Date: Wed, 24 Apr 2002 15:56:42 -0500
Subject: [Tutor] Alan Gauld's site
Message-ID: <3CC71C0A.2030700@jam.rr.com>

I'm trying to follow up on a dead link to Alan Gauld's site from Useless 
Python. Does anyone know what has become of it?

Rob




From alan.gauld@bt.com  Wed Apr 24 22:41:27 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Apr 2002 22:41:27 +0100
Subject: [Tutor] program to count keys with timer display and clock di
 splay
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56C@mbtlipnt02.btlabs.bt.co.uk>

Way late, sorry, I've been out of the office...

> run under Linux and Windows.  He wants to be able to 
> distinguish keys at a relatively low level e.g. 
> RightShift-a, LeftShift-a.

Look at the examples in the 'event driven programming' page 
of my tutor. It shows a windows Tkinter version which 
should be fairly portable to Linux (uses the msvcrt module's 
getch() function which has a twin in curses)

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From wesleyabbott@hotmail.com  Wed Apr 24 23:02:41 2002
From: wesleyabbott@hotmail.com (Wesley Abbott)
Date: Wed, 24 Apr 2002 16:02:41 -0600
Subject: [Tutor] Problems understanding List reverse()
Message-ID: <F559NUpuabjKoMFYsDS0000897b@hotmail.com>

Hello everyody.

I am having a slight problem with relation to 'list.reverse'. I am able ot 
get the reverse to work if a list is static, but if I have a user input 
information it does not seem to abe able to reverse. Please help. Code is 
below. TIA for all your help. I am totally new to programming, coming from a 
network engineer background. I am going through Wesley Chun's book right 
now. I also have the O'Reilly Learning to program Python. Once again thanks 
to all who can help me. I have all the different lists jsut to help me 
figure this out. Not trying to confuse anybody, :)

# a simple reverse function
def reversel(list):
    list.reverse()
    return list

alist = []
alist2 = [1, 2, 3, 4, 5]
alist.append(raw_input('Enter a string:  '))
print alist
print reversel(alist)
a = reversel(alist2)
print a

_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com




From scarblac@pino.selwerd.nl  Wed Apr 24 23:11:28 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Thu, 25 Apr 2002 00:11:28 +0200
Subject: [Tutor] Problems understanding List reverse()
In-Reply-To: <F559NUpuabjKoMFYsDS0000897b@hotmail.com>; from wesleyabbott@hotmail.com on Wed, Apr 24, 2002 at 04:02:41PM -0600
References: <F559NUpuabjKoMFYsDS0000897b@hotmail.com>
Message-ID: <20020425001128.A30029@pino.selwerd.nl>

On  0, Wesley Abbott <wesleyabbott@hotmail.com> wrote:
> 
> Hello everyody.
> 
> I am having a slight problem with relation to 'list.reverse'. I am able ot 
> get the reverse to work if a list is static, but if I have a user input 
> information it does not seem to abe able to reverse. Please help. Code is 
> below. TIA for all your help. I am totally new to programming, coming from a 
> network engineer background. I am going through Wesley Chun's book right 
> now. I also have the O'Reilly Learning to program Python. Once again thanks 
> to all who can help me. I have all the different lists jsut to help me 
> figure this out. Not trying to confuse anybody, :)
> 
> # a simple reverse function
> def reversel(list):
>     list.reverse()
>     return list

First, note this is dangerous - the list you give as an argument is actually
changed! When you do 'a = reversel(alist2)' below, it looks like only a is
the new list, but in fact alist2 itself also changed (and they refer to the
same list - so if you make any changes in either, the other is also changed).

It's better to do something like
a = alist2[:] # make a copy
a.reverse()

> alist = []
> alist2 = [1, 2, 3, 4, 5]
> alist.append(raw_input('Enter a string:  '))
> print alist
> print reversel(alist)
> a = reversel(alist2)
> print a

alist has 1 element, namely the string the user gave as input.

Reversing an 1-element list has no effect :).

If you want to reverse a string, you have to change it into a list, reverse
that, then join the characters together again, something like:

word = raw_input('Enter a string: ')
wordlist = list(word)
wordlist.reverse()
drow = ''.join(wordlist)
print drow

I hope this helps.

-- 
Remco Gerlich



From shalehperry@attbi.com  Wed Apr 24 23:13:31 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Wed, 24 Apr 2002 15:13:31 -0700 (PDT)
Subject: [Tutor] Problems understanding List reverse()
In-Reply-To: <F559NUpuabjKoMFYsDS0000897b@hotmail.com>
Message-ID: <XFMail.20020424151331.shalehperry@attbi.com>

> 
># a simple reverse function
> def reversel(list):
>     list.reverse()
>     return list
> 
> alist = []
> alist2 = [1, 2, 3, 4, 5]
> alist.append(raw_input('Enter a string:  '))
> print alist
> print reversel(alist)
> a = reversel(alist2)
> print a
> 

A string is not a list.

import string

input = raw_input("Enter a string: ")
l = list(input)
l.reverse()
input = string.join(l, '') # that is an empty string not a space



From alan.gauld@bt.com  Wed Apr 24 23:14:07 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Apr 2002 23:14:07 +0100
Subject: [Tutor] using class methods (security)
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56F@mbtlipnt02.btlabs.bt.co.uk>

> I am wondering if there is a good way to create class methods in
> python.

See the static method feature of the latest Python version

However most of the things you use class or static methods 
for in C++ or Java can be done by other means in Python....


Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld




From alan.gauld@bt.com  Wed Apr 24 23:09:44 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Apr 2002 23:09:44 +0100
Subject: [Tutor] lists
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56E@mbtlipnt02.btlabs.bt.co.uk>

> Linked lists are created using pointers in lanquages like C and C++.
> Nodes are accessed in a linear fashion. However, the design makes the
> removal or insertion of nodes very efficient.
> 
> You do not need linked lists in Python. In fact it would be very
> difficult to create (if not impossible), because Python does not have
> pointers. 

C/C++ pointers are simply memory addresses however a pointer 
in a pure CS terms is a reference to an object, Thus Python 
does indeed have pointers. A node simply becomes a list 
containing the data and a reference to the next node(or None)

root = [None,None]
def addNode(node, list): # prepends node
    node[1] = list
    list = node
    return list

for i in range(5):
    root = addNode([i,None],root)

#print list
n = root
while n[1] != None:
   print n[0],
   n = n[1]

produces:

4,3,2,1,0

You can also use the trick C programmers have used for years 
where they want very fast linked lists - create a large 
array then use the array index of the next item as the pointer.
This also works in Python using a big list.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Wed Apr 24 22:53:21 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Apr 2002 22:53:21 +0100
Subject: [Tutor] Visual Basic AND Python, is there a way to...
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56D@mbtlipnt02.btlabs.bt.co.uk>

> > "Robert Garber" <garber@centralcatholic.org> wrote:
> is there an IDE out ther that wroks like 
> VB 6.0 for setting up and writting GUI apps? 


> Another option is to check out Boa Constructor 
> (http://boa-constructor.sourceforge.net), which is a GUI 
> builder for Python and the wxPython GUI framework.  I haven't 

There is a whole bunch of these for the different GUI toolkits:

SpecTcl(with pySpec) for Tkinter 
	- old and unsupported but still seems to work!
BlackAdder(for PyQt)
	- commercial IDE with Gui builder, maybe free for personal use?
Glade(for pyGTk)
	- good reviews, has a brief tutor on using Python with it 
        by Deirdre..

ActiveState do a commercial tool too, but I've forgotten the name...
There will be others I'm sure.

Also there is Python Card (PyCard?) which takes a higher level 
text based approach than Tkinter and I believe has some kind 
of Gui builder too. Its on my list of things I really really 
must look at soon!

Parrot(not the spoof!) also uses a text based GUI building technique.

The reason I add the text based tools is simply that although 
writing GUIs in text is much less fun its also much faster 
than using drag n drop GUI builders and nearly always produces 
more maintainable code!.

Alan G





From alan.gauld@bt.com  Wed Apr 24 23:23:37 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed, 24 Apr 2002 23:23:37 +0100
Subject: [Tutor] Alan Gauld's site
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C570@mbtlipnt02.btlabs.bt.co.uk>

> I'm trying to follow up on a dead link to Alan Gauld's site 
> from Useless Python. Does anyone know what has become of it?

Yep, I do :-)

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From jgregorio@ultrasw.com  Thu Apr 25 00:26:19 2002
From: jgregorio@ultrasw.com (Josh Gregorio)
Date: Wed, 24 Apr 2002 16:26:19 -0700
Subject: [Tutor] Problems understanding List reverse()
References: <F559NUpuabjKoMFYsDS0000897b@hotmail.com>
Message-ID: <007501c1ebe7$715d57c0$a6f1b542@computer>

I'm a newbie too, so this may not be the right way to do it. I found a
similar example on page 41 of Learning Python. The second to last paragraph
explains string.split (I have the first edition).

# a simple reverse function
import string #import the string module, chapter 3 in learning python
def reversel(list):
    list.reverse()
    return list

alist = []
alist2 = [1, 2, 3, 4, 5]
x = (raw_input('Enter a string:  '))
alist = string.split(x) #take the string and split its stuff into a list
print alist
print reversel(alist)
a = reversel(alist2)
print a

It only works if you enter a string with more than one word, like 'hello my
friend' or something. I'm not sure how to take a one word string like
'hello' and break it up into its individual characters. The following works,
but may not be the best/correct way to do it.

import string
x = 'hello'
alist = []
for i in x:
   alist.append(i)

print x
print alist
alist.reverse()
print alist


Thanks for any comments,

Josh

----- Original Message -----
From: Wesley Abbott <wesleyabbott@hotmail.com>
To: <tutor@python.org>
Sent: Wednesday, April 24, 2002 3:02 PM
Subject: [Tutor] Problems understanding List reverse()


>
> Hello everyody.
>
> I am having a slight problem with relation to 'list.reverse'. I am able ot
> get the reverse to work if a list is static, but if I have a user input
> information it does not seem to abe able to reverse. Please help. Code is
> below. TIA for all your help. I am totally new to programming, coming from
a
> network engineer background. I am going through Wesley Chun's book right
> now. I also have the O'Reilly Learning to program Python. Once again
thanks
> to all who can help me. I have all the different lists jsut to help me
> figure this out. Not trying to confuse anybody, :)
>
> # a simple reverse function
> def reversel(list):
>     list.reverse()
>     return list
>
> alist = []
> alist2 = [1, 2, 3, 4, 5]
> alist.append(raw_input('Enter a string:  '))
> print alist
> print reversel(alist)
> a = reversel(alist2)
> print a
>
> _________________________________________________________________
> Send and receive Hotmail on your mobile device: http://mobile.msn.com
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor




From jeff@ccvcorp.com  Thu Apr 25 01:45:57 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 24 Apr 2002 17:45:57 -0700
Subject: [Tutor] counting occurrences of pairings
References: <20020424221502.17386.33354.Mailman@mail.python.org>
Message-ID: <3CC751C5.5BE5ECCF@ccvcorp.com>

> Israel Evans <israel@lith.com> wrote:
>
> I found that I had to create the spaces before I started assigning values to
> them in a different way than I was.

There's a nice feature of dicts that you might want to take advantage of...

Instead of initializing your dictionaries with 0 for each pair of numbers that you
expect, you can use the dictionary's get() method.  This will return the value for a
key if it exists, or a default value if it doesn't exist.

>>> d = {'one':1, 'two':2}
>>> d.get('one', 0)
1
>>> d.get('two', 0)
2
>>> d.get('three', 0)
0
>>> d.get('three', 3)
3
>>>

Thus, the simple way to count, using dictionaries, is this:

    d[key] = d.get(key, 0) + 1

This will add one to whatever preexisting value d[key] had, or create a new key with
the value of one if it didn't exist previously.

Another trick you might want to use -- instead of using nested dictionaries, like
you do, you could instead use a single dictionary, and have the key be an (x, y)
tuple instead of a string.

If we combine these two tricks, then your code will end up looking something like
this:


>>> atupe = ('a', 'b', 'c', 'd', 'e')
>>> btupe = ('a', 'f', 'g', 'd', 'h')
>>> ctupe = ('a', 'i', 'j', 'f', 'd')
>>> alltupe = (atupe, btupe, ctupe)
>>> alldict = {}
>>> for tupe in alltupe:
...  for char in tupe:
...   for other in tupe:
...    alldict[(char,other)] = alldict.get((char,other), 0) + 1
...
>>> for key, value in alldict.items():
...  print key, '--', value
...
('a', 'd') -- 3
('a', 'e') -- 1
('c', 'c') -- 1
('c', 'a') -- 1
('a', 'a') -- 3
('a', 'b') -- 1
< ......  >  # ommitting numerous lines of output
('d', 'f') -- 2
('b', 'c') -- 1
('b', 'b') -- 1
>>>

Hope that helps!

Jeff Shannon
Technician/Programmer
Credit International






From jeff@ccvcorp.com  Thu Apr 25 02:05:00 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed, 24 Apr 2002 18:05:00 -0700
Subject: [Tutor] Re: Tutor digest, Vol 1 #1594 - 15 msgs
References: <20020424221502.17386.33354.Mailman@mail.python.org>
Message-ID: <3CC7563B.8DCF6080@ccvcorp.com>

> Message: 12
> From: "Wesley Abbott" <wesleyabbott@hotmail.com>
> To: tutor@python.org
> Date: Wed, 24 Apr 2002 16:02:41 -0600
> Subject: [Tutor] Problems understanding List reverse()
>
> Hello everyody.
>
> I am having a slight problem with relation to 'list.reverse'. I am able ot
> get the reverse to work if a list is static, but if I have a user input
> information it does not seem to abe able to reverse.

It has nothing to do with the user input, it's because you're not using
list.reverse() quite right.  :)

As someone else mentioned, that reversel() function is dangerous.  Here's why:

>>> def reversel(alist):
...  alist.reverse()
...  return alist
...
>>> mylist = [1, 2, 3, 4]
>>> print mylist
[1, 2, 3, 4]
>>> otherlist = reversel(mylist)
>>> print otherlist
[4, 3, 2, 1]   # seems to work fine so far, but...
>>> print mylist
[4, 3, 2, 1]   # the original list is reversed, too!
>>>

That's probably not what was intended or expected.  As was pointed out, this can be
fixed by making a *copy* of the list before you reverse it:

>>> def reversel(alist):
...     listcopy = alist[:]
...     listcopy.reverse()
...     return listcopy
>>>

Now, as for your "user input" problem...

>>> print mylist
[4, 3, 2, 1]
>>> print mylist.reverse()
None    # It doesn't work!
>>> print mylist
[1, 2, 3, 4]    # Or does it?
>>>

You tried to print the result of list.reverse(), but since it reverses the list
*in-place*, there is *no* result.  It reversed the list all right, and then returned
None.  In fact, this was done deliberately so that the mistake you made with your
reversel() function would be less likely -- if list.reverse() returned the reversed
list, it would be easy to forget that it also *modified* the original list.

Hope that helps...

Jeff Shannon
Technician/Programmer
Credit International





From dyoo@hkn.eecs.berkeley.edu  Thu Apr 25 03:02:00 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 24 Apr 2002 19:02:00 -0700 (PDT)
Subject: [Tutor] lists   [Twisted Linked Lists]
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56E@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <Pine.LNX.4.44.0204241824380.19603-100000@hkn.eecs.berkeley.edu>

> You can also use the trick C programmers have used for years where they
> want very fast linked lists - create a large array then use the array
> index of the next item as the pointer. This also works in Python using a
> big list.


Hmmm... it might be good to see what linked lists would look like if we
DIDN't have pointers... *grin*


###
"""PrimitiveLinkedLists.py

Danny Yoo (dyoo@hkn.eecs.berkeley.edu)

This is a sample implementation of a linked list using an index as a way
of reference to another object.

This representation is twisted.  No sane person should use this in a
production system.  *grin*
"""


MAX_NODES = 1000
NODES = [0] * MAX_NODES
NEXTS = [0] * MAX_NODES
EMPTY_LIST = MAX_NODES


class LinkedListError(Exception): pass

def head(i):
    if i == EMPTY_LIST:
        raise LinkedListError, "Can't take the head of the empty list!"
    return NODES[i]

def tail(i):
    if i == EMPTY_LIST:
        raise LinkedListError, "Can't take the tail of the empty list!"
    return NEXTS[i]

def cons(obj, j):
    i = 0
    while i < MAX_NODES:
        if NEXTS[i] == 0: break
        i = i + 1
    if i == MAX_NODES:
        raise LinkedListError, "No more memory!"
    NEXTS[i] = j
    NODES[i] = obj
    return i

## Let's "waste" the first cell of memory so that the user doesn't fiddle
## with it.
assert (cons("sentinel", EMPTY_LIST) == 0)
###




The key is to understand that a linked list only requires a way of
"referring" to another element.  As long as we can conceptually refer to
an element, we have enough machinery to build linked lists, and being able
to refer to an list item by index is just enough to get things rolling:

###
>>> mylist = cons("This", cons("is", cons("a", cons("test", EMPTY_LIST))))
>>> head(mylist)
'This'
>>> head(tail(mylist))
'is'
>>> head(tail(tail(mylist)))
'a'
>>> head(tail(tail(tail(mylist))))
'test'
>>> head(tail(tail(tail(tail(mylist)))))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/tmp/python-22546FBD", line 11, in head
__main__.LinkedListError: Can't take the head of the empty list!
>>> def empty(L): return L == EMPTY_LIST
...
>>> def length(L):
...     if empty(L): return 0
...     return 1 + length(tail(L))
...
>>> length(mylist)
4
###


So it's possible to do linked lists even without pointers.  The code above
doesn't use the trick that Alan mentioned, but it shouldn't be hard to
change it to optimize finding a new node to cons()truct.



Hope this helps!




From wwestpa@yahoo.com  Thu Apr 25 03:21:45 2002
From: wwestpa@yahoo.com (westpa westpa)
Date: Wed, 24 Apr 2002 19:21:45 -0700 (PDT)
Subject: [Tutor] (no subject)
Message-ID: <20020425022145.24190.qmail@web21408.mail.yahoo.com>

ok I am reading down throught the article and I get
most of it, but i need to find the interpreter on my
computer, i have windows 98, how do i interpret the
text, i am typing it in "notepad"
thanks
wwestpa

__________________________________________________
Do You Yahoo!?
Yahoo! Games - play chess, backgammon, pool and more
http://games.yahoo.com/



From wwestpa@yahoo.com  Thu Apr 25 03:27:22 2002
From: wwestpa@yahoo.com (westpa westpa)
Date: Wed, 24 Apr 2002 19:27:22 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <20020425022145.24190.qmail@web21408.mail.yahoo.com>
Message-ID: <20020425022722.47504.qmail@web21407.mail.yahoo.com>

--- westpa westpa <wwestpa@yahoo.com> wrote:
> ok I am reading down throught the article and I get
> most of it, but i need to find the interpreter on my
> computer, i have windows 98, how do i interpret the
> text, i am typing it in "notepad"
> thanks
> wwestpa
> 
> __________________________________________________
> Do You Yahoo!?
> Yahoo! Games - play chess, backgammon, pool and more
> http://games.yahoo.com/
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


__________________________________________________
Do You Yahoo!?
Yahoo! Games - play chess, backgammon, pool and more
http://games.yahoo.com/



From dyoo@hkn.eecs.berkeley.edu  Thu Apr 25 03:27:44 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 24 Apr 2002 19:27:44 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <20020425022145.24190.qmail@web21408.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0204241923400.19603-100000@hkn.eecs.berkeley.edu>


On Wed, 24 Apr 2002, westpa westpa wrote:

> ok I am reading down throught the article and I get most of it, but i
> need to find the interpreter on my computer, i have windows 98, how do i
> interpret the text, i am typing it in "notepad" thanks wwestpa

Hi Westpa,

Welcome!

You'll need to download the Python interpreter and run your program from
there.  You can find a link to the interpreter here:

    http://www.python.org/ftp/python/2.2/Python-2.2.exe

Just install the Python-2.2.exe executable, and you should be ok.


Instead of using Notepad, you might want to use IDLE, a text editor
designed for editing Python --- many people have found it easier to use
because it handles indentation and does syntax colorizing too.  Here's a
tutorial for using IDLE with Python:

    http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/


Please feel free to ask more questions.  We'll be happy to get you
started.  Good luck!




From vcardon@siue.edu  Wed Apr 24 21:39:53 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Wed, 24 Apr 2002 15:39:53 -0500
Subject: [Tutor] lists   [Twisted Linked Lists]
In-Reply-To: <Pine.LNX.4.44.0204241824380.19603-100000@hkn.eecs.berkeley.edu>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56E@mbtlipnt02.btlabs.bt.co.uk> <Pine.LNX.4.44.0204241824380.19603-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020424203953.GA11890@spastic.siue.edu>

--bp/iNruPH9dso1Pn
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Apr 24, 2002 at 07:02:00PM -0700, Danny Yoo wrote:
<Code snipped...>
> The key is to understand that a linked list only requires a way of
> "referring" to another element.  As long as we can conceptually refer to
> an element, we have enough machinery to build linked lists, and being able
> to refer to an list item by index is just enough to get things rolling:

<More code snipped...>
> So it's possible to do linked lists even without pointers.  The code above
> doesn't use the trick that Alan mentioned, but it shouldn't be hard to
> change it to optimize finding a new node to cons()truct.
=20
My mistake. Although, I still can't think of a reason why you would want
to go out of your way to implement a linked list in Python.

Thanks,
Victor

--bp/iNruPH9dso1Pn
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8xxgYZU/bSegbOhwRAkFJAKCseAiFBj2zclVC1JLWMtmTYSvPvwCfR68T
CRqg+jr4/NG9nDkP5qVYx5s=
=AoTv
-----END PGP SIGNATURE-----

--bp/iNruPH9dso1Pn--



From dman@dman.ddts.net  Thu Apr 25 04:19:41 2002
From: dman@dman.ddts.net (dman)
Date: Wed, 24 Apr 2002 22:19:41 -0500
Subject: [Tutor] Python with readline
In-Reply-To: <178BB710-56AF-11D6-864B-00039351FE6A@mac.com>
References: <20020418035330.GA15806@dman.ddts.net> <178BB710-56AF-11D6-864B-00039351FE6A@mac.com>
Message-ID: <20020425031941.GA8486@dman.ddts.net>

On Tue, Apr 23, 2002 at 07:41:46AM -0400, Erik Price wrote:
| 
| On Wednesday, April 17, 2002, at 11:53  PM, dman wrote:
| 
| >No .so files?  They are always named libfoo.so, where 'foo' is the name
| >of the library.
| 
| Not any that I could see.
| 
| >| And I believe my readline library is /sw/include/readline (if the /sw/
| >| dir looks unfamiliar, it's the equivalent of /usr/local/ used by Fink,
| >| the Unix ported package management app for Mac OS X).
| >
| >The .h is the "include" file.  It is C source that is required for
| >compiling anything that uses the library.  The .so file is the "shared
| >library" file.  It is the already-compiled implementation of the
| >library.  The app (python in your case) will be dynamically linked
| >against that .so when it runs.
| 
| Useful knowledge.  Why does it need to be source code -- couldn't this 
| information just be placed into the shared library (.so) file?

It is probably at least partly due to historical reasons.  The source
is not just C itself, but also preprocessor directives.  The C
compilation model is :
    1)  preprocessor (cpp) reads files and generates intermediary source.
        it removes comments, handles all #include and #define and
        other # commands, and "normalizes" the tokens

    2)  compiler reads preprocessor output and generates object (.o) file
        (but I think there are more intermediary steps here)

    3)  linker links all object files (.o) together to create one of
        a.out binary, ELF binary, shared library (.so) or static
        library (.a)

        (static libraries are actually 'ar' archives of the binary
        library files themselves)

The include files contain important information such as function
prototypes, structure declarations, and global constants.  Due to the
way the preprocessor handles #include, this must be source code.  If
it was in the .so (or .a) then the preprocessor would have to
understand the binary format as well, and the binaries would be much
larger.  For example, compile something non-trivial with and without
a -g option and compare the size.  (or compile with -g and then run
'strip' on the binary afterwards)
        
| >Stuff in /usr/share is typically just arbitrary data the app/lib uses
| >as it runs.
| 
| Someone told me that the "setup.py" script automatically checks for the 
| presence of GNU Readline.  I didn't even know about this script, I 
| assumed that all you do is ./configure; make; make install.  So I looked 
| at it, and then I looked at the ./configure script.  Nope, setup.py does 
| not appear to be called by ./configure (although I would have assumed it 
| was).  So I need to run setup.py myself.  This is interesting for two 
| reasons --
| 
| 1) setup.py is not an executable.  No reason it should be, but then, 
| doesn't that assume that I have a working version of Python on my 
| system?  Otherwise this "setup" script wouldn't work.  Fortunately I do, 
| but if this was my first time building Python... well, it just seems 
| strange.
| 
| 2) the interface is not readily apparent.  Although running "python 
| setup.py --help" does display a list of options, it does not display a 
| list of COMMANDS that need to be given (as arguments?) with the setup.py 
| script.  I didn't actually get a chance to look at the source code yet, 
| to see if I can figure out what I'm supposed to do, but perhaps someone 
| on this list is more familiar with setup.py and can tell me what I 
| should be doing.

setup.py is a distutils thing.  (search for the distutils SIG on
python.org)  I've never used one myself because everything I need is
already packaged for my distro.  Yes, setup.py does require a working
python, but how (or why) would you install python modules if you don't
have python itself?  The dependency isn't as crazy as it first sounds.

The only time I've built python was on Solaris.  Then I followed the
instructions and edited Modules/Setup (I think it is named) and
uncommented the readline line and had no problems.

I've never used OSX so I'm not familiar with the quirks of its build
system.

-D

-- 

The remote desktop feature of Windows XP is really nice (and *novel*!).
As a Microsoft consultant can *remotely* disable the personal firewall
and control the system.  We'll ignore the fact that this tampering with
the firewall is not logged, and more importantly, that the firewall
isn't restored when the clowns from Redmond are done with their job.
                                                            -- bugtraq




From idiot1@netzero.net  Thu Apr 25 04:53:41 2002
From: idiot1@netzero.net (kirk Bailey)
Date: Wed, 24 Apr 2002 23:53:41 -0400
Subject: [Tutor] 1 only book
Message-ID: <3CC77DC5.CF3F7EEC@netzero.net>

Gang, I managed to scrape up some loot; I am going to Barnes & Noble
this saterday to purchase a book on python. ONE BOOK ONLY, cash is
tight with Bea sick.

So, gang, WHICH ONE should I buy if I am buying only one- and why that
one? Suggestions please!

-- 
 
end
	    Respectfully,
			 Kirk D Bailey


+---------------------"Thou Art Free." -Eris----------------------+
| http://www.howlermonkey.net mailto:highprimate@howlermonkey.net |
| http://www.tinylist.org  +--------+  mailto:grumpy@tinylist.org |
+------------------Thinking| NORMAL |Thinking---------------------+
                           +--------+

NOTE: By sending SPAM to this address you agree to pay me a service
fee of $100 for the service of receiving,  storing,  examining, and
deleting your piece of SPAM. I am a postmaster, and take a dim view
of such.



From dman@dman.ddts.net  Thu Apr 25 05:29:21 2002
From: dman@dman.ddts.net (dman)
Date: Wed, 24 Apr 2002 23:29:21 -0500
Subject: [Tutor] 1 only book
In-Reply-To: <3CC77DC5.CF3F7EEC@netzero.net>
References: <3CC77DC5.CF3F7EEC@netzero.net>
Message-ID: <20020425042921.GA8922@dman.ddts.net>

--y0ulUmNC+osPPQO6
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Apr 24, 2002 at 11:53:41PM -0400, kirk Bailey wrote:
| Gang, I managed to scrape up some loot; I am going to Barnes & Noble
| this saterday to purchase a book on python. ONE BOOK ONLY, cash is
| tight with Bea sick.
|=20
| So, gang, WHICH ONE should I buy if I am buying only one- and why that
| one? Suggestions please!

What is your goal, and what books do you already have?


The Practice of Programming,  Kernighan & Pike, ISBN 0-201-61586-X

    K&P discuss _how_ to program.  They don't discuss particular
    technologies or APIs, but rather the (general) process a
    programmer should follow to be effective in developing software.

    (I'm in the process of reading it now)


Design Patterns,  "Gang of Four",  ISBN 0-201-63361-2
    The "Gang of Four" (Gamma, Helm, Johnson, Vlissides) discuss many
    patterns that appear frequently in Object Oriented systems.  They
    provide the rational and the tradeoffs each pattern provides.
    Using this as a basis for designing subsystems allows developers
    to reduce reinvention of the wheel and to raise the level of
    discussions by increasing vocabulary.

    (I have read this book a couple times and keep it handy for
    reference)

   =20
Refactoring,  Martin Fowler,  ISBN 0-201-48567-2
    Fowler discusses refactoring to improve the design of existing
    code.  This book is commonly referred to as a "classic" and is
    often recommended.  I have it, but have not read it yet.


Mastering Regular Expressions, Jeffrey Friedl,  ISBN 1-56592-257-3
    Friedl explains many details of regular expressions including
    common pitfalls, variations in dialect, and performance
    considerations.  The python-specific section is very outdated, but
    other than that is a great tool for learning.  Unlike the other
    titles I mention, this one covers a specific technology, but
    doesn't cover the general aspects of how to work with software
    technology.

HTH,
-D

--=20

If you hold to [Jesus'] teaching, you are really [Jesus'] disciples.
Then you will know the truth, and the truth will set you free.
        John 8:31-32


--y0ulUmNC+osPPQO6
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8x4YhO8l8XBKTpRQRAgykAKCR03CmVGgYLKZ5BkVmWCHOLwuwSgCfYd8d
81JRRBbi+P4KjBE/dxPDQOE=
=9SRz
-----END PGP SIGNATURE-----

--y0ulUmNC+osPPQO6--



From randytalbot@comcast.net  Thu Apr 25 05:36:47 2002
From: randytalbot@comcast.net (Randy Talbot)
Date: Thu, 25 Apr 2002 00:36:47 -0400
Subject: [Tutor] 1 only book
In-Reply-To: <3CC77DC5.CF3F7EEC@netzero.net>
Message-ID: <000001c1ec12$cf8ee720$5b582144@aberdn01.md.comcast.net>

I would recommend The Quick Python Book by Daryl Harms. It is the best
book for getting you up to speed on Python. It has a clear and concise
description of the Python language. Read the reader's review at
Amazon.com.
Randy Talbot


> To: tutor
> Subject: [Tutor] 1 only book
> 
> Gang, I managed to scrape up some loot; I am going to Barnes & Noble
> this saterday to purchase a book on python. ONE BOOK ONLY, cash is
> tight with Bea sick.
> 
> So, gang, WHICH ONE should I buy if I am buying only one- and why that
> one? Suggestions please!
> 
> --
> 
> end
> 	    Respectfully,
> 			 Kirk D Bailey




From kojo@hal-pc.org  Thu Apr 25 05:41:01 2002
From: kojo@hal-pc.org (Kojo Idrissa)
Date: Wed, 24 Apr 2002 23:41:01 -0500
Subject: [Tutor] 1 only book
In-Reply-To: <3CC77DC5.CF3F7EEC@netzero.net>
Message-ID: <5.1.0.14.0.20020424234010.027ab548@mail.hal-pc.org>

--=====================_28960482==_.ALT
Content-Type: text/plain; charset="us-ascii"; format=flowed

Well, from what you've done (TinyList), I'd say at this point it depends on 
where you want to go.  It's obvious you should get an advanced book.  The 
ones that come to mind are:

NOTE: Just as I finished typing this, I read DMan's response.  I worked 
from the assumption you wanted a Python book.

Programming Python
         This is the standard Python "bible".  It seems like it would be a 
good place to go for someone who isn't trying to learn the langauge, but 
someone trying to learn what to do with it.  This sounds like you.  I don't 
have the 2nd Ed., but it seems to be a favorite

Python Essential Reference (Second Edition)
         I have the first Ed.,and I love it.  If you want a language ref, 
this would be the way to go.  It seems that someone who already knows how 
to use the language (you), but wanting to take it to the next level, a 
language ref is very useful.  I'm still pretty basic with my Python 
knowledge, but I find this ref extremely helpful.  "How do I...?"

On the financial note, you might want to try Bruce Eckel's Thinking in 
Python <http://www.mindview.net/Books/TIPython>.  It's free, and I've read 
and heard nothing but rave reviews of his Thinking in Java/C++ books.  It's 
not complete, but it's designed for the intermediate/advanced Pythonista.

Just my 2 Gold pieces,

At 11:53 PM 4/24/2002 -0400, kirk Bailey wrote:
>Gang, I managed to scrape up some loot; I am going to Barnes & Noble
>this saterday to purchase a book on python. ONE BOOK ONLY, cash is
>tight with Bea sick.
>
>So, gang, WHICH ONE should I buy if I am buying only one- and why that
>one? Suggestions please!

****************************
Kojo Idrissa

kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************
--=====================_28960482==_.ALT
Content-Type: text/html; charset="us-ascii"

<html>
Well, from what you've done (TinyList), I'd say at this point it depends
on where you want to go.&nbsp; It's obvious you should get an advanced
book.&nbsp; The ones that come to mind are:<br><br>
NOTE: Just as I finished typing this, I read DMan's response.&nbsp; I
worked from the assumption you wanted a <b>Python</b> book.<br><br>
<b>Programming Python<br>
</b><x-tab>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</x-tab>This
is the standard Python &quot;bible&quot;.&nbsp; It seems like it would be
a good place to go for someone who isn't trying to learn the langauge,
but someone trying to learn what to do with it.&nbsp; This sounds like
you.&nbsp; I don't have the 2nd Ed., but it seems to be a
favorite<br><br>
<b>Python Essential Reference (Second Edition)<br>
</b><x-tab>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</x-tab>I have
the first Ed.,and I love it.&nbsp; If you want a language ref, this would
be the way to go.&nbsp; It seems that someone who already knows how to
use the language (you), but wanting to take it to the next level, a
language ref is very useful.&nbsp; I'm still pretty basic with my Python
knowledge, but I find this ref extremely helpful.&nbsp; &quot;How do
I...?&quot;<br><br>
On the financial note, you might want to try Bruce Eckel's <b>Thinking in
Python
</b>&lt;<a href="http://www.mindview.net/Books/TIPython" eudora="autourl">http://www.mindview.net/Books/TIPython</a>&gt;.&nbsp;
It's free, and I've read and heard nothing but rave reviews of his
Thinking in Java/C++ books.&nbsp; It's not complete, but it's designed
for the intermediate/advanced Pythonista.<br><br>
Just my 2 Gold pieces,<br><br>
At 11:53 PM 4/24/2002 -0400, kirk Bailey wrote:<br>
<blockquote type=cite class=cite cite>Gang, I managed to scrape up some
loot; I am going to Barnes &amp; Noble<br>
this saterday to purchase a book on python. ONE BOOK ONLY, cash is<br>
tight with Bea sick.<br><br>
So, gang, WHICH ONE should I buy if I am buying only one- and why
that<br>
one? Suggestions please!</blockquote>
<x-sigsep><p></x-sigsep>
**************************** <br>
Kojo Idrissa <br>
&nbsp; <br>
kojo@hal-pc.org<br>
<a href="http://www.hal-pc.org/~kojo/" eudora="autourl">http://www.hal-pc.org/~kojo/<br>
</a>****************************</html>

--=====================_28960482==_.ALT--





From paulsid@shaw.ca  Thu Apr 25 05:46:44 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Wed, 24 Apr 2002 22:46:44 -0600
Subject: [Tutor] lists   [Twisted Linked Lists]
References: <Pine.LNX.4.44.0204241824380.19603-100000@hkn.eecs.berkeley.edu>
Message-ID: <3CC78A34.8A7B5E98@shaw.ca>

Danny Yoo wrote:

> Hmmm... it might be good to see what linked lists would look like if we
> DIDN't have pointers... *grin*

This reminds me of one of the things that got me so interested in Python
in the first place.  

I first met Python in Data Structures class, where they teach us Python
so we can focus on the data structures and not on memory allocation and
stuff like we'd have to with C/C++.

When they got to trees we were taught the standard class-based approach
to trees, and then the prof showed us a Python approach:

[(key, data), leftsubtree, rightsubtree]

No pointers, no classes, just the stock Python data types.  Being a
long-time C guy this concept just blew me away.  It was foreign.  It was
new.  It was even a bit naughty.  And I liked it.  (Whew, it's getting
hot in here!)

Anyhow the point is that one could, if one were in a suitably deranged
state of mind, build a linked list this way.  A linked-list is really
just a special type of tree, i.e. with every node having at most one
subtree and direction essentially being irrelevant.  So you could also
build a pointerless singly-linked list using this node structure:

[(key, data), nextnode]

This is significantly different than Danny's implementation since it
combines his NODES and NEXTS into one and uses an incredibly-nested list
instead of a flat list.

For trees this is quite nice since the deeply nested list structure
resembles the deep nesting of a tree.  For linked lists it is of course
completely insane.

Hey, who says there's only one way to do things in Python?!  :-)

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From python@rcn.com  Thu Apr 25 05:55:20 2002
From: python@rcn.com (Raymond Hettinger)
Date: Thu, 25 Apr 2002 00:55:20 -0400
Subject: [Tutor] 1 only book
References: <3CC77DC5.CF3F7EEC@netzero.net> <20020425042921.GA8922@dman.ddts.net>
Message-ID: <003b01c1ec15$6784a860$36b53bd0@othello>

Hey dman,  Nice list.  I would add The Pragmatic Programmer by Hunt and
Thomas.

Raymond Hettinger







From lha2@columbia.edu  Thu Apr 25 11:23:05 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Thu, 25 Apr 2002 06:23:05 -0400
Subject: [Tutor] lists   [Twisted Linked Lists]
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56E@mbtlipnt02.btlabs.bt.co.uk> <Pine.LNX.4.44.0204241824380.19603-100000@hkn.eecs.berkeley.edu> <20020424203953.GA11890@spastic.siue.edu>
Message-ID: <3CC7D909.44E91B71@mail.verizon.net>

"Victor R. Cardona" wrote:
> My mistake. Although, I still can't think of a reason why you would want
> to go out of your way to implement a linked list in Python.
> 
> Thanks,
> Victor

I'd like to, as an academic exercise...I hear they're an important
construct to understand. I Python okay, but don't C so well (-4.0 in one
eye, -4.5 in the other).



From alex@gabuzomeu.net  Thu Apr 25 13:47:30 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Thu, 25 Apr 2002 14:47:30 +0200
Subject: [Tutor] Dependencies among objects
Message-ID: <4.3.2.7.2.20020425140828.00b6f420@pop3.norton.antivirus>

Hello,


while working on my pet project, I find it increasingly difficult to manage 
dependencies across objects.

Some classes defined objects that are used throughout the app (a page index 
and a full-text index for instance). Other classes might need one or more 
of these objects to work properly (eg. macros that carry out special tasks 
for instance).

Passing around lost of references as arguments is getting messy. Hence I 
thought about this design: storing references to helper objects in a parent 
class so that every child class can access it easily.

Here is an example:

##
class BaseObject:
     pass

class Foo(BaseObject):
     """Helper class used by several
     other classes throughout the app."""

     def __init__(self):
         # Do initialisation stuff and register self
         # in the parent class.
         BaseObject.foo = self

     def getValue(self):
         return "Value from Foo"

class Bar(BaseObject):
     """Class Bar need a foo instance
     to perform some task."""

     def doIt(self):
         value = "I am Bar and I use '%s'."
         return value % BaseObject.foo.getValue()

if __name__ == "__main__":
     # Initialised somewhere when the app starts up
     foo = Foo()
     # Instance that uses foo through its parent class.
     bar = Bar()
     print bar.doIt()

 >>> I am Bar and I use 'Value from Foo'.
##

Do you think this is a good design?


Thanks.

Alexandre




From vcardon@siue.edu  Thu Apr 25 08:01:16 2002
From: vcardon@siue.edu (Victor R. Cardona)
Date: Thu, 25 Apr 2002 02:01:16 -0500
Subject: [Tutor] 1 only book
In-Reply-To: <3CC77DC5.CF3F7EEC@netzero.net>
References: <3CC77DC5.CF3F7EEC@netzero.net>
Message-ID: <20020425070116.GA12436@spastic.siue.edu>

--PEIAKu/WMn1b1Hv9
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline

On Wed, Apr 24, 2002 at 11:53:41PM -0400, kirk Bailey wrote:
> So, gang, WHICH ONE should I buy if I am buying only one- and why that
> one? Suggestions please!

I would definately go for one of the O'Reilly titles. "Programming
Python" and "Learning Python" have both been invaluable to me.

Victor

--PEIAKu/WMn1b1Hv9
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8x6m8ZU/bSegbOhwRAsB0AKCLvJ4ubPgGW5Z1m1ZoWGrX78d+ggCeNS6d
RVC61oFw9OVW7JcdPZR9ng8=
=ltYH
-----END PGP SIGNATURE-----

--PEIAKu/WMn1b1Hv9--



From max_ig@yahoo.com  Thu Apr 25 14:11:37 2002
From: max_ig@yahoo.com (Maximiliano Ichazo)
Date: Thu, 25 Apr 2002 06:11:37 -0700 (PDT)
Subject: [Tutor] working with Tkinter
Message-ID: <20020425131137.32576.qmail@web11307.mail.yahoo.com>

I'm working out a small program with Tkinter that has an initial dialog
with many buttons calling many dialogs with many buttons calling more
dialogs.

My problem is about the code, it looks like spaghetti. I would like to
hear some advice re how to organize code preventing spaghetti-like
programming.

Thanx,

Max

__________________________________________________
Do You Yahoo!?
Yahoo! Games - play chess, backgammon, pool and more
http://games.yahoo.com/



From bryce@bembry.org  Thu Apr 25 14:17:32 2002
From: bryce@bembry.org (Bryce Embry)
Date: Thu, 25 Apr 2002 08:17:32 -0500
Subject: [Tutor] working with Tkinter
In-Reply-To: <20020425131137.32576.qmail@web11307.mail.yahoo.com>
Message-ID: <5.1.0.14.0.20020425081531.00ad9f90@www.bembry.org>

Can you post some of the code you are working with?  It will be easier to 
help if we can see what you are trying to do.

Thanks,
Bryce

At 08:11 AM 4/25/2002, you wrote:
>I'm working out a small program with Tkinter that has an initial dialog
>with many buttons calling many dialogs with many buttons calling more
>dialogs.
>
>My problem is about the code, it looks like spaghetti. I would like to
>hear some advice re how to organize code preventing spaghetti-like
>programming.
>
>Thanx,
>
>Max
>
>__________________________________________________
>Do You Yahoo!?
>Yahoo! Games - play chess, backgammon, pool and more
>http://games.yahoo.com/
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

--------------------------------------------------------------------------------------------
"Lord, you establish peace for us.
All that we have accomplished
you have done for us" -- Isaiah 26:12




From wolf_binary@hotmail.com  Thu Apr 25 14:52:40 2002
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Thu, 25 Apr 2002 08:52:40 -0500
Subject: [Tutor] OOP design
Message-ID: <DAV66ZTW5k1Ed28kIN400002227@hotmail.com>

This is a multi-part message in MIME format.

------=_NextPart_000_002D_01C1EC36.8EAD5D80
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Hi all,

When using OOP practices for the first time, but understand how to use =
it.  How do you design how it should work? Like flowcharts and psuedo =
code is used for designing functions and basic programs.  I have heard =
of Booch and UML as modeling graphics, but if someone has a link that =
could tell me how to use them in design I would much appreciate it.  I =
need some way to design my programs graphically or with a pseudo code =
like fashion only with objects and classes in mind.  Does any body have =
any suggestions?

Thanks,
Cameron Stoner

------=_NextPart_000_002D_01C1EC36.8EAD5D80
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 http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2713.1100" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>Hi all,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>When using OOP practices for the first =
time, but=20
understand how to use it.&nbsp; How do you design how it should work? =
Like=20
flowcharts and psuedo code is used for designing functions and basic=20
programs.&nbsp; I have heard of Booch and UML as modeling graphics, but =
if=20
someone has a link that could tell me how to use them in design I would =
much=20
appreciate it.&nbsp; I need some way to design my programs graphically =
or with a=20
pseudo code like fashion only with objects and classes in mind.&nbsp; =
Does any=20
body have any suggestions?</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Thanks,</FONT></DIV>
<DIV><FONT face=3DArial size=3D2>Cameron =
Stoner</FONT></DIV></BODY></HTML>

------=_NextPart_000_002D_01C1EC36.8EAD5D80--



From max_ig@yahoo.com  Thu Apr 25 15:16:09 2002
From: max_ig@yahoo.com (Maximiliano Ichazo)
Date: Thu, 25 Apr 2002 07:16:09 -0700 (PDT)
Subject: [Tutor] working with Tkinter
In-Reply-To: <5.1.0.14.0.20020425081531.00ad9f90@www.bembry.org>
Message-ID: <20020425141609.3497.qmail@web11304.mail.yahoo.com>

I don't have the code in the computer I'm using right now but the code
is in the following style:

class prg:
  
   button1= Button(text="whatever", command= self.do_whatever)
more buttons and widgets

   def whatever(self):
      and here other dialog with its buttons calling more dialogs.

At the end, the different dialogs call MySQL to put or fetch data (BTW,
MySQL and Python is just marvellous).






--- Bryce Embry <bryce@bembry.org> wrote:
> Can you post some of the code you are working with?  It will be
> easier to 
> help if we can see what you are trying to do.
> 
> Thanks,
> Bryce
> 
> At 08:11 AM 4/25/2002, you wrote:
> >I'm working out a small program with Tkinter that has an initial
> dialog
> >with many buttons calling many dialogs with many buttons calling
> more
> >dialogs.
> >
> >My problem is about the code, it looks like spaghetti. I would like
> to
> >hear some advice re how to organize code preventing spaghetti-like
> >programming.
> >
> >Thanx,
> >
> >Max
> >
> >__________________________________________________
> >Do You Yahoo!?
> >Yahoo! Games - play chess, backgammon, pool and more
> >http://games.yahoo.com/
> >
> >
> >_______________________________________________
> >Tutor maillist  -  Tutor@python.org
> >http://mail.python.org/mailman/listinfo/tutor
> 
>
--------------------------------------------------------------------------------------------
> "Lord, you establish peace for us.
> All that we have accomplished
> you have done for us" -- Isaiah 26:12
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


__________________________________________________
Do You Yahoo!?
Yahoo! Games - play chess, backgammon, pool and more
http://games.yahoo.com/



From israel@lith.com  Thu Apr 25 15:38:15 2002
From: israel@lith.com (Israel Evans)
Date: Thu, 25 Apr 2002 07:38:15 -0700
Subject: [Tutor] counting occurrences of pairings
Message-ID: <AF020C5FC551DD43A4958A679EA16A15028E2595@abbott.lith.com>

Cool!  Nice tricks.

I was just thinking about the tuple key thing last night, but I didn't know
about the .get() method.  That smoothes things out a bit.

I was trying to think of a way of figuring out the pairings/groupings of all
possible combinations, so this tuple key and .get() methods seem like they
will help.  I'll probably end up with huge dictionaries, but I think it
could work quite nicely.  Sorting will be easier as well.

Thanks!


~Israel~


-----Original Message-----
From: Jeff Shannon [mailto:jeff@ccvcorp.com] 
Sent: 24 April 2002 5:46 PM
To: tutor@python.org
Subject: Re: [Tutor] counting occurrences of pairings

> Israel Evans <israel@lith.com> wrote:
>
> I found that I had to create the spaces before I started assigning values
to
> them in a different way than I was.

There's a nice feature of dicts that you might want to take advantage of...

Instead of initializing your dictionaries with 0 for each pair of numbers
that you
expect, you can use the dictionary's get() method.  This will return the
value for a
key if it exists, or a default value if it doesn't exist.

>>> d = {'one':1, 'two':2}
>>> d.get('one', 0)
1
>>> d.get('two', 0)
2
>>> d.get('three', 0)
0
>>> d.get('three', 3)
3
>>>

Thus, the simple way to count, using dictionaries, is this:

    d[key] = d.get(key, 0) + 1

This will add one to whatever preexisting value d[key] had, or create a new
key with
the value of one if it didn't exist previously.

Another trick you might want to use -- instead of using nested dictionaries,
like
you do, you could instead use a single dictionary, and have the key be an
(x, y)
tuple instead of a string.

If we combine these two tricks, then your code will end up looking something
like
this:


>>> atupe = ('a', 'b', 'c', 'd', 'e')
>>> btupe = ('a', 'f', 'g', 'd', 'h')
>>> ctupe = ('a', 'i', 'j', 'f', 'd')
>>> alltupe = (atupe, btupe, ctupe)
>>> alldict = {}
>>> for tupe in alltupe:
...  for char in tupe:
...   for other in tupe:
...    alldict[(char,other)] = alldict.get((char,other), 0) + 1
...
>>> for key, value in alldict.items():
...  print key, '--', value
...
('a', 'd') -- 3
('a', 'e') -- 1
('c', 'c') -- 1
('c', 'a') -- 1
('a', 'a') -- 3
('a', 'b') -- 1
< ......  >  # ommitting numerous lines of output
('d', 'f') -- 2
('b', 'c') -- 1
('b', 'b') -- 1
>>>

Hope that helps!

Jeff Shannon
Technician/Programmer
Credit International





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



From bryce@bembry.org  Thu Apr 25 15:42:30 2002
From: bryce@bembry.org (Bryce Embry)
Date: Thu, 25 Apr 2002 09:42:30 -0500
Subject: [Tutor] working with Tkinter
In-Reply-To: <20020425141609.3497.qmail@web11304.mail.yahoo.com>
References: <5.1.0.14.0.20020425081531.00ad9f90@www.bembry.org>
Message-ID: <5.1.0.14.0.20020425092209.00ae3520@www.bembry.org>

If the buttons are all doing something similar, it might be easier to 
create a generic function / method and pass it whatever button-dependent 
information you need by using a lambda function.

Here's an example that I developed recently as a teaching project:

from Tkinter import *
root = Tk()

box = Entry(root, width=30)
box.grid(row=0, column=0, columnspan=5)

def boxupdate(critter):
      length=len(box.get())
      box.delete(0, length)
      box.insert(0, critter)

dict = {}
col = 0
words = ["Tiger", "Parrot", "Elephant", "Mouse", "Python"]
for animal in words:
       action = lambda x =animal: boxupdate(x)
      dict[animal] = Button(root, text=animal, command=action)
      dict[animal].grid(row=1, column = col)
      col += 1


This method allows the buttons to be dynamically created and mapped and 
might make your code a little less bulky.  Each button passes to the 
function its unique word, then the function does whatever it is supposed to 
do using that word.  This example does not call a second dialogue box, but 
the boxupdate(x) function could be made to do that, or could even be in a 
separate class definition.

  If you haven't seen lambda much before, this explanation may not make any 
sense.  I just finished teaching a unit on dynamically designing buttons in 
Tkinter using dictionaries and lambda.  I have the notes posted at 
http://www.bembry.org/tech/python/tknotes4.shtml.  There are a number of 
examples on that site and perhaps some more useful explanations.

Well, this won't fix everything, but it's one direction that might help.

Bryce





At 09:16 AM 4/25/2002, you wrote:
>I don't have the code in the computer I'm using right now but the code
>is in the following style:
>
>class prg:
>
>    button1= Button(text="whatever", command= self.do_whatever)
>more buttons and widgets
>
>    def whatever(self):
>       and here other dialog with its buttons calling more dialogs.
>
>At the end, the different dialogs call MySQL to put or fetch data (BTW,
>MySQL and Python is just marvellous).
>
>
>
>
>
>
>--- Bryce Embry <bryce@bembry.org> wrote:
> > Can you post some of the code you are working with?  It will be
> > easier to
> > help if we can see what you are trying to do.
> >
> > Thanks,
> > Bryce
> >
> > At 08:11 AM 4/25/2002, you wrote:
> > >I'm working out a small program with Tkinter that has an initial
> > dialog
> > >with many buttons calling many dialogs with many buttons calling
> > more
> > >dialogs.
> > >
> > >My problem is about the code, it looks like spaghetti. I would like
> > to
> > >hear some advice re how to organize code preventing spaghetti-like
> > >programming.
> > >
> > >Thanx,
> > >
> > >Max
> > >
> > >__________________________________________________
> > >Do You Yahoo!?
> > >Yahoo! Games - play chess, backgammon, pool and more
> > >http://games.yahoo.com/
> > >
> > >
> > >_______________________________________________
> > >Tutor maillist  -  Tutor@python.org
> > >http://mail.python.org/mailman/listinfo/tutor
> >
> >
>--------------------------------------------------------------------------------------------
> > "Lord, you establish peace for us.
> > All that we have accomplished
> > you have done for us" -- Isaiah 26:12
> >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
>
>__________________________________________________
>Do You Yahoo!?
>Yahoo! Games - play chess, backgammon, pool and more
>http://games.yahoo.com/


Bryce Embry
Geek-Of-All-Trades / Master-Of-None

www.bembry.org
--------------------------------------------------------------------------------------------------------------------------------------------------------
Technology Coordinator for MHA/FYOS ^ 390 South White Station ^ Memphis, TN 
38117 ^ (901)682-2409
--------------------------------------------------------------------------------------------------------------------------------------------------------




From pythontutor@venix.com  Thu Apr 25 15:51:40 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Thu, 25 Apr 2002 10:51:40 -0400
Subject: [Tutor] program to count keys with timer display and clock display
References: <3CC42713.6060609@venix.com>
Message-ID: <3CC817FC.7080102@venix.com>

Thank you for your suggestions.  He starts work this weekend.  I
hope he will teach me what he learns.

Lloyd Kvam wrote:

> My son (age 18) is looking to write a program that would count 
> keypresses while
> displaying a 15 minute countdown timer and the current time.  He wants 
> this to
> run under Linux and Windows.  He wants to be able to distinguish keys at 
> a relatively
> low level e.g. RightShift-a, LeftShift-a.
> 
> I (of course) recommended learning some Python to do this, but then 
> started checking.
> The curses module would work for Linux, but not Windows.
> The WConio module would work for Windows, but is fairly different from 
> curses.
> PyGame seems to support timers and keypresses, but looks to be more 
> complex.
> 
> My inclination is to recommend writing two programss, one based on 
> WConio and the other
> based on curses.
> 
> Any suggestions??
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From alan.gauld@bt.com  Thu Apr 25 17:31:25 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Apr 2002 17:31:25 +0100
Subject: [Tutor] 1 only book
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C576@mbtlipnt02.btlabs.bt.co.uk>

If I only had one Python book it would have to 
be Programming Python by Lutz.

The reasoning is simple: 
1) The standard online documentation covers my 
   reference requirements adequately (although 
   I'd hate to give up Beazley's Python Essential 
   Reference I could, at a pinch, survive using 
   the official docs)
2) Of all the Python books I think PP best explains 
   the ideas behind Python as well as covering a lot 
   of stuff the reference docs don't. Especially 
   Pythonic idioms.
3) Its a well made book that won't fall apart thru' 
   regular use.

But if I could have a second book it'd be Beazley
every time!

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Thu Apr 25 17:36:17 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Apr 2002 17:36:17 +0100
Subject: [Tutor] 1 only book
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C577@mbtlipnt02.btlabs.bt.co.uk>

> Hey dman,  Nice list.  I would add The Pragmatic Programmer 
> by Hunt and Thomas.

Yes, and if we are going outside Python, the one book *everyone* 
who writes code should have is Code Complete by McConnell.

It's language independant but is a definitive source of 
good coding practice (and based on real data not just 
his personal opinion - it literally changed how I write 
programs!).

Alan g



From dyoo@hkn.eecs.berkeley.edu  Thu Apr 25 17:47:46 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Apr 2002 09:47:46 -0700 (PDT)
Subject: [Tutor] 1 only book
In-Reply-To: <20020425042921.GA8922@dman.ddts.net>
Message-ID: <Pine.LNX.4.44.0204250943580.21383-100000@hkn.eecs.berkeley.edu>


On Wed, 24 Apr 2002, dman wrote:

> On Wed, Apr 24, 2002 at 11:53:41PM -0400, kirk Bailey wrote:
> | Gang, I managed to scrape up some loot; I am going to Barnes & Noble
> | this saterday to purchase a book on python. ONE BOOK ONLY, cash is
> | tight with Bea sick.
> |
> | So, gang, WHICH ONE should I buy if I am buying only one- and why that
> | one? Suggestions please!
>
> What is your goal, and what books do you already have?
>
>
> The Practice of Programming,  Kernighan & Pike, ISBN 0-201-61586-X
>
>     K&P discuss _how_ to program.  They don't discuss particular
>     technologies or APIs, but rather the (general) process a
>     programmer should follow to be effective in developing software.
>
>     (I'm in the process of reading it now)


Another good one would be "Programming Pearls", by Jon Bentley.  Like the
"Practice of Programming", this one doesn't cover Python, but it does
cover important programming ideas.

It's also thin and easy to carry.



Good luck!




From alan.gauld@bt.com  Thu Apr 25 17:48:16 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Apr 2002 17:48:16 +0100
Subject: [Tutor] Dependencies among objects
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C578@mbtlipnt02.btlabs.bt.co.uk>

> while working on my pet project, I find it increasingly 
> difficult to manage dependencies across objects.

OK, thats strange since OO is supposed to tackle that very 
problem. This suggests your design may be using objects 
but not actually be very object oriented...?

Have you defined your program in terms of a small
(comparitively) set of abstract classes which you can 
subclass to get the concrete behaviour? This normally 
means that the amount of object passing between 
instances is limited to a subset of the asbstract 
objects - and certainly rarely more than 4 or 5.

> Some classes defined objects that are used throughout 
> the app (a page index and a full-text index for instance). 

OK, In that case put them in a module and create 
"global variables" for them.

If you want to be OO pure then make them attributes of 
your application class. Then pass a reference to the 
Application to the other objets.

> Passing around lost of references as arguments is getting 
> messy. 

You should only need to pass a reference to the container 
of your shared objects - usually the Application object itself.

> thought about this design: storing references to helper 
> objects in a parent class so that every child class can 
> access it easily.

What does this buy you over simply setting the helper in 
the constructor for each class?

> class BaseObject:
>      pass
> 
> class Foo(BaseObject):
>      """Helper class used by several
>      other classes throughout the app."""
> 
>      def __init__(self):
>          # Do initialisation stuff and register self
>          # in the parent class.
>          BaseObject.foo = self

What does this give -  if you already have a Foo instance 
you have access to Foo anyway.

> class Bar(BaseObject):
  class Bar(Foo):
>      def doIt(self):
>          value = "I am Bar and I use '%s'."
>          return value % BaseObject.foo.getValue()
           return value % self.getValue()

> Do you think this is a good design?

I guess you realize I'm going to say no... ;-)

I think maybe theres either something I'm missing about
your proposal, or you are missing in the way you're using 
the objects.

Alan G.



From alan.gauld@bt.com  Thu Apr 25 17:51:03 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Apr 2002 17:51:03 +0100
Subject: [Tutor] working with Tkinter
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C579@mbtlipnt02.btlabs.bt.co.uk>

> I'm working out a small program with Tkinter that has an 
> initial dialog with many buttons calling many dialogs 
> with many buttons calling more dialogs.
> 
> My problem is about the code, it looks like spaghetti. 

This is why, once you go beyond small examples, GUIs are 
usually written in an OO style.

A class for each dialog type with the button event handlers 
as methods of the class. Put each class in a module to 
further separate things. The dialog classes should inherit 
from TopLevel in Tkinter.

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld





From rob@uselesspython.com  Thu Apr 25 17:56:43 2002
From: rob@uselesspython.com (Rob Andrews)
Date: Thu, 25 Apr 2002 11:56:43 -0500
Subject: [Tutor] 1 only book
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C576@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <3CC8354B.6040605@uselesspython.com>

alan.gauld@bt.com wrote:

> If I only had one Python book it would have to 
> be Programming Python by Lutz.
> 

If I had to hang onto only one Python book, *Programming Python, 2nd 
ed.* (Lutz) would be my choice at this point. It's like a bottle of fine 
tequila.... You can enjoy it by sip, shot, or binge.

Aside from all other points of discussion, it's the book I actually turn 
to more than the others combined for real-life coding. It's among the 
most practical/useful books I've ever handled, plus I can read the very 
same section of text several times and learn something new with each 
reading.

Rob




From dyoo@hkn.eecs.berkeley.edu  Thu Apr 25 18:03:32 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Apr 2002 10:03:32 -0700 (PDT)
Subject: [Tutor] lists   [Twisted Linked Lists / Hansel and Gretel]
In-Reply-To: <3CC7D909.44E91B71@mail.verizon.net>
Message-ID: <Pine.LNX.4.44.0204250952410.21383-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Apr 2002, Lloyd Hugh Allen wrote:

> "Victor R. Cardona" wrote:
> > My mistake. Although, I still can't think of a reason why you would want
> > to go out of your way to implement a linked list in Python.
> >
> > Thanks,
> > Victor
>
> I'd like to, as an academic exercise...I hear they're an important
> construct to understand. I Python okay, but don't C so well (-4.0 in one
> eye, -4.5 in the other).

My personal feeling is that you don't need "linked lists"... at least, not
at first.  For most purposes, normal Python lists work perfectly well to
allow us to store collections of data.


But when we get more involved with programming, we might find outselves
less interested in collecting objects, and more interested in representing
the relationships between those objects.


Here's a concrete example of why structure is important:

    http://www.mordent.com/folktales/grimms/hng/hng.html

"""
Early in the morning came the woman, and took the children out of their
beds. Their piece of bread was given to them, but it was still smaller
than the time before. On the way into the forest Hansel crumbled his in
his pocket, and often stood still and threw a morsel on the ground.
"Hansel, why do you stop and look round " said the father, "go on." "I am
looking back at my little pigeon which is sitting on the roof, and wants
to say good-bye to me," answered Hansel. "Fool!" said the woman, "that is
not Your little pigeon, that is the morning sun that is shining on the
chimney." Hansel, however, little by little, threw all the crumbs on the
path.

The woman led the children still deeper into the forest, where they had
never in their lives been before. Then a great fire was again made, and
the mother said: "Just sit there, you children, and when you are tired you
may sleep a little; we are going into the forest to cut wood, and in the
evening when we are done, we will come and fetch you away." When it was
noon, Gretel shared her piece of bread with Hansel, who had scattered his
by the way. Then they fell asleep and evening passed, but no one came to
the poor children. They did not awake until it was dark night, and Hansel
comforted his little sister and said: "Just wait, Gretel, until the moon
rises, and then we shall see the crumbs of bread which I have strewn
about, they will show us our way home again."
"""


Hansel is using a linked list traversal algorithm.  Here, it's the linkage
--- the structural relationship --- between the breadcrumbs that Hansel
really cares about, and not the breadcrumbs itself.


Hope this helps!




From alan.gauld@bt.com  Thu Apr 25 18:02:49 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Apr 2002 18:02:49 +0100
Subject: [Tutor] OOP design
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C57A@mbtlipnt02.btlabs.bt.co.uk>

> When using OOP practices for the first time, but understand 
> how to use it.  How do you design how it should work? 

The easiest way to start is using CRC cards.
C = Class
R = Responsibilities
C = Collaborators

Use a postit note (or index card) and  draw a big 'T' 
shape such that there is a top line and two panels 
on the postit.

ASCII art example:

-----------------------------------+
class name                         |
-----------------+-----------------+
responsibilities | collaborators   |
                 |                 |
-----------------+-----------------+

In the first line(above the T) write the class name.
Then in the Left hand box write the classes responsibilities 
- what the class is supposed to do(forget data at this point 
- you should NEVER design classes based on data.
Finally decide which other classes you need to collaborate 
with to achieve the responsibilities. Write these down in 
the Right hand panel.

You can then arrange the postits on a whitboard or table 
top and work through some scenarios for your system. 
Imagine the objects as living actors on a stage, passing 
information between each other to accomplish a task 
- in fact invite some friends around to play the parts 
of the objects - can be fun! :-)

This will determine what messages need to be passed, what 
data needs to be stored to meet the responsibilities(and 
which objects should hold (ie own as a responsibility) 
that data and what parameters should be passed in the 
messages.

This is a fun and simple way of designing OO systems and 
works for small to medium sized jobs(say 20-30 top level 
classes).

You can then document the outcome of the excercise in a more 
compact way using UML if you wish.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld



From alan.gauld@bt.com  Thu Apr 25 18:06:49 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu, 25 Apr 2002 18:06:49 +0100
Subject: [Tutor] working with Tkinter
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C57B@mbtlipnt02.btlabs.bt.co.uk>

> class prg:
>    button1= Button(text="whatever", command= self.do_whatever)
>    # more buttons and widgets
> 
>    def whatever(self):
>    #   and here other dialog with its buttons calling more dialogs.

Do you mean inline or do you create the other dialog definitions in other
classes?

class Dialog1(TopLevel):
    button1 = Button(.... command=self.doButton1)

    def doButton1(self):
    # do stuff here

class Dialog2(TopLevel):
    button1 = Button(.... command=self.doButton1)

    def doButton1(self):
    # do stuff here

You can use parameters to the constructor to explicitly pass 
a reference to the calling class or navigate the parent 
heirarchy maintained by Tkinter.

Alan g.



From jeff@ccvcorp.com  Thu Apr 25 18:27:38 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu, 25 Apr 2002 10:27:38 -0700
Subject: [Tutor] Dependencies among objects
References: <20020425143901.28940.32800.Mailman@mail.python.org>
Message-ID: <3CC83C89.B8A39305@ccvcorp.com>

> Alexandre Ratti <alex@gabuzomeu.net> wrote:
>
> while working on my pet project, I find it increasingly difficult to manage
> dependencies across objects.
> [...]

> Passing around lost of references as arguments is getting messy. Hence I
> thought about this design: storing references to helper objects in a parent
> class so that every child class can access it easily.

[...]

> Do you think this is a good design?

I think there are better ways of handling the issue.  To a fair degree, the best way to do it will depend on your overall
architecture for the project.  Lately, most of my projects have been GUI (wxPython) apps, so I tend to store any widely useful
objects as attributes of the window object (or an appropriate dialog object, etc.)  Since everything is already "owned" by either
the window or the App object, this makes sense.  In a console app, however, it might not be such a good choice (unless you already
have an App object, or something similar).

At the most basic level, what you're doing could be simply expressed by creating a global dictionary, and storing object references
in that.

archive = {}
...
class Bar:
    def DoIt(self):
         value = "I am Bar and I use '%s'."
         return value % archive['foo'].getValue()

if __name__ == '__main__':
    archive['foo'] = Foo()
    bar = Bar()
    bar.DoIt()

A better way would be to look at how your project is structured, conceptually, and to make these objects "belong" to the class that
they're most conceptually related to.  For instance, you might have a Document class, and have the PageIndex and TextIndex classes
stored as attributes of the Document.  When someone modifies the Document (using Document's methods, of course), then the Document
could automatically update the Indexes.  Document could also provide methods to give easy access to the indexes, either by
delegating individual function calls (Document.FindTextLocation() calling into TextIndex and returning the result), or by directly
returning a reference to the TextIndex object.  The first method is usually better, if practical, because it lets you change your
TextIndex without disturbing anything that uses the Document class, but if there's a lot of different method calls to delegate, it
might not be practical.

Keep in mind that the whole point of objects is to let the structure of your code mimic the conceptual structure of your problem.
Object references should be kept where the conceptually "belong", and if you've broken your project into appropriate parts, this
*should* minimize the cross-dependencies.  Of course, there always will be dependencies, but a good design should reduce them.

Jeff Shannon
Technician/Programmer
Credit International






From jeff@ccvcorp.com  Thu Apr 25 18:45:55 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu, 25 Apr 2002 10:45:55 -0700
Subject: [Tutor] working with Tkinter
References: <20020425143901.28940.32800.Mailman@mail.python.org>
Message-ID: <3CC840D3.CF96073F@ccvcorp.com>

> Maximiliano Ichazo <max_ig@yahoo.com> wrote:
>
> I'm working out a small program with Tkinter that has an initial dialog
> with many buttons calling many dialogs with many buttons calling more
> dialogs.
>
> My problem is about the code, it looks like spaghetti. I would like to
> hear some advice re how to organize code preventing spaghetti-like
> programming.

I'm not overly familiar with Tkinter, but this is really more about general design than it is about Tkinter, so feel free to ignore
anything Tkinter-specific that I say and just pay attention to the general intent, here.  ;)

The first thing to do, is to try to make your program as modular as possible.  This means breaking it up into small, independent
chunks.  In your case, since you seem to be using lots of special dialogs, the most obvious choice for how to break things up is to
make each dialog a separate unit.

The first thing to do, is to make sure that each dialog is represented by a separate class.  It's probably even a good idea to put
each one into a separate .py file.  Any information that you need to set up the dialog, should be passed in as an argument to its
__init__() method.  Try to make each dialog as independent as possible.  Since you are (presumably) already grouping everything on
the dialogs so that they make sense to the user (everything to do 'foo' on one dialog, everything to do 'bar' on another, etc), it
shouldn't be *too* hard to make the code for each dialog relatively independent too.  Keep in mind that, while a given dialog is
being shown, it's probably the *only* thing that the user is looking at, so you can consider that dialog to be the entire
application for that moment.  Each dialog has a purpose, and you can focus on *just* that purpose while coding that dialog --
whether that purpose is "write some selected information into the database" or "set various options for the parent dialog", you can
(mostly) ignore any other considerations while that dialog is up.

This way, when you have a button that should pull up another dialog, you can simply create an instance of the subdialog class and
run its DoModal() method (or whatever Tkinter uses).  Once *that* method returns, you can gather any changed settings from the
subdialog (if applicable) and then destroy it (often by just returning from the button's OnClick() handler).

Hope this makes some sense -- if not, feel free to ask more specific questions.  :)

Jeff Shannon
Technician/Programmer
Credit International






From alex@gabuzomeu.net  Thu Apr 25 19:20:57 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Thu, 25 Apr 2002 20:20:57 +0200
Subject: [Tutor] Dependencies among objects
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C578@mbtlipnt02.btlabs
 .bt.co.uk>
Message-ID: <4.3.2.7.2.20020425190004.00cf9910@pop3.norton.antivirus>

Hi Alan,


At 17:48 25/04/2002 +0100, alan.gauld@bt.com wrote:
> > while working on my pet project, I find it increasingly
> > difficult to manage dependencies across objects.
>
>OK, thats strange since OO is supposed to tackle that very
>problem. This suggests your design may be using objects
>but not actually be very object oriented...?

Well, I try (and I try) to make it object-oriented. The app will be GPLed, 
so that everybody will be able to comment on its design and suggest 
improvements.

I believe the main problem is that it's getting complex and I'm unsure how 
to best organise cooperation between objects.

>Have you defined your program in terms of a small
>(comparitively) set of abstract classes which you can
>subclass to get the concrete behaviour? This normally
>means that the amount of object passing between
>instances is limited to a subset of the asbstract
>objects - and certainly rarely more than 4 or 5.

I don't need to pass that many objects around (usually 2 or 3), but I find 
it awkward sometimes; eg. when object A creates an instance of object B 
that will ask object C for an instance of object D. Yes, it does occur at 
least once in the app.

> > Some classes defined objects that are used throughout
> > the app (a page index and a full-text index for instance).
>
>OK, In that case put them in a module and create
>"global variables" for them.
>
>If you want to be OO pure then make them attributes of
>your application class. Then pass a reference to the
>Application to the other objets.

I see. That's probably the simplest solution. Thus if SomeMacro needs both 
the TextIndex and the PageIndex components, I could do:

theApp = Application()
textIndex = TextIndex()
pageIndex = PageIndex()
theApp.textIndex = textIndex # or use a setIndex() method
theApp.pageIndex = pageIndex # same here

macro = SomeMacro(theApp, otherArgs)
# Within macro, I can now access both indexes through theApp instance

=> As a result, you would only use and move around one global 
variable:  the "theApp" instance. Any other instances that are needed 
globally would be stored as class attributes of Application. Is this correct?

> > Passing around lost of references as arguments is getting
> > messy.
>
>You should only need to pass a reference to the container
>of your shared objects - usually the Application object itself.

OK.

> > thought about this design: storing references to helper
> > objects in a parent class so that every child class can
> > access it easily.
>
>What does this buy you over simply setting the helper in
>the constructor for each class?

To do that, I'd need to pass direct references to existing objects when 
instanciating the class. I was trying to avoid passing around many references.

> > class BaseObject:
> >      pass
> >
> > class Foo(BaseObject):
> >      """Helper class used by several
> >      other classes throughout the app."""
> >
> >      def __init__(self):
> >          # Do initialisation stuff and register self
> >          # in the parent class.
> >          BaseObject.foo = self
>
>What does this give -  if you already have a Foo instance
>you have access to Foo anyway.
>
> > class Bar(BaseObject):
>   class Bar(Foo):

I do not want Bar to inherit Foo, because these are very different objects. 
Bar only uses Foo (as in textbook examples for composition). I was trying 
to find a way to provide Bar with a reference to the Foo instance without 
passing it directly to Bar. I think your App object solution makes more sense.

>I think maybe theres either something I'm missing about
>your proposal, or you are missing in the way you're using
>the objects.

Probably both; I have trouble explaining the issue in a clear way without 
getting down into the gory details, but I believe your App idea should work 
fine. I'll try to implement it and get back to the list about it.


Thanks for your help.

Alexandre





From virketis@fas.harvard.edu  Thu Apr 25 19:27:01 2002
From: virketis@fas.harvard.edu (Pijus Virketis)
Date: Thu, 25 Apr 2002 14:27:01 -0400
Subject: [Tutor] lists   [Twisted Linked Lists / Hansel and Gretel]
In-Reply-To: <Pine.LNX.4.44.0204250952410.21383-100000@hkn.eecs.berkeley.edu>
Message-ID: <200204251827.g3PIRFk19988@smtp4.fas.harvard.edu>

<HTML><HEAD>
<BASEFONT FACE=3D"Arial" SIZE=3D"2" COLOR=3D"#000000">
</HEAD>
<BODY>
<div>Danny,<br></div>
<div>&nbsp;</div>
<div>wow, that was a great illustration of a programming=
 concept!<br></div>
<div>&nbsp;</div>
<FONT COLOR=3D"#000080"></FONT><div><FONT=
 COLOR=3D"#000080">&gt;Hansel is using a linked list traversal=
 algorithm. &nbsp;Here, it's the</FONT><br>
<FONT COLOR=3D"#000080">&gt;linkage --- the structural relationship=
 --- between the breadcrumbs </FONT><br></div>
<div><FONT COLOR=3D"#000080">&gt;that Hansel really cares about,=
 and not the breadcrumbs itself.</FONT><br></div>
<div>&nbsp;</div>
<div>Well, but the Python list also preserves structure. Hansel=
 could have been appending the crumbs to the path list, as he was=
 dropping them on the ground, that's all. :) I think linked lists=
 don't add that much conceptually, but they are speedier, if you=
 want to stick something in the middle of a very long=
 array.<br></div>
<div>&nbsp;</div>
<div>-P<br></div>
<div>&nbsp;</div>
<div>-- <br></div>
<div>Certainly there are things in life that money can't buy, But=
 it's very funny -- did you ever try buying them without money?=
 -- Ogden Nash<br></div>
</body></html>




From stuart_clemons@us.ibm.com  Thu Apr 25 20:19:49 2002
From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com)
Date: Thu, 25 Apr 2002 15:19:49 -0400
Subject: [Tutor] Newbie with question about readfiles()
Message-ID: <OF3EABF75C.C47D06BA-ON85256BA6.00698F33@lotus.com>

--0__=0ABBE135DFFA09A38f9e8a93df938690918c0ABBE135DFFA09A3
Content-type: text/plain; charset=US-ASCII

Hi all:

Just wondering how I would print only a given line in a text file.  For
example, I would like to print the 8th line in this multi-line file, foo.
txt.

      in_file = open ("foo.txt", "r")
      for line in in_file.readlines():
            print line        # I know this prints all lines
            print ????        # How do I print line 8 only ???


Thanks,

Stuart, the Python newbie
--0__=0ABBE135DFFA09A38f9e8a93df938690918c0ABBE135DFFA09A3
Content-type: text/html; charset=US-ASCII
Content-Disposition: inline

<html><body>
<p>Hi all:<br>
<br>
Just wondering how I would print only a given line in a text file.  For example, I would like to print the 8th line in this multi-line file, foo.txt.<br>
<br>
	in_file = open (&quot;foo.txt&quot;, &quot;r&quot;)<br>
	for line in in_file.readlines():<br>
    		print line		# I know this prints all lines<br>
		print ????		# How do I print line 8 only ???<br>
<br>
<br>
Thanks,<br>
<br>
Stuart, the Python newbie</body></html>
--0__=0ABBE135DFFA09A38f9e8a93df938690918c0ABBE135DFFA09A3--




From shalehperry@attbi.com  Thu Apr 25 20:57:00 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Thu, 25 Apr 2002 12:57:00 -0700 (PDT)
Subject: [Tutor] Newbie with question about readfiles()
In-Reply-To: <OF3EABF75C.C47D06BA-ON85256BA6.00698F33@lotus.com>
Message-ID: <XFMail.20020425125700.shalehperry@attbi.com>

On 25-Apr-2002 stuart_clemons@us.ibm.com wrote:
> Hi all:
> 
> Just wondering how I would print only a given line in a text file.  For
> example, I would like to print the 8th line in this multi-line file, foo.
> txt.
> 
>       in_file = open ("foo.txt", "r")
>       for line in in_file.readlines():
>             print line        # I know this prints all lines
>             print ????        # How do I print line 8 only ???
> 
> 

you have to count lines.  There is no easy (and efficient) way.

wanted = 8
while wanted > 0:
    line = in_file.readline() # note readline(), this reads one line at a time
    wanted = wanted -1
print line



From scarblac@pino.selwerd.nl  Thu Apr 25 21:06:32 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Thu, 25 Apr 2002 22:06:32 +0200
Subject: [Tutor] Newbie with question about readfiles()
In-Reply-To: <OF3EABF75C.C47D06BA-ON85256BA6.00698F33@lotus.com>; from stuart_clemons@us.ibm.com on Thu, Apr 25, 2002 at 03:19:49PM -0400
References: <OF3EABF75C.C47D06BA-ON85256BA6.00698F33@lotus.com>
Message-ID: <20020425220632.A3554@pino.selwerd.nl>

On  0, stuart_clemons@us.ibm.com wrote:
> Hi all:
> 
> Just wondering how I would print only a given line in a text file.  For
> example, I would like to print the 8th line in this multi-line file, foo.
> txt.
> 
>       in_file = open ("foo.txt", "r")
>       for line in in_file.readlines():
>             print line        # I know this prints all lines
>             print ????        # How do I print line 8 only ???

in_file = open("foo.txt", "r")
lines = in_file.readlines()  # lines is a list with all lines now
print lines[7]               # print the 8th line (Python counts from 0)

-- 
Remco Gerlich



From kojo@hal-pc.org  Thu Apr 25 21:05:01 2002
From: kojo@hal-pc.org (Kojo Idrissa)
Date: Thu, 25 Apr 2002 15:05:01 -0500
Subject: [Tutor] OOP design
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C57A@mbtlipnt02.btlabs
 .bt.co.uk>
Message-ID: <5.1.0.14.0.20020425150319.00aef210@mail.hal-pc.org>

Wow, this is helpful.  Cameron, thanks for the question.  Alan, thanks for 
the answer.

At 06:02 PM 4/25/2002 +0100, alan.gauld@bt.com wrote:
> > When using OOP practices for the first time, but understand
> > how to use it.  How do you design how it should work?
>
>The easiest way to start is using CRC cards.
>C = Class
>R = Responsibilities
>C = Collaborators
>
>Use a postit note (or index card) and  draw a big 'T'
>shape such that there is a top line and two panels
>on the postit.
<SNIPped for convenience>


****************************
Kojo Idrissa

kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************





From kojo@hal-pc.org  Thu Apr 25 21:15:42 2002
From: kojo@hal-pc.org (Kojo Idrissa)
Date: Thu, 25 Apr 2002 15:15:42 -0500
Subject: [Tutor] Newbie with question about readfiles()
In-Reply-To: <OF3EABF75C.C47D06BA-ON85256BA6.00698F33@lotus.com>
Message-ID: <5.1.0.14.0.20020425151440.02578dc8@mail.hal-pc.org>

--=====================_24377332==_.ALT
Content-Type: text/plain; charset="us-ascii"; format=flowed

Use readline()  instead of readlines(). The first reads lines one at a 
time  The second reads all the lines in a file.

Then just add a counter that starts 0.  When it gets to 7, print that line.

At 03:19 PM 4/25/2002 -0400, stuart_clemons@us.ibm.com wrote:

>Hi all:
>
>Just wondering how I would print only a given line in a text file. For 
>example, I would like to print the 8th line in this multi-line file, foo.txt.
>
>in_file = open ("foo.txt", "r")
>for line in in_file.readlines():
>print line# I know this prints all lines
>print ????# How do I print line 8 only ???
>
>
>Thanks,
>
>Stuart, the Python newbie

****************************
Kojo Idrissa

kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
****************************
--=====================_24377332==_.ALT
Content-Type: text/html; charset="us-ascii"

<html>
Use readline<b>()&nbsp; </b>instead of readline<b><i>s</i></b>(). The
first reads lines one at a time&nbsp; The second reads all the lines in a
file.<br><br>
Then just add a counter that starts 0.&nbsp; When it gets to 7, print
that line.<br><br>
At 03:19 PM 4/25/2002 -0400, stuart_clemons@us.ibm.com wrote:<br><br>
<blockquote type=cite class=cite cite>Hi all:<br><br>
Just wondering how I would print only a given line in a text file. For
example, I would like to print the 8th line in this multi-line file,
foo.txt.<br><br>
in_file = open (&quot;foo.txt&quot;, &quot;r&quot;)<br>
for line in in_file.readlines():<br>
print line# I know this prints all lines<br>
print ????# How do I print line 8 only ???<br><br>
<br>
Thanks,<br><br>
Stuart, the Python newbie </blockquote>
<x-sigsep><p></x-sigsep>
**************************** <br>
Kojo Idrissa <br>
&nbsp; <br>
kojo@hal-pc.org<br>
<a href="http://www.hal-pc.org/~kojo/" eudora="autourl">http://www.hal-pc.org/~kojo/<br>
</a>****************************</html>

--=====================_24377332==_.ALT--





From dyoo@hkn.eecs.berkeley.edu  Thu Apr 25 22:28:49 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Apr 2002 14:28:49 -0700 (PDT)
Subject: [Tutor] lists   [Twisted Linked Lists / Hansel and Gretel]
In-Reply-To: <200204251827.g3PIRFk19988@smtp4.fas.harvard.edu>
Message-ID: <Pine.LNX.4.44.0204251408580.19023-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Apr 2002, Pijus Virketis wrote:

> Danny,
>
> wow, that was a great illustration of a programming concept!
>
> >Hansel is using a linked list traversal algorithm.  Here, it's the
> >linkage --- the structural relationship --- between the breadcrumbs
> >that Hansel really cares about, and not the breadcrumbs itself.
>
>  Well, but the Python list also preserves structure. Hansel could have
> been appending the crumbs to the path list, as he was dropping them on
> the ground, that's all. :) I think linked lists don't add that much
> conceptually, but they are speedier, if you want to stick something in
> the middle of a very long array.



There are certain things that are easier to see in a linked-list
structure.  For example, let's say that we're writing an adventure game.

###
class Place:
    def __init__(self, name, to):
        self.name, self.to = name, to

def follow(current_location, limit=20):
    i = 0
    while i < limit:
        if current_location.name == 'Home':
            print "I'm home!"
            return
        print "I'm going to", current_location.name
        current_location = current_location.to
        i = i + 1
    print "I'm tired of walking!"
###


We can simulate walking through this world by following() a path.

###
>>> path_home = Place('big scary forest',
                  Place('underground cave',
                        Place('grassy field',
                              Place('Home', None))))
>>> follow(path_home)
I'm going to big scary forest
I'm going to underground cave
I'm going to grassy field
I'm home!
###


But that's not so fun --- it's too straight and narrow.  Let's say we have
a meddling witch who can redirect the road in a particularly mischevious
way:

###
>>> path_home.to.to.to = Place("Witch's Maze", path_home)
>>> follow(path_home)
I'm going to big scary forest
I'm going to underground cave
I'm going to grassy field
I'm going to Witch's Maze
I'm going to big scary forest
I'm going to underground cave
I'm going to grassy field
I'm going to Witch's Maze
I'm going to big scary forest
I'm going to underground cave
I'm going to grassy field
I'm going to Witch's Maze
I'm going to big scary forest
I'm going to underground cave
I'm going to grassy field
I'm going to Witch's Maze
I'm going to big scary forest
I'm going to underground cave
I'm going to grassy field
I'm going to Witch's Maze
I'm tired of walking!
###

So the idea of having a reference can lead naturally to the question:
what happens if we allow self-reference?  What's so nice about linked
lists is that it's just so easy to bend them, twist them in such a way
that we get a loop.  The concepts behind linked lists are surprisingly
powerful.


Hope this helps!




From phthenry@earthlink.net  Thu Apr 25 22:21:13 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Thu, 25 Apr 2002 17:21:13 -0400
Subject: [Tutor] using class methods (security)
In-Reply-To: <OF620FAEAA.A361AF81-ON65256BA5.001D62D9@i2.com>
References: <OF620FAEAA.A361AF81-ON65256BA5.001D62D9@i2.com>
Message-ID: <20020425172113.B14532@localhost.localdomain>

On Wed, Apr 24, 2002 at 10:52:58AM +0530, Karthik_Gurumurthy@i2.com wrote:

I have a few questions about this:

(1) Looking over the documentation, I have noticed that in
python 2.2, you have to subclass every class. If there is no
super class to base your new class, then you have to use the
default "(object)". Am I correct?

(2) If I am right in number (1), then I really should get python
2.2. Otherwise, I will be writing code that will eventually be
incompatible.

(3) Since my version of python (2.1) is working so well, I am
just a bit reluctant to install a new version. I am running
Mandrake 8.1 on a pentium 1 box. Has anyone out there had any
problems with installation?

Thanks!

Paul 

> > I am wondering if there is a good way to create class methods in
> > python.
> 
> python2.2 has  a way to specify static methods. There is somethign called 
> class method as well which is different from static methods which you are 
> referring to.
> 
> class test(object):
>     __count = 0
>     def __init__(self):
>         test.__count+=1
>         print test.__count
>  
>     def func(self):
>         pass
>  
>     def get_count():
>         return test.__count
>  
>     def __del__(self):
>         test.__count-=1
>  
>     get_count = staticmethod(get_count)
> 
> if __name__ == '__main__':
>     t1 = test()
>     print test.get_count()
> 
> 
> 
> 

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From jeff@ccvcorp.com  Fri Apr 26 00:07:05 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu, 25 Apr 2002 16:07:05 -0700
Subject: [Tutor] 2.1 v 2.2 (was re: using class methods (security))
References: <OF620FAEAA.A361AF81-ON65256BA5.001D62D9@i2.com> <20020425172113.B14532@localhost.localdomain>
Message-ID: <3CC88C19.B2CBB56F@ccvcorp.com>


Paul Tremblay wrote:

> (1) Looking over the documentation, I have noticed that in
> python 2.2, you have to subclass every class. If there is no
> super class to base your new class, then you have to use the
> default "(object)". Am I correct?

No, that's not correct.  Python 2.2 introduces "new-style" classes, as part of
combining Python's built-in types (ints, floats, lists, dicts, etc) with the
instance-class mechanisms.  This will allow you to do things like subclassing
built-in types.

New-style classes will eventually become the default, but this will break a
certain amount of code that uses some of the deep characteristics of the
current ("old-style") class mechanisms.  In order to give people time to update
their old code, while still making use of the new features (not to mention the
ability to gradually rewrite code, using new-style and old-style pieces
side-by-side), Python 2.2 has made it possible to optionally specify whether a
class should be new-style or old-style.  If you *don't* specify that you want a
new-style class, then it will be defined as an old-style class.  The way that
you specify that you want a new-style class is to inherit from object.

Thus, old code works just as before, using old-style classes.  New code can be
written using new-style classes, by inheriting from object, which lets you
create code that will be compatible with future versions of Python.  And
old-style classes can be changed to new-style, and tested to make sure they
function properly, one by one.


> (2) If I am right in number (1), then I really should get python
> 2.2. Otherwise, I will be writing code that will eventually be
> incompatible.

That depends on how deeply into class internals you're digging.  Most typical
Python code will probably never notice the difference--I suspect that a lot
more code will be affected by the integer division change, than by new-style
classes.  Still, it's probably not a bad idea to upgrade to 2.2, because
there's a lot of great new features.

(Keep in mind, though, that the code you're writing for 2.1 won't be truly
incompatible until at least version 2.3, even if you're using features that are
changing.)


> (3) Since my version of python (2.1) is working so well, I am
> just a bit reluctant to install a new version. I am running
> Mandrake 8.1 on a pentium 1 box. Has anyone out there had any
> problems with installation?

I've upgraded a couple of workstations from 2.1 to 2.2, and had absolutely no
problems or code breakage, even with the code that I wrote under 2.0, so you
probably have nothing to worry about.  (Of course, there's a lot of code that
I'm itching to rewrite, just to take advantage of the new features and new
library modules, but that's a different story. ;) )

Jeff Shannon
Technician/Programmer
Credit International





From Karthik_Gurumurthy@i2.com  Fri Apr 26 02:54:17 2002
From: Karthik_Gurumurthy@i2.com (Karthik_Gurumurthy@i2.com)
Date: Fri, 26 Apr 2002 07:24:17 +0530
Subject: [Tutor] using class methods (security)
Message-ID: <OF54271130.5163CB51-ON65256BA7.0009A6F8@i2.com>

This is a multipart message in MIME format.
--=_alternative 000A769465256BA7_=
Content-Type: text/plain; charset="us-ascii"

I have a few questions about this:

> (1) Looking over the documentation, I have noticed that in
> python 2.2, you have to subclass every class. If there is no
> super class to base your new class, then you have to use the
> default "(object)". Am I correct?

No. Actually you need to specify "object" as the super class only if you 
intend to use some nice
python2.2 features like properties etc.

Further, i noticed that having "object" @ the top gives the exact type of 
the object am working with.

But then, i guess, for a dynamically typed language like python, i s'd'nt 
be writing code based on the 
current type of the object!

Anyways I have done a cut-paste of an idle session..

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> class test:
        pass

>>> t = test()
>>> type(t)
<type 'instance'>
>>> class test(object):
        pass

>>> t = test()
>>> type(t)
<class '__main__.test'>
>>> 



> (2) If I am right in number (1), then I really should get python
> 2.2. Otherwise, I will be writing code that will eventually be
> incompatible.

So if you don't plan to use python2.2 features, i guess most of your code 
s'd'nt break.
am not aware of subtle changes in the versions.

regards,
karthik


--=_alternative 000A769465256BA7_=
Content-Type: text/html; charset="us-ascii"


<br>
<br>
<br><font size=2 face="Courier New">I have a few questions about this:<br>
<br>
&gt; (1) Looking over the documentation, I have noticed that in<br>
&gt; python 2.2, you have to subclass every class. If there is no<br>
&gt; super class to base your new class, then you have to use the<br>
&gt; default &quot;(object)&quot;. Am I correct?</font>
<br>
<br><font size=2 face="Courier New">No. Actually you need to specify &quot;object&quot; as the super class only if you intend to use some nice</font>
<br><font size=2 face="Courier New">python2.2 features like properties etc.</font>
<br>
<br><font size=2 face="Courier New">Further, i noticed that having &quot;object&quot; @ the top gives the exact type of the object am working with.</font>
<br>
<br><font size=2 face="Courier New">But then, i guess, for a dynamically typed language like python, i s'd'nt be writing code based on the </font>
<br><font size=2 face="Courier New">current type of the object!</font>
<br>
<br><font size=2 face="Courier New">Anyways I have done a cut-paste of an idle session..</font>
<br>
<br><font size=2 face="Courier New">Python 2.2.1 (#34, Apr &nbsp;9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32</font>
<br><font size=2 face="Courier New">Type &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.</font>
<br><font size=2 face="Courier New">IDLE 0.8 -- press F1 for help</font>
<br><font size=2 face="Courier New">&gt;&gt;&gt; class test:</font>
<br><font size=2 face="Courier New">&nbsp; &nbsp; &nbsp; &nbsp; pass</font>
<br>
<br><font size=2 face="Courier New">&gt;&gt;&gt; t = test()</font>
<br><font size=2 face="Courier New">&gt;&gt;&gt; type(t)</font>
<br><font size=2 face="Courier New">&lt;type 'instance'&gt;</font>
<br><font size=2 face="Courier New">&gt;&gt;&gt; class test(object):</font>
<br><font size=2 face="Courier New">&nbsp; &nbsp; &nbsp; &nbsp; pass</font>
<br>
<br><font size=2 face="Courier New">&gt;&gt;&gt; t = test()</font>
<br><font size=2 face="Courier New">&gt;&gt;&gt; type(t)</font>
<br><font size=2 face="Courier New">&lt;class '__main__.test'&gt;</font>
<br><font size=2 face="Courier New">&gt;&gt;&gt; </font>
<br>
<br><font size=2 face="Courier New"><br>
<br>
&gt; (2) If I am right in number (1), then I really should get python<br>
&gt; 2.2. Otherwise, I will be writing code that will eventually be<br>
&gt; incompatible.</font>
<br>
<br><font size=2 face="Courier New">So if you don't plan to use python2.2 features, i guess most of your code s'd'nt break.</font>
<br><font size=2 face="Courier New">am not aware of subtle changes in the versions.<br>
</font>
<br><font size=2 face="Courier New">regards,</font>
<br><font size=2 face="Courier New">karthik</font>
<br>
<br>
--=_alternative 000A769465256BA7_=--



From imcmeans@shaw.ca  Fri Apr 26 04:39:31 2002
From: imcmeans@shaw.ca (Ian!)
Date: Thu, 25 Apr 2002 20:39:31 -0700
Subject: [Tutor] windows and filenames
Message-ID: <000b01c1ecd3$f9f96410$da494e18@cr536745a>

I've recently written a script so that it can perform an action when it's
given a filename. I bound it to the windows right-click popup menu by
editing the windows registry, so that I can right-click on files and call
the script on them.

Although the script is called, and it works like it should, the values it's
recieving are a little bit wrong. It's recieving DOS-style truncated
filenames, which makes the script useless. For example, instead of
F:\mp3s\electronica, the script recieves the parameter of F:\mp3s\ELECTR~1.

Does anyone know of a way I can look up the full path-name, given the
truncated pathname? I've tried setting and getting the path with os., but
that doesn't change it.

Alternately, is anyone good with windows? The right-click menu calls:
cmd.exe /c "f:\nerd stuff\clipurl.py" %1

where clipurl.py is the script. Is there a way I could make it pass the
correct path, instead of the windows-style truncated path?




From python@rcn.com  Fri Apr 26 04:59:48 2002
From: python@rcn.com (Raymond Hettinger)
Date: Thu, 25 Apr 2002 23:59:48 -0400
Subject: [Tutor] 1 only book
References: <Pine.LNX.4.44.0204250943580.21383-100000@hkn.eecs.berkeley.edu>
Message-ID: <00ad01c1ecd6$cff85740$5cec7ad1@othello>

> Another good one would be "Programming Pearls", by Jon Bentley.  Like the
> "Practice of Programming", this one doesn't cover Python, but it does
> cover important programming ideas.

Get both of his books.  Programming Pearls and More Programming Pearls.

Anyone who has gone through Dman's reading list with the few additions can't
help but become a highly skilled code crafter.  If you can't afford them,
it's worth a trip to the library.

-- Raymond




From paulsid@shaw.ca  Fri Apr 26 05:25:39 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Thu, 25 Apr 2002 22:25:39 -0600
Subject: [Tutor] windows and filenames
References: <000b01c1ecd3$f9f96410$da494e18@cr536745a>
Message-ID: <3CC8D6C3.BE95054C@shaw.ca>

"Ian!" wrote:

> Does anyone know of a way I can look up the full path-name, given the
> truncated pathname? I've tried setting and getting the path with os., but
> that doesn't change it.
> 
> Alternately, is anyone good with windows? The right-click menu calls:
> cmd.exe /c "f:\nerd stuff\clipurl.py" %1
> 
> where clipurl.py is the script. Is there a way I could make it pass the
> correct path, instead of the windows-style truncated path?

Yeah this is a Windows quirk, it happens with anything.  You probably
will have to use the Python win32 extensions to call the Windows API
function GetFullPathName().  I'm not sure if there's any way to get
Python to do this for you.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 26 06:36:46 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Apr 2002 22:36:46 -0700 (PDT)
Subject: [Tutor] uselesspython.com.... no, really!
In-Reply-To: <3CC70397.5090002@jam.rr.com>
Message-ID: <Pine.LNX.4.44.0204252231250.937-100000@hkn.eecs.berkeley.edu>

> In addition to uploading all the new source code (and deleting one or
> two things that people don't want to be remembered for), I'm working on
> a hopefully sleeker user experience. One of the python-friendly web
> hosting services mentioned on Useless has volunteered to donate a
> special treat to some randomly-chosen Useless Python contributor, and
> it's not too late to send in that *hello world* you've been hanging onto
> if you haven't sent in anything yet. The new site also supports Python
> CGI, and I'll find out from the host soon which version of Python they
> have running.

That's great!

One project I'd love to see done is a sort of 'Jitterbug' bug tracking
system for Tutor.  Sometimes, questions come in that don't receive a
reply.  Having some sort of big blinking red light pop up on those
unanswered messages would be pretty neat.  It's probably overkill, but it
still might be a fun project to work on.

Long live Useless Python!




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 26 06:52:25 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Apr 2002 22:52:25 -0700 (PDT)
Subject: [Tutor] windows and filenames
In-Reply-To: <000b01c1ecd3$f9f96410$da494e18@cr536745a>
Message-ID: <Pine.LNX.4.44.0204252237110.937-100000@hkn.eecs.berkeley.edu>


On Thu, 25 Apr 2002, Ian! wrote:

> I've recently written a script so that it can perform an action when it's
> given a filename. I bound it to the windows right-click popup menu by
> editing the windows registry, so that I can right-click on files and call
> the script on them.

Very cool!


> Although the script is called, and it works like it should, the values
> it's recieving are a little bit wrong. It's recieving DOS-style
> truncated filenames, which makes the script useless. For example,
> instead of F:\mp3s\electronica, the script recieves the parameter of
> F:\mp3s\ELECTR~1.
>
> Does anyone know of a way I can look up the full path-name, given the
> truncated pathname? I've tried setting and getting the path with os.,
> but that doesn't change it.

FAQTS has an entry about this:

     http://www.faqts.com/knowledge_base/view.phtml/aid/6159


It sounds like you may want to use the win32api function FindFiles():

###
import win32api
def getFullFilename(truncated):
    return win32api.FindFiles(truncated)[0][8]
###


(The code above is untested since I'm still booted in Linux, sorry!)  The
code above should hopefully do what you want.


However, I would have assumed that there'd be something in the 'os.path'
module that could do this, since it feels like a file-path manipulation
sort of thing.  Let's see...

    http://www.python.org/doc/lib/module-os.path.html

Hmmm... there's something like it for UNIX systems called
os.path.realpath() that removes symbolic names.  It would be very nice if
os.path.realpath() would be extended to work with Win32 systems to give
the full filename.  Perhaps someone can suggest this change to the
developers?


Anyway, I hope this helps!




From lonetwin <lonetwin@yahoo.com>  Fri Apr 26 07:00:54 2002
From: lonetwin <lonetwin@yahoo.com> (lonetwin)
Date: Fri, 26 Apr 2002 11:30:54 +0530 (IST)
Subject: [Tutor] better map/lambda solution needed
Message-ID: <Pine.LNX.4.44.0204261123350.8032-100000@mercury.sapatmt>

Hi everybody,
     Firstly I'd like to say it's good to be back here, I was working on
 non-python stuff lately (for about 3 months) and so missed all the fun
 happening here :).
 	Anyways, here's a quick question, is there a better way to express
the following code (Note: I'm working on Python1.5). Actually, I know
there should be....but somehow, I'm not seeing the obvious.
Here goes :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>> popList = ['steve', 'foo']
>>> hostname = '@mail.foo'
>>> for nick, user in map(None, map(lambda x: x+hostname, popList), popList):
...     print nick, user
...
steve@mail.foo steve
foo@mail.foo foo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I have a problem with all that map(None, map(lambda ...) ...) stuff.
Shows that I haven't been using python much, right ?? ;)

Peace
Steve


-- 
"Today's robots are very primitive, capable of understanding only a few
 simple instructions such as 'go left', 'go right', and 'build car'."
 --John Sladek




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 26 07:13:40 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 25 Apr 2002 23:13:40 -0700 (PDT)
Subject: [Tutor] better map/lambda solution needed
In-Reply-To: <Pine.LNX.4.44.0204261123350.8032-100000@mercury.sapatmt>
Message-ID: <Pine.LNX.4.44.0204252309570.937-100000@hkn.eecs.berkeley.edu>


>  	Anyways, here's a quick question, is there a better way to express
> the following code (Note: I'm working on Python1.5). Actually, I know
> there should be....but somehow, I'm not seeing the obvious.

> Here goes :
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> >>> popList = ['steve', 'foo']
> >>> hostname = '@mail.foo'
> >>> for nick, user in map(None, map(lambda x: x+hostname, popList), popList):
> ...     print nick, user
> ...
> steve@mail.foo steve
> foo@mail.foo foo


In this case, you might not even need the map or lambda stuff.  How about
string formatting?

###
popList = ['steve', 'foo']
hostname = '%s@mail.foo %s'
for popName in popList:
    print hostname % (popName, popName)
###



Good luck!




From scarblac@pino.selwerd.nl  Fri Apr 26 07:13:09 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Fri, 26 Apr 2002 08:13:09 +0200
Subject: [Tutor] better map/lambda solution needed
In-Reply-To: <Pine.LNX.4.44.0204261123350.8032-100000@mercury.sapatmt>; from lonetwin@yahoo.com on Fri, Apr 26, 2002 at 11:30:54AM +0530
References: <Pine.LNX.4.44.0204261123350.8032-100000@mercury.sapatmt>
Message-ID: <20020426081309.A6075@pino.selwerd.nl>

On  0, lonetwin <lonetwin@yahoo.com> wrote:
> Hi everybody,
>      Firstly I'd like to say it's good to be back here, I was working on
>  non-python stuff lately (for about 3 months) and so missed all the fun
>  happening here :).
>  	Anyways, here's a quick question, is there a better way to express
> the following code (Note: I'm working on Python1.5). Actually, I know
> there should be....but somehow, I'm not seeing the obvious.
> Here goes :
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> >>> popList = ['steve', 'foo']
> >>> hostname = '@mail.foo'
> >>> for nick, user in map(None, map(lambda x: x+hostname, popList), popList):
> ...     print nick, user
> ...
> steve@mail.foo steve
> foo@mail.foo foo
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 
> I have a problem with all that map(None, map(lambda ...) ...) stuff.
> Shows that I haven't been using python much, right ?? ;)

Or maybe it shows you're being over enthusiastic :)

Firstly, it won't work once you put this inside a function, it will only
work while 'hostname' is global - otherwise it can't be seen from inside the
lambda in 1.5. You have to pass it into the lambda as a default argument;
lambda x,hostname=hostname: x+hostname.

However, what is wrong with:

popList = ['steve', 'foo']
hostname = '@mail.foo'
for user in popList:
   print user+hostname, user
   
Isn't that easier? :)

-- 
Remco Gerlich



From lonetwin <lonetwin@yahoo.com>  Fri Apr 26 07:12:34 2002
From: lonetwin <lonetwin@yahoo.com> (lonetwin)
Date: Fri, 26 Apr 2002 11:42:34 +0530 (IST)
Subject: [Tutor] better map/lambda solution needed (fwd)
Message-ID: <Pine.LNX.4.44.0204261134510.8046-100000@mercury.sapatmt>

Hi again,
	Just to add to my message below, I know I cud do some string
manipulation like
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for user in popList:
	print user+hostname, user
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	but I need to do it the way mentioned because
a) I won't just adding the hosname part, there'll be more to be done
b) I need to refer to the two strings (ie: the created one and the
original one) plenty of times ....and maybe doing the string
manipulation each time may be a __BAD THING__

---------- Forwarded message ----------
Date: Fri, 26 Apr 2002 11:30:54 +0530 (IST)
From: lonetwin <lonetwin@yahoo.com>
To: Python Tutor list <tutor@python.org>
Subject: better map/lambda solution needed

Hi everybody,
     Firstly I'd like to say it's good to be back here, I was working on
 non-python stuff lately (for about 3 months) and so missed all the fun
 happening here :).
 	Anyways, here's a quick question, is there a better way to express
the following code (Note: I'm working on Python1.5). Actually, I know
there should be....but somehow, I'm not seeing the obvious.
Here goes :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>> popList = ['steve', 'foo']
>>> hostname = '@mail.foo'
>>> for nick, user in map(None, map(lambda x: x+hostname, popList), popList):
...     print nick, user
...
steve@mail.foo steve
foo@mail.foo foo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I have a problem with all that map(None, map(lambda ...) ...) stuff.
Shows that I haven't been using python much, right ?? ;)

Peace
Steve


-- 
"Today's robots are very primitive, capable of understanding only a few
 simple instructions such as 'go left', 'go right', and 'build car'."
 --John Sladek





From scarblac@pino.selwerd.nl  Fri Apr 26 07:33:38 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Fri, 26 Apr 2002 08:33:38 +0200
Subject: [Tutor] better map/lambda solution needed (fwd)
In-Reply-To: <Pine.LNX.4.44.0204261134510.8046-100000@mercury.sapatmt>; from steve@yahoo.com on Fri, Apr 26, 2002 at 11:42:34AM +0530
References: <Pine.LNX.4.44.0204261134510.8046-100000@mercury.sapatmt>
Message-ID: <20020426083338.A6204@pino.selwerd.nl>

On  0, lonetwin <steve@yahoo.com> wrote:
> Hi again,
> 	Just to add to my message below, I know I cud do some string
> manipulation like
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> for user in popList:
> 	print user+hostname, user
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 	but I need to do it the way mentioned because
> a) I won't just adding the hosname part, there'll be more to be done

Unfortunately, if you give us a simplified example, we can only give help on
that simplified example.

Anyway, if you do more than that, the map/lambda/etc solution will soon look
more and more like magic.

You can always do e.g.

for user in popList:
   address = user+hostname # and whatever else you need
   # process user and address here

> b) I need to refer to the two strings (ie: the created one and the
> original one) plenty of times ....and maybe doing the string
> manipulation each time may be a __BAD THING__

Maybe? Bad things?

It works like this: first you write it the most simple, most readable way.
Don't care about minimal efficiency issues (intuition tells me that
map/lambda is actually going to be slower because of function calls, but a)
intuition is of no help whatsoever in efficiency stuff, b) this doesn't
matter if this is not a bottleneck in the finished product).

If your finished product is too slow, *then* you use the profiler to see
where it spends the most time. Then you try to improve the algorithm there,
and finally, if it still needs to be faster, you can do optimization on the
Python, but personally I've never needed to do such tricks yet. If it's
still to slow, pick the most important part and code it in C.

-- 
Remco Gerlich



From imcmeans@shaw.ca  Fri Apr 26 10:27:37 2002
From: imcmeans@shaw.ca (Ian!)
Date: Fri, 26 Apr 2002 02:27:37 -0700
Subject: [Tutor] windows and filenames
Message-ID: <002001c1ed04$9af2a590$da494e18@cr536745a>

Paul - when I use win32api.GetFullPathName('f:\\mp3s\\electr~1'), it just
returns the exact same string I fed it. I think by "Full", it means "local
files get returned with whole path", not "windows filenames get resolved".

bah!




From yduppen@xs4all.nl  Fri Apr 26 11:03:26 2002
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Fri, 26 Apr 2002 12:03:26 +0200
Subject: [Tutor] Dependencies among objects
In-Reply-To: <4.3.2.7.2.20020425140828.00b6f420@pop3.norton.antivirus>
References: <4.3.2.7.2.20020425140828.00b6f420@pop3.norton.antivirus>
Message-ID: <200204261003.g3QA3RaW074557@smtpzilla2.xs4all.nl>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> while working on my pet project, I find it increasingly difficult to manage
> dependencies across objects.

As others have already pointed out, your solution might not be the best one. 
I can really advise the following books if you want to maintain a grasp of 
your structure:

M. Fowler, Refactoring
Gamma et al., Design Patterns

The latter explains the "best" way to design certain kinds of behaviour; it's 
a good book, and it caused a minor revolution in thinking about programs. 
However, I find it hard to always appreciate which pattern is needed for my 
choice.

The Refactoring book is in my opinion a must-have; it describes specific 
problems in designs; for every problem, it describes how this problem can be 
circumvented in a structural way, AND a step by step approach for refactoring 
your code to fit this new structre.

For example (book not at hand, so it's from the top of my hand), he describes 
the problem of "long argument lists": methods taking too many arguments.

He then reasons: if that is the case, it might very well be that many of 
these parameters are related -- put those parameters in a new class.

And he then explains how to transform the following code:

def printEmployee(firstname, surname, street, zipcode, city, country, age, 
gender):
	print firstname, surname
	print street
	print zipcode, city


into the following code


class Employee:
	def firstname():
		...

	def surname():
		...

def printEmployee(employee):
	print employee.firstname(), employee.surname()
	print street()
	print zipcode(), city()



The best part is that the resulting code often makes it easier to spot 
_other_ flaws (why have the name-combining logic in de print method?)

In short: get that book. Your programs will definitely improve.

YDD
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE8ySXvLsKMuCf5EdwRAng+AJ0SxPcZO37ThPrbSdSYqH+30i4cCQCfYe/5
s1VFZWijxIzzGAvLM50+ahg=
=XyIb
-----END PGP SIGNATURE-----



From alan.gauld@bt.com  Fri Apr 26 11:43:07 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Apr 2002 11:43:07 +0100
Subject: [Tutor] Dependencies among objects
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C57C@mbtlipnt02.btlabs.bt.co.uk>

> eg. when object A creates an instance 
> of object B that will ask object C for 
> an instance of object D. Yes, it does 
> occur at least once in the app.

Yes it should be happening all the time thats how 
OOP works! But its a matter of responsibilities.
B knows about C, A does not(probably) so the 
constructor for B should set up the relationship 
with C and maintain that. If it uses several Cs 
then it sets up the container for the Cs and 
maintains all the relationships - its Bs job 
to know about Cs...

Likewise its Cs job to know about Ds...

Thus in A you just ask B to do something.
Within B's 'something' method it asks C for 
anotherthing and within Cs method 'anotherthing' 
it gets a D.... The complexity is thius hideen 
within the called objects.

> the TextIndex and the PageIndex components, I could do:
> 
> theApp = Application()
> textIndex = TextIndex()
> pageIndex = PageIndex()
> theApp.textIndex = textIndex # or use a setIndex() method
> theApp.pageIndex = pageIndex # same here

Or use the app constructor:

theApp = Application(TextIndex(),PageIndex())

ie the Aopplicatiuon has a responsibility to manage these 
indexes so its the job of the constructor to initialise 
those relationships. Because we may want to use diffrent 
indexes in different application instances we pass them 
as parameters to the constructor. If we always use the 
same index types we could just hard wire the constructor 
code....

> macro = SomeMacro(theApp, otherArgs)

Or since someMacro is a part of the Application implement 
it as a method of the Application class, that way it has 
direct access to the self of the Application instance.

> To do that, I'd need to pass direct references to existing 
> objects when instanciating the class. I was trying to avoid 
> passing around many references.

If you pass them to the constructor at creation time it saves 
you having to pass them in every method call!

> I do not want Bar to inherit Foo, because these are very 
> different objects. Bar only uses Foo.... I was trying 
> to find a way to provide Bar with a reference to the Foo 
> instance without passing it directly to Bar. 

In that case I'd go for the constructor again. Pass 
the reference to Foo in Bars constructor and let Bar keep 
an internal reference to it.

> I think your App object solution makes more sense.

Not necessarily in this case. There are a few things 
that the Application should expose as 'globals' and 
for those cases its a useful technique but having seen 
more about the issues you have I think that containment 
by the "responsible object" is more suitable in this case.

Alan g.



From alan.gauld@bt.com  Fri Apr 26 11:47:10 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Apr 2002 11:47:10 +0100
Subject: [Tutor] OOP design
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C57D@mbtlipnt02.btlabs.bt.co.uk>

> Wow, this is helpful.  Cameron, thanks for the question.  
> Alan, thanks for the answer.

You're very welcome, there's lots more on CRC cards on the net
I think the original idea came from the Wirfs-Brock book, 
"Responsibility Driven Design"(??)  - and maybe Kent Beck 
was involved too?

There should be lots to find via Google and on cetus-links

Alan g.



From alan.gauld@bt.com  Fri Apr 26 12:00:52 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Apr 2002 12:00:52 +0100
Subject: [Tutor] lists   [Twisted Linked Lists / Hansel and Gretel]
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C57E@mbtlipnt02.btlabs.bt.co.uk>

------_=_NextPart_001_01C1ED11.A1D56BB0
Content-type: text/plain; charset="iso-8859-1"

>  Well, but the Python list also preserves structure. Hansel could have
been  
>  appending the crumbs to the path list, as he was dropping them on the  
>  ground, that's all. :) I think linked lists don't add that much
conceptually,  
 
In Python I agree. I can't think of a single place where 
a linked list actually adds benefit over a python list.
But most languages are not so endowed and thats why most 
text books include linked lists. They are much more 
useful than big arrays as porovided by most languages.
 
>  but they are speedier, if you want to stick something in the middle of a

>  very long array. 
 
In Python, even that's debateable in that you have to 
find the place in the list first. I suspect that using 
the C coded native lists index() and insert() methods 
is probably faster than traversing a list in Python 
code and then manipulating the pointers to insert 
an element. But I haven't tried... :-)
 
And of course you can fake a linked list using Python 
lists by wrapping the list in some utility functions 
so the interface looks the same!
 

Alan g.

------_=_NextPart_001_01C1ED11.A1D56BB0
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.50.4807.2300" name=GENERATOR></HEAD>
<BODY>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>&gt; &nbsp;</FONT></SPAN>Well, but the Python list also preserves 
structure. Hansel could have been&nbsp;<SPAN class=040555710-26042002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>appending the crumbs to the path list, as he was 
dropping them on the&nbsp;<SPAN class=040555710-26042002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>ground, that's all. :) I think linked lists 
don't add that much conceptually,&nbsp;<SPAN class=040555710-26042002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>In Python I agree. I can't think of a single place where 
</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>a linked list actually adds benefit over a python 
list.</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>But most languages are not so endowed and thats why most 
</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>text books include linked lists. They are much more </FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>useful than big arrays as porovided by&nbsp;most 
languages.</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>&gt;&nbsp;</FONT>&nbsp;</SPAN>but they are speedier, if you want to stick 
something in the middle of a&nbsp;<SPAN class=040555710-26042002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>&gt; </FONT>&nbsp;</SPAN>very long array.<SPAN 
class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>In Python, even that's debateable in that you have to 
</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>find the place </FONT></SPAN><SPAN class=040555710-26042002><FONT 
face="Courier New" color=#0000ff size=2>in the&nbsp;list 
first.</FONT>&nbsp;<FONT face="Courier New" color=#0000ff size=2>I suspect that 
using </FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>the C coded native lists&nbsp;index() and insert() methods 
</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>is probably faster than traversing a list in Python </FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>code and then manipulating the pointers to insert </FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>an element.&nbsp;But I haven't tried... :-)</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002></SPAN><SPAN class=040555710-26042002><FONT 
face="Courier New" color=#0000ff size=2>&nbsp;</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>And of course you can fake a linked list using Python 
</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>lists by wrapping the list in some utility functions </FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>so the interface looks the same!</FONT></SPAN></DIV>
<DIV><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2></FONT></SPAN>&nbsp;</DIV>
<DIV><BR><SPAN class=040555710-26042002><FONT face="Courier New" color=#0000ff 
size=2>Alan g.</FONT></SPAN></DIV></BODY></HTML>

------_=_NextPart_001_01C1ED11.A1D56BB0--



From alan.gauld@bt.com  Fri Apr 26 12:16:11 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Fri, 26 Apr 2002 12:16:11 +0100
Subject: [Tutor] windows and filenames
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C57F@mbtlipnt02.btlabs.bt.co.uk>

> Although the script is called, and it works like it should, 
> the values it's recieving are a little bit wrong. 
> It's recieving DOS-style truncated filenames, which makes 
> the script useless. 

I'm confused. You say it receives the filename and works.
Then you say its useless. a working program sound useful 
to me....?

> F:\mp3s\electronica, the script recieves the parameter of 
> F:\mp3s\ELECTR~1.


But to windoze they resolve to the same place, why is 
this a problem? Or are you trying to display the 
long path name to the users?

> Alternately, is anyone good with windows? The right-click menu calls:
> cmd.exe /c "f:\nerd stuff\clipurl.py" %1

Dunno if this would work but maybe putting quotes around 
the %1 might work? OTOH it probably just passes a literal 
%1 to the program!

> where clipurl.py is the script. Is there a way I could make 
> it pass the correct path, 

It is passing the correct path, just using a shortened form 
of the name....

If you really need the long name then I guess its into 
the Windows API via winall....

Alan g.




From erikprice@mac.com  Fri Apr 26 12:36:42 2002
From: erikprice@mac.com (Erik Price)
Date: Fri, 26 Apr 2002 07:36:42 -0400
Subject: [Tutor] Python with readline
In-Reply-To: <20020425031941.GA8486@dman.ddts.net>
Message-ID: <E187694B-5909-11D6-BE8D-00039351FE6A@mac.com>

On Wednesday, April 24, 2002, at 11:19  PM, dman wrote:

> larger.  For example, compile something non-trivial with and without
> a -g option and compare the size.  (or compile with -g and then run
> 'strip' on the binary afterwards)

I think that's going to have to wait! :)  Someday I would like to get 
some time to learn C*, but I am still learning Java (and there's always 
more to learn about Python).

* "The Practice of Programming" was recommended to me, and I looked at 
it -- it looks like a good book, and uses C quite a bit

> setup.py is a distutils thing.  (search for the distutils SIG on
> python.org)  I've never used one myself because everything I need is
> already packaged for my distro.  Yes, setup.py does require a working
> python, but how (or why) would you install python modules if you don't
> have python itself?  The dependency isn't as crazy as it first sounds.

I must have been mistaken.  I had assumed that setup.py was used to help 
build Python itself, not install Python modules.  Does this mean that 
(in theory) I can add the GNU Readline module without recompiling my 
Python binary?  I can go one way or the other, but I'm just curious if 
it works like Apache's DSOs (where you don't have to recompile Apache to 
add a module).

> I've never used OSX so I'm not familiar with the quirks of its build
> system.

Yeah, I've got to figure this puppy out.  Thanks for the info Dman.


Erik




From stuart_clemons@us.ibm.com  Fri Apr 26 16:28:42 2002
From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com)
Date: Fri, 26 Apr 2002 11:28:42 -0400
Subject: [Tutor] re: Newbie with question about readfiles()
Message-ID: <OFF78E18D6.BE1977F8-ON85256BA7.00521A0A@lotus.com>

--0__=0ABBE134DFC19C9A8f9e8a93df938690918c0ABBE134DFC19C9A
Content-type: text/plain; charset=US-ASCII


Thanks to all who replied.  Here's what I learned from this exercise.

Here's the question:

Just wondering how I would print only a given line in a text file.  For
example, I would like to print the 8th line in this multi-line file, foo.
txt.

      in_file = open ("foo.txt", "r")
      for line in in_file.readlines():
            print line        # I know this prints all lines
            print ????        # How do I print line 8 only ???
1)          print [8]               # Will print the 8th element of the
first line, not the 8th line.

2)  The following construct, using readline( ) (read one line at a time)
will print the 8th element of the first line, not the 8th line

      # This prints the 8th element of the first line
      in_file = open ("foo.txt", "r")
      line = in_file.readline()
      print line[8]       # prints the 8th element of the first line

3) Adding a counter to readline( ) can do it, but the solution in 4) below
using readlines( ) is more straightforward (in my opinion anyway)

      wanted = 8
      while wanted > 0:
            line = in_file.readline() # note readline(), this reads one
line at a time
      wanted = wanted -1
      print line


4) This one works !  This construct, using readlines( ), will print the 8th
line

      ## This prints the 8th line
      in_file = open("foo.txt", "r")
      lines = in_file.readlines()    # lines is a list with all lines now
      print lines[7]                      # print the 8th line (Python
counts from 0)


Thanks again to all who replied.  I definitely learned something.  This
tutor list is a great resource for a newbie like me.

- Stuart
--0__=0ABBE134DFC19C9A8f9e8a93df938690918c0ABBE134DFC19C9A
Content-type: text/html; charset=US-ASCII
Content-Disposition: inline

<html><body>
<p>Thanks to all who replied.  Here's what I learned from this exercise.<br>
<br>
Here's the question:<br>
<br>
Just wondering how I would print only a given line in a text file.  For example, I would like to print the 8th line in this multi-line file, foo.txt.<br>
<br>
	in_file = open (&quot;foo.txt&quot;, &quot;r&quot;)<br>
	for line in in_file.readlines():<br>
    		print line		# I know this prints all lines<br>
		print ????		# How do I print line 8 only ???<br>
1)  		print [8]			# Will print the 8th element of the first line, not the 8th line.<br>
<br>
2)  The following construct, using readline( ) (read one line at a time) will print the 8th element of the first line, not the 8th line<br>
<br>
	# This prints the 8th element of the first line<br>
	in_file = open (&quot;foo.txt&quot;, &quot;r&quot;)<br>
	line = in_file.readline()<br>
	print line[8]       # prints the 8th element of the first line<br>
<br>
3) Adding a counter to readline( ) can do it, but the solution in 4) below using readlines( ) is more straightforward (in my opinion anyway)<br>
<br>
	<font size="4" face="Courier New">wanted = 8<br>
	while wanted &gt; 0:<br>
    		line = in_file.readline() # note readline(), this reads one line at a time<br>
    	wanted = wanted -1<br>
	print line<br>
</font>	<br>
<br>
4) This one works !  This construct, using readlines( ), will print the 8th line<br>
<br>
	## This prints the 8th line<br>
	in_file = open(&quot;foo.txt&quot;, &quot;r&quot;)<br>
	lines = in_file.readlines() 	 # lines is a list with all lines now<br>
	print lines[7]               		# print the 8th line (Python counts from 0)<br>
<br>
<br>
Thanks again to all who replied.  I definitely learned something.  This tutor list is a great resource for a newbie like me.<br>
<br>
- Stuart</body></html>
--0__=0ABBE134DFC19C9A8f9e8a93df938690918c0ABBE134DFC19C9A--




From lonetwin <lonetwin@subdimension.com>  Fri Apr 26 09:51:52 2002
From: lonetwin <lonetwin@subdimension.com> (lonetwin)
Date: Fri, 26 Apr 2002 14:21:52 +0530 (IST)
Subject: [Tutor] better map/lambda solution needed (fwd)
Message-ID: <Pine.LNX.4.44.0204261416400.8121-100000@mercury.sapatmt>

Hi yet again,
	Ok, now I feel like a complete bozo, for asking that earlier
question (included below). Please disregard it. I have decided to do
something equvialent to
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for user in popList:
	mail_id = user+hostname
	....
	....
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	Sorry for dumping 3 (including this one), useless mails in your
mailboxes.

Catch you later when I'm saner :)

Peace
Steve

-- 
I don't have any use for bodyguards, but I do have a specific use for two
highly trained certified public accountants.
		-- Elvis Presley

---------- Forwarded message ----------
Date: Fri, 26 Apr 2002 11:42:34 +0530 (IST)
From: lonetwin <steve@yahoo.com>
Reply-To: lonetwin <lonetwin@yahoo.com>
To: Python Tutor list <tutor@python.org>
Subject: better map/lambda solution needed (fwd)

Hi again,
	Just to add to my message below, I know I cud do some string
manipulation like
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for user in popList:
	print user+hostname, user
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	but I need to do it the way mentioned because
a) I won't just adding the hosname part, there'll be more to be done
b) I need to refer to the two strings (ie: the created one and the
original one) plenty of times ....and maybe doing the string
manipulation each time may be a __BAD THING__

---------- Forwarded message ----------
Date: Fri, 26 Apr 2002 11:30:54 +0530 (IST)
From: lonetwin <lonetwin@yahoo.com>
To: Python Tutor list <tutor@python.org>
Subject: better map/lambda solution needed

Hi everybody,
     Firstly I'd like to say it's good to be back here, I was working on
 non-python stuff lately (for about 3 months) and so missed all the fun
 happening here :).
 	Anyways, here's a quick question, is there a better way to express
the following code (Note: I'm working on Python1.5). Actually, I know
there should be....but somehow, I'm not seeing the obvious.
Here goes :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>> popList = ['steve', 'foo']
>>> hostname = '@mail.foo'
>>> for nick, user in map(None, map(lambda x: x+hostname, popList), popList):
...     print nick, user
...
steve@mail.foo steve
foo@mail.foo foo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I have a problem with all that map(None, map(lambda ...) ...) stuff.
Shows that I haven't been using python much, right ?? ;)

Peace
Steve


-- 
"Today's robots are very primitive, capable of understanding only a few
 simple instructions such as 'go left', 'go right', and 'build car'."
 --John Sladek






From rpinder@usc.edu  Fri Apr 26 15:59:32 2002
From: rpinder@usc.edu (Rich Pinder)
Date: Fri, 26 Apr 2002 07:59:32 -0700
Subject: [Tutor] Perl refugee
Message-ID: <3CC96B54.D416E67F@usc.edu>

--------------8F9C34CC7747D2EB44498E3A
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Ok... i'm a zope user (not a good one), and long time perl user.
Each time i get a little 'utility' type project, I think "A ha..  I'll
use Python this time" - then the time gets low, i never get around to
it, and say  "heck, i'll just do it in Perl".....

So this morning I said no - wanna get the first one under my belt !

realized the machine i'm using doesnt have Python - so loading it now.

.... here's my goal.....

I need to copy 80,000 files from one directory and put them in one of 20
other directories.  I'm into chaper 12&13 in the pyton book, and am sure
I can get the looping structure over the directory listing....

But to progam the logic to decide where the files go, I need substring
parsing of the file names (think thats easy) PLUS something like a CASE
statement.  I don't see the CASE statement anywhere.

So will i have to use a bunch of cludgy if/then statements, or is there
something more elequent...

  if subval > "0001"  and subval < "0010" :
     <filecopyingsteps>
 elif subval > "0009"  and subval < "0020" :
     <filecopyingsteps>
........

Thanks
(python 2.2.1 is installed...whoo hoo!)

rich pinder
usc school of medicine

--------------8F9C34CC7747D2EB44498E3A
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
Ok... i'm a zope user (not a good one), and long time perl user.
<br>Each time i get a little 'utility' type project, I think "A ha..&nbsp;
I'll use Python this time" - then the time gets low, i never get around
to it, and say&nbsp; "heck, i'll just do it in Perl".....
<p>So this morning I said no - wanna get the first one under my belt !
<p>realized the machine i'm using doesnt have Python - so loading it now.
<p>.... here's my goal.....
<p>I need to copy 80,000 files from one directory and put them in one of
20 other directories.&nbsp; I'm into chaper 12&amp;13 in the pyton book,
and am sure I can get the looping structure over the directory listing....
<p>But to progam the logic to decide where the files go, I need substring
parsing of the file names (think thats easy) PLUS something like a CASE
statement.&nbsp; I don't see the CASE statement anywhere.
<p>So will i have to use a bunch of cludgy if/then statements, or is there
something more elequent...
<p><tt>&nbsp; if subval > "0001"&nbsp; and subval &lt; "0010" :</tt>
<br><tt>&nbsp;&nbsp;&nbsp;&nbsp; &lt;filecopyingsteps></tt>
<br><tt>&nbsp;elif subval > "0009"&nbsp; and subval &lt; "0020" :</tt>
<br><tt>&nbsp;&nbsp;&nbsp;&nbsp; &lt;filecopyingsteps></tt>
<br><tt>........</tt>
<p>Thanks
<br>(python 2.2.1 is installed...whoo hoo!)
<p>rich pinder
<br>usc school of medicine</html>

--------------8F9C34CC7747D2EB44498E3A--




From shalehperry@attbi.com  Fri Apr 26 17:19:40 2002
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Fri, 26 Apr 2002 09:19:40 -0700 (PDT)
Subject: [Tutor] Perl refugee
In-Reply-To: <3CC96B54.D416E67F@usc.edu>
Message-ID: <XFMail.20020426091940.shalehperry@attbi.com>

> 
> So will i have to use a bunch of cludgy if/then statements, or is there
> something more elequent...
> 
>   if subval > "0001"  and subval < "0010" :
>      <filecopyingsteps>
>  elif subval > "0009"  and subval < "0020" :
>      <filecopyingsteps>
> ........
> 

(like perl has a case statement? well, 6 will ....)

Yes you can use the if statement, this is standard practice.  The other option
is to store the info in a dictionary and key off the dictionary.  This works
for menus and the like, it may not here because you are using a range.

BTw a nifty python ism is:

if "0001" < subval < "0010": foo



From glingl@aon.at  Fri Apr 26 18:02:10 2002
From: glingl@aon.at (Gregor Lingl)
Date: Fri, 26 Apr 2002 19:02:10 +0200
Subject: [Tutor] How to deal with strange errors?
Message-ID: <3CC98812.38670CBB@rg16.asn-wien.ac.at>

Hi Pythonistas!

Im using Python in an educational setting for about a year
now and from time to time i'm stumbling (?) over same
strange behaviour of IDLE which I consider serious drawbacks
in a classroom. One of these is that IDLE cannot react properly
to infinite loops. So nothing else but using the Windows taskmanager
helps and then reloading everything. Today this occured, when
a (quite good) student renamed a loop-variable in the body of
a loop during his program development efforts and forgot to do
this also in the condition of the while-loop. Ooops.

Unfortunately this occured during some sort of exam. Not good!

It seems to me that every mistake you can think of also does occur
eventually especially when teaching programming.
Here I'll report a very special one which occured also during
the exam-assignment this afternoon and which the student could
not resolve on his own.

For me it was interesting, because it did not occur because of a
flaw of IDLE but because of a special powerful feature of the language
itself.

My student wrote this lines:


print "Gib jeweils eine Note ein."
note = ziffer = durchschnitt = input = ("Wenn du fertig bist, gib 0
ein")
eingaben = 0
ziffernsumme = 0
while note > 0:
    ziffer = note % 10
    note = note / 10

Don't think about the meanig of this but look at the
syntax error.

He got the error message:

Gib jeweils eine Note ein.
Traceback (most recent call last):
  File "Z:\6b-20020426\spaula\notendurchschnitt.py", line 10, in ?
    ziffer = note % 10
TypeError: not all arguments converted

Naturally it took him a considerable amount of time
to find the cause of this error (which was the = 4 lines above)

O.k. he corrected his mistake and tried to rerun his program,
this time getting the following error-message:

Traceback (most recent call last):
  File "Z:\6b-20020426\spaula\notendurchschnitt.py", line 6, in ?
    note = ziffer = durchschnitt = input("Wenn du fertig bist, gib 0
ein")
TypeError: 'str' object is not callable

k.o.!
He could not find out what was - or has been - going on, and even
me didn't realize immediately what was the cause of this strange
behaviour.

Now there occur several questions to me (not in order of importance):

1. What do you do, when errors of this type occur? How do you
   explain it to students, just beginning to learn programming?
2. How could one develop means, which makes restarting the IDE or
   the interpreter obsolete?
   As far as I remember there is a good example in the
TeachScheme-Project,
   where language-features can be turned on/off according to the level
   of knowledge of the students.
   One could imagine - in the case obove - to turn off the possibility
   of overwriting built-in functions in Python ( does there exist a
switch
   concerning this?).
3. Is it possible to rebind input() to it's original built-in function
   without restarting the whole machinery.
4. Is there a list somewhere of features to implement / provide for
educational
   use of IDLE or some special eduactional-IDE? Or should we start to
collect
   ideas in this direction?

My experience tells me (and my opinion is) that it is of crucial
importance
to have a (nearly) foolprove programming environment when working in
school
and trying to promote the use of Python. Interestingly it's not so
important
for the students but much more for the acceptance of the new tool by the

majority of the teachers, who already have to learn so many new things
concerning all the aspects of computer-science and who because of this
show a rather sound(?) amount of inertia when asked to decide for new
ways
of teaching. (From time to time I do Python courses for teachers here in
Vienna).

I'm interested in your opinion about these problems
and also to contribute to this development, but how?

Regards
Gregor Lingl




From dyoo@hkn.eecs.berkeley.edu  Fri Apr 26 18:35:15 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 26 Apr 2002 10:35:15 -0700 (PDT)
Subject: [Tutor] How to deal with strange errors?
In-Reply-To: <3CC98812.38670CBB@rg16.asn-wien.ac.at>
Message-ID: <Pine.LNX.4.44.0204261009280.14857-100000@hkn.eecs.berkeley.edu>


> note = ziffer = durchschnitt = input = ("Wenn du fertig bist, gib 0
                                 ^^^^^^^^^

Yes.  This doesn't call the input() function at all, but rebinds all those
variables to a string.  But one question is to ask: is there a reason why
all those variables are directed to the same value?



> He got the error message:
>
> Gib jeweils eine Note ein.
> Traceback (most recent call last):
>   File "Z:\6b-20020426\spaula\notendurchschnitt.py", line 10, in ?
>     ziffer = note % 10
> TypeError: not all arguments converted


This is an error message that occurs during string formatting.  However, I
think you're right: this error message doesn't seem descriptive enough for
a newcomer to understand what's happening.  Even for an intermediate user,
this error message doesn't really mention the cause of the error, but only
the side effect of it.

It might be good to modify the error message to explicitely say something
like:

"TypeError: not all arguments converted during string formatting"

to give a better hint that 'note' here is a string.  I've entered a
feature request into Sourceforge for this.

http://sourceforge.net/tracker/index.php?func=detail&aid=549187&group_id=5470&atid=355470

and perhaps the error message itself can be improved to make the error
more clear.




> 2. How could one develop means, which makes restarting the IDE or
>    the interpreter obsolete?
>    As far as I remember there is a good example in the
>    TeachScheme-Project,
>    where language-features can be turned on/off according to the level
>    of knowledge of the students.
>    One could imagine - in the case obove - to turn off the possibility
>    of overwriting built-in functions in Python ( does there exist a
>    switch
>    concerning this?).

DrScheme will, in fact, warn the user to clear off the previous session if
a program has changed.  It even has a large RESET button with red letters
to make clearing the environment easy to do.





> 3. Is it possible to rebind input() to it's original built-in function
>    without restarting the whole machinery.

Although 'input' in the global environment is bound to that string now,
it's still possible to fix this by going through the __builtin__ module
and refix things:

###
>>> input = 'argh'
>>> input
'argh'
>>> from __builtin__ import *
>>> input
<built-in function input>
###

That's probably one way of doing it.



> 4. Is there a list somewhere of features to implement / provide for
> educational use of IDLE or some special eduactional-IDE? Or should we
> start to collect ideas in this direction?

The IDLEFork-dev mailing list might be a good place to place to discuss
educational issues with IDLE.


Good luck to you!




From pobrien@orbtech.com  Fri Apr 26 18:50:15 2002
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Fri, 26 Apr 2002 12:50:15 -0500
Subject: [Edu-sig] Re: [Tutor] How to deal with strange errors?
In-Reply-To: <Pine.LNX.4.44.0204261009280.14857-100000@hkn.eecs.berkeley.edu>
Message-ID: <NBBBIOJPGKJEKIECEMCBEEPIMOAA.pobrien@orbtech.com>

[Danny Yoo]
> > 3. Is it possible to rebind input() to it's original built-in function
> >    without restarting the whole machinery.
> 
> Although 'input' in the global environment is bound to that string now,
> it's still possible to fix this by going through the __builtin__ module
> and refix things:
> 
> ###
> >>> input = 'argh'
> >>> input
> 'argh'
> >>> from __builtin__ import *
> >>> input
> <built-in function input>
> ###
> 
> That's probably one way of doing it.

Here is another:

>>> input = 'blah'
>>> input
'blah'
>>> input = __builtins__['input']  # Note the trailing 's'
>>> input
<built-in function input>
>>> 

---
Patrick K. O'Brien
Orbtech



From pobrien@orbtech.com  Fri Apr 26 19:03:45 2002
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Fri, 26 Apr 2002 13:03:45 -0500
Subject: [Tutor] RE: [Edu-sig] How to deal with strange errors?
In-Reply-To: <3CC98812.38670CBB@rg16.asn-wien.ac.at>
Message-ID: <NBBBIOJPGKJEKIECEMCBOEPJMOAA.pobrien@orbtech.com>

> I'm interested in your opinion about these problems
> and also to contribute to this development, but how?
>
> Regards
> Gregor Lingl

I'll repeat an offer I've made on more than one occassion. As the creator of
PyCrust, I would be more than happy to work with anyone that wanted to
extend its use as a teaching tool. PyCrust is an interactive Python shell
and namespace viewer written in Python with the wxPython gui toolkit.
PyCrust now ships with wxPython (http://www.wxpython.org). The latest
development version is available from CVS at SourceForge
(http://sourceforge.net/projects/pycrust).

All the foundation work is done. The PyCrust environment can be manipulated
like any other Python object and was designed to be modular and extendable.
PyCrust has many features that lend themselves to a teaching environment,
like autocompletion, calltips, a namespace tree, command recall and full
multi-line editing. But it still has most (if not all) of the flaws that
were pointed out in this email. I think they are all fixable, but I have a
limited amount of time and energy that I can devote to this. What's missing
is someone with a little imagination that wanted to take the lead and run
with this. Let me know if anyone is interested.

---
Patrick K. O'Brien
Orbtech




From scot@possum.in-berlin.de  Fri Apr 26 19:47:35 2002
From: scot@possum.in-berlin.de (Scot Stevenson)
Date: Fri, 26 Apr 2002 20:47:35 +0200
Subject: [Tutor] 1 only book
In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C577@mbtlipnt02.btlabs.bt.co.uk>
References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C577@mbtlipnt02.btlabs.bt.co.uk>
Message-ID: <200204260158.g3Q1wJR30825@possum.cozen.org>

Hi, 

> Yes, and if we are going outside Python, the one book *everyone*
> who writes code should have is Code Complete by McConnell.

I would like to second that. Based on a recommendation on this list, I 
went out and bought it, and it has helped a lot - in fact, I is on my list 
to go over /again/ and catch the stuff that I didn't get the first time. 

[I only have two gripes, none of which have to do with the content: First, 
nobody warned me it was published by Microsoft Press, which even caused my 
KDE-loving wife to snicker and point. Second, there is a careless mistake 
the German on page 157 [the word is /Benutzerfreundlichkeit/, without any 
dots - /Umlaute/ - above the first 'u']. --- Note to authors: If for some 
reason you feel absolutely compelled to use German words, please get them 
right, and don't just randomly insert Umlaute. The most amazing mistake 
I've found so far is in Bob Shaw's "Orbitsville", where he has 
/Liebensraum/ - 'room to love' - instead of /Lebensraum/ - 'room to live' 
- which I'm sure his Polish readers just love. Tom Clancy has one novel 
where the German is so bad (at least in the hard cover version) it ruins 
the whole book - you just can feel that he couldn't be bothered to check 
it, which makes you wonder about the technical "facts" he has.]

Oops, I'm ranting. Anyway, a very good book, and one I wish I'd had 
earlier.

In contrast, I've had problems applying "Design Patters" to the real 
world. It might be my lack of programming experience or a firm computer 
science background, but I have trouble translating the abstract patterns 
into real code. I'm aiming to go over it again, too, when I have more 
hands-on experience.

Y, Scot




From scot@possum.in-berlin.de  Fri Apr 26 19:03:59 2002
From: scot@possum.in-berlin.de (Scot Stevenson)
Date: Fri, 26 Apr 2002 20:03:59 +0200
Subject: [Tutor] Strange join syntax
In-Reply-To: <20020425001128.A30029@pino.selwerd.nl>
References: <F559NUpuabjKoMFYsDS0000897b@hotmail.com> <20020425001128.A30029@pino.selwerd.nl>
Message-ID: <200204260114.g3Q1EhR30722@possum.cozen.org>

Hello Remco, 

While talking about list reverse, you gave an example that included

> drow = ''.join(wordlist)

I tried this construction myself, and I see that it works, but I'm not 
sure if I understand what is happening here. My docs [Python 2.1.1, yes 
I'll be updating when I have time to install SuSE 8.0] say:

=================
join(words[, sep]) 
Concatenate a list or tuple of words with intervening occurrences of sep. 
The default value for sep is a single space character. It is always true 
that "string.join(string.split(s, sep), sep)" equals s. 
=================

So I would have expected 

>>> wordlist = list('alabaster')
>>> wordlist
['a', 'l', 'a', 'b', 'a', 's', 't', 'e', 'r']
>>> newlist = string.join(wordlist, '')
>>> newlist
'alabaster'

Is there any special reason why you didn't do it this way? 

I'm amazed that the Python Elves know what do to with the '' at the 
beginning, but then I guess that's just magic for you =8).

Thanks, 
Y, Scot



From tjenkins@devis.com  Fri Apr 26 20:09:33 2002
From: tjenkins@devis.com (Tom Jenkins)
Date: 26 Apr 2002 15:09:33 -0400
Subject: [Tutor] Strange join syntax
In-Reply-To: <200204260114.g3Q1EhR30722@possum.cozen.org>
References: <F559NUpuabjKoMFYsDS0000897b@hotmail.com>
 <20020425001128.A30029@pino.selwerd.nl>
 <200204260114.g3Q1EhR30722@possum.cozen.org>
Message-ID: <1019848173.14684.52.camel@asimov>

On Fri, 2002-04-26 at 14:03, Scot Stevenson wrote:
> Hello Remco, 
> 
> While talking about list reverse, you gave an example that included
> 
> > drow = ''.join(wordlist)
> 
> I tried this construction myself, and I see that it works, but I'm not 
> sure if I understand what is happening here. My docs [Python 2.1.1, yes 
> I'll be updating when I have time to install SuSE 8.0] say:

well this is a change that was added to 2.0+ that I frankly think
detracts from the readability of python (not that i can think of a
different way off the top of my head)

previous versions had a string module, so you would have to say:
  import string
  drow = string.join(wordlist, '')

starting in 2.0, you didn't need to import string, because strings now
had methods (basically the functions from the string module).  so by
saying
  drow = ''.join(wordlist)
you were saying "join the list wordlist using the string '' (empty
string) as the delimiter"


> 
> =================
> join(words[, sep]) 
> Concatenate a list or tuple of words with intervening occurrences of sep. 
> The default value for sep is a single space character. It is always true 
> that "string.join(string.split(s, sep), sep)" equals s. 
> =================
> 

or in version 2+ terms
sep.join(words)

ython.org/mailman/listinfo/tutor
-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com





From paulsid@shaw.ca  Fri Apr 26 20:16:38 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Fri, 26 Apr 2002 13:16:38 -0600
Subject: [Tutor] windows and filenames
References: <002001c1ed04$9af2a590$da494e18@cr536745a>
Message-ID: <3CC9A796.639FF738@shaw.ca>

"Ian!" wrote:

> Paul - when I use win32api.GetFullPathName('f:\\mp3s\\electr~1'), it just
> returns the exact same string I fed it. I think by "Full", it means "local
> files get returned with whole path", not "windows filenames get resolved".

That's very strange.  The Win32 SDK docs say the following under
GetFullPathName():

lpFilePart
   Points to a variable that receives the address (in lpBuffer) of the 
   final filename component in the path. This filename component is 
   the long filename, if any, rather than the 8.3 form of the filename.

Maybe there's a bug in the win32api wrapper?  I've never used it though
so I probably shuldn't guess as to what's going on.  Hopefully somebody
else has an answer.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From paulsid@shaw.ca  Fri Apr 26 20:56:11 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Fri, 26 Apr 2002 13:56:11 -0600
Subject: [Tutor] Strange join syntax
References: <F559NUpuabjKoMFYsDS0000897b@hotmail.com>
 <20020425001128.A30029@pino.selwerd.nl>
 <200204260114.g3Q1EhR30722@possum.cozen.org>
Message-ID: <3CC9B0DB.CABC4D1C@shaw.ca>

Scot Stevenson wrote:

> While talking about list reverse, you gave an example that included
> 
> > drow = ''.join(wordlist)
> 
> I tried this construction myself, and I see that it works, but I'm not
> sure if I understand what is happening here. My docs [Python 2.1.1, yes
> I'll be updating when I have time to install SuSE 8.0] say:

I guess the no-nonsense explanation is this:

String objects have member methods.
String constants are string objects.
------------------------------------
String constants have member methods.

You probably understand this part already but just in case, there's the
answer.  As for join itself:

> =================
> join(words[, sep]) 
> Concatenate a list or tuple of words with intervening occurrences of sep.
> The default value for sep is a single space character. It is always true 
> that "string.join(string.split(s, sep), sep)" equals s. 
> =================

I wasn't around when this debate took place but it seems logical that
the reason strings were given methods is because all of the functions in
the string module take a string to work on as their first parameter. 
All, that is, except for join().  join() works on a list, not a string. 
The only string join() takes is that optional separator, sep.  So I
guess TPTB decided that this would be what the string object would be
used for when calling join() as a method, rather than leaving join()
out.  It makes some degree of sense, even though I agree that it's a
tricky concept to grasp.

> Is there any special reason why you didn't do it this way?

Brevity, I expect, but by all means do it the other way if you find it
clearer.  The string module may be considered by some to be obsolete but
I don't think it's going to be deprecated any time soon.  

Even clearer (though much slower) would be the manual approach:

newstr = None
for s in strlist:
    if newstr is None:
        newstr = s
    else:
        newstr = newstr + sep + s

Just because shortcuts exist doesn't mean they have to be used.  :-)

> I'm amazed that the Python Elves know what do to with the '' at the
> beginning, but then I guess that's just magic for you =8).

I actually find it more amazing that the "elves" know what to do with
the dot and the function call at the end.  Directly using a literal as
an object just seems really weird to me.  Nevertheless it is quite neat,
and handy at times.

BTW you can also subscript string literals (and lists) directly, e.g.:

>>> "hey there"[2:5]
'y t'
>>> [1, 2, 3, 4][1:3]
[2, 3]

When I first saw this I thought, "Huh?  There's a subscript there but no
variable!"  Took me a few minutes to realize that the literal _was_ the
variable, and my head was spinning the rest of the day.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From dman@dman.ddts.net  Fri Apr 26 21:26:32 2002
From: dman@dman.ddts.net (dman)
Date: Fri, 26 Apr 2002 15:26:32 -0500
Subject: [Tutor] How to deal with strange errors?
In-Reply-To: <Pine.LNX.4.44.0204261009280.14857-100000@hkn.eecs.berkeley.edu>
References: <3CC98812.38670CBB@rg16.asn-wien.ac.at> <Pine.LNX.4.44.0204261009280.14857-100000@hkn.eecs.berkeley.edu>
Message-ID: <20020426202632.GB28399@dman.ddts.net>

--qcHopEYAB45HaUaB
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Apr 26, 2002 at 10:35:15AM -0700, Danny Yoo wrote:
=20
| > 3. Is it possible to rebind input() to it's original built-in function
| >    without restarting the whole machinery.
|=20
| Although 'input' in the global environment is bound to that string now,

Nope.  It was rebound only in the current environment (module-level
scope).

| it's still possible to fix this by going through the __builtin__ module
| and refix things:

Simply delete the local binding.

>>> input
<built-in function input>
>>> input =3D "foo"
>>> input
'foo'
>>> del input
>>> input
<built-in function input>
>>>=20


As for explaining this to new programmers ... first they need to
understand scope before they can understand how "deleteing" the object
makes it "come back".  In this one case I think curly braces are cool
-- wacky nested scope examples in C are easier to visualize with the
braces and with braces in the middle of a block (as opposed to a new
function).  Perhaps throw some braces into the diagrams as you explain
scopes, but say they are just for visualization in the teaching aid
and that python doesn't use them.

HTH,
-D

--=20

How great is the love the Father has lavished on us,
that we should be called children of God!
        1 John 3:1=20
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--qcHopEYAB45HaUaB
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzJt/gACgkQO8l8XBKTpRR2qgCfRKt4lt4Dqh6WrffGcBcv/uk4
AIUAoKq0HxYluih4qySxkE2Xu3LncEeq
=Cpqy
-----END PGP SIGNATURE-----

--qcHopEYAB45HaUaB--



From dman@dman.ddts.net  Fri Apr 26 21:33:38 2002
From: dman@dman.ddts.net (dman)
Date: Fri, 26 Apr 2002 15:33:38 -0500
Subject: [Tutor] Strange join syntax
In-Reply-To: <200204260114.g3Q1EhR30722@possum.cozen.org>
References: <F559NUpuabjKoMFYsDS0000897b@hotmail.com> <20020425001128.A30029@pino.selwerd.nl> <200204260114.g3Q1EhR30722@possum.cozen.org>
Message-ID: <20020426203338.GC28399@dman.ddts.net>

--i7F3eY7HS/tUJxUd
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Apr 26, 2002 at 08:03:59PM +0200, Scot Stevenson wrote:
| Hello Remco,=20
|=20
| While talking about list reverse, you gave an example that included
|=20
| > drow =3D ''.join(wordlist)

Consider the following python-ish java-ish pseudo-ish code.


interface Joiner :
    public abstract object join( self , sequence )


# this is the built-in string type
class string( Joiner ) :

    # note: untested, but might work, and is _not_ efficient
    def join( self , sequence ) :
        res =3D str( sequence[0] )
        for item in sequence[1:] :
            res +=3D self + str( item )
        return res


The '' at the beginning is a string object, the empty string.  Strings
are "joiners" and know how to join a sequence of items together.  Thus
you can pass a list of things to a string object's join() method and
it joins them together (returning a string).


I agree that it looks odd at first, but once you get used to the fact
that literals (strings, lists, etc) are still objects, and once the
"joiner" interface seems reasonable, then the whole thing makes
perfect sense and is nicely compact.

-D

--=20

How great is the love the Father has lavished on us,
that we should be called children of God!
        1 John 3:1=20
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--i7F3eY7HS/tUJxUd
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzJuaIACgkQO8l8XBKTpRTNbACfYefY0Q9ff94x7N3m/wC9d6xF
upEAoLe9oqs7G7hrHfto4LKAywGMn110
=wPuq
-----END PGP SIGNATURE-----

--i7F3eY7HS/tUJxUd--



From phthenry@earthlink.net  Fri Apr 26 21:40:42 2002
From: phthenry@earthlink.net (Paul Tremblay)
Date: Fri, 26 Apr 2002 16:40:42 -0400
Subject: [Tutor] new class vs. old class [was using class methods (security)]
Message-ID: <20020426164042.C14532@localhost.localdomain>

Sorry to be so dense on this issue, but I still am not sure about
the difference between new and old classes in python 2.2. Here is
an excerpt from the documentation linked to python.org:

http://www.amk.ca/python/2.2/

"First, you should know that Python 2.2 really has two kinds of classes: classic or old-style classes, and new-style
classes. The old-style class model is exactly the same as the class model in earlier versions of Python. All the new
features described in this section apply only to new-style classes. This divergence isn't intended to last forever;
eventually old-style classes will be dropped, possibly in Python 3.0. 

"So how do you define a new-style class? You do it by subclassing an existing new-style class. Most of Python's
built-in types, such as integers, lists, dictionaries, and even files, are new-style classes now. A new-style class named
object, the base class for all built-in types, has been also been added so if no built-in type is suitable, you can
just subclass object:" 

I understand that at this point I can continue using classes as
I have been in the past. However, what if I want to get in the
habit of writing new classes, since eventually I will have to?
According to the documentatin I quoted above,  I *have* to
subclass new classes. (I am looking at the first sentence of the
second paragraph.)

In other words, when python 3.0 rolls around, I won't be able to
write this code:

class MyClass:
	pass

Instead, won't I have to write 

class MyClass(object):
	pass

?

I have already downloaded the source rpm (I have linux) for
python 2.2. Maybe I should just go ahead and install it and play
around with it. 

Thanks!

Paul


-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************



From jeff@ccvcorp.com  Fri Apr 26 22:45:11 2002
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Fri, 26 Apr 2002 14:45:11 -0700
Subject: [Tutor] new class vs. old class [was using class methods (security)]
References: <20020426164042.C14532@localhost.localdomain>
Message-ID: <3CC9CA67.8710FDF1@ccvcorp.com>


Paul Tremblay wrote:

> In other words, when python 3.0 rolls around, I won't be able to
> write this code:
>
> class MyClass:
>         pass

That's not correct, as I understand it.  In Python 3.0 (or whenever), the above code will create a new-style class, and will
be functionally equivalent to the same definition subclassed from object.  It's only during the transitional period that
subclassing from object is required for new-style classes, and the only reason for that requirement is so that the parser can
differentiate new-style classes from old-style.

Jeff Shannon
Technician/Programmer
Credit International







From imcmeans@shaw.ca  Sat Apr 27 00:04:14 2002
From: imcmeans@shaw.ca (Ian!)
Date: Fri, 26 Apr 2002 16:04:14 -0700
Subject: [Tutor] windows and filenames
Message-ID: <003001c1ed76$afbe4250$da494e18@cr536745a>

I need the full pathname because the script takes the filename and converts
it into a URL that will work on my webserver. So f:\mp3s\song.mp3 gets
converted into http://24.78.73.218/mp3s/song.mp3, and
f:\apache\htdocs\somefile.html gets converted into
http://24.78.73.218/somefile.html

the dos-style filenames are ugly, but they also don't work with apache.
Apache needs the full filenames, so you can see why "mp3s\electr~1" doesn't
work when "electronica" would.

I guess I'll look around for winall and see if that has anything that could
help.




From dman@dman.ddts.net  Sat Apr 27 03:38:20 2002
From: dman@dman.ddts.net (dman)
Date: Fri, 26 Apr 2002 21:38:20 -0500
Subject: [Tutor] Perl refugee
In-Reply-To: <3CC96B54.D416E67F@usc.edu>
References: <3CC96B54.D416E67F@usc.edu>
Message-ID: <20020427023820.GA32343@dman.ddts.net>

--opJtzjQTFsWo+cga
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Apr 26, 2002 at 07:59:32AM -0700, Rich Pinder wrote:
| Ok... i'm a zope user (not a good one), and long time perl user.
| Each time i get a little 'utility' type project, I think "A ha..  I'll
| use Python this time" - then the time gets low, i never get around to
| it, and say  "heck, i'll just do it in Perl".....
|=20
| So this morning I said no - wanna get the first one under my belt !

Good!  You won't regret it!  (zope is really cool too, isn't it?)

| realized the machine i'm using doesnt have Python - so loading it now.
|=20
| .... here's my goal.....
|=20
| I need to copy 80,000 files from one directory and put them in one of 20
| other directories.  I'm into chaper 12&13 in the pyton book, and am sure
| I can get the looping structure over the directory listing....
|=20
| But to progam the logic to decide where the files go, I need substring
| parsing of the file names (think thats easy)

Yeah python is quite good at string manipulation.  Unless you write
some really wacky code you'll even be able to comprehend it in a few
weeks!

| PLUS something like a CASE statement.  I don't see the CASE
| statement anywhere.

A switch/case statement is just a hangover from C.  It is faster
because it is simply a computed jump, but as a result is restricted to
int and char.

| So will i have to use a bunch of cludgy if/then statements, or is there
| something more elequent...
|=20
|   if subval > "0001"  and subval < "0010" :

You really don't want that in a switch either!  You'd have to write
out each and every number and have them fall through.  Better to use
an if-else ladder.

|      <filecopyingsteps>
|  elif subval > "0009"  and subval < "0020" :
|      <filecopyingsteps>
| ........

Change
    <filecopyingsteps>
to be a function call instead.  Write your function generally enough
so that you can pass some simple arguments to it from the if-else
ladder and have it correctly handle all (or at least many) of the
operations you need to do.

Do something like :

if "0001" < subval < "0010" :
    # you didn't actually mention the parameters for moving the files,
    # so I'm just wildy guessing here
    copyfile( subval , "subdir1" )
elif "0009"  < subval < "0020" :
    copyfile( subval , "subdir2" )


It really isn't that bad, now is it?

IME switch statements are rarely used (even in C/C++/Java) anyways,
and in the situations where it might be useful a dictionary lookup can
be much more elegant.

-D

--=20

In the way of righteousness there is life;
along that path is immortality.
        Proverbs 12:28
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--opJtzjQTFsWo+cga
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzKDxwACgkQO8l8XBKTpRQsCQCgyIm1H6lOOh82VkzqEWcM8sVT
FEEAnjqEGImrekevh22jPxvqM9O5bb1n
=DqK6
-----END PGP SIGNATURE-----

--opJtzjQTFsWo+cga--



From dyoo@hkn.eecs.berkeley.edu  Sat Apr 27 03:56:25 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 26 Apr 2002 19:56:25 -0700 (PDT)
Subject: [Tutor] Perl refugee
In-Reply-To: <20020427023820.GA32343@dman.ddts.net>
Message-ID: <Pine.LNX.4.44.0204261941170.2134-100000@hkn.eecs.berkeley.edu>

> | So will i have to use a bunch of cludgy if/then statements, or is there
> | something more elequent...
> |
> |   if subval > "0001"  and subval < "0010" :
>
> You really don't want that in a switch either!  You'd have to write
> out each and every number and have them fall through.  Better to use
> an if-else ladder.
>
> |      <filecopyingsteps>
> |  elif subval > "0009"  and subval < "0020" :
> |      <filecopyingsteps>
> | ........


Is it always in groups of 10?  If so, you might be able to do something
like a switch statement, by creativly using a list of functions:

###
def copy_steps_up_to_ten():
    print "You've chosen 1-10."

def copy_steps_up_to_twenty():
    print "Hmmm... you've chosen something between 10-20."

def copy_steps_up_to_thirty():
    print "Ok, from 20-30."

subval = raw_input("What's subval? ")
group = int(subval) / 10             ## Division can be thought of as
                                     ## an operation that can group
                                     ## numbers together.
possible_commands = [copy_steps_up_to_ten,
                     copy_steps_up_to_twenty,
                     copy_steps_up_to_thirty,
                     ]
possible_commands[group]()   ## <--- This is the thing that "switch"es.
###

(This actually approximates sorta what switch does, except switch in C is
a very low-level flow control thing, also called a "jump table".)


If we find ourselves writing repetitive code, we might be able to
generalize the code so that it doesn't induce carpal tunnel.  If you tell
us more about these "filecopyingsteps", we might be able to tease some
generality out of the code.

Talk to you later!




From sman1337@hotmail.com  Sat Apr 27 05:29:12 2002
From: sman1337@hotmail.com (Spotacus Macell)
Date: Sat, 27 Apr 2002 01:29:12 -0300
Subject: [Tutor] Two Problems (databases, and branching)
Message-ID: <F1913EciyR9nvhg1vSi000013bc@hotmail.com>

//connected to SPOTACUS
//begin transmition

Coding/programming background:
HTML (pretty much everything, excluding stuff dealing w/ other languages 
[CGI, JavaScript, etc])
#RPGCode (programming language made for RPG Toolkit)

Now, I have two problems, both of which I can't find answers to. First of 
all: I've been reading through the archived messages on Tutor, and what I'm 
getting is that you can't make databases right in Python, that you need to 
use something else (I was seeing SQL being said a bit). If it IS possible to 
make databases right in Python, could someone point me at some documentation 
or some other such thing so I could figure it out? The reason I need this is 
because I'm trying to make a (what then seemed "simple") text based RPG. 
But, I need to make a merchant in my program to buy/sell items, and I can't 
figure it out.

And now for my second problem. From my (albeit minimal) work with #RPGCode, 
I found a very useful command, but I can't find it in Python. I'm sure 
there'd be something at least similar, but I can't find it. Anyway, what it 
is is the branch command. In RPGCode, it basically looks like this:

-------------
#branch(:here)

#mwin("Text in a message window")

:here
-------------

What it does, if you can't see (no disrespect, of course), is that the 
branch command skips everything after it, until it reaches :here. You can 
basically go anywhere in the program, either way. Combined with an if 
statement, it's rather useful. But I can't find anything like it in Python, 
and it perturbs me. I've used while loops where they were un-needed, to 
imitate it to go back _up_ through a program (my first program was 80-odd 
lines, and only about 5 of which were outside of a giant while loop), but 
there's no way to dopplegang it in the down direction.

Hmm...this message was _way_ longer than expected, so I'll stop now. That's 
it, anyways...thanks for taking the time to actually read all this!


//end transmition
//SPOTACUS connection dead

_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com




From dman@dman.ddts.net  Sat Apr 27 06:38:36 2002
From: dman@dman.ddts.net (dman)
Date: Sat, 27 Apr 2002 00:38:36 -0500
Subject: [Tutor] Two Problems (databases, and branching)
In-Reply-To: <F1913EciyR9nvhg1vSi000013bc@hotmail.com>
References: <F1913EciyR9nvhg1vSi000013bc@hotmail.com>
Message-ID: <20020427053836.GA2395@dman.ddts.net>

--BXVAT5kNtrzKuDFl
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Apr 27, 2002 at 01:29:12AM -0300, Spotacus Macell wrote:

| Now, I have two problems, both of which I can't find answers to. First of=
=20
| all: I've been reading through the archived messages on Tutor, and what I=
'm=20
| getting is that you can't make databases right in Python, that you need t=
o=20
| use something else (I was seeing SQL being said a bit). If it IS possible=
=20
| to make databases right in Python, could someone point me at some=20
| documentation or some other such thing so I could figure it out?

What are your requirements for this database?  There are many choices
out there.  If you want a pure-python implementation, gadfly is the
only one I know of.  It implements a subset of SQL.  SQL is the
industry-standard language for interacting with a Relational database.
If you want a more heavy-duty database there are python modules for
connecting to a PostgreSQL or MySQL or other relational databases (all
involve SQL).  There are also bindings to dbm and bsddb
implementations, but I know little of these database systems.  There's
the ZODB (Zope Object Database) which can be used if you want to store
a hierarchical collection of objects.  On the simpler side there's the
standard 'pickle' module, or you could create your own plain-text
format.  It all depends on what your needs are and what your
restrictions are.

| And now for my second problem. From my (albeit minimal) work with #RPGCod=
e,=20
| I found a very useful command, but I can't find it in Python. I'm sure=20
| there'd be something at least similar, but I can't find it. Anyway, what =
it=20
| is is the branch command. In RPGCode, it basically looks like this:
|=20
| -------------
| #branch(:here)
|=20
| #mwin("Text in a message window")
|=20
| :here
| -------------

<shudder>.  You really don't want to start writing spaghetti-code :-).
Python, like C and other modern languages, is structured.  I presume
that before your #branch statement you have a condition to determine
whether or not to branch this time?  Structured languages do it this
way :

    # decide which way to branch
    if cond :
        mwin("Text in a message window")
    else :
        # :here
        print "the else block"

The improvement is that the text flow much more clearly indicates how
the execution will flow.  With the "goto" example all the code looks
like it flows in one line.  It is also very easy to start putting
"gotos" all over the code, and then it can become impossible to
follow.

| Combined with an if statement, it's rather useful. But I can't find
| anything like it in Python, and it perturbs me. I've used while
| loops where they were un-needed, to imitate it to go back _up_
| through a program (my first program was 80-odd lines, and only about
| 5 of which were outside of a giant while loop), but there's no way
| to dopplegang it in the down direction.

You need to refactor the code into "sub programs" (functions, in
python).  Put the statements that are executed together into a
separate function so that you can call it from multiple places and
have manageable code.  Break the "goto" habit as fast as you can!


How about posting that 80-odd line script and letting someone with
some spare cycles refactor it to give you a concrete example of how it
works?


-D

--=20

I tell you the truth, everyone who sins is a slave to sin.  Now a slave
has no permanent place in the family, but a son belongs to it forever.
So if the Son sets you free, you will be free indeed.
        John 8:34-36
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--BXVAT5kNtrzKuDFl
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzKOVwACgkQO8l8XBKTpRQXFACfV2AID85G8e6e+iXk6/DwcVfv
m8gAnRKExk5+vrwRVeqHqUcY0a2OdBt7
=4fYC
-----END PGP SIGNATURE-----

--BXVAT5kNtrzKuDFl--



From lkvam@venix.com  Sat Apr 27 14:20:10 2002
From: lkvam@venix.com (Lloyd Kvam)
Date: Sat, 27 Apr 2002 09:20:10 -0400
Subject: [Tutor] Two Problems (databases, and branching)
References: <F1913EciyR9nvhg1vSi000013bc@hotmail.com> <20020427053836.GA2395@dman.ddts.net>
Message-ID: <3CCAA58A.7000700@venix.com>

Some of the old programming languages (BASIC, COBOL, RPG, FORTRAN66)
fit a narrative style of programming.  You start at the beginning
and simply plow along until you reach the end.  This works OK for
small programs and makes these small programs fairly easy to follow.
An occasional branch or GoTo can be understood in context, especially
with some comments to assist.

However, "War and Peace" really is a narrative.  A program is not.  Some
lines are executed more often than others.  Short blocks of repeated
code can be used with 'for' or 'while' loops.  Bigger blocks should get
pushed off into functions.  Blocks of lines that get written repeatedly
also get split off into functions.  You wind up with a manageable
narrative of what the program is trying to do while effectively
pushing chunks off into appendices.

Object oriented programming tends to break the narrative among the
actors.  It becomes sort of a play where each actor nudges the next
one to say the proper lines.  The lines are organized actor by actor
and it is hard to see the overall narrative.  This organization makes
it is easier to focus on each little piece of "script" and get it right.

Sometimes (for instance with multiple threads) there is no narrative.
The challenge is to write a program that is understood by both the
computer that executes it and the person who reads it.

dman wrote:

> On Sat, Apr 27, 2002 at 01:29:12AM -0300, Spotacus Macell wrote:

.....

> have manageable code.  Break the "goto" habit as fast as you can!
> 
> 
> How about posting that 80-odd line script and letting someone with
> some spare cycles refactor it to give you a concrete example of how it
> works?
> 
> 
> -D
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From sman1337@hotmail.com  Sat Apr 27 17:42:52 2002
From: sman1337@hotmail.com (Spotacus)
Date: Sat, 27 Apr 2002 13:42:52 -0300
Subject: [Tutor] Two Problems (databases, and branching)
Message-ID: <000001c1ee0a$931fc120$147a250a@wolf>

This is a multi-part message in MIME format.

------=_NextPart_000_0001_01C1EDF1.6DDBB0E0
Content-Type: text/plain;
	charset="us-ascii"
Content-Transfer-Encoding: 7bit

\\ What are your requirements for this database?  There are many choices
out there.
 
I don't have much in the way of requirements. Just, something where part
of it can't be changed, that stores the info about the items the
merchant sells (name, buying price, selling price, etc), and then
another part that stores everything that the character is carrying. I'm
pretty sure that's how it'd work.
 
\\ Structured <file:///\\Structured>  languages do it this way:
\\ # decide which way to branch
\\ if cond :
\\     mwin("Text in a message window")
\\ else :
\\     # :here
\\     print "the else block"
 
I could do that, but I was thinking of something along the lines of
skipping the whole program over. An example could be something that
needed a password? Not anything high calibur, but simple, like:
 
password = raw_input("What's the password? ")
if password != "whatever"
    branch(":end")
#---entire program goes here
:end
 
That's the kind of thing I was thinking, possibly. If I used an if
statement to that effect, wouldn't I have to put the entire program
inside the if statement?
 
\\ How about posting that 80-odd line script and letting someone with
\\ some spare cycles refactor it to give you a concrete example of
\\ how it works?
 
Um, okay. The program's just a simple calculator that I was doing to
test out some things, and it ended up being a gigantic mess of whiles
and ifs. But here it is anyway. Actually, I've been tweaking it for a
while, and after I took out all the comments (except the one at the
beginning), it was I think 90 lines.
 
---begin code---
 
#Spotacus' "fivecalc" v2.0
mask = 1
def wait():
    wait = raw_input("Press [Enter]")
name = raw_input("What's your first name? ")
print "Welcome to the calculator,", name
wait()
while mask == 1:
    print ""
    print ""
    print "1: Add"
    print "2: Subtract"
    print "3: Multiply"
    print "4: Divide"
    print "5: Exponents"
    print "9: Exit"
    print ""
    action = input("What will you do? (1|2|3|4|5|9) ")
    if action == 1:
        addnum = 1
        while addnum == 1:
            addnum = input("How many numbers are you going to add?
(2|3|4) ")
            if addnum == 2:
                add_1 = input("What's the first number? ")
                add_2 = input("What's the second number? ")
                sum = add_1 + add_2
                print "The sum of", add_1, "and", add_2, "is equal to",
sum
                wait()
            elif addnum == 3:
                add_1 = input("What's the first number? ")
                add_2 = input("What's the second number? ")
                add_3 = input("What's the third number? ")
                sum = add_1 + add_2 + add_3
                print "The sum of", add_1, ",", add_2, "and", add_3,
                print "is", sum
                wait()
            elif addnum == 4:
                add_1 = input("What's the first number? ")
                add_2 = input("What's the second number? ")
                add_3 = input("What's the third number? ")
                add_4 = input("What's the fourth number? ")
                sum = add_1 + add_2 + add_3 + add_4
                print "The sum of", add_1, ",", add_2, ",", add_3,
"and",
                print add_4, "is equal to", sum
                wait()
            else:
                addnum = 1
    elif action == 2:
        sub_1 = input("What's the first number? ")
        sub_2 = input("What's the second number? ")
        difference = sub_1 - sub_2
        print "the difference between", sub_1, "and", sub_2, "is",
difference
        wait()
    elif action == 3:
        mulnum = 1
        while mulnum == 1:
            mulnum = input("How many numbers are you going to multiply?
(2|3) ")
            if mulnum == 2:
                mul_1 = input("What's the first number? ")
                mul_2 = input("What's the second number? ")
                mul_4 = mul_1 * mul_2
                print mul_1, "multiplied by", mul_2, "is equal to",
mul_4
                wait()
            elif mulnum == 3:
                mul_1 = input("What's the first number? ")
                mul_2 = input("What's the second number? ")
                mul_3 = input("What's the third number? ")
                mul_4 = mul_1 * mul_2 * mul_3
                print mul_1, "multiplied by", mul_2, "multiplied by",
mul_3,
                print "is equal to", mul_4
                wait()
            else:
                mulnum = 1
    elif action == 4:
        div_1 = input("What's the first number? ")
        div_2 = input("What's the second number? ")
        div_3 = div_1 / div_2
        div_4 = div_1 % div_2
        print div_1, "divided by", div_2, "is equal to", div_3, "R",
div_4
        wait()
    elif action == 5:
        exp_1 = input("What's the base number? ")
        exp_2 = input("What's the exponent? ")
        exp_3 = exp_1 ** exp_2
        print exp_1, "to the power of", exp_2, "is equal to", exp_3
        wait()
    elif action == 9:
        mask = 2
print "Thank you,", name
end = raw_input("Press [Enter] at your leisure")
 
---end code---
 
I've fixed it up, too, so that now it's only 52 lines and works a lot
better.but I don't have the time to put it down here.

------=_NextPart_000_0001_01C1EDF1.6DDBB0E0
Content-Type: text/html;
	charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

<html xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns=3D"http://www.w3.org/TR/REC-html40">

<head>
<META HTTP-EQUIV=3D"Content-Type" CONTENT=3D"text/html; =
charset=3Dus-ascii">


<meta name=3DProgId content=3DWord.Document>
<meta name=3DGenerator content=3D"Microsoft Word 10">
<meta name=3DOriginator content=3D"Microsoft Word 10">
<link rel=3DFile-List href=3D"cid:filelist.xml@01C1EDF1.6CB53240">
<!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:DoNotRelyOnCSS/>
 </o:OfficeDocumentSettings>
</xml><![endif]--><!--[if gte mso 9]><xml>
 <w:WordDocument>
  <w:SpellingState>Clean</w:SpellingState>
  <w:GrammarState>Clean</w:GrammarState>
  <w:DocumentKind>DocumentEmail</w:DocumentKind>
  <w:EnvelopeVis/>
  <w:Compatibility>
   <w:BreakWrappedTables/>
   <w:SnapToGridInCell/>
   <w:WrapTextWithPunct/>
   <w:UseAsianBreakRules/>
  </w:Compatibility>
  <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
 </w:WordDocument>
</xml><![endif]-->
<style>
<!--
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
	{mso-style-parent:"";
	margin:0in;
	margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:12.0pt;
	font-family:"Times New Roman";
	mso-fareast-font-family:"Times New Roman";}
a:link, span.MsoHyperlink
	{color:blue;
	text-decoration:underline;
	text-underline:single;}
a:visited, span.MsoHyperlinkFollowed
	{color:purple;
	text-decoration:underline;
	text-underline:single;}
span.EmailStyle17
	{mso-style-type:personal-compose;
	mso-style-noshow:yes;
	mso-ansi-font-size:10.0pt;
	mso-bidi-font-size:10.0pt;
	font-family:Arial;
	mso-ascii-font-family:Arial;
	mso-hansi-font-family:Arial;
	mso-bidi-font-family:Arial;
	color:windowtext;}
span.SpellE
	{mso-style-name:"";
	mso-spl-e:yes;}
span.GramE
	{mso-style-name:"";
	mso-gram-e:yes;}
@page Section1
	{size:8.5in 11.0in;
	margin:1.0in 1.25in 1.0in 1.25in;
	mso-header-margin:.5in;
	mso-footer-margin:.5in;
	mso-paper-source:0;}
div.Section1
	{page:Section1;}
-->
</style>
<!--[if gte mso 10]>
<style>
 /* Style Definitions */=20
 table.MsoNormalTable
	{mso-style-name:"Table Normal";
	mso-tstyle-rowband-size:0;
	mso-tstyle-colband-size:0;
	mso-style-noshow:yes;
	mso-style-parent:"";
	mso-padding-alt:0in 5.4pt 0in 5.4pt;
	mso-para-margin:0in;
	mso-para-margin-bottom:.0001pt;
	mso-pagination:widow-orphan;
	font-size:10.0pt;
	font-family:"Times New Roman";}
</style>
<![endif]-->
</head>

<body lang=3DEN-US link=3Dblue vlink=3Dpurple =
style=3D'tab-interval:.5in'>

<div class=3DSection1>

<p class=3DMsoNormal =
style=3D'mso-layout-grid-align:none;text-autospace:none'><font
size=3D2 face=3DArial><span =
style=3D'font-size:10.0pt;font-family:Arial'>\\ </span></font><span
class=3DGramE><font size=3D2 face=3D"Courier New"><span lang=3DEN-CA =
style=3D'font-size:
10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>What</span></font></span><font
size=3D2 face=3D"Courier New"><span lang=3DEN-CA =
style=3D'font-size:10.0pt;font-family:
"Courier New";mso-ansi-language:EN-CA'> are your requirements for this
database?<span style=3D'mso-spacerun:yes'>&nbsp; </span>There are many =
choices<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>out</span></font></span><font size=3D2 face=3D"Courier New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> there.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>I
don&#8217;t have much in the way of requirements. Just, something where =
part of
it can&#8217;t be changed, that stores the info about the items the =
merchant
sells (name, buying price, selling price, etc), and then another part =
that
stores everything that the character is carrying. I&#8217;m pretty sure =
that&#8217;s
how it&#8217;d work.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\
Structured<a href=3D"file:///\\Structured"></a> languages do it this =
way:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\ #
decide which way to branch<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\ <span
class=3DGramE>if</span> <span class=3DSpellE>cond</span> =
:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\<span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp; </span><span =
class=3DSpellE><span
class=3DGramE>mwin</span></span><span class=3DGramE>(</span>&#8220;Text =
in a
message window&#8221;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\ <span
class=3DGramE>else :</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\<span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>#
:here</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\<span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&#8220;the else block&#8221;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>I
could do that, but I was thinking of something along the lines of =
skipping the
whole program over. An example could be something that needed a =
password? Not
anything high <span class=3DSpellE>calibur</span>, but simple, =
like:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>password</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> =3D <span class=3DSpellE>raw_input</span>(&#8220;What&#8217;s =
the password?
&#8220;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>if</span></font></span><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>
password !=3D &#8220;whatever&#8221;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>branch(</span>&#8220;:end&#8221;)<o:p></o:p></span></font><=
/p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>#---entire
program goes here<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>:end</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>That&#8217;s
the kind of thing I was thinking, possibly. If I used <span =
class=3DGramE>an if</span>
statement to that effect, wouldn&#8217;t I have to put the entire =
program
inside the if statement?<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\
How about posting that 80-odd line script and letting someone =
with<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\
some spare cycles <span class=3DSpellE><span =
class=3DGramE>refactor</span></span>
it to give you a concrete example of<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>\\ <span
class=3DGramE>how</span> it works?<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>Um,
okay. The program&#8217;s just a simple calculator that I was doing to =
test out
some things, and it ended up being a gigantic mess of whiles and ifs. =
But here
it is anyway. Actually, I&#8217;ve been tweaking it for a while, and =
after I
took out all the comments (<span class=3DGramE>except</span> the one at =
the
beginning), it was I think 90 lines.<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>---<span
class=3DGramE>begin</span> code---<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>#<span
class=3DSpellE>Spotacus</span>' &quot;<span =
class=3DSpellE>fivecalc</span>&quot;
v2.0<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>mask</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> =3D 1<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>def</span></font></span><font size=3D2 face=3D"Courier New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> wait():<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>wait</span>
=3D <span class=3DSpellE>raw_input</span>(&quot;Press =
[Enter]&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>name</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> =3D <span class=3DSpellE>raw_input</span>(&quot;What's your =
first name?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>print</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> &quot;Welcome to the calculator,&quot;, =
name<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>wait()</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'><o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>while</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> mask =3D=3D 1:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;1: Add&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;2: Subtract&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;3: Multiply&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;4: Divide&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;5: Exponents&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;9: Exit&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>print</span>
&quot;&quot;<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>action</span>
=3D input(&quot;What will you do? (1|2|3|4|5|9) =
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DGramE>if</span>
action =3D=3D 1:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DSpellE><span class=3DGramE>addnum</span></span> =3D =
1<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>while</span> <span class=3DSpellE>addnum</span> =3D=3D =
1:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DSpellE><span class=3DGramE>addnum</span></span> =3D
input(&quot;How many numbers are you going to add? (2|3|4) =
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>if</span> <span class=3DSpellE>addnum</span> =
=3D=3D 2:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_1 =3D <span class=3DGramE>input(</span>&quot;What's the first =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
second number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>sum</span> =3D add_1 + =
add_2<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>print</span> &quot;The sum of&quot;, add_1,
&quot;and&quot;, add_2, &quot;is equal to&quot;, =
sum<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp; </span><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;</span><span
class=3DSpellE><span class=3DGramE>elif</span></span> <span =
class=3DSpellE>addnum</span>
=3D=3D 3:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_1 =3D <span class=3DGramE>input(</span>&quot;What's the first =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
second number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_3 =3D <span class=3DGramE>input(</span>&quot;What's the third =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>sum</span> =3D add_1 + add_2 + =
add_3<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;</span><span
class=3DGramE>print</span> &quot;The sum of&quot;, add_1, &quot;,&quot;, =
add_2,
&quot;and&quot;, add_3,<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>print</span> &quot;is&quot;, =
sum<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DSpellE><span class=3DGramE>elif</span></span> <span
class=3DSpellE>addnum</span> =3D=3D 4:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_1 =3D <span class=3DGramE>input(</span>&quot;What's the first =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
second number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_3 =3D <span class=3DGramE>input(</span>&quot;What's the third =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>add_4 =3D <span class=3DGramE>input(</span>&quot;What's the =
fourth number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>sum</span> =3D add_1 + add_2 + add_3 + =
add_4<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>print</span> &quot;The sum of&quot;, add_1,
&quot;,&quot;, add_2, &quot;,&quot;, add_3, =
&quot;and&quot;,<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>print</span> add_4, &quot;is equal to&quot;, =
sum<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>else</span>:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DSpellE><span class=3DGramE>addnum</span></span> =3D =
1<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DSpellE><span
class=3DGramE>elif</span></span> action =3D=3D =
2:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>sub_1 =3D <span class=3DGramE>input(</span>&quot;What's the first =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>sub_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
second number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>difference</span> =3D sub_1 - =
sub_2<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>print</span> &quot;the difference between&quot;, sub_1,
&quot;and&quot;, sub_2, &quot;is&quot;, =
difference<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DSpellE><span
class=3DGramE>elif</span></span> action =3D=3D =
3:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DSpellE><span class=3DGramE>mulnum</span></span> =3D =
1<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>while</span> <span class=3DSpellE>mulnum</span> =3D=3D =
1:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DSpellE><span class=3DGramE>mulnum</span></span> =3D
input(&quot;How many numbers are you going to multiply? (2|3) =
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>if</span> <span class=3DSpellE>mulnum</span> =
=3D=3D 2:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>mul_1 =3D <span class=3DGramE>input(</span>&quot;What's the first =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>mul_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
second number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>mul_4 =3D mul_1 * mul_2<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>print</span> mul_1, &quot;multiplied =
by&quot;, mul_2,
&quot;is equal to&quot;, mul_4<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DSpellE><span class=3DGramE>elif</span></span> <span
class=3DSpellE>mulnum</span> =3D=3D 3:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>mul_1 =3D <span class=3DGramE>input(</span>&quot;What's the first =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>mul_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
second number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>mul_3 =3D <span class=3DGramE>input(</span>&quot;What's the third =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;</span><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>mul_4 =3D mul_1 * mul_2 * mul_3<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>print</span> mul_1, &quot;multiplied =
by&quot;, mul_2,
&quot;multiplied by&quot;, mul_3,<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>print</span> &quot;is equal to&quot;, =
mul_4<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;
</span><span class=3DGramE>else</span>:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs=
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span><span class=3DSpellE><span class=3DGramE>mulnum</span></span> =3D =
1<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DSpellE><span
class=3DGramE>elif</span></span> action =3D=3D =
4:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;</span><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span>div_1 =3D <span
class=3DGramE>input(</span>&quot;What's the first number? =
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>div_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
second number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>div_3 =3D div_1 / div_2<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>div_4 =3D div_1 % div_2<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>print</span> div_1, &quot;divided by&quot;, div_2, =
&quot;is equal
to&quot;, div_3, &quot;R&quot;, div_4<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DSpellE><span
class=3DGramE>elif</span></span> action =3D=3D =
5:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>exp_1 =3D <span class=3DGramE>input(</span>&quot;What's the base =
number?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>exp_2 =3D <span class=3DGramE>input(</span>&quot;What's the =
exponent?
&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</span>exp_3 =3D exp_1 ** exp_2<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>print</span> exp_1, &quot;to the power of&quot;, exp_2, =
&quot;is
equal to&quot;, exp_3<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>wait()</span><o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp; </span><span =
class=3DSpellE><span
class=3DGramE>elif</span></span> action =3D=3D =
9:<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><span
style=3D'mso-spacerun:yes'>&nbsp;</span><span
style=3D'mso-spacerun:yes'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =
</span><span
class=3DGramE>mask</span> =3D 2<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>print</span></font></span><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> &quot;Thank you,&quot;, name<o:p></o:p></span></font></p>

<p class=3DMsoNormal><span class=3DGramE><font size=3D2 face=3D"Courier =
New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'>end</span></font></span><font size=3D2 face=3D"Courier New"><span
lang=3DEN-CA style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:
EN-CA'> =3D <span class=3DSpellE>raw_input</span>(&quot;Press [Enter] at =
your
leisure&quot;)<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>---<span
class=3DGramE>end</span> code---<o:p></o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'><o:p>&nbsp;</o:p></span></font></p>

<p class=3DMsoNormal><font size=3D2 face=3D"Courier New"><span =
lang=3DEN-CA
style=3D'font-size:10.0pt;font-family:"Courier =
New";mso-ansi-language:EN-CA'>I&#8217;ve
fixed it up, too, so that now it&#8217;s only 52 lines and works a lot =
better&#8230;but
I don&#8217;t have the time to put it down =
here.<o:p></o:p></span></font></p>

</div>

</body>

</html>

------=_NextPart_000_0001_01C1EDF1.6DDBB0E0--



From dman@dman.ddts.net  Sat Apr 27 20:18:41 2002
From: dman@dman.ddts.net (dman)
Date: Sat, 27 Apr 2002 14:18:41 -0500
Subject: [Tutor] Two Problems (databases, and branching)
In-Reply-To: <000001c1ee0a$931fc120$147a250a@wolf>
References: <000001c1ee0a$931fc120$147a250a@wolf>
Message-ID: <20020427191841.GA7714@dman.ddts.net>

--KsGdsel6WgEHnImy
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Apr 27, 2002 at 01:42:52PM -0300, Spotacus wrote:
| \\ What are your requirements for this database?  There are many choices
| out there.
| =20
| I don't have much in the way of requirements. Just, something where part
| of it can't be changed, that stores the info about the items the
| merchant sells (name, buying price, selling price, etc), and then
| another part that stores everything that the character is carrying. I'm
| pretty sure that's how it'd work.

I think that pickle is probably best suited for your task.  See the
documentation for the pickle module for the details, but basically
there are two methods.  One takes an object and stuffs it in a file,
the other takes a file and gives back an object.

You'll want to make Merchant and Player classes that you can
instantiate so that you have some cohesive objects to work with rather
than lots of globals to try and manage.

| \\ Structured <file:///\\Structured>  languages do it this way:
| \\ # decide which way to branch
| \\ if cond :
| \\     mwin("Text in a message window")
| \\ else :
| \\     # :here
| \\     print "the else block"
| =20
| I could do that, but I was thinking of something along the lines of
| skipping the whole program over. An example could be something that
| needed a password? Not anything high calibur, but simple, like:
| =20
| password =3D raw_input("What's the password? ")
| if password !=3D "whatever"
|     branch(":end")
| #---entire program goes here
| :end
| =20
| That's the kind of thing I was thinking, possibly. If I used an if
| statement to that effect, wouldn't I have to put the entire program
| inside the if statement?

Yes and no.  The _source code_ for the entire program doesn't need to
go inside the if-block, but a function call can.  For example :


def my_apps_main() :
    # beginning of the entire program goes here
    # the rest of the program should be in other functions
   =20
# give the user 3 tries
for _ in range( 3 ) :
    password =3D raw_input("What's the password? ")
    if password =3D=3D "whatever"
        my_apps_main()
        break
    else :
        print "Wrong password, try again"
   =20

The addition of the loop gives the user 3 chanced to enter the right
password.  If they get it right, control will move to the "main"
function, then the loop will terminate and the app will terminate.
Otherwise the error message will be printed and the program will try
again.  If the limit is reached then the program terminates (without
reporting it).

The "branch" is done by calling a function.  In that manner the whole
program is "in" the if-block, but you don't write all the source code
there.

| \\ How about posting that 80-odd line script and letting someone with
| \\ some spare cycles refactor it to give you a concrete example of
| \\ how it works?
| =20
| Um, okay. The program's just a simple calculator that I was doing to
| test out some things,

Cool.  That's a good way to start.

| and it ended up being a gigantic mess of whiles and ifs.

Without structure that can happen easily :-).

I'll post a response to that in another message.

WHile you're at it, check out Alan Gauld's tutorial.  It's called "How
to Program" or something like that.  Google knows how to find it :-).

-D

--=20

"Don't use C;  In my opinion,  C is a library programming language
 not an app programming language."  - Owen Taylor (GTK+ developer)
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--KsGdsel6WgEHnImy
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzK+ZEACgkQO8l8XBKTpRRUbQCguBkb5Agd34Y47Q+LcZN3GVie
sqoAoLiaqdOa3b+CW7l40hsoQwu11mbt
=QRP/
-----END PGP SIGNATURE-----

--KsGdsel6WgEHnImy--



From dman@dman.ddts.net  Sat Apr 27 21:11:30 2002
From: dman@dman.ddts.net (dman)
Date: Sat, 27 Apr 2002 15:11:30 -0500
Subject: [Tutor] calculator structuring (was question about branching/goto)
Message-ID: <20020427201130.GB7714@dman.ddts.net>

--XMCwj5IQnwKtuyBG
Content-Type: multipart/mixed; boundary="ftEhullJWpWg/VHq"
Content-Disposition: inline


--ftEhullJWpWg/VHq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable


Spotacus,

I took your calculator program and restructured it to use functions to
encapsulate the smaller pieces the program is built up from.  I used a
dictionary to achieve the same result as a switch in C and vastly
shortened the main "while" loop.  I also shortened the functions to
handle addition and multiplication while extending them to handle an
arbitrary number of inputs.  (eg 1+2+3+4+5+6+3+4+5+6+9). =20

Do make a note that input() is very bad.  It is a security hole in the
face of malicious users, or users who mistype something.  (eg instead
of entering a number enter  open('c:/a/file/I/want/to/clobber','w')
and watch that file get clobbered).  For someone just learning how to
program it is ok to use it, but when you better understand python
(in particular types and exceptions) use raw_input() instead and
convert the data to the type you are expecting.

Also note that there are a variety of ways the functions could have
been implemented (for example using reduce()) and have various
tradeoffs in terms of that data is present at the end of the function.
There is a tradeoff between having all the numbers to print out (as
you originally did) and how much memory is used as it runs.

I also used string interpolation in some places when printing out
data.  String interpolation is a convenient way of first describing
exactly how you want the output formated and then letting python put
your data in it.  You can do things like specify how many columns some
data will use and how many digits of precision you want.

You'll learn all of these details in time.  Just keep working at it
and ask on the list whenever you run into something you don't
understand.

The restructured script is attached.

-D

--=20

"...In the UNIX world, people tend to interpret `non-technical user' as
meaning someone who's only ever written one device driver."
    --Daniel Pead
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--ftEhullJWpWg/VHq
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment; filename="calculator.py"
Content-Transfer-Encoding: quoted-printable

=20
#Spotacus' "fivecalc" v2.0

import sys


menu =3D """
1: Add
2: Subtract
3: Multiply
4: Divide
5: Exponents
9: Exit

"""


#
# Here we define each of the operations the program will be performing.  It
# improves modularity and reduces clutter in other parts.
#

def wait():
    raw_input( "Press [Enter] " )


def input_count( min , max ) :
    # Prompt the user for the number of inputs they will provide.  Only
    # responses between min and max (inclusive) are allowed.  Use the flag =
value
    # 'None' to indicate no limit.

    message =3D \
          "How many numbers are you going to provide? (min: %s, max: %s) : =
" %\
                    ( str(min) , str(max) )

    while 1 :
        numcount =3D input( message )=20

        # see if the number is in the allowed range
        if (
             ( (min is None) or (min <=3D numcount) )=20
                and
             ( (max is None) or (numcount <=3D max) )=20
            ) :
                # it is, break the loop now
                break

        print "Invalid number."

    # once the loop terminates we have a valid count
    # return it to the caller
    return numcount=20


def add() :
    addnum =3D input_count( 1 , None )
    # start with the additive identity
    sum =3D 0
    for i in xrange( 1 , addnum+1 , 1 ) :
        sum +=3D input( "Enter number %d : " % i )

    print "The sum of the numbers is equal to" , sum=20
    wait()


def subtract() :
    subnum =3D input_count( 2 , None )
    # there is no subtractive identity, I think
    numbers =3D []
    for i in xrange( 1 , subnum+1 , 1 ) :
        numbers.append( input( "Enter number %d : " % i ) )

    difference =3D numbers[0] - numbers[1]

    for num in numbers[2:] :
        difference -=3D num

    print "The difference of the numbers is equal to" , difference
    wait()


def multiply() :
    # generalize this to handle any number of factors

    numcount =3D input_count( 1 , None )=20

    # start with the multiplicative identity
    product =3D 1
    for i in xrange( 1 , numcount+1 , 1 ) :
        product *=3D input( "Enter factor %d : " % i )

    print "The product of the numbers is" , product=20
    wait()


def divide() :
    # if you decide to convert to floats rather than keep separate quotient=
 and
    # remainder values you can extend this like the others to support any n=
umber
    # of divisions
   =20
    div_1 =3D input("What's the first number? ")
    div_2 =3D input("What's the second number? ")
    div_3 =3D div_1 / div_2
    div_4 =3D div_1 % div_2
    print div_1, "divided by", div_2, "is equal to", div_3, "R",

    # here I'll show how to convert ints to floats, and how to ues string
    # formatting
    print  "%f divided by %f is equal to %f" % \
                ( div_1 , div_2 , float(div_1)/div_2 )
    wait()


def pow() :
    base =3D input("What's the base number? ")
    exp =3D input("What's the exponent? ")
    result =3D base ** exp
    print base , "to the power of", exp , "is equal to", result
    wait()


def exit() :
    print "Thank you,", name
    raw_input("Press [Enter] at your leisure ")
    sys.exit()
=20

# Here we define the table (dict) for our "switch" later on
action_table =3D {
    1 : add ,
    2 : subtract ,
    3 : multiply ,
    4 : divide ,
    5 : pow ,
    9 : exit
}



# note that 'name' is a global variable.  that's fine for this small progra=
m,
# but doesn't scale well in large applications
name =3D raw_input("What's your first name? ")

print "Welcome to the calculator,", name
wait()


while 1 :
    print menu
    # Note: input() is very bad (think about security and malicious users).=
=20
    # It is sufficient for a beginner, though.
    action =3D input("What will you do? (1|2|3|4|5|9) ")

    # You can use an if-else ladder here, or as you have commented, a "swit=
ch"
    # is more appropriate

    if action not in action_table :
        print "That action is not known"
        # skip the rest of the loop and prompt again
        # use 'break' and 'continue' very carefully, they _can_ lead to
        # spaghetti code
        continue

    # here's how we do switches in python -- lookup the handler function fr=
om a
    # table (dict)
    handler =3D action_table[ action ]

    # now call the function that is going to do the dirty work
    handler()



--ftEhullJWpWg/VHq--

--XMCwj5IQnwKtuyBG
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzLBfIACgkQO8l8XBKTpRRXkQCfZOJDG8pLgb3rQZUCfjrmBGBd
KTAAn0ChfkYwfz+iM4x5Uz4U/Q8FdtxS
=nv4L
-----END PGP SIGNATURE-----

--XMCwj5IQnwKtuyBG--



From erikprice@mac.com  Sun Apr 28 02:06:31 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 27 Apr 2002 21:06:31 -0400
Subject: [Tutor] Perl refugee
In-Reply-To: <20020427023820.GA32343@dman.ddts.net>
Message-ID: <2D1D0AD2-5A44-11D6-8F36-00039351FE6A@mac.com>

On Friday, April 26, 2002, at 10:38  PM, dman wrote:

> IME switch statements are rarely used (even in C/C++/Java) anyways,
> and in the situations where it might be useful a dictionary lookup can
> be much more elegant.

I use them religiously in PHP for web site development.  Often a PHP 
"script" will have more than one "instantiation".  That is to say, it 
displays a different page (from the user's perspective) depending on 
what data it is working with.  Usually I use an HTML hidden form field 
to send a variable named "action" which could do something like this 
(pseudocode based on Python):

# this is a form that accepts user input and enters it into a database
switch(action):
   case 'commit':
     commit data to database (execute query)
     print success message to user
     break
   case 'confirm':
     print a confirmation message with yes/no button
     including a hidden form field sending
     POST variable 'action=commit'
     break
   case 'display_form':
     print an HTML form to accept user input
     including a hidden form field sending POST
     variable 'action=confirm'
     break
   default:
     print instructions for user
     button to send POST variable 'action=display_form'


Of course, they get a bit more complex than that, but that's why I like 
switch() -- because sometimes I want the user to cascade down into the 
next case statement to do some other thing, so I don't have a "break" at 
the end of the case that picked up the "action" variable.  Anyway, it's 
a nice feature, but since I haven't yet done any real dynamic HTML with 
Python I haven't really missed.

and Python more than makes up for it by being more fully object-oriented.


Erik




From erikprice@mac.com  Sun Apr 28 03:02:26 2002
From: erikprice@mac.com (Erik Price)
Date: Sat, 27 Apr 2002 22:02:26 -0400
Subject: [Tutor] Two Problems (databases, and branching)
In-Reply-To: <000001c1ee0a$931fc120$147a250a@wolf>
Message-ID: <FD3B9008-5A4B-11D6-8F36-00039351FE6A@mac.com>

On Saturday, April 27, 2002, at 12:42  PM, Spotacus wrote:

> I could do that, but I was thinking of something along the lines of=20
> skipping the whole program over. An example could be something that=20
> needed a password? Not anything high calibur, but simple, like:
>
> =A0
>
> password=3D raw_input(=93What=92s the password? =93)
>
> ifpassword !=3D =93whatever=94
>
> =A0=A0=A0branch(=93:end=94)
>
> #---entire program goes here
>
> :end
>
> =A0
>
> That=92s the kind of thing I was thinking, possibly. If I used an if=20=

> statement to that effect, wouldn=92t I have to put the entire program=20=

> inside the if statement?

Hey I know exactly what you mean, Spotacus.  When I first was interested=20=

in programming, I remember learning some BASIC that let me say, "go to=20=

line 40" or something (I forget the exact syntax).  It was great,=20
because I always thought of a program as being a start-to-finish path. =20=

It let me turn that path into a choose your own adventure kind of thing,=20=

where I could tell the parser to "go to page 45" depending on what I=20
want to do.

(Come to think of it, I suppose my first programs were D&D modules I=20
wrote when I was younger -- I sort of "programmed" the way that I=20
anticipated my players interacting with my world.  I never thought of=20
that before.)

Anyway, to get back to my main point, I learned that very few=20
programming languages these days let you get away with this kind of=20
technique.  It easily gets far out of hand when dealing with programs=20
that are hundreds or thousands of lines long.  However, what you can do=20=

is make chunks of code that do very specific things, and then tie them=20=

all together using a script.  For instance:

You could write a chunk of code that describes what characters in the=20
game look like.  Merchant is one such character, he has an oily demeanor=20=

and shifty eyes.  His inventory consists of a lantern, a battle axe,=20
some rations, and he has 34 silver pieces.  You can also have this chunk=20=

of code describe how to interact with the Merchant -- you can buy from=20=

him, you can sell to him, you can pay him for a rumor or advice... you=20=

could even write code that lets you rob him of his money or something.

You can also write a chunk of code that describes a monster in a similar=20=

way.  This chunk of code could keep track of the monster's strength and=20=

the experience points you get for killing it.  Of course, the beauty of=20=

programming is that you can do whatever you want, so don't limit=20
yourself to these ideas (and I know you won't).

In fact, you can even write a chunk of code that describes a city.  It=20=

would obviously get very complex, but this is for the sake of=20
illustration -- this chunk of code contains a list of all of the=20
important buildings in the city (places that the player can go to), all=20=

of the important people in the city (such as the Merchant), and any=20
other information that you think is appropriate for this city.

Each of these chunks of code is called a class definition.  A class is=20=

simply a description.  The point is that you try to create these class=20=

definitions so that the things they describe are completely=20
self-contained.  Then you can become very flexible with how you deal=20
with these things -- for instance, you could decide that there are five=20=

cities (each uses the same class to define the city, but each is a=20
completely separate city with its own unique name, population, important=20=

buildings, important people, etc).  Since you have made the Merchant a=20=

self-contained class, you could easily create a new Merchant and put=20
this one in one of the other cities.  Or you could put the original=20
Merchant in one of the other cities.  You don't have to change your=20
entire program this way, because ideally your program will know that no=20=

matter where a Merchant is encountered (even if you coded him into a=20
dungeon), there is a specific set of things that you can do with a=20
Merchant.

These things that are described using class definitions are called=20
objects, and using objects in your programs is called object oriented=20
programming.  I just learned about this recently, but it has helped me=20=

write better code in a big way.  I now try to think of my programs as=20
being composed of things, rather than one big amorphous piece of code=20
that is tightly dependent on the way I've already written it in order to=20=

work.  For instance, using the example from above, you might decide that=20=

you want to allow players to capture monsters to use them as pets or=20
attack creatures.  You would simply add code to your Monster class=20
definition that allows this.  You don't have to go back and change every=20=

single part of your program that interacts with the Monster, you can=20
just start adding this functionality now (and if you want to add it to=20=

your earlier code you can always go back and change it).

Of course, I am using a relatively simple example, which in real life=20
would probably be very difficult to write -- it's easy to say "write the=20=

program to subdue the monster and have it fight on your side", when in=20=

reality the code to do just that would probably be very complex indeed. =20=

But the idea is the same -- that you will go far if you try to write=20
programs that are modular and "chunked" so that when changes need to be=20=

made, you don't need to go through the whole program tearing your hair=20=

out.



Erik




From dman@dman.ddts.net  Sun Apr 28 05:02:22 2002
From: dman@dman.ddts.net (dman)
Date: Sat, 27 Apr 2002 23:02:22 -0500
Subject: [Tutor] Perl refugee
In-Reply-To: <2D1D0AD2-5A44-11D6-8F36-00039351FE6A@mac.com>
References: <20020427023820.GA32343@dman.ddts.net> <2D1D0AD2-5A44-11D6-8F36-00039351FE6A@mac.com>
Message-ID: <20020428040222.GB13869@dman.ddts.net>

--GRPZ8SYKNexpdSJ7
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Apr 27, 2002 at 09:06:31PM -0400, Erik Price wrote:
|=20
| On Friday, April 26, 2002, at 10:38  PM, dman wrote:
|=20
| >IME switch statements are rarely used (even in C/C++/Java) anyways,
| >and in the situations where it might be useful a dictionary lookup can
| >be much more elegant.
|=20
| I use them religiously in PHP for web site development.  Often a PHP=20
| "script" will have more than one "instantiation".  That is to say, it=20
| displays a different page (from the user's perspective) depending on=20
| what data it is working with.

This sounds to me like making it a different page (URL, script) is
more suitable.  I'm thinking in terms of cohesiveness.  Maybe you're
right though (see the last paragraph for more info).

| Usually I use an HTML hidden form field to send a variable named
| "action" which could do something like this (pseudocode based on
| Python):
|=20
| # this is a form that accepts user input and enters it into a database
| switch(action):
|   case 'commit':

At least PHPs switch is less restrictive.  In C/C++/Java the
switch/case can only match equality on a single char or int.

| and Python more than makes up for it by being more fully object-oriented.

It does.  Here's where I would split the script into separate
functions, even in separate modules if they're different enough, and
use a dict to simulate a switch on it.

In fact, now that I've started using Zope I would just use it instead.
Just imagine -- each page template is an object unto itself and you
can call them from python scripts and pass named (object, not just
string) arguments.  To top it off, zope handles all the glue code for
you!  This includes connections to RDBMSes and SQL Method objects.  It
is _really_ sweet.  I know I'll never get into major CGI script
writing now.  (I've only ever done trivial cgi scripts and didn't get
past that.  Now I have no reason to learn.)

With zope you could make the "page" be a Python Script that checks
some data and decides which Page Template to pass the data to for
rendering and return it to the user.  That keeps cohesiveness and
separates logic from presentation.  Zope promotes good design as well
as easing the implementation.  It even has really flexible ways for
handling authentication too.

HAND,
-D

--=20

Stay away from a foolish man,
for you will not find knowledge on his lips.
        Proverbs 14:7
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--GRPZ8SYKNexpdSJ7
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzLdE4ACgkQO8l8XBKTpRRlUwCfXf8jjOKsPuHdUyAPUBeIMzri
AesAnRhL0Xq5Xw7htKYtsOrnrH3LxF77
=TJti
-----END PGP SIGNATURE-----

--GRPZ8SYKNexpdSJ7--



From brian@coolnamehere.com  Sat Apr 27 22:46:41 2002
From: brian@coolnamehere.com (Brian Wisti)
Date: Sat, 27 Apr 2002 21:46:41 +0000
Subject: [Tutor] Perl refugee
In-Reply-To: <2D1D0AD2-5A44-11D6-8F36-00039351FE6A@mac.com>
References: <20020427023820.GA32343@dman.ddts.net>
 <2D1D0AD2-5A44-11D6-8F36-00039351FE6A@mac.com>
Message-ID: <15563.7233.928092.424562@www.coolnamehere.com>

Hi all,

Erik Price writes:
 > 
 > On Friday, April 26, 2002, at 10:38  PM, dman wrote:
 > 
 > > IME switch statements are rarely used (even in C/C++/Java) anyways,
 > > and in the situations where it might be useful a dictionary lookup can
 > > be much more elegant.
 > 
 > I use them religiously in PHP for web site development.  Often a PHP 
 > "script" will have more than one "instantiation".  That is to say, it 
 > displays a different page (from the user's perspective) depending on 
 > what data it is working with.  Usually I use an HTML hidden form field 
 > to send a variable named "action" which could do something like this 
 > (pseudocode based on Python):
 > 

Ooh, ooh, I know this one! ... Sorry, I don't really know where that
came from.  Not really sure if anybody would want to know this, but
that doesn't stop me ;-)

Anyhow, there's an alternate approach to the type of situation you
describe.

1. Create a "common_page" function which returns a site-standardized
page with provided content. An "error_page" might be a good idea, too.

-----
def common_page(title, content):
    # ... Insert the title and content into a template page ...
    return output

def error_page(error, help_text=""):
    # Turn the error and help_text into a helpful error message
    return common_page("Error", content)
-----

2. Create a series of action functions ("new_user", "profile_edit_view",
"profile_save", etc) which build some content based on cgi's form
values, and return the content inserted into the common_page function.

-----
def profile_save():
    # ... Do some processing
    # Generate some content and a title based on the processing
    return common_page("Your Profile Has Been Saved", content)
-----

3. Create an actions dictionary.  The keys are legitimate action
names, while the values point to action methods.  Like so ...

-----
actions = {
	'new': new_user,
	'edit': profile_edit_view,
	'save': profile_save,
	'default': front_page
}
-----

4. In your actual form processing code, figure out which action is
required and call the appropriate function.  Kinda like this:

-----
form = cgi.FieldStorage()
action = "default"
output = None

if form.has_key('action'):
   action = form['action'].value

try:
   output = actions[action]()
except Exception, e:
   output = error_page(e, "Please try again later.")

print headers
print output

-----

This is just off the top of my head, so it's missing nearly all of the
errer cheking that would normally be there.  The point of all this is
that ... uhh ... oh yeah - it hides the processing away in functions
(if there is common processing between two functions, then it's time
for some refactoring!), it provides case-like functionality without
worrying about the break statement, and it's a technique that works
equally well for me in Python, Ruby, or Perl.  Actually, the idea
occurred to me while trying to get something like a case statement
under Perl.

I've gotten quite used to it, and use case statements much less
frequently nowadays (in languages that support them, of course).

A co-worker once told me that this approach has an actual name with
big words attached to it.  I am a Geek of Very Small Brain, however,
and that name has been lost in a fog of caffeine consumption and
coding frenzy.  Sorry about that.  Maybe a real programmer in here 
can tell me what it's called. Besides "very silly."

Okay, no more reading email after the 3rd pot of coffee.  I'm going to
school this Fall so I can find out the names of all the tricks I've
learned over the years :-)

Later,
Brian Wisti
brian@coolnamehere.com
http://www.coolnamehere.com/



From brian@coolnamehere.com  Sat Apr 27 22:48:41 2002
From: brian@coolnamehere.com (Brian Wisti)
Date: Sat, 27 Apr 2002 21:48:41 +0000
Subject: [Tutor] Perl refugee
In-Reply-To: <20020428040222.GB13869@dman.ddts.net>
References: <20020427023820.GA32343@dman.ddts.net>
 <2D1D0AD2-5A44-11D6-8F36-00039351FE6A@mac.com>
 <20020428040222.GB13869@dman.ddts.net>
Message-ID: <15563.7353.656383.83230@www.coolnamehere.com>

dman writes:
 [ snip]
 > 
 > It does.  Here's where I would split the script into separate
 > functions, even in separate modules if they're different enough, and
 > use a dict to simulate a switch on it.

Terseness is good. I should learn it someday!

 > -- 
 > 
 > Stay away from a foolish man,
 > for you will not find knowledge on his lips.
 >         Proverbs 14:7

I don't know why, but I'm taking that sig personally right now ;-)

Brian Wisti
brian@coolnamehere.com
http://www.coolnamehere.com/



From Ares.liu@Clarent.com  Sun Apr 28 08:22:40 2002
From: Ares.liu@Clarent.com (Ares Liu)
Date: Sun, 28 Apr 2002 15:22:40 +0800
Subject: [Tutor] How can I do IP_MASQ by using Python?
Message-ID: <001a01c1ee85$7e41ff40$8500a8c0@gege>

This is a multi-part message in MIME format.

------=_NextPart_000_0017_01C1EEC8.895985E0
Content-Type: text/plain;
	charset="gb2312"
Content-Transfer-Encoding: quoted-printable

I want to transfer MGCP packages via NAT. Not so much flux, so I think =
I
can use python to do it. Does anyone can give me some advises?
=20
Regards
=20
Ares

------=_NextPart_000_0017_01C1EEC8.895985E0
Content-Type: text/html;
	charset="gb2312"
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>

<META content=3D"MSHTML 6.00.2715.400" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>I want to transfer MGCP packages via =
NAT. Not so=20
much flux, so I think I can use python to do it. Does anyone can give =
me some=20
advises?</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Regards</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Ares</FONT></DIV></BODY></HTML>

------=_NextPart_000_0017_01C1EEC8.895985E0--



From fasal.waseem@cis.co.uk  Sun Apr 28 13:24:32 2002
From: fasal.waseem@cis.co.uk (fasal.waseem@cis.co.uk)
Date: Sun, 28 Apr 2002 12:24:32 +0000
Subject: [Tutor] strptime
Message-ID: <OFB85FC9C9.BBE29FA2-ON00256BA9.0043FB4D@cis.co.uk>

Hi

Can any body tell me if strptime is an attribute in 1.5.1 or is there a
replacement for it, in 1.5.1. Currently we have 1.5.1 on HP server (unix)
and can not upgrade it.

Regards

Faz
Distributed system support Analyst
CIS
Miller Street
Manchester
M60 0AL
0161 837 4487 (office)
www.cis.co.uk (our web page)

*************************************************************************

This e-mail may contain confidential information or be privileged. It is intended to be read and used only by the named recipient(s). If you are not the intended recipient(s) please notify us immediately so that we can make arrangements for its return: you should not disclose the contents of this e-mail to any other person, or take any copies. Unless stated otherwise by an authorised individual, nothing contained in this e-mail is intended to create binding legal obligations between us and opinions expressed are those of the individual author.

The CIS marketing group, which is regulated for Investment Business by the Financial Services Authority, includes:
Co-operative Insurance Society Limited Registered in England number 3615R - for life assurance and pensions
CIS Unit Managers Limited Registered in England and Wales number 2369965  - for unit trusts and PEPs
CIS Policyholder Services Limited Registered in England and Wales number 3390839 - for ISAs and investment products bearing the CIS name
Registered offices: Miller Street, Manchester M60 0AL   Telephone  0161-832-8686   Internet  http://www.cis.co.uk   E-mail cis@cis.co.uk

CIS Deposit and Instant Access Savings Accounts are held with The Co-operative Bank p.l.c., registered in England and Wales number 990937, P.O. Box 101, 1 Balloon Street, Manchester M60 4EP, and administered by CIS Policyholder Services Limited as agent of the Bank.

CIS is a member of the General Insurance Standards Council

CIS & the CIS logo (R) Co-operative Insurance Society Limited

********************************************************************************



From JoachimThoene@web.de  Sun Apr 28 13:30:17 2002
From: JoachimThoene@web.de (Joachim =?iso-8859-1?Q?Th=F6ne?=)
Date: Sun, 28 Apr 2002 14:30:17 +0200
Subject: [Tutor] Printing?
Message-ID: <3CCBEB59.99C9282F@web.de>

Hi all,

I'm writing a small application using Tkinter and a MySQL database on a
Linux system. What I want to do is to display my databasequeries
forinstance as  postsript document and send them to a printer to have a
paper copy. Unfortunately I didn't find anything about printing in the
web. Does anybody have a hint?

Joachim



From erikprice@mac.com  Sun Apr 28 13:57:09 2002
From: erikprice@mac.com (Erik Price)
Date: Sun, 28 Apr 2002 08:57:09 -0400
Subject: [Tutor] Perl refugee
In-Reply-To: <20020428040222.GB13869@dman.ddts.net>
Message-ID: <735F8242-5AA7-11D6-805D-00039351FE6A@mac.com>

On Sunday, April 28, 2002, at 12:02  AM, dman wrote:

> In fact, now that I've started using Zope I would just use it instead.
> Just imagine -- each page template is an object unto itself and you
> can call them from python scripts and pass named (object, not just
> string) arguments.  To top it off, zope handles all the glue code for
> you!  This includes connections to RDBMSes and SQL Method objects.  It
> is _really_ sweet.  I know I'll never get into major CGI script
> writing now.  (I've only ever done trivial cgi scripts and didn't get
> past that.  Now I have no reason to learn.)

Yes, Zope sounds very cool but I have not had opportunity to check it 
out.  My PHP app is too mature to go back at this point (about ten 
thousand lines of code but that includes comments and whitespace), but 
Zope is the next web technology I plan to learn.


Erik




From tim.one@comcast.net  Sun Apr 28 17:15:32 2002
From: tim.one@comcast.net (Tim Peters)
Date: Sun, 28 Apr 2002 12:15:32 -0400
Subject: [Tutor] strptime
In-Reply-To: <OFB85FC9C9.BBE29FA2-ON00256BA9.0043FB4D@cis.co.uk>
Message-ID: <LNBBLJKPBEHFEDALKOLCIEJOPBAA.tim.one@comcast.net>

[fasal.waseem@cis.co.uk]
> Can any body tell me if strptime is an attribute in 1.5.1 or is there a
> replacement for it, in 1.5.1. Currently we have 1.5.1 on HP server
> (unix) and can not upgrade it.

You should actually ask Hewlett-Packard:  even today, Python supplies
strptime only if the platform C library supplies it, and I presume you're
using HP's C libraries.

You can find pure Python implementations of strptime by doing a google
search on

    Python strptime

You may have to do some work to backport them to 1.5.1.




From dman@dman.ddts.net  Sun Apr 28 20:05:54 2002
From: dman@dman.ddts.net (dman)
Date: Sun, 28 Apr 2002 14:05:54 -0500
Subject: [Tutor] How can I do IP_MASQ by using Python?
In-Reply-To: <001a01c1ee85$7e41ff40$8500a8c0@gege>
References: <001a01c1ee85$7e41ff40$8500a8c0@gege>
Message-ID: <20020428190554.GC18030@dman.ddts.net>

--96YOpH+ONegL0A3E
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sun, Apr 28, 2002 at 03:22:40PM +0800, Ares Liu wrote:
| I want to transfer MGCP packages via NAT. Not so much flux, so I think I
| can use python to do it. Does anyone can give me some advises?

I don't know what MGCP is, but all the times I've seen the terms
IPMASQ or NAT it is referring to the IP stack of a system.  The IP
stack is in the kernel and requires access to the kernel to adjust how
the routing and NAT will operate.  With linux the netfilter modules
provide the actual implementation and the userspace tool 'iptables'
provides an interface for the admin to configure it.

Maybe if you can explain MGCP and what you want to do with it a bit
more I'll understand whether or not python is suitable for the task.

HTH,
-D

--=20

Python is executable pseudocode. Perl is executable line noise.
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--96YOpH+ONegL0A3E
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzMSBIACgkQO8l8XBKTpRRQLACfa5b3yh3ygt5Hf7w6HXOUCcM3
xG0Anj9utsZSLIj3WwxY9kr3f+cHgyJ8
=naxV
-----END PGP SIGNATURE-----

--96YOpH+ONegL0A3E--



From lsloan@umich.edu  Sun Apr 28 20:31:38 2002
From: lsloan@umich.edu (Lance E Sloan)
Date: Sun, 28 Apr 2002 15:31:38 -0400
Subject: [Tutor] HP preinstalled Python!
Message-ID: <1020022298.3ccc4e1a234ec@carrierpigeon.mail.umich.edu>

This weekend, my wife and I finally gave in and bought a Windows computer.  Well, we've had one before, but we mostly used Macs and I use UNIX a lot.  This is our first purchase of a brand-new, semi-beefy Windows computer.  My wife wanted it to run certain programs that were only available for Windows and I figured it's best to "know thy enemy".  So we bought an HP Pavilion 531w.  It's not the most powerful machine, but good enough.

So, as I was installing various apps, I discovered that in the "Program Files" directory, there is a Python directory.  And there was also a TCL directory.  Both of them apparently have working versions of those languages.  I've not found anything in the documentation about them yet, but I figure that among the other third-party programs HP installed, there must be one that uses Python, probably with Tkinter.

Has anybody else noticed this on new HP computers?

--
Lance E Sloan
Web Services, Univ. of Michigan: Full-service Web and database design,
development, and hosting.  Specializing in Python & Perl CGIs.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"



From dyoo@hkn.eecs.berkeley.edu  Sun Apr 28 22:43:41 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Apr 2002 14:43:41 -0700 (PDT)
Subject: [Tutor] Printing?
In-Reply-To: <3CCBEB59.99C9282F@web.de>
Message-ID: <Pine.LNX.4.44.0204281439210.23743-100000@hkn.eecs.berkeley.edu>


On Sun, 28 Apr 2002, Joachim [iso-8859-1] Th=F6ne wrote:


> I'm writing a small application using Tkinter and a MySQL database on a
> Linux system. What I want to do is to display my databasequeries
> forinstance as postsript document and send them to a printer to have a
> paper copy. Unfortunately I didn't find anything about printing in the
> web. Does anybody have a hint?

Hi Joachim,

You might want to try out the ReportLab package: it should allow you to
generate PDF forms from Python:

    http://www.reportlab.com/download.html



Good luck!




From dyoo@hkn.eecs.berkeley.edu  Sun Apr 28 22:50:35 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Apr 2002 14:50:35 -0700 (PDT)
Subject: [Tutor] Deleting Lines of text
In-Reply-To: <23356490135.20020416114730@yahoo.com>
Message-ID: <Pine.LNX.4.44.0204161325330.6294-100000@hkn.eecs.berkeley.edu>

On Tue, 16 Apr 2002 pythonhack@yahoo.com wrote:

> as far as i know, it's not possible to edit a file in place.  you'll

It's not too hard to do in-place replacements of characters in a file:

###
>>> f = open("test.txt", "w")
>>> f.write("hello world!\n")
>>> f.close()
>>> print open("test.txt").read()
hello world!

>>> f = open("test.txt", "r+")
>>> f.seek(1)
>>> f.write("a")
>>> f.seek(0)
>>> print f.read()
hallo world!

###

So in-place modification isn't bad: it's the insertions and deletions that
cause problems.  Insertions and deletions involve shifing all the
characters in a file either left or right when we do an insertion or
deletion.  Removing or deleting a line in-place is also problematic
because not all lines are the same length --- some lines are longer than
others.


Text editors provide the illusion that it's easy to edit a file in place.
What often happens is that the file is temporarily held in some data
structure like a list (or linked list!  *grin*0, and all manipulations are
done on this structure in memory. Lists are much easier to deal with than
files: it's relatively easy to do insertions or other things.

Finally, when the work is done, a "Save" command will write the contents
of the data structure back to disk.  That's why word processors make a
distinction between "editing" and "saving", because editing does
manipulation on a copy of the document in memory, rather than directly on
the file.




From dyoo@hkn.eecs.berkeley.edu  Mon Apr 29 04:34:07 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Apr 2002 20:34:07 -0700 (PDT)
Subject: [Tutor] windows and filenames (fwd)
Message-ID: <Pine.LNX.4.44.0204282033370.5726-100000@hkn.eecs.berkeley.edu>

(Ian! verified it; it works.  *grin*)

---------- Forwarded message ----------
Date: Sun, 28 Apr 2002 14:35:34 -0700 (PDT)
From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
To: Ian! <imcmeans@shaw.ca>
Subject: Re: [Tutor] windows and filenames


On Fri, 26 Apr 2002, Ian! wrote:

> hmm.. that's not really what I need, FindFiles only returns the base of the
> path (the filename without the directory). I would hack together a version
> that goes down the path to the root of the drive and concatenates the
> returned values from FindFiles, but FindFiles returns nothing for
> directories, so I can't use it for directories.

Doh.  There's another FAQTS entry that might be more useful here:

    http://www.faqts.com/knowledge_base/view.phtml/aid/4444

According to them, FindFiles() should work with directories if you do it
piecewise, starting from the root directory, and working downward.


I'd like to forward this to Tutor as well, just in case this actually does
work... *grin*  Is this ok with you?


Good luck!





From dyoo@hkn.eecs.berkeley.edu  Mon Apr 29 06:55:57 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 28 Apr 2002 22:55:57 -0700 (PDT)
Subject: [Tutor] A problem: scanning for keywords in a bunch of text?
Message-ID: <Pine.LNX.4.44.0204282215230.8770-100000@hkn.eecs.berkeley.edu>

Hi everyone,

I have a small project that I've been working on.  Being lazy, I thought
it might be good to ask about it here and hear what people think.


Part of this project involves scanning for a preprepared list of
"keywords"  though a lot of text.  More specifically: I'm searching for
biological terms in a huge collection of journal articles.

###
>>> import MySQLdb
>>> conn = MySQLdb.connect(db='pub2')
>>> cursor = conn.cursor()
>>> cursor.execute("select name from term")
46627L
>>> def first(x): return x[0]
...
>>> terms = map(first, cursor.fetchall())
>>> terms[:8]
['(+)-camphor metabolism',
 '(3R)-hydroxymyristol acyl carrier protein dehydratase',
 '(3\\,5-dichlorophenylurea)acetate amidohydrolase',
 '(delayed) early viral mRNA transcription',
 '(N-acetylneuraminyl)-galactosylglucosylceramide',
 '(R)-4-hydroxymandelate catabolism',
 '(R)-aminopropanol dehydrogenase',
 '(R)-mandelate catabolism to benzoate']
###

The one immediate problem I have is that I'm actually scanning through
quite a few terms here.  Another problem is that these keywords have
spaces in them, and that can complicate things.

(See: http://www.geneontology.org/ if you're wondering what these curious
terms are about.)


Python's regular expression engine might not be powerful enough to handle
this in one big gulp:

###
>>> import re
>>> decorated_terms = map(re.escape, terms)
>>> re.compile('|'.join(decorated_terms), re.IGNORECASE)
<SRE_Pattern object at 0x403b0008>
>>> big_pattern = re.compile('|'.join(decorated_terms), re.IGNORECASE)
>>>
>>> big_pattern.findall('''The activity of the Arabidopsis heat shock
transcription factor (HSF) is repressed at normal conditions but activated
by cellular stresses. Circumstantial evidence suggests that HSP70 may
function as a negative feedback regulator of HSF activity. Here the
interaction between HSF and HSP70 is reported using electrophoretic
mobility shift and yeast two-hybrid assays. Subdomain mapping indicates an
interaction of the activation domain and DNA-binding domain of HSF1 with
HSP70.''')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
RuntimeError: internal error in regular expression engine
###

Ouch.  So if I really want to go through this with regular expressions,
I'll probably need to break my set of keywords into smaller chunks that
the expression engine can handle.

But regular expressions are still too slow. I've tested a subset of the
keywords on the text above, and it takes around 5 seconds to do a
findall() scan across the test abstract above.  This is not nearly fast
enough: I need to be able to scan my documents in milliseconds.



I actually don't use regular expressions at the moment: I've done
something even sillier with "Suffix Trees":

    http://hkn.eecs.berkeley.edu/~dyoo/python/suffix_trees/

So I do have something that does work for the moment... but it's just not
as straightforward as I'd like.  Perhaps 'agrep' at:

    http://www.bio.cam.ac.uk/~mw263/pyagrep.html

might help... Hmmm...


In any case, I'm curious to hear suggestions on ways to simplify this
problem.  Thanks for any help!




From kauphlyn@speakeasy.org  Mon Apr 29 08:44:53 2002
From: kauphlyn@speakeasy.org (Daniel Coughlin)
Date: Mon, 29 Apr 2002 00:44:53 -0700 (PDT)
Subject: [Tutor] A problem: scanning for keywords in a bunch of text?
In-Reply-To: <Pine.LNX.4.44.0204282215230.8770-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0204290016360.2473-100000@grace.speakeasy.net>


This is just a thought, and I might be entirely off base, but can you process 
the the strings prior to searching through them? If so then you should be able 
to create some kind of numerical index on each chunk of searchable data and that 
could make your 
scanning go faster. I have thought about this for about 20 minutes so it might 
not make too much sense or be very clear.

It is inspired by the anagram algorithm in Programming Perls (Which i am so happy you encouraged us to read!). 
  
If you could process each 
searchable text (it looks like you might be seaching through abstracts?) into 
a list of numbers, you could then search that list of numbers. And it would 
be faster then searching the whole text. 

As I said this is quick thought. Hope it at least adds to the thinking.

It also looks a little less complicated than the suffix trees ;-)

Daniel
 






From faizal@umland.com.my  Mon Apr 29 09:22:24 2002
From: faizal@umland.com.my (Faizal)
Date: Mon, 29 Apr 2002 16:22:24 +0800
Subject: [Tutor] (no subject)
Message-ID: <01C1EF9A.0C523240@faizal>

hi there,

i just want to know..how unsubscribe python mailist


thank....

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.325 / Virus Database: 182 - Release Date: 19/02/02
 





From kauphlyn@speakeasy.org  Mon Apr 29 09:42:05 2002
From: kauphlyn@speakeasy.org (Daniel Coughlin)
Date: Mon, 29 Apr 2002 01:42:05 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <01C1EF9A.0C523240@faizal>
Message-ID: <Pine.LNX.4.44.0204290136240.7653-100000@grace.speakeasy.net>



visit this page:
http://mail.python.org/mailman/listinfo/tutor
to change your subscription options.

or read the headers of emails sent to you 
by the tutor list...

-
Daniel


On Mon, 29 Apr 2002, Faizal wrote:

> hi there,
> 
> i just want to know..how unsubscribe python mailist
> 
> 
> thank....
> 
> ---
> Outgoing mail is certified Virus Free.
> Checked by AVG anti-virus system (http://www.grisoft.com).
> Version: 6.0.325 / Virus Database: 182 - Release Date: 19/02/02
>  
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




From alan.gauld@bt.com  Mon Apr 29 10:18:06 2002
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon, 29 Apr 2002 10:18:06 +0100
Subject: [Tutor] windows and filenames
Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C584@mbtlipnt02.btlabs.bt.co.uk>

> it into a URL that will work on my webserver.... 
> 
> the dos-style filenames are ugly, but they also don't work 
> with apache.

Ah! that'd be because the tilde gets interpreted as a home 
directory I'd guess...

> Apache needs the full filenames, so you can see why 
> "mp3s\electr~1" doesn't work when "electronica" would.

mp3s/electr~1 might work (tildes permitting). The web 
server won't like backslashes but converting them to 
forward slashes should work fine.

I do agree they aren't pretty, but then neither are GUIDs 
and lots of sites use those in URLs!

> I guess I'll look around for winall and see if that has 
> anything that could help.

Sounds like your best bet.

Other random thoughts include - are you running the server 
in win9x? I thought NT based OS's returned the non DOS style 
names. Have you tried running the script on NT/W2k/XP?

Alan g.



From gege@nst.pku.edu.cn  Mon Apr 29 14:03:14 2002
From: gege@nst.pku.edu.cn (Wenlong Liu)
Date: Mon, 29 Apr 2002 21:03:14 +0800
Subject: [Tutor] How can I do IP_MASQ by using Python?
References: <20020428190554.GC18030@dman.ddts.net>
Message-ID: <067b01c1ef7e$3d6a9f00$34461e0a@gege>

This is a multi-part message in MIME format.

------=_NextPart_000_0678_01C1EFC1.4701A020
Content-Type: text/plain;
	charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Re: [Tutor] How can I do IP_MASQ by using Python?MGCP is Media Gateway =
Control Protocol. IETF RFC 2705
http://www.ietf.org/rfc/rfc2705.txt?number=3D2705

The Media Gateway Control Protocol (MGCP) is a signaling protocol for =
controlling Voice over IP (VoIP) Gateways from external call control =
elements across the Internet.  The protocol itself make extensive use of =
network addresses located inside the message body, since that it is =
impossible to use MGCP through basic network address translation/network =
address port translation without an Application Level Gateway (ALG).

A MGCP message is identified by the ALG using UDP port 2427 or 2727 as =
the destination port.  Actually the specified port number should be =
configurable. Most NAT implementations identify the type of traffic they =
will modify by using the port as an identifier, so this restriction =
seems practical.

Regards

Ares
  ----- Original Message -----=20
  From: dman=20
  To: tutor@python.org=20
  Sent: Monday, April 29, 2002 3:05 AM
  Subject: Re: [Tutor] How can I do IP_MASQ by using Python?


  On Sun, Apr 28, 2002 at 03:22:40PM +0800, Ares Liu wrote:=20
  | I want to transfer MGCP packages via NAT. Not so much flux, so I =
think I=20
  | can use python to do it. Does anyone can give me some advises?=20

  I don't know what MGCP is, but all the times I've seen the terms=20
  IPMASQ or NAT it is referring to the IP stack of a system.  The IP=20
  stack is in the kernel and requires access to the kernel to adjust how =

  the routing and NAT will operate.  With linux the netfilter modules=20
  provide the actual implementation and the userspace tool 'iptables'=20
  provides an interface for the admin to configure it.=20

  Maybe if you can explain MGCP and what you want to do with it a bit=20
  more I'll understand whether or not python is suitable for the task.=20

  HTH,=20
  -D=20

  --=20

  Python is executable pseudocode. Perl is executable line noise.=20
   =20
  GnuPG key : http://dman.ddts.net/~dman/public_key.gpg=20


------=_NextPart_000_0678_01C1EFC1.4701A020
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><TITLE>Re: [Tutor] How can I do IP_MASQ by using =
Python?</TITLE>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2715.400" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>
<DIV><FONT face=3DArial size=3D2>MGCP is Media Gateway Control Protocol. =
IETF RFC=20
2705</FONT></DIV>
<DIV><FONT face=3DArial size=3D2><A=20
href=3D"http://www.ietf.org/rfc/rfc2705.txt?number=3D2705">http://www.iet=
f.org/rfc/rfc2705.txt?number=3D2705</A></FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT>&nbsp;</DIV>
<DIV>
<P class=3DIndentNormal style=3D"MARGIN: 0cm 0cm 6pt 18pt"><SPAN =
lang=3DEN-US><FONT=20
face=3DArial>The Media Gateway Control Protocol (MGCP) is a signaling =
protocol for=20
controlling Voice over IP (VoIP) Gateways from external call control =
elements=20
across the Internet.<SPAN style=3D"mso-spacerun: yes">&nbsp; </SPAN>The =
protocol=20
itself make extensive use of network addresses located inside the =
message body,=20
since that it is impossible to use MGCP through basic network address=20
translation/network address port translation without an Application =
Level=20
Gateway (ALG).</FONT></SPAN></P><SPAN lang=3DEN-US><FONT face=3DArial>
<P class=3DMsoNormal style=3D"MARGIN: 0cm 0cm 6pt 18pt"><SPAN =
lang=3DEN-US>A MGCP=20
message is identified by the ALG using UDP port 2427 or 2727 as the =
destination=20
port.<SPAN style=3D"mso-spacerun: yes">&nbsp; </SPAN>Actually the =
specified port=20
number should be configurable. Most NAT implementations identify the =
type of=20
traffic they will modify by using the port as an identifier, so this =
restriction=20
seems practical.<?xml:namespace prefix =3D o ns =3D=20
"urn:schemas-microsoft-com:office:office"=20
/><o:p></o:p></SPAN></P><o:p></o:p></FONT></SPAN></DIV></FONT></DIV>
<DIV>Regards</DIV>
<DIV>&nbsp;</DIV>
<DIV>Ares</DIV>
<BLOCKQUOTE dir=3Dltr=20
style=3D"PADDING-RIGHT: 0px; PADDING-LEFT: 5px; MARGIN-LEFT: 5px; =
BORDER-LEFT: #000000 2px solid; MARGIN-RIGHT: 0px">
  <DIV style=3D"FONT: 9pt &#23435;&#20307;">----- Original Message ----- =
</DIV>
  <DIV style=3D"BACKGROUND: #e4e4e4; FONT: 9pt &#23435;&#20307;; =
font-color: black"><B>From:</B>=20
  <A title=3Ddman@dman.ddts.net =
href=3D"mailto:dman@dman.ddts.net">dman</A> </DIV>
  <DIV style=3D"FONT: 9pt &#23435;&#20307;"><B>To:</B> <A =
title=3Dtutor@python.org=20
  href=3D"mailto:tutor@python.org">tutor@python.org</A> </DIV>
  <DIV style=3D"FONT: 9pt &#23435;&#20307;"><B>Sent:</B> Monday, April =
29, 2002 3:05 AM</DIV>
  <DIV style=3D"FONT: 9pt &#23435;&#20307;"><B>Subject:</B> Re: [Tutor] =
How can I do IP_MASQ by=20
  using Python?</DIV>
  <DIV><BR></DIV>
  <P><FONT size=3D2>On Sun, Apr 28, 2002 at 03:22:40PM +0800, Ares Liu=20
  wrote:</FONT> <BR><FONT size=3D2>| I want to transfer MGCP packages =
via NAT. Not=20
  so much flux, so I think I</FONT> <BR><FONT size=3D2>| can use python =
to do it.=20
  Does anyone can give me some advises?</FONT> </P>
  <P><FONT size=3D2>I don't know what MGCP is, but all the times I've =
seen the=20
  terms</FONT> <BR><FONT size=3D2>IPMASQ or NAT it is referring to the =
IP stack of=20
  a system.&nbsp; The IP</FONT> <BR><FONT size=3D2>stack is in the =
kernel and=20
  requires access to the kernel to adjust how</FONT> <BR><FONT =
size=3D2>the=20
  routing and NAT will operate.&nbsp; With linux the netfilter =
modules</FONT>=20
  <BR><FONT size=3D2>provide the actual implementation and the userspace =
tool=20
  'iptables'</FONT> <BR><FONT size=3D2>provides an interface for the =
admin to=20
  configure it.</FONT> </P>
  <P><FONT size=3D2>Maybe if you can explain MGCP and what you want to =
do with it=20
  a bit</FONT> <BR><FONT size=3D2>more I'll understand whether or not =
python is=20
  suitable for the task.</FONT> </P>
  <P><FONT size=3D2>HTH,</FONT> <BR><FONT size=3D2>-D</FONT> </P>
  <P><FONT size=3D2>-- </FONT></P>
  <P><FONT size=3D2>Python is executable pseudocode. Perl is executable =
line=20
  noise.</FONT> <BR><FONT size=3D2>&nbsp;</FONT> <BR><FONT =
size=3D2>GnuPG key : <A=20
  href=3D"http://dman.ddts.net/~dman/public_key.gpg"=20
  target=3D_blank>http://dman.ddts.net/~dman/public_key.gpg</A></FONT>=20
</P></BLOCKQUOTE></BODY></HTML>

------=_NextPart_000_0678_01C1EFC1.4701A020--




From erikprice@mac.com  Mon Apr 29 14:33:04 2002
From: erikprice@mac.com (Erik Price)
Date: Mon, 29 Apr 2002 09:33:04 -0400
Subject: [Tutor] jython and dynamic typing
Message-ID: <A1FFE0C8-5B75-11D6-8E6F-00039351FE6A@mac.com>

Okay... admittedly I don't know much about Python, and I know even less 
about Java.  But I was wondering something about Jython --

 From what I understand, in Java the types must be declared and cannot be 
interchanged like they can in Python.  So then how does Jython 
"translate" Python programs that take advantage of dynamic typing into 
the stricter Java code?  Mind you, since I don't know much about Java, a 
layman's answer would be great if possible.

TIA,


Erik




From freddie@tumsan.fi  Mon Apr 29 11:03:21 2002
From: freddie@tumsan.fi (freddie)
Date: Mon, 29 Apr 2002 13:03:21 +0300
Subject: [Tutor] newbie with some basic questions
Message-ID: <20020429100321.GC6621@fede2.tumsan.fi>

hi,
im a total newbie to both programming and python (well i can write a 
decent shell script...).
just a few questions, most important one first:
1.whats better for a newbie like myself, learning python or core python 
programming? or any other recommendations?
2.how can i make input take only one character and not requrie a CR?
3.i have a simple list of lists for example: people = 
[["A","john","12345"],["B","joe","1231234"],["X","sally","1234"]]
and i need to do something like:
some_variable = X
new_variable = people[*][0] 
that is, find the corresponding list with the list that has [0] = X

i could use a dictionary like {"X":["sally","1234"]} but is there a 
better way to do it?




From brian@coolnamehere.com  Mon Apr 29 11:59:59 2002
From: brian@coolnamehere.com (Brian Wisti)
Date: Mon, 29 Apr 2002 10:59:59 +0000
Subject: [Tutor] newbie with some basic questions
In-Reply-To: <20020429100321.GC6621@fede2.tumsan.fi>
References: <20020429100321.GC6621@fede2.tumsan.fi>
Message-ID: <15565.10159.495379.487700@www.coolnamehere.com>

Hi Freddie,

Welcome!  You'll probably get a flood of replies, but I don't feel bad
about adding my own voice to the chaos :-)

freddie writes:
 > hi,
 > im a total newbie to both programming and python (well i can write a 
 > decent shell script...).
 > just a few questions, most important one first:
 > 1.whats better for a newbie like myself, learning python or core python 
 > programming? or any other recommendations?

Of those two, I'd go with Learning Python.  There are a lot of
introductory Python books out there, though, and your best bet would
probably be to go to the local bookstore, skim through the pages, and
see which one is the most accessible for you.  Of the books that I've
read, "The Quick Python Book" was the best first book on the subject.
Python has moved on since it was published, so there are a lot of
anxiety-reducing new features that it doesn't cover.  I keep hoping
that a 2nd edition will come out that I can recommend to my friends.


 > 2.how can i make input take only one character and not requrie a
CR?

The answer to this kinda depends on your operating system, from what I
understand, and might get complicated.  There is a solution in the
Python Faqts site:

     http://www.faqts.com/knowledge_base/view.phtml/aid/4490

 > 3.i have a simple list of lists for example: people = 
 > [["A","john","12345"],["B","joe","1231234"],["X","sally","1234"]]
 > and i need to do something like:
 > some_variable = X
 > new_variable = people[*][0] 
 > that is, find the corresponding list with the list that has [0] = X
 > 
 > i could use a dictionary like {"X":["sally","1234"]} but is there a 
 > better way to do it?

Personally, I'd go with the dictionary.  Maybe that's a personal style
issue.  If you're sticking with the list of lists, you could use the 
filter() function:

>>> new_variable = filter(lambda x: x[0] == some_variable, people)
>>> new_variable
[['X', 'sally', '1234']]
>>> new_variable[0]
['X', 'sally', '1234']
>>> 

filter() returns a list of all items that match the test given.  Even
though it's only got 1 item in it (the 'X' list), it's still a list.

There's other ways, too - list comprehensions, nested if's, and
probably a lot more.  filter() is short and sweet, though.

Hope this answer (and anybody else's) is helpful!

Later,
Brian Wisti
brian@coolnamehere.com
http://www.coolnamehere.com/



From paulsid@shaw.ca  Mon Apr 29 19:21:32 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Mon, 29 Apr 2002 12:21:32 -0600
Subject: [Tutor] newbie with some basic questions
References: <20020429100321.GC6621@fede2.tumsan.fi>
Message-ID: <3CCD8F2C.A374C745@shaw.ca>

freddie wrote:

> 2.how can i make input take only one character and not requrie a CR?

Unfortunately this is not an easy thing to do and the solution is
generally platform-specific.  See the Python FAQ at python.org for
ideas.

> 3.i have a simple list of lists for example: people =
> [["A","john","12345"],["B","joe","1231234"],["X","sally","1234"]]
> and i need to do something like:
> some_variable = X
> new_variable = people[*][0]
> that is, find the corresponding list with the list that has [0] = X
> 
> i could use a dictionary like {"X":["sally","1234"]} but is there a
> better way to do it?

If the single character is going to be the only search criteria, then
using a dictionary is definitely "right" here.  It's not only easier but
faster too.

If you may need to search by other fields (e.g. the name field in your
example) then you have a few options.  One is to build two dictionaries
like this:

chardict = {"A": ["A","john","12345"], "B": ["B","joe","1231234"], "X":
["X","sally","1234"]}
namedict = {"john": ["A","john","12345"], "joe": ["B","joe","1231234"],
"sally": ["X","sally","1234"]}

If you put the inner lists in variables first and put those variables in
the dictionaries then it'll cut down on the memory this uses (basically
it'll just be the data in the lists, the keys for both dictionaries, and
a small amount of overhead for references).  Note that if the
dictionaries will be modified then you have to keep the cross-references
updated which slows down insertions and deletions, but the searching
will be very fast.

Another option if search speed isn't a concern is to "unzip" the single
list of lists into three different lists, like this:

chars = ["A", "B", "X"]
names = ["john", "joe", "sally"]
nums = ["12345", "1231234", "1234"]

Then use Python's list object methods, in this case index(), to find
your answer:

idx = chars.index("X")  # Find index of first occurrence of "X".
nameofx = names[idx]    # Get the associated name.

BTW I called this "unzip" because you can use zip(chars, names, nums)
method to build your original single list of lists if you need to, if
you're using Python 2.0 or higher.

I would almost always go for the double-dictionary method (or some
variation thereof) if I couldn't use just a single dictionary, but there
are situations where the multiple-list methods can be better - namely if
insertion/deletion is going to be done much more frequently than
searching.  

Dictionaries are very handy so they would be very much worth learning. 
Besides, knowing the tutor crowd somewhat as I do now, I expect any
other suggestions you get are also going to be dictionary-based.  :-)

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/



From linuxconsult@yahoo.com.br  Mon Apr 29 20:30:30 2002
From: linuxconsult@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Mon, 29 Apr 2002 16:30:30 -0300
Subject: [Tutor] Printable versions of "What's new" documents?
Message-ID: <20020429193030.GA3669@ime.usp.br>

	Dear all,

	I am a newbie in Python and I am currently reading some
	documents on the language.

	I just finished reading the tutorial for version 2.0 of Python
	and I saw that there are documents written by A.M. Kuchling
	entitled "What's New in Python" for versions 2.0, 2.1 and 2.2.
	I would like to read them in order to catch up with the
	language improvements and also see a longer discussion on the
	language.

	Unfortunately, while I found a Postscript version of the
	document for version 2.2, I only found on-line versions of the
	documents corresponding to versions 2.0 and 2.1.

	So, my question is: are there printable (postscript?) versions
	of the documents "What's New in Python" for Python 2.0 and 2.1
	available?

	I would appreciate any help you could provide.


	Thank you very much, Roger...

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



From dman@dman.ddts.net  Mon Apr 29 21:53:15 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 29 Apr 2002 15:53:15 -0500
Subject: [Tutor] How can I do IP_MASQ by using Python?
In-Reply-To: <067b01c1ef7e$3d6a9f00$34461e0a@gege>
References: <20020428190554.GC18030@dman.ddts.net> <067b01c1ef7e$3d6a9f00$34461e0a@gege>
Message-ID: <20020429205315.GB709@dman.ddts.net>

--U+BazGySraz5kW0T
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Apr 29, 2002 at 09:03:14PM +0800, Wenlong Liu wrote:
| Re: [Tutor] How can I do IP_MASQ by using Python?MGCP is Media Gateway Co=
ntrol Protocol. IETF RFC 2705
| http://www.ietf.org/rfc/rfc2705.txt?number=3D2705
|=20
| The Media Gateway Control Protocol (MGCP) is a signaling protocol
| for controlling Voice over IP (VoIP) Gateways from external call
| control elements across the Internet.  The protocol itself make
| extensive use of network addresses located inside the message body,
| since that it is impossible to use MGCP through basic network
| address translation/network address port translation without an
| Application Level Gateway (ALG).
|=20
| A MGCP message is identified by the ALG using UDP port 2427 or 2727
| as the destination port.  Actually the specified port number should
| be configurable. Most NAT implementations identify the type of
| traffic they will modify by using the port as an identifier, so this
| restriction seems practical.

Ok, I see now.  Yes you could do this sort of task with python.  You
would write a deamon to accept those packets on some other port,
parses and rewrites the body, then sends it out to the real
destination.  Use iptables to redirect incoming packets to be
intercepted by your daemon rather than being forwarded out the other
interface.

HTH,
-D

--=20

You have heard the saying that if you put a thousand monkeys in a room with=
 a
thousand typewriters and waited long enough, eventually you would have a ro=
om
full of dead monkeys.
                                (Scott Adams - The Dilbert principle)
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--U+BazGySraz5kW0T
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzNsrsACgkQO8l8XBKTpRRGJgCgm95rP6Jm3LGNfbNW61L5VgJ8
wkwAniH6PAaablR8fwoDWXK6XAU60Bqg
=gI9M
-----END PGP SIGNATURE-----

--U+BazGySraz5kW0T--



From dman@dman.ddts.net  Mon Apr 29 21:54:45 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 29 Apr 2002 15:54:45 -0500
Subject: [Tutor] jython and dynamic typing
In-Reply-To: <A1FFE0C8-5B75-11D6-8E6F-00039351FE6A@mac.com>
References: <A1FFE0C8-5B75-11D6-8E6F-00039351FE6A@mac.com>
Message-ID: <20020429205445.GC709@dman.ddts.net>

--Md/poaVZ8hnGTzuv
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Apr 29, 2002 at 09:33:04AM -0400, Erik Price wrote:
| Okay... admittedly I don't know much about Python, and I know even less=
=20
| about Java.  But I was wondering something about Jython --
|=20
| From what I understand, in Java the types must be declared and cannot be=
=20
| interchanged like they can in Python.  So then how does Jython=20
| "translate" Python programs that take advantage of dynamic typing into=20
| the stricter Java code?  Mind you, since I don't know much about Java, a=
=20
| layman's answer would be great if possible.

The generated code just calls methods in the jython interpreter to do
the dirty work.  The generated stuff _is_ java, but is _not_
independent of jython.

-D

--=20

Come to me, all you who are weary and burdened, and I will give you
rest.  Take my yoke upon you and learn from me, for I am gentle and
humble in heart, and you will find rest for your souls.  For my yoke
is easy and my burden is light.
        Matthew 11:28-30
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--Md/poaVZ8hnGTzuv
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzNsxUACgkQO8l8XBKTpRQnaQCeNgNapsAaPX0LPosLoBQ0TB48
ye4An2fgZIiZ1eMQEm+6XPdeHHl5w8wJ
=w2kE
-----END PGP SIGNATURE-----

--Md/poaVZ8hnGTzuv--



From Hugh Stewart" <hughstewart@optushome.com.au  Tue Apr 30 01:07:32 2002
From: Hugh Stewart" <hughstewart@optushome.com.au (Hugh Stewart)
Date: Tue, 30 Apr 2002 10:07:32 +1000
Subject: [Tutor] Nested list anomaly
Message-ID: <000c01c1efdb$136d6fe0$795c1cd3@nsw.optushome.com.au>

This is a multi-part message in MIME format.

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

Hi Folk,
I was toying with the idea of producing a suite of=20
matrix operations using list comprehensions. At one point
I needed to initialize a matrix so all elements were zero.
Three possiblities came to mind:

>>> c1 =3D [[0]*2]*3
>>> c1
[[0, 0], [0, 0], [0, 0]]
>>> c2 =3D [[0,0]]*3
>>> c2
[[0, 0], [0, 0], [0, 0]]
>>> c3 =3D [[0,0],[0,0],[0,0]]
>>> c3
[[0, 0], [0, 0], [0, 0]]
>>> c1=3D=3Dc2=3D=3Dc3
1
>>>=20

I believed these three matrices c1,c2 and c3 were equivalent,
but when used in the following simple matrix multipication=20
algorithm it became evident c1 and c2 are not the 'same' as c3.

>>> a=3D[[1,2,3],[3,4,5],[5,6,7]]
>>> b=3D[[1,1],[1,1],[1,1]]
>>> i1=3D3
>>> j1=3D2
>>> k1=3D3
>>> for i in range(i1):
 for j in range(j1):
  #c[i][j]=3D0 #not necessary if c is a zero matrix
  for k in range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]

Test 1:
>>> c1 =3D [[0]*2]*3
>>> c1
[[0, 0], [0, 0], [0, 0]]
>>> c=3Dc1
>>> c
[[0, 0], [0, 0], [0, 0]]
>>> for i in range(i1):
 for j in range(j1):
  #c[i][j]=3D0
  for k in range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]

  =20
>>> c
[[36, 36], [36, 36], [36, 36]]
Test 2:
>>> c2 =3D [[0,0]]*3
>>> c2
[[0, 0], [0, 0], [0, 0]]
>>> c=3Dc2
>>> c
[[0, 0], [0, 0], [0, 0]]
>>> for i in range(i1):
 for j in range(j1):
  #c[i][j]=3D0
  for k in range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]

  =20
>>> c
[[36, 36], [36, 36], [36, 36]]

Test 3:
>>> c3 =3D [[0,0],[0,0],[0,0]]
>>> c3
[[0, 0], [0, 0], [0, 0]]
>>> c=3Dc3
>>> c
[[0, 0], [0, 0], [0, 0]]
>>> for i in range(i1):
 for j in range(j1):
  #c[i][j]=3D0
  for k in range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]

  =20
>>> c
[[6, 6], [12, 12], [18, 18]]
>>>=20

It is only the matrix c3 which yields the correct result.
Can any of you gurus explain what is an anomaly to me.
Thanks  Hugh

------=_NextPart_000_0009_01C1F02E.D82A57A0
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#fffff0>
<DIV><FONT face=3DArial size=3D2>Hi Folk,<BR>I was toying with the idea =
of producing=20
a suite of <BR>matrix operations using list comprehensions. At one =
point<BR>I=20
needed to initialize a matrix so all elements were zero.<BR>Three =
possiblities=20
came to mind:</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt; c1 =3D =
[[0]*2]*3<BR>&gt;&gt;&gt;=20
c1<BR>[[0, 0], [0, 0], [0, 0]]<BR>&gt;&gt;&gt; c2 =3D =
[[0,0]]*3<BR>&gt;&gt;&gt;=20
c2<BR>[[0, 0], [0, 0], [0, 0]]<BR>&gt;&gt;&gt; c3 =3D=20
[[0,0],[0,0],[0,0]]<BR>&gt;&gt;&gt; c3<BR>[[0, 0], [0, 0], [0,=20
0]]<BR>&gt;&gt;&gt; c1=3D=3Dc2=3D=3Dc3<BR>1<BR>&gt;&gt;&gt; =
</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>I believed these three matrices c1,c2 =
and c3 were=20
equivalent,<BR>but when used in the following simple matrix =
multipication=20
<BR>algorithm it became evident c1 and c2 are not the 'same' as =
c3.</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&gt;&gt;&gt;=20
a=3D[[1,2,3],[3,4,5],[5,6,7]]<BR>&gt;&gt;&gt;=20
b=3D[[1,1],[1,1],[1,1]]<BR>&gt;&gt;&gt; i1=3D3<BR>&gt;&gt;&gt; =
j1=3D2<BR>&gt;&gt;&gt;=20
k1=3D3<BR>&gt;&gt;&gt; for i in range(i1):<BR>&nbsp;for j in=20
range(j1):<BR>&nbsp;&nbsp;#c[i][j]=3D0 #not necessary if c is a zero=20
matrix<BR>&nbsp;&nbsp;for k in=20
range(k1):<BR>&nbsp;&nbsp;&nbsp;c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]</FONT><=
/DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Test 1:<BR>&gt;&gt;&gt; c1 =3D=20
[[0]*2]*3<BR>&gt;&gt;&gt; c1<BR>[[0, 0], [0, 0], [0, 0]]<BR>&gt;&gt;&gt; =

c=3Dc1<BR>&gt;&gt;&gt; c<BR>[[0, 0], [0, 0], [0, 0]]<BR>&gt;&gt;&gt; for =
i in=20
range(i1):<BR>&nbsp;for j in=20
range(j1):<BR>&nbsp;&nbsp;#c[i][j]=3D0<BR>&nbsp;&nbsp;for k in=20
range(k1):<BR>&nbsp;&nbsp;&nbsp;c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]</FONT><=
/DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp;<BR>&gt;&gt;&gt; =
c<BR>[[36, 36],=20
[36, 36], [36, 36]]<BR>Test 2:<BR>&gt;&gt;&gt; c2 =3D =
[[0,0]]*3<BR>&gt;&gt;&gt;=20
c2<BR>[[0, 0], [0, 0], [0, 0]]<BR>&gt;&gt;&gt; c=3Dc2<BR>&gt;&gt;&gt; =
c<BR>[[0,=20
0], [0, 0], [0, 0]]<BR>&gt;&gt;&gt; for i in range(i1):<BR>&nbsp;for j =
in=20
range(j1):<BR>&nbsp;&nbsp;#c[i][j]=3D0<BR>&nbsp;&nbsp;for k in=20
range(k1):<BR>&nbsp;&nbsp;&nbsp;c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]</FONT><=
/DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp;<BR>&gt;&gt;&gt; =
c<BR>[[36, 36],=20
[36, 36], [36, 36]]</FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>Test 3:<BR>&gt;&gt;&gt; c3 =3D=20
[[0,0],[0,0],[0,0]]<BR>&gt;&gt;&gt; c3<BR>[[0, 0], [0, 0], [0,=20
0]]<BR>&gt;&gt;&gt; c=3Dc3<BR>&gt;&gt;&gt; c<BR>[[0, 0], [0, 0], [0,=20
0]]<BR>&gt;&gt;&gt; for i in range(i1):<BR>&nbsp;for j in=20
range(j1):<BR>&nbsp;&nbsp;#c[i][j]=3D0<BR>&nbsp;&nbsp;for k in=20
range(k1):<BR>&nbsp;&nbsp;&nbsp;c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]</FONT><=
/DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>&nbsp;&nbsp;&nbsp;<BR>&gt;&gt;&gt; =
c<BR>[[6, 6],=20
[12, 12], [18, 18]]<BR>&gt;&gt;&gt; </FONT></DIV>
<DIV>&nbsp;</DIV>
<DIV><FONT face=3DArial size=3D2>It is only the matrix c3 which yields =
the correct=20
result.<BR>Can any of you gurus explain what is an anomaly to=20
me.<BR>Thanks&nbsp; Hugh</FONT></DIV></BODY></HTML>

------=_NextPart_000_0009_01C1F02E.D82A57A0--




From dman@dman.ddts.net  Tue Apr 30 02:04:04 2002
From: dman@dman.ddts.net (dman)
Date: Mon, 29 Apr 2002 20:04:04 -0500
Subject: [Tutor] Nested list anomaly
In-Reply-To: <000c01c1efdb$136d6fe0$795c1cd3@nsw.optushome.com.au>
References: <000c01c1efdb$136d6fe0$795c1cd3@nsw.optushome.com.au>
Message-ID: <20020430010404.GA4254@dman.ddts.net>

--pWyiEgJYm5f9v55/
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Apr 30, 2002 at 10:07:32AM +1000, Hugh Stewart wrote:

| Test 1:
| >>> c1 =3D [[0]*2]*3
| >>> c1
| [[0, 0], [0, 0], [0, 0]]

This looks good, but what you have is a 3-element list where all
elements are identical references to the same 2-element list.  Since
lists are mutable, if you change the list, the change is seen by all
the references to it.

| Test 2:
| >>> c2 =3D [[0,0]]*3

Same situation.

| Test 3:
| >>> c3 =3D [[0,0],[0,0],[0,0]]

Here's what you wanted -- a 3-element list where each element is a
_separate_ list.


A shorter way of writing that (for longer lists) is :
    c =3D []
    for i in range(3) :
        c.append( [0]*2 )

    or

    c =3D [ [0]*2  for i in range(3) ]


-D

--=20

Come to me, all you who are weary and burdened, and I will give you
rest.  Take my yoke upon you and learn from me, for I am gentle and
humble in heart, and you will find rest for your souls.  For my yoke
is easy and my burden is light.
        Matthew 11:28-30
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--pWyiEgJYm5f9v55/
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzN7YQACgkQO8l8XBKTpRTPSQCdF7CH9x50rkSx9ogq2NCWuS4N
FAkAnjReNp6MWLNO7TWmdza7QPdKhd6d
=73Cg
-----END PGP SIGNATURE-----

--pWyiEgJYm5f9v55/--



From lha2@columbia.edu  Tue Apr 30 03:03:38 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Mon, 29 Apr 2002 22:03:38 -0400
Subject: [Tutor] A small math puzzle            [recreational Python]
References: <Pine.LNX.4.21.0201051221460.9280-100000@hkn.eecs.berkeley.edu>
Message-ID: <3CCDFB7A.366A9462@mail.verizon.net>

Danny Yoo wrote:
> 
> On Sat, 5 Jan 2002, Lloyd Hugh Allen wrote:
> 
> > Danny Yoo wrote:
> > > However, here's an example that is a rearrangement but doesn't work
> > > because it has a fixed letter:
> > >
> > >     'TRESAE'
> > >      ^
> > >
> > > In this example, the 'T' makes this rearrangement inacceptable, since
> > > 'TERESA' itself begins with a 'T' too.
> > >
> > > The puzzle is to write a program that counts all the possible
> > > rearrangements without fixed letters.
> > >
> > > Have fun!
> >
> > Is it necessary to actually construct the list of rearrangements, or
> > do you just want a function that will compute how many rearrangements
> > exist?
> 
> If you can think of a way to do it without actually generating the
> rearrangements, that would be great!
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

I know that this is late, but I just came across this while teaching
combinatorics in precalculus--

if you have n spaces to fill with objects that occur e1, e2, e3, ...
etc. times, (e.g., "TERESA" has six spaces, and 'E' occurs twice), the
number of DISTINCT PERMUTATIONS (which is what you would check an index
for if you were interested in such things) is

n!/(e1!e2!e3!...)

e.g./

6!/(2!1!1!1!1!) == 6!/(2!)

The cleverest algorithm for evaluating that puppy while trying really,
really hard to avoid Longs would probably try to find common factors
between the factors of n! and the denominator, since multiplying and
then dividing is slow and costly where smart multiplying is cheap. Each
factor of the denominator should either appear or share a factor with a
factor of the numerator (take for instance 4!/(2!2!)--every other
integer is even, and so every other integer is divisible by two; 4!,
having four consecutive integers for factors, is guaranteed to have two
exactly two even factors).

Or something.

Sorry to bring up old business. And sorry also if someone else had
already posted this algorithm and I had missed it--I looked back through
my python-tutor folder and couldn't find mention of this formula.

As for why, n! gives the number of permutations; the denominator tells
us how many distinct ways we could arrange the parts that we consider to
be identical. Spraypaint one of the 'E's red and the other blue, and for
each arrangement of TERESA, there are two distinct ways to arrange our
'E's. And so on for more repeated events.

I'll stop blathering now.



From lha2@columbia.edu  Tue Apr 30 03:09:46 2002
From: lha2@columbia.edu (Lloyd Hugh Allen)
Date: Mon, 29 Apr 2002 22:09:46 -0400
Subject: [Tutor] A small math puzzle            [recreational Python]
References: <Pine.LNX.4.21.0201051221460.9280-100000@hkn.eecs.berkeley.edu> <3CCDFB7A.366A9462@mail.verizon.net>
Message-ID: <3CCDFCEA.C017DA3D@mail.verizon.net>

Oops. Wrong puzzle. Now I feel sheepish. Seems related though (and it's
how I had remembered the puzzle until I reread my own post).

Sorry 'bout that.

Lloyd Hugh Allen wrote:
> 
> Danny Yoo wrote:
> >
> > On Sat, 5 Jan 2002, Lloyd Hugh Allen wrote:
> >
> > > Danny Yoo wrote:
> > > > However, here's an example that is a rearrangement but doesn't work
> > > > because it has a fixed letter:
> > > >
> > > >     'TRESAE'
> > > >      ^
> > > >
> > > > In this example, the 'T' makes this rearrangement inacceptable, since
> > > > 'TERESA' itself begins with a 'T' too.
> > > >
> > > > The puzzle is to write a program that counts all the possible
> > > > rearrangements without fixed letters.
> > > >
> > > > Have fun!
> > >
> > > Is it necessary to actually construct the list of rearrangements, or
> > > do you just want a function that will compute how many rearrangements
> > > exist?
> >
> > If you can think of a way to do it without actually generating the
> > rearrangements, that would be great!
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> 
> I know that this is late, but I just came across this while teaching
> combinatorics in precalculus--
> 
> if you have n spaces to fill with objects that occur e1, e2, e3, ...
> etc. times, (e.g., "TERESA" has six spaces, and 'E' occurs twice), the
> number of DISTINCT PERMUTATIONS (which is what you would check an index
> for if you were interested in such things) is
> 
> n!/(e1!e2!e3!...)
> 
> e.g./
> 
> 6!/(2!1!1!1!1!) == 6!/(2!)
> 
> The cleverest algorithm for evaluating that puppy while trying really,
> really hard to avoid Longs would probably try to find common factors
> between the factors of n! and the denominator, since multiplying and
> then dividing is slow and costly where smart multiplying is cheap. Each
> factor of the denominator should either appear or share a factor with a
> factor of the numerator (take for instance 4!/(2!2!)--every other
> integer is even, and so every other integer is divisible by two; 4!,
> having four consecutive integers for factors, is guaranteed to have two
> exactly two even factors).
> 
> Or something.
> 
> Sorry to bring up old business. And sorry also if someone else had
> already posted this algorithm and I had missed it--I looked back through
> my python-tutor folder and couldn't find mention of this formula.
> 
> As for why, n! gives the number of permutations; the denominator tells
> us how many distinct ways we could arrange the parts that we consider to
> be identical. Spraypaint one of the 'E's red and the other blue, and for
> each arrangement of TERESA, there are two distinct ways to arrange our
> 'E's. And so on for more repeated events.
> 
> I'll stop blathering now.



From gege@nst.pku.edu.cn  Tue Apr 30 04:50:51 2002
From: gege@nst.pku.edu.cn (Wenlong Liu)
Date: Tue, 30 Apr 2002 11:50:51 +0800
Subject: [Tutor] How can I do IP_MASQ by using Python?
References: <20020428190554.GC18030@dman.ddts.net> <067b01c1ef7e$3d6a9f00$34461e0a@gege> <20020429205315.GB709@dman.ddts.net>
Message-ID: <001b01c1effa$3c41eb20$34461e0a@gege>

I want it can be run under linux/windows. so cannot related to iptables.
That means I need a lonely deamon to accept packages, rewite and redirect
them.

Regards

Ares
----- Original Message -----
From: "dman" <dman@dman.ddts.net>
To: <tutor@python.org>
Sent: Tuesday, April 30, 2002 4:53 AM
Subject: Re: [Tutor] How can I do IP_MASQ by using Python?

On Mon, Apr 29, 2002 at 09:03:14PM +0800, Wenlong Liu wrote:
| Re: [Tutor] How can I do IP_MASQ by using Python?MGCP is Media Gateway
Control Protocol. IETF RFC 2705
| http://www.ietf.org/rfc/rfc2705.txt?number=2705
|
| The Media Gateway Control Protocol (MGCP) is a signaling protocol
| for controlling Voice over IP (VoIP) Gateways from external call
| control elements across the Internet.  The protocol itself make
| extensive use of network addresses located inside the message body,
| since that it is impossible to use MGCP through basic network
| address translation/network address port translation without an
| Application Level Gateway (ALG).
|
| A MGCP message is identified by the ALG using UDP port 2427 or 2727
| as the destination port.  Actually the specified port number should
| be configurable. Most NAT implementations identify the type of
| traffic they will modify by using the port as an identifier, so this
| restriction seems practical.

Ok, I see now.  Yes you could do this sort of task with python.  You
would write a deamon to accept those packets on some other port,
parses and rewrites the body, then sends it out to the real
destination.  Use iptables to redirect incoming packets to be
intercepted by your daemon rather than being forwarded out the other
interface.

HTH,
-D

--




From brian@coolnamehere.com  Tue Apr 30 00:42:08 2002
From: brian@coolnamehere.com (Brian Wisti)
Date: Mon, 29 Apr 2002 23:42:08 +0000
Subject: [Tutor] Pre-Tk Hacking Question
Message-ID: <15565.55888.456230.764835@www.coolnamehere.com>

Hi all,

I'm really starting to get bored of the default look of Tkinter under
Linux.  There are a few Tk patches out there which change the look to
emulate Windows and NextStep widgets (among others).  Does anybody
have any idea whether applying these patches would affect Tkinter? If
so, would it be in a good way, or a bad way? It's been a few years
since I messed with these patches, but back then they didn't have any
impact on the performance of my system's Tcl/Tk stuff.

Then again, maybe I should just learn more about the wxPython
interface and use happy little GTK themes to solve my eye-candy
dilemma.  So, next question:  any good wxPython / wxWindows books in
the works?

Thanks,
Brian Wisti
brian@coolnamehere.com
http://www.coolnamehere.com/



From alex@gabuzomeu.net  Tue Apr 30 10:20:47 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Tue, 30 Apr 2002 11:20:47 +0200
Subject: [Tutor] Re: Printable versions of "What's new" documents?
In-Reply-To: <20020430021202.12675.82815.Mailman@mail.python.org>
Message-ID: <4.3.2.7.2.20020430104434.00b766a0@pop3.norton.antivirus>

Hi Rogério,


At 22:12 29/04/2002 -0400, you wrote:
>Date: Mon, 29 Apr 2002 16:30:30 -0300
>From: Rogério Brito <linuxconsult@yahoo.com.br>
>Subject: [Tutor] Printable versions of "What's new" documents?

>         I just finished reading the tutorial for version 2.0 of Python
>         and I saw that there are documents written by A.M. Kuchling
>         entitled "What's New in Python" for versions 2.0, 2.1 and 2.2.
>         I would like to read them in order to catch up with the
>         language improvements and also see a longer discussion on the
>         language.
>
>         Unfortunately, while I found a Postscript version of the
>         document for version 2.2, I only found on-line versions of the
>         documents corresponding to versions 2.0 and 2.1.

I only have PDF copies of these docs. If you can't use PDF, I can try 
outputting these docs to PS and put them somewhere for download. Let me 
know if you need them.


Cheers.

Alexandre





From m_konermann@gmx.de  Tue Apr 30 10:20:47 2002
From: m_konermann@gmx.de (Marcus)
Date: Tue, 30 Apr 2002 11:20:47 +0200
Subject: [Tutor] I need python22_d.lib for debug mode generation
Message-ID: <3CCE61EF.2060608@gmx.de>

Hi !

I need python22_d.lib for a debug mode generation.
Can anyone tell me where to find it ? I don´t want to generate it for my 
own, because i read that it might cause a lot of trouble and i´m not so 
familiar in programming.

Greetings
Marcus





From linuxconsult@yahoo.com.br  Tue Apr 30 10:51:08 2002
From: linuxconsult@yahoo.com.br (=?iso-8859-1?Q?Rog=E9rio?= Brito)
Date: Tue, 30 Apr 2002 06:51:08 -0300
Subject: [Tutor] Re: Printable versions of "What's new" documents?
In-Reply-To: <4.3.2.7.2.20020430104434.00b766a0@pop3.norton.antivirus>
References: <20020430021202.12675.82815.Mailman@mail.python.org> <4.3.2.7.2.20020430104434.00b766a0@pop3.norton.antivirus>
Message-ID: <20020430095108.GA4681@ime.usp.br>

On Apr 30 2002, Alexandre Ratti wrote:
> Hi Rogério,
(...)
> I only have PDF copies of these docs. If you can't use PDF, I can
> try outputting these docs to PS and put them somewhere for download.
> Let me know if you need them.

	Dear Alexandre,

	Thank you very much for answering my message. Yes, PDF files
	would be fine. I would love to get them somehow.
	Unfortunately, they are not available anymore from all the
	sources I could find through Google (including the place where
	printable versions used to be, like py-howto.sf.net). :-(

	So, yes, if it is not a problem with you, I'd like to get a
	copy of them.


	Thank you very much, Roger...

-- 
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  Rogério Brito - rbrito@iname.com - http://www.ime.usp.br/~rbrito/
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



From urgrue@tumsan.fi  Tue Apr 30 11:43:20 2002
From: urgrue@tumsan.fi (urgrue)
Date: Tue, 30 Apr 2002 13:43:20 +0300
Subject: [Tutor] more newbie questions
Message-ID: <20020430104320.GA10071@fede2.tumsan.fi>

thanks to everyone who helped me out with my first post.
i'm getting a python book today so hopefully then i'll have less to 
post about ;)

just a couple little questions:
1. how to simply clear the screen? im using print "\n"*24  which works 
of course, but is a bit ugly.
2. how can i avoid every print statement forcing a space between what 
it prints?



From alex@gabuzomeu.net  Tue Apr 30 11:48:31 2002
From: alex@gabuzomeu.net (Alexandre Ratti)
Date: Tue, 30 Apr 2002 12:48:31 +0200
Subject: [Tutor] Re: Printable versions of "What's new" documents?
In-Reply-To: <20020430095108.GA4681@ime.usp.br>
References: <4.3.2.7.2.20020430104434.00b766a0@pop3.norton.antivirus>
 <20020430021202.12675.82815.Mailman@mail.python.org>
 <4.3.2.7.2.20020430104434.00b766a0@pop3.norton.antivirus>
Message-ID: <4.3.2.7.2.20020430124637.00cff6e0@pop3.norton.antivirus>

Hi Rogério,


At 06:51 30/04/2002 -0300, Rogério Brito wrote:
[Looking for the What's New docs for Python 2.0 to 2.2]
>         Thank you very much for answering my message. Yes, PDF files
>         would be fine. I would love to get them somehow.

I just uploaded them to:

         http://alexandre.ratti.free.fr/python/docs/


Cheers.

Alexandre




From pythontutor@venix.com  Tue Apr 30 13:28:45 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 30 Apr 2002 08:28:45 -0400
Subject: [Tutor] Nested list anomaly
References: <000c01c1efdb$136d6fe0$795c1cd3@nsw.optushome.com.au> <20020430010404.GA4254@dman.ddts.net>
Message-ID: <3CCE8DFD.6060902@venix.com>

I have to confess that I still get burned by unexpectedly creating lists
with multiple references.  Is there a simple rule of thumb for recognizing
when you have simply created multiple references?

[[0]*2]*3 
multiple references
[[0]*2 for i in range(3)]	multiple lists

On casual inspection these seem awfully similar.

dman wrote:

> On Tue, Apr 30, 2002 at 10:07:32AM +1000, Hugh Stewart wrote:
> 
> | Test 1:
> | >>> c1 = [[0]*2]*3
> | >>> c1
> | [[0, 0], [0, 0], [0, 0]]
> 
> This looks good, but what you have is a 3-element list where all
> elements are identical references to the same 2-element list.  Since
> lists are mutable, if you change the list, the change is seen by all
> the references to it.
> 
> | Test 2:
> | >>> c2 = [[0,0]]*3
> 
> Same situation.
> 
> | Test 3:
> | >>> c3 = [[0,0],[0,0],[0,0]]
> 
> Here's what you wanted -- a 3-element list where each element is a
> _separate_ list.
> 
> 
> A shorter way of writing that (for longer lists) is :
>     c = []
>     for i in range(3) :
>         c.append( [0]*2 )
> 
>     or
> 
>     c = [ [0]*2  for i in range(3) ]
> 
> 
> -D
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From dyoo@hkn.eecs.berkeley.edu  Tue Apr 30 16:20:49 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Apr 2002 08:20:49 -0700 (PDT)
Subject: [Tutor] I need python22_d.lib for debug mode generation
In-Reply-To: <3CCE61EF.2060608@gmx.de>
Message-ID: <Pine.LNX.4.44.0204300807260.4785-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Apr 2002, Marcus wrote:

> I need python22_d.lib for a debug mode generation.

One question: are you sure you need this?  Python22_d.lib is only useful
if you're doing things with Visual C++: normal Python programmers will not
need it.


If you really do need this, you can generate it by compiling Python 2.2 in
"DEBUG" mode in Visual C++.  Alternatively, it comes packaged with
ActiveState's ActivePython distribution:

    http://activestate.com/Products/Download/Get.plex?id=ActivePython


Using ActiveState's distribution will probably be the easiest way to get
the DEBUG libraries, according to Mark Hammond:

    http://aspn.activestate.com/ASPN/Mail/Message/python-list/779867


Good luck!




From dman@dman.ddts.net  Tue Apr 30 17:31:36 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 30 Apr 2002 11:31:36 -0500
Subject: [Tutor] Nested list anomaly
In-Reply-To: <3CCE8DFD.6060902@venix.com>
References: <000c01c1efdb$136d6fe0$795c1cd3@nsw.optushome.com.au> <20020430010404.GA4254@dman.ddts.net> <3CCE8DFD.6060902@venix.com>
Message-ID: <20020430163136.GB13577@dman.ddts.net>

--KFztAG8eRSV9hGtP
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Apr 30, 2002 at 08:28:45AM -0400, Lloyd Kvam wrote:
| I have to confess that I still get burned by unexpectedly creating lists
| with multiple references.  Is there a simple rule of thumb for recognizing
| when you have simply created multiple references?

The key is when expressions are evaluated and what expressions
evaluate to.

0

evaluates to a reference to an int object whose value is 0

[0]

evaluates to a list containing a reference to the int object whose
value is 0.

[0]*2=20

the inside expression (0) is evaluated once, so this is a list whose 2
elements are copies of the same reference to the same int object.
This is acceptable because ints are immutable.

| [[0]*2]*3=20

The inside expression (0) is evaluated once.  Then the next expression
([0]*2]) is evaluated once.  This is what we have above -- a 2-element
list containing duplicate references to the int object 0.  Finally the
outer expression is evaluated, which becomes a 3-element list with
duplicate references to the single 2-element list on the inside.

| [[0]*2 for i in range(3)]

Here the expression
    [0]*2
is evaluated for each iteration of the loop.  Thus, each time that
expression is evaluated we have a new reference to a new list object.

| On casual inspection these seem awfully similar.

Here's some code that (if it works) will help visualize what happens.
What it does is use a function to report how many times the expression
'[0]' is evaluated rather than using that expression directly.

calls =3D 0
def make_list() :
    global calls
    calls +=3D 1
    print "called %d times" % calls
    return [0]

print make_list()

# be sure and reset the counter for each example
calls =3D 0
print make_list()*2

calls =3D 0
print [make_list()*2]*3

calls =3D 0
print [ make_list()*2 for i in range(3) ]


Now if you wanted to make this matrix have a mutable object at the
lowest level you wouldn't be able to use the *2 expression in the list
comp.  For example :

# use instances of this class instead of ints
class M : pass

print [ [ M() ]*2 for i in range(3) ]

Notice how the ids of the instances are duplicated.  There are only 3
distinct M instances in the 2x3 table.  Instead this can be used :

print [ [ M() for i in range(2) ] for i in range(3) ]

If you wish, substitute the above make_list() function and make a
corresponding factory function to see how many times M() is called.

-D

--=20

I tell you the truth, everyone who sins is a slave to sin.  Now a slave
has no permanent place in the family, but a son belongs to it forever.
So if the Son sets you free, you will be free indeed.
        John 8:34-36
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--KFztAG8eRSV9hGtP
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzOxugACgkQO8l8XBKTpRTRIACeOP5QFujSo5EtgPYpSdyl0uNJ
g3QAnRLgeUhx1q28GoArGa62NCSaNnu/
=CR93
-----END PGP SIGNATURE-----

--KFztAG8eRSV9hGtP--



From jay.jordan@eds.com  Tue Apr 30 17:23:46 2002
From: jay.jordan@eds.com (Jordan, Jay)
Date: Tue, 30 Apr 2002 11:23:46 -0500
Subject: [Tutor] Multifunction mapping
Message-ID: <B6C890CB5E29D211A78B00A02461EDE91460AA81@USPLM209>

how would it be possible to multi finction a map statement. Consider the
following. 

I have a sequence of characters  (a,b,c,d,e,f,g,h,i)
I want to convert the whole list to their ascii codes (ord)
(61,62,63,64,65,66,67,68,69)
I want to zfill them all to three digits
(061,062,063,064,065,066,067,068,069)
and then concatenate the whole list into a single string
(061062063064065066067068069)

Can that be done with a single map statement? Python is such an elegant
language for doing big complicated things with just a very few statements so
I am certan there has to be a better way than running through the list one
at a time or mapping, writing, mapping, writing, mapping, writing.

Thanks
Jay




From dman@dman.ddts.net  Tue Apr 30 17:37:30 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 30 Apr 2002 11:37:30 -0500
Subject: [Tutor] How can I do IP_MASQ by using Python?
In-Reply-To: <001b01c1effa$3c41eb20$34461e0a@gege>
References: <20020428190554.GC18030@dman.ddts.net> <067b01c1ef7e$3d6a9f00$34461e0a@gege> <20020429205315.GB709@dman.ddts.net> <001b01c1effa$3c41eb20$34461e0a@gege>
Message-ID: <20020430163730.GC13577@dman.ddts.net>

--iFRdW5/EC4oqxDHL
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Apr 30, 2002 at 11:50:51AM +0800, Wenlong Liu wrote:
| I want it can be run under linux/windows. so cannot related to iptables.
| That means I need a lonely deamon to accept packages, rewite and redirect
| them.

How will you manage to get packets into the daemon?  Suppose you have
a gateway server with addresses 192.168.0.1 and 65.107.69.216 and a
client with address 192.168.0.10.  You make your daemon and have it
listen on 192.168.0.1:2427.  However the client sends the packets out
with a destination address of 64.213.121.140.  Your daemon will never
see the packet because the kernel's routing will see that it isn't
destined for the gateway server.  That's why you need iptables to
redirect (DNAT) that packet to the gateway machine itself where your
daemon will happily mangle and resend it to the real destination.  The
daemon itself isn't related to iptables, but you need to use IP-level
DNAT to get the packets to the daemon.  I have no clue if any part of
windows is capable of that sort of functionality.  The only other
alternative I can think of is to have the client send the packets to
192.168.0.1 instead of 64.213.121.140.  If the client does that,
though, I don't know how your daemon would be able to determine the
"real" destination.

HTH,
-D

--=20

"...In the UNIX world, people tend to interpret `non-technical user' as
meaning someone who's only ever written one device driver."
    --Daniel Pead
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--iFRdW5/EC4oqxDHL
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzOyEoACgkQO8l8XBKTpRRldgCdFvepgOo0DZr+Kjqh1jivHIbK
Hm8AoKZVkDYdC1rih57hwxWK5RBWq92n
=ZFu7
-----END PGP SIGNATURE-----

--iFRdW5/EC4oqxDHL--



From dman@dman.ddts.net  Tue Apr 30 17:46:19 2002
From: dman@dman.ddts.net (dman)
Date: Tue, 30 Apr 2002 11:46:19 -0500
Subject: [Tutor] Multifunction mapping
In-Reply-To: <B6C890CB5E29D211A78B00A02461EDE91460AA81@USPLM209>
References: <B6C890CB5E29D211A78B00A02461EDE91460AA81@USPLM209>
Message-ID: <20020430164619.GD13577@dman.ddts.net>

--hoZxPH4CaxYzWscb
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Apr 30, 2002 at 11:23:46AM -0500, Jordan, Jay wrote:
| how would it be possible to multi finction a map statement.

You only use 1 function.  The complexity of that function is up to
you.

| Consider the following.=20
|=20
| I have a sequence of characters  (a,b,c,d,e,f,g,h,i)
| I want to convert the whole list to their ascii codes (ord)
| (61,62,63,64,65,66,67,68,69)

That's not right.  'a' =3D> 97.  'A' =3D> 65.

| I want to zfill them all to three digits
| (061,062,063,064,065,066,067,068,069)
|
| and then concatenate the whole list into a single string
| (061062063064065066067068069)

reduce(
    # here's the concatenate function
    lambda s1 , s2 : s1+s2 ,
    map(
        # here's the formatting function
        lambda ch : "%3.3d" % ord(ch) ,
        # here's the data, a sequence of characters
        ('A','B','C','D','E','F','G','H','I')
    )
)


It would also work like this :

reduce(
    lambda s1 , s2 : s1+s2 ,
    map(
        lambda ch : "%3.3d" % ord(ch) ,
        'ABCDEFGHI'
    )
)


| Can that be done with a single map statement?

Yep.

| Python is such an elegant language for doing big complicated things
| with just a very few statements so

It is.  This example works a lot like LISP or Scheme due to the
functional-style of processing the list.

-D

--=20

All a man's ways seem innocent to him,
but motives are weighed by the Lord.
        Proverbs 16:2
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--hoZxPH4CaxYzWscb
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzOylsACgkQO8l8XBKTpRSm/ACdE7vt3QRtR4QJImv4LScCVAr8
Y6cAnRuFtdeX4Y41/Suk4Kb7gK7/u9Re
=sZR2
-----END PGP SIGNATURE-----

--hoZxPH4CaxYzWscb--



From scarblac@pino.selwerd.nl  Tue Apr 30 17:43:55 2002
From: scarblac@pino.selwerd.nl (Remco Gerlich)
Date: Tue, 30 Apr 2002 18:43:55 +0200
Subject: [Tutor] Multifunction mapping
In-Reply-To: <B6C890CB5E29D211A78B00A02461EDE91460AA81@USPLM209>; from jay.jordan@eds.com on Tue, Apr 30, 2002 at 11:23:46AM -0500
References: <B6C890CB5E29D211A78B00A02461EDE91460AA81@USPLM209>
Message-ID: <20020430184355.A30445@pino.selwerd.nl>

On  0, "Jordan, Jay" <jay.jordan@eds.com> wrote:
> how would it be possible to multi finction a map statement. Consider the
> following. 
> 
> I have a sequence of characters  (a,b,c,d,e,f,g,h,i)
> I want to convert the whole list to their ascii codes (ord)
> (61,62,63,64,65,66,67,68,69)
> I want to zfill them all to three digits
> (061,062,063,064,065,066,067,068,069)

zfill? I don't know what that is.

I'll assume you want to convert them into strings, filling them to three
characters with leading zeroes when necessary.

> and then concatenate the whole list into a single string
> (061062063064065066067068069)
> 
> Can that be done with a single map statement? Python is such an elegant
> language for doing big complicated things with just a very few statements so
> I am certan there has to be a better way than running through the list one
> at a time or mapping, writing, mapping, writing, mapping, writing.

Shorter is not better. Clearer is better. Something can be obfuscated both
by making it too short and by making it too verbose.

The shortest way to do this is

L = "abcdefghij"

s = ''.join(map(lambda x: '%03d' % ord(x), L))

or with a list comprehension, even shorter:

s = ''.join(['%03d' % ord(x) for x in L])

Personally I don't think this is the best way though - too much happens on
one line. I'd prefer

import string

L = "abcdefghij"
ords = [ord(x) for x in L]
strs = ['%03d' % o for o in ords]
s = string.join(strs, '')

Although maybe this is slightly too much on the verbose side, it is easier
to see which steps are taken.

Note the use of the % string formatting operator to get a number that's
filled up with leading zeroes, and string.join(list, '') or ''.join(list) to
join the parts together with nothing in between.

-- 
Remco Gerlich



From dyoo@hkn.eecs.berkeley.edu  Tue Apr 30 18:27:19 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Apr 2002 10:27:19 -0700 (PDT)
Subject: [Tutor] Multifunction mapping
In-Reply-To: <B6C890CB5E29D211A78B00A02461EDE91460AA81@USPLM209>
Message-ID: <Pine.LNX.4.44.0204300935110.7823-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Apr 2002, Jordan, Jay wrote:

> how would it be possible to multi finction a map statement. Consider the
> following.
>
> I have a sequence of characters  (a,b,c,d,e,f,g,h,i)
> I want to convert the whole list to their ascii codes (ord)
> (61,62,63,64,65,66,67,68,69)
> I want to zfill them all to three digits
> (061,062,063,064,065,066,067,068,069)
> and then concatenate the whole list into a single string
> (061062063064065066067068069)
>
> Can that be done with a single map statement? Python is such an elegant
> language for doing big complicated things with just a very few
> statements so I am certan there has to be a better way than running
> through the list one at a time or mapping, writing, mapping, writing,
> mapping, writing.

It's possible to do most of what you want with a single map:

###
>>> ''.join(map(lambda l: "%03d" % ord(l), letters))
'097098099100101102103104105'
###

We need a little extra to join the elements into a single string, because
mapping across a list will return a list of the results.


Python offers an alternative syntax for this using list comprehensions:

###
>>> ["%03d" % ord(l) for l in letters]
['097', '098', '099', '100', '101', '102', '103', '104', '105']
###


Good luck!




From ak@silmarill.org  Tue Apr 30 18:50:34 2002
From: ak@silmarill.org (Andrei Kulakov)
Date: Tue, 30 Apr 2002 13:50:34 -0400
Subject: [Tutor] more newbie questions
In-Reply-To: <20020430104320.GA10071@fede2.tumsan.fi>
References: <20020430104320.GA10071@fede2.tumsan.fi>
Message-ID: <20020430175034.GA11241@ak.silmarill.org>

On Tue, Apr 30, 2002 at 01:43:20PM +0300, urgrue wrote:
> thanks to everyone who helped me out with my first post.
> i'm getting a python book today so hopefully then i'll have less to 
> post about ;)
> 
> just a couple little questions:
> 1. how to simply clear the screen? im using print "\n"*24  which works 
> of course, but is a bit ugly.
>
os.system("clear") on unix, os.system("cls") on windows

> 2. how can i avoid every print statement forcing a space between what 
> it prints?
>
print "%s%s%d" % (mystr, mystr2, myint)

or sys.stdout.write(blah); sys.stdout.write(drah)
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org



From urgrue@tumsan.fi  Tue Apr 30 21:01:34 2002
From: urgrue@tumsan.fi (urgrue)
Date: Tue, 30 Apr 2002 23:01:34 +0300
Subject: [Tutor] more newbie questions
In-Reply-To: <010d01c1f039$9194e160$12f6c50a@LDR.local>
References: <20020430104320.GA10071@fede2.tumsan.fi>
Message-ID: <5.1.0.14.0.20020430225652.00aa12a0@mail.tumsan.fi>

>You can try <Ctrl+L> in command-line Python on *NIX OSes.

is there no cross-platform alternative?
well, i guess print "\n"*24 is fine, its just a bit sloppy.

> >>> print "this", "is", "a", "test"
>this is a test
> >>> print "this" + "is" + "a" + "test"
>thisisatest

thanks, thats what i wanted indeed. but, how would this be done for example 
in this case:
grid = [[1,2,3],[4,5,6],[7,8,9]]
for row in grid:
         for column in row:
                 print column,
         print

now this does:
1 2 3
4 5 6
7 8 9
but i need:
123
456
789

thanks,
fred




From pythontutor@venix.com  Tue Apr 30 21:31:44 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 30 Apr 2002 16:31:44 -0400
Subject: [Tutor] more newbie questions
References: <20020430104320.GA10071@fede2.tumsan.fi> <5.1.0.14.0.20020430225652.00aa12a0@mail.tumsan.fi>
Message-ID: <3CCEFF30.3070704@venix.com>

 >>> for row in grid:
... 	print "%s%s%s" % tuple(row)
... 	
123
456
789

Then I had a brain storm for when you don't know the size of the
row:
 >>> for row in grid:
... 	fmt = "%s" * len(row)
... 	print fmt % tuple(row)
... 	
123
456
789

You will need to get a better format if you have digits of differing widths.

Each print after a "print ," will introduce a leading space.


urgrue wrote:

> 
>> You can try <Ctrl+L> in command-line Python on *NIX OSes.
> 
> 
> is there no cross-platform alternative?
> well, i guess print "\n"*24 is fine, its just a bit sloppy.
> 
>> >>> print "this", "is", "a", "test"
>> this is a test
>> >>> print "this" + "is" + "a" + "test"
>> thisisatest
> 
> 
> thanks, thats what i wanted indeed. but, how would this be done for 
> example in this case:
> grid = [[1,2,3],[4,5,6],[7,8,9]]
> for row in grid:
>         for column in row:
>                 print column,
>         print
> 
> now this does:
> 1 2 3
> 4 5 6
> 7 8 9
> but i need:
> 123
> 456
> 789
> 
> thanks,
> fred
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From dyoo@hkn.eecs.berkeley.edu  Tue Apr 30 21:55:47 2002
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 30 Apr 2002 13:55:47 -0700 (PDT)
Subject: [Tutor] more newbie questions
In-Reply-To: <3CCEFF30.3070704@venix.com>
Message-ID: <Pine.LNX.4.44.0204301345130.17552-100000@hkn.eecs.berkeley.edu>


On Tue, 30 Apr 2002, Lloyd Kvam wrote:

>  >>> for row in grid:
> ... 	print "%s%s%s" % tuple(row)
> ...
> 123
> 456
> 789
>
> Then I had a brain storm for when you don't know the size of the
> row:
>  >>> for row in grid:
> ... 	fmt = "%s" * len(row)
> ... 	print fmt % tuple(row)
> ...
> 123
> 456
> 789


Here's an alternative way of doing it, but it needs a little more care:

###
>>> def printgrid(grid):
...     for row in grid:
...         stringed_row = map(str, row)
...         print ''.join(stringed_row)
...
>>> grid = [[1, 2, 3],
...         [4, 5, 6],
...         [7, 8, 9]]
>>>
>>> printgrid(grid)
123
456
789
###

One part of the printgrid() definition might seem a little weird, so it
might be good to mention it. The reason why printGrid() does a
'map(str, row)' thing right before the joining is because string
joining assumes that it's joining a list of strings:

###
>>> print ''.join(['one', 'two', 'three'])
onetwothree
>>>
>>> print ''.join([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found
###

and trying to string.join() a list of numbers will result in a TypeError,
warning us that we're doing something potentially suspicious.

The map() is there to apply the str()ing function on every element of row,
and collects all those results into stringed_row, so that the
string.join() can work.




From pythontutor@venix.com  Tue Apr 30 23:09:27 2002
From: pythontutor@venix.com (Lloyd Kvam)
Date: Tue, 30 Apr 2002 18:09:27 -0400
Subject: [Tutor] more newbie questions
References: <Pine.LNX.4.44.0204301345130.17552-100000@hkn.eecs.berkeley.edu>
Message-ID: <3CCF1617.6060803@venix.com>

At the risk of totally beating this kind of subject to death, I had
written a short program to produce pascal triangles.  I've used it
for up to 20 rows (actually 0 - 20).  I used the new fractional
division so this won't work on an old version.

from __future__ import division

def fact(n,r=None):
	if r is None: r = n
	assert 0 <= r <= n, "r must be between 0 and n"
	if r > 1:
		return n * fact(n-1, r-1)
	else:
		return n or 1	# 0! == 1

def combo(n, r=None):
	if r is None: r = int(n/2)
	assert 0 <= r <= n, "r must be between 0 and n"
	return int(fact(n,r)/fact(r))

def pascal(rows=5):
	numlen = len(str(combo(rows)))
	for i in range(rows+1):
		indent = int( (numlen+1)*((rows - i)/2))
		print " "*indent,
		for r in range(i+1):
			ptn = combo(i,r)
			# attempt to center numbers in their slot
			ptnlen = len(str(ptn))
			ptnpad = int((numlen - ptnlen + 1) / 2)
			ptnlen = numlen - ptnpad
			print "%*s%s" % (ptnlen, ptn, " "*ptnpad),
		print

pascal()

Danny Yoo wrote:

> 
> On Tue, 30 Apr 2002, Lloyd Kvam wrote:
> 
> 
>> >>> for row in grid:
>>... 	print "%s%s%s" % tuple(row)
>>...
>>123
>>456
>>789
>>
>>Then I had a brain storm for when you don't know the size of the
>>row:
>> >>> for row in grid:
>>... 	fmt = "%s" * len(row)
>>... 	print fmt % tuple(row)
>>...
>>123
>>456
>>789
>>
> 
> 
> Here's an alternative way of doing it, but it needs a little more care:
> 
> ###
> 
>>>>def printgrid(grid):
>>>>
> ...     for row in grid:
> ...         stringed_row = map(str, row)
> ...         print ''.join(stringed_row)
> ...
> 
>>>>grid = [[1, 2, 3],
>>>>
> ...         [4, 5, 6],
> ...         [7, 8, 9]]
> 
>>>>printgrid(grid)
>>>>
> 123
> 456
> 789
> ###
> 
> One part of the printgrid() definition might seem a little weird, so it
> might be good to mention it. The reason why printGrid() does a
> 'map(str, row)' thing right before the joining is because string
> joining assumes that it's joining a list of strings:
> 
> ###
> 
>>>>print ''.join(['one', 'two', 'three'])
>>>>
> onetwothree
> 
>>>>print ''.join([1, 2, 3])
>>>>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: sequence item 0: expected string, int found
> ###
> 
> and trying to string.join() a list of numbers will result in a TypeError,
> warning us that we're doing something potentially suspicious.
> 
> The map() is there to apply the str()ing function on every element of row,
> and collects all those results into stringed_row, so that the
> string.join() can work.
> 
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582




From paulsid@shaw.ca  Tue Apr 30 22:52:00 2002
From: paulsid@shaw.ca (Paul Sidorsky)
Date: Tue, 30 Apr 2002 15:52:00 -0600
Subject: [Tutor] Multifunction mapping
References: <B6C890CB5E29D211A78B00A02461EDE91460AA81@USPLM209>
 <20020430164619.GD13577@dman.ddts.net>
Message-ID: <3CCF1200.7C21E5D5@shaw.ca>

dman wrote:

> | I have a sequence of characters  (a,b,c,d,e,f,g,h,i)
> | I want to convert the whole list to their ascii codes (ord)
> | (61,62,63,64,65,66,67,68,69)
> 
> That's not right.  'a' => 97.  'A' => 65.

Tsk, doesn't anybody speak hex anymore?  :-)

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/