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: 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: 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: 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 > 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: 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: > 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: [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: ; from tim.one@comcast.net on Mon, Apr 01, 2002 at 01:19:47AM -0500 References: <20020401001924.A25655@client156-52.ll.siue.edu> 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: [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 >'' > >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: 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: 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" 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 Subject: Re: [Tutor] hacking 101 To: tutor 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" 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"
 >  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-- --__--__-- 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. 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. 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 To: tutor Subject: Re: [Tutor] hacking 101 * Remco Gerlich [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 "

Could somene please me to a simple = heloworld cgi script written in python?


TIA

-ScottTavares-

------_=_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: 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("", 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: 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: 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: ', '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" ', 'From: BrainyQ= uote Who Said That ', 'Subject: Who Said That? Websit= es...', 'Sender: ', '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: 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: References: 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

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-- 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: > > 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: 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" To: "Eve Kotyk" Cc: 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: References: <20020406184055.6260e81d.e.kotyk@shaw.ca> 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: > > 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: 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: > > 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: 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: > > 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: 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: 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: 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: References: <20020406201222.7cffb0bd.e.kotyk@shaw.ca> 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: 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: 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
Hi all,
 
If you make a compound list like = this:
 
>>> l =3D = ["1","1","1"]
>>> ll =3D=20 ["2","2","2"]
>>> lll=3D ["3","3","3"]
>>> ll = =3D=20 [l,l,l]
>>> lll =3D [ll,ll,]
>>> lll
[[['1', = '1', '1'],=20 ['1', '1', '1'], ['1', '1', '1']], [['1', '1', '1'], ['1', '1', '1'], = ['1', '1',=20 '1']]]
 
are you making a matrix?
 
Cameron
------=_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: 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: Message-ID: 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: 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: Message-ID: 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" To: 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: References: Message-ID: 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: 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: 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: Message-ID: <21FDB4C8-4A70-11D6-B17B-00039351FE6A@mac.com> On Thursday, April 4, 2002, at 10:56 AM, 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: [ 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" To: ; ; 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" To: ; ; 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

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-- 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 ------_=_NextPart_001_01C1DE7E.E3B28E60 Content-type: text/html; 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

 
------_=_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: 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 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> 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: > 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: 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
Hi all,
 
Can you declare variable types like in = C++ in=20 Python.
example:
 
int variableName =3D 0
float variableName =3D 0.0
char variableName =3D " "
 
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.
 
Thanks for any help on = this,
Cameron = Stoner
------=_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: Message-ID: 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: Message-ID: 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: Message-ID: <200204072313.g37NDul08400@smtp2.fas.harvard.edu>
Cameron,
 
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:
 
list =3D []    # I have to make sure Python= knows this will be a list
list.append("a")
 
There is little real advantage of saying "variable =3D= 0" at the top of the program, because it seems to me there= is nothing preventing you from assigning a string to this= "variable" twenty lines down in Python. Or maybe I am= just missing the point ... :)
 
Cheers,
 
Pijus
--
All bad precedents began as justifiable measures. -- Gaius= Julius Caesar, quoted in "The Conspiracy of Catiline",= by Sallust
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: 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: 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: Message-ID: 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: | 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: References: 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: > > 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: 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: 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: Message-ID: > 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: Message-ID: > 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> 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: 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: 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, =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: 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: References: Message-ID: 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: Message-ID: <3CB1DF6E.745B2BF4@ccvcorp.com> > sentinel805 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: 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

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-- 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: Message-ID: 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: 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 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-- 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: 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" >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: 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('', 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: References: 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" 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 "", 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: 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: References: 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: 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
Hi all,
 
Is it a good or bad idea to call = functions with in=20 functions?  What could you do to not have functions calling = functions? I=20 have given an example of this bellow.
 
def splitter(sentence):
 import = string
 list =3D string.split(sentence, sep=3D" = ")
 return=20 list
 
# Encrypt sentences
def=20 encryptsent(sentence):
 list =3D splitter(sentence) # list is = the list of=20 the
      # the words in the=20 sentence
 count_of_sent =3D len(list)
 count =3D = count_of_sent - 1 #=20 -1 of count_of_sent to account for slicing
 # initialize=20 variables
 x =3D 0
 list_sentence =3D = []
 
 while x=20 <=3D count: # x is the counter of each word to be = processed
  word=20 =3D list[x]
  word_encrypted =3D encrypting(word) # encrypt = word
  
  quashed_word =3D = flow(word_encrypted) # mash=20 character = encryption
          #=20 together
  list_sentence.append(quashed_word)
  = ;
  x=20 =3D x + 1
  message =3D = flow(list_sentence)
 
 return=20 message
 
Thanks,
Cameron Stoner
 
 
------=_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: Message-ID: 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: Message-ID: 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: Message-ID: <200204092228.g39MSv313374@smtp1.fas.harvard.edu>
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.
 
Cheers,
 
Pijus
--
All bad precedents began as justifiable measures. -- Gaius= Julius Caesar, quoted in "The Conspiracy of Catiline",= by Sallust
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: 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 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: 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: 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: References: 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 >>> 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: 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: 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: 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 "", 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: 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: 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: > > 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: 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: Message-ID: > 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: Message-ID: > 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 >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 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 >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: 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: 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: > 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: <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, ): self.bind("", self.update_graphics) #IMPORTANT def onUpdate(self): if self.winfo_viewable: #this guy exists so we can also update from outside #the class (but only if we can see it) 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: 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: Message-ID: I put your test code in and it give me this error: diffed_square = diff(square) Traceback (most recent call last): File "", 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 > > 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: <4.3.2.7.2.20020404175549.00cd99f0@pop3.norton.antivirus> Message-ID: 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 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: References: Message-ID: 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 "", 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 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: 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 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: Message-ID: 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 "", 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: 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 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: References: 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: Message-ID: 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 >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: 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 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: <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: Message-ID: 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 | | 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: [ 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 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: 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: 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__ >>> 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: > 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: 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: > 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" 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 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: 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: 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: 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
, since
has two more bytes than you really need and it can add up if you use a lot of
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: 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: 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: >> 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 >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: References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C53D@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020411094639.A22173@tor.dhs.org> * Karthik Gurumurthy [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: References: Message-ID: 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: <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> <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 [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. <> <> ------_=_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: 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 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: 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: 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: 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: 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: 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: 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 > 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: Message-ID: 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: References: Message-ID: 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 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: 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 ? > 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 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: 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 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" >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 Subject: Re: [Tutor] The Evil eval() To: Sean 'Shaleh' Perry 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 . 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 >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: 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. 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 #include 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: <0F757892D113D611BD2E0002559C1FF465BAA0@EMAIL> References: <0F757892D113D611BD2E0002559C1FF4637FE0@EMAIL> <0F757892D113D611BD2E0002559C1FF465BAA0@EMAIL> Message-ID: Hi, On Fri, 12 Apr 2002 Guido Goldstein spewed into the ether: > > Hi! > > On Fri, 12 Apr 2002 04:29:27 -0400 > Prahlad Vaidyanathan wrote: > [...] > > http://www.symonds.net/~prahladv/files/MailMsg.py > > > You're not authorized to view this document > The permissions set on this file says you can't view it. > Oops ! Pardon my faux pas. The perms have been fixed - so try again now. pv. -- Prahlad Vaidyanathan 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: Hi, On Fri, 12 Apr 2002 Alexandre Ratti spewed into the ether: [-- snippity --] > Here is a definition I came across: > > > 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 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 [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: 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

 

 

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 =3D ['maude', 'claire', = 'eudelle']

 

class pip:

       &nbs= p;    def __init__(self, name, number):

       &nbs= p;           &nbs= p;    self.name =3D name

       &nbs= p;           &nbs= p;    self.number =3D number

 

for name in = names:

       &nbs= p;    name =3D 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:

       &nbs= p;    def __init__(self, name, number):

       &nbs= p;           &nbs= p;    self.__name__ =3D name

       &nbs= p;           &nbs= p;    self.number =3D number

 

for name in = names:

       &nbs= p;    dynapip(name, counter)

       &nbs= p;    counter =3D 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<= font size=3D2 face=3D"Courier New">~

 

------_=_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 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 >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
Sir/Madam,
          &nbs= p;     =20 Please unsubscribe me from the mailing list because i am recieving too = much=20 mail.
          &nbs= p;            = ;            =             &= nbsp;      =20 Thanking you in anticipation.
          &nbs= p;            = ;            =             &= nbsp;  =20 Your's faithfully,
          &nbs= p;            = ;            =    =20 telepathy@vsnl.com
 
------=_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: > 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: 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: 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: 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" > 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: 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" To: "Carlo Bifulco" Cc: 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
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)-- 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: Message-ID: 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: 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 "", 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: Message-ID: 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 "", 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: 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 "", 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 >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 "", 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 "", 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: 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
Hi all,
 
How do you approach error trapping and = use=20 exceptions in Python to take care of it?  How do you for all the = possible=20 dumb user mistakes?  I mean give me the kind of thought process of = how I=20 should go about thinking this through in planning my = program.
 
Thanks guys for your help,
 
Cameron = Stoner
------=_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: 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: Message-ID: 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: Message-ID: > > 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: 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: References: Message-ID: 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: Message-ID: 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 with the representation 3 >>> f[3:10] I see with the representation slice(3, 10, None) >>> f[3:2:10] I see with the representation slice(3, 2, 10) >>> f[:10] I see with the representation slice(0, 10, None) >>> f[10:] I see 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__ >>> t.__setslice__ ### 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: 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
Hi all,
 
I am currently writing and teaching my = brother how=20 to program, cause he says he wants to make his own computer games.  = 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?  I didn't really start at either one.  I started = with the=20 Python tutorials and that didn't go to far at first.  I am trying = to help=20 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-- 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: ; from wolf_binary@hotmail.com on Sun, Apr 14, 2002 at 03:21:56PM -0500 References: Message-ID: <20020414222924.A2902@pino.selwerd.nl> On 0, Cameron Stoner 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: 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
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
------=_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: References: 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: . 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: and Alan Gauld's "How to Program": . 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 . 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: 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 "", line 1, in ? File "", 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: <20020414101018.GD263@st-annes.oxford.ac.uk> Message-ID: 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: <20020414101018.GD263@st-annes.oxford.ac.uk> 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: Message-ID: 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: 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 ------_=_NextPart_001_01C1E45F.222683A0 Content-type: text/html; 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

 
------_=_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 ------_=_NextPart_001_01C1E460.8BA95BD0 Content-type: text/html; 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

------_=_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" 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" 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: 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: ; from jay.jordan@eds.com on Mon, Apr 15, 2002 at 11:03:56AM -0500 References: Message-ID: <20020415182823.A8012@pino.selwerd.nl> On 0, "Jordan, Jay" 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: Message-ID: <000d01c1e4b1$a4f8d600$51b53bd0@othello> From: "Jordan, Jay" > 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: 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: 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: 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: References: 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: References: <20020411191424.GA24388@dman.ddts.net> 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" To: 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: 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 >To: "'python'" , "'python'" >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: 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: 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: References: Message-ID: 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: 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: References: 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: References: 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: 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: Message-ID: 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: References: 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: Message-ID: 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]) >>> 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]) >>> 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: 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: # 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 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: 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: > > 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: 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 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: References: 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: | | | # 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 | | | 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: 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

 

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<= font size=3D2 face=3D"Courier New">~

 

------_=_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 Similar guides can be found on the other online tutorials. You will probably need to do some string manipulation too: -- 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 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: 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." > | > > | > > | > Search the tutor archives. With only a couple minor modifications = the > | > answer is already there. > | > > | > | 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: > > 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: 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: Message-ID: 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 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: Message-ID: 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 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: Message-ID: 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 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: 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 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 RE: [Tutor] Getting range to produce float lists

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.wi= lliams@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 =3D 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)-- 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" >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 >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: 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: > 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) >>> 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: 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: 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: 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: ------=_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
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?
------=_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: 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: References: Message-ID: 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: ------=_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
I was wonderin= g where I could find an interperter?

------=_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" To: > 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 "", line 1, in ? input('gimme an expression: ') File "", 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" To: > 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 "", line 1, in ? input('gimme an expression: ') File "", 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: 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: 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) > > >>> 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 = "" self.delTag = "%s" self.insTag = "%s" 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 generation pythonista raised in the shadows of the Cold War assumes new responsibilities in a world warmed by the sunshine of spam and 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" > To: > > > 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 "", line 1, in ? > input('gimme an expression: ') > File "", 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
Dear sir,
 
I require a set of multiple choice = question test=20 papers for my company. I searched a lot but could not find = any.
 
These tests are preliminary tests for = new=20 recruitments in our company.
 
I require atmost 30 = questions.
 
Could you help with me this...like any = website you=20 know that has such stuff.
 
regards,
Amit.
 
------=_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" 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: References: <20020418184245.B11174@localhost.localdomain> 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: 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: On Friday, April 19, 2002, at 09:54 PM, 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: Message-ID: 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: 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: References: Message-ID: 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.

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

 
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
 and 
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
 
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
 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 
 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: 

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: 
References: 
Message-ID: 

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: 

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: 

[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 "", 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: 
References:  
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: 

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 
>To: "Daryl Gallatin" , 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. 

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

 
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
 and 
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
 
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
 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 
 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: 
Message-ID: 

> ###
> 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: 

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: 

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
|               (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: 
References: 
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""

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: 
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: 
References: 
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: 
References: 
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: 


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: 

>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: 

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








Hi all,
 
How do you clear the screen?  Is = there a=20 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=20 through the modules without much luck.
 
Thanks for any help,
Cameron = Stoner
------=_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: 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: References: 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: Message-ID: > 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: 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
I guess what I meant was to change it = into the 0s=20 and 1s of every key on the keyboard.
 
Right now I have a dictionary that = holds all the=20 values, but I would like to remove the need for it if possible.  = ei: dict =3D=20 {'A':'01000001','B':'01000010','C':'01000011','D':'01000100'}  This = is the=20 machine lanuage or what ever the proper term is.  I am not = sure.  I=20 was calling it binary.
 
Thanks,
Cameron
 
------=_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: 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: --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

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-- 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: References: Message-ID: > 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: References: Message-ID: > 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: 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: 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" 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 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: 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> 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> 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> <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: >From: Kirby Urner >To: "Daryl Gallatin" , 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> <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

What are linked lists and do you need = them in=20 Python?
 
Thanks,
Josh
------=_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: 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: 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 "", 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: Message-ID: > 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: 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: Message-ID: 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: 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"

> 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_=-- 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

 

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-- 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
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.
 
Josh
----- Original Message -----
From:=20 Josh=20 Gregorio
Sent: Tuesday, April 23, 2002 = 10:20=20 AM
Subject: [Tutor] lists

What are linked lists and do you need = them in=20 Python?
 
Thanks,
Josh
------=_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: 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: Message-ID: >>> 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: 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
I think you can use chr() and ord() to = switch=20 between ascii characters and their numbers.
>>>chr(35)
'#'
>>>ord('#')
35
>>>chr(33)
'!'
>>>ord('!')
33
 
 
Josh
 
----- Original Message -----
From:=20 Cameron=20 Stoner
Sent: Sunday, April 21, 2002 = 4:10=20 PM
Subject: [Tutor] slearing the=20 screen

Hi all,
 
How do you clear the screen?  Is = there a=20 command like in C++ to clear the screen in Python?  Also is there = a=20 function for turning numbers and letters into ASCII?  I have been = going=20 through the modules without much luck.
 
Thanks for any help,
Cameron=20 Stoner
------=_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: 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: Message-ID: > > 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: 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: ; from wesleyabbott@hotmail.com on Wed, Apr 24, 2002 at 04:02:41PM -0600 References: Message-ID: <20020425001128.A30029@pino.selwerd.nl> On 0, Wesley Abbott 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: Message-ID: > ># 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" 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: 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 To: 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 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" > 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: > 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 "", 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 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: 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: References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C56E@mbtlipnt02.btlabs.bt.co.uk> 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: > 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: > 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 . 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" 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-- 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: 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> <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: 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

Hi all,
 
When using OOP practices for the first = time, but=20 understand how to use it.  How do you design how it should work? = Like=20 flowcharts and psuedo code is used for designing functions and basic=20 programs.  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.  I need some way to design my programs graphically = or with a=20 pseudo code like fashion only with objects and classes in mind.  = Does any=20 body have any suggestions?
 
Thanks,
Cameron = Stoner
------=_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 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: 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 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 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: 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: 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 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 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: Message-ID: <200204251827.g3PIRFk19988@smtp4.fas.harvard.edu>
Danny,
 
wow, that was a great illustration of a programming= concept!
 
>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.
 
-P
 
--
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
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: --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

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-- 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: Message-ID: 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: ; from stuart_clemons@us.ibm.com on Thu, Apr 25, 2002 at 03:19:49PM -0400 References: 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. **************************** 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: 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" 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-- 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: 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: References: 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: <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: 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) >>> class test(object): pass >>> t = test() >>> type(t) >>> > (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"


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_=-- 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: 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: > 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: 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 Fri Apr 26 07:00:54 2002 From: lonetwin (lonetwin) Date: Fri, 26 Apr 2002 11:30:54 +0530 (IST) Subject: [Tutor] better map/lambda solution needed Message-ID: 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: Message-ID: > 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: ; from lonetwin@yahoo.com on Fri, Apr 26, 2002 at 11:30:54AM +0530 References: Message-ID: <20020426081309.A6075@pino.selwerd.nl> On 0, lonetwin 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 Fri Apr 26 07:12:34 2002 From: lonetwin (lonetwin) Date: Fri, 26 Apr 2002 11:42:34 +0530 (IST) Subject: [Tutor] better map/lambda solution needed (fwd) Message-ID: 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 To: Python Tutor list 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: ; from steve@yahoo.com on Fri, Apr 26, 2002 at 11:42:34AM +0530 References: Message-ID: <20020426083338.A6204@pino.selwerd.nl> On 0, lonetwin 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"

>  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-- 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: 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: --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

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-- From lonetwin Fri Apr 26 09:51:52 2002 From: lonetwin (lonetwin) Date: Fri, 26 Apr 2002 14:21:52 +0530 (IST) Subject: [Tutor] better map/lambda solution needed (fwd) Message-ID: 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 Reply-To: lonetwin To: Python Tutor list 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 To: Python Tutor list 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" : elif subval > "0009" and subval < "0020" : ........ 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 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-- 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: > > 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" : > > elif subval > "0009" and subval < "0020" : > > ........ > (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: > 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 ### 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: Message-ID: [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 > > ### > > That's probably one way of doing it. Here is another: >>> input = 'blah' >>> input 'blah' >>> input = __builtins__['input'] # Note the trailing 's' >>> 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: > 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: <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: <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: <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: References: <3CC98812.38670CBB@rg16.asn-wien.ac.at> 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 >>> input =3D "foo" >>> input 'foo' >>> del input >>> 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: <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. | | elif subval > "0009" and subval < "0020" : | | ........ Change 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: > | 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. > > | > | elif subval > "0009" and subval < "0020" : > | > | ........ 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: //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: References: 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 | ------------- . 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: <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 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

\\ 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 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 =3D raw_input(“What’s = the password? “)

if password !=3D “whatever”

    branch(“:end”)<= /p>

#---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 =3D 1

def wait():

    wait =3D raw_input("Press = [Enter]")

name =3D raw_input("What's your = first name? ")

print "Welcome to the calculator,", = name

wait()

while mask =3D=3D 1:

    print ""

    print ""

    print "1: Add"

    print "2: Subtract"

    print "3: Multiply"

    print "4: Divide"

    print "5: Exponents"

    print "9: Exit"

    print ""

    action =3D input("What will you do? (1|2|3|4|5|9) = ")

    if action =3D=3D 1:

        = addnum =3D = 1

        = while addnum =3D=3D = 1:

       &nbs= p;    addnum =3D input("How many numbers are you going to add? (2|3|4) = ")

       &nbs= p;    if addnum = =3D=3D 2:

       &nbs= p;        add_1 =3D input("What's the first = number? ")

       &nbs= p;        add_2 =3D input("What's the = second number? ")

       &nbs= p;        sum =3D add_1 + = add_2

       &nbs= p;        print "The sum of", add_1, "and", add_2, "is equal to", = sum

       &nbs= p;        wait()

         &nbs= p;  elif addnum =3D=3D 3:

       &nbs= p;        add_1 =3D input("What's the first = number? ")

       &nbs= p;        add_2 =3D input("What's the = second number? ")

       &nbs= p;        add_3 =3D input("What's the third = number? ")

       &nbs= p;        sum =3D add_1 + add_2 + = add_3

             &nbs= p;  print "The sum of", add_1, ",", = add_2, "and", add_3,

       &nbs= p;        print "is", = sum

       &nbs= p;        wait()

       &nbs= p;    elif addnum =3D=3D 4:

       &nbs= p;        add_1 =3D input("What's the first = number? ")

       &nbs= p;        add_2 =3D input("What's the = second number? ")

       &nbs= p;        add_3 =3D input("What's the third = number? ")

       &nbs= p;        add_4 =3D input("What's the = fourth number? ")

       &nbs= p;        sum =3D add_1 + add_2 + add_3 + = add_4

       &nbs= p;        print "The sum of", add_1, ",", add_2, ",", add_3, = "and",

       &nbs= p;        print add_4, "is equal to", = sum

       &nbs= p;        wait()

       &nbs= p;    else:

       &nbs= p;        addnum =3D = 1

    elif action =3D=3D = 2:

        sub_1 =3D input("What's the first = number? ")

        sub_2 =3D input("What's the = second number? ")

        = difference =3D sub_1 - = sub_2

        = print "the difference between", sub_1, "and", sub_2, "is", = difference

        = wait()

    elif action =3D=3D = 3:

        = mulnum =3D = 1

        = while mulnum =3D=3D = 1:

       &nbs= p;    mulnum =3D input("How many numbers are you going to multiply? (2|3) = ")

       &nbs= p;    if mulnum = =3D=3D 2:

       &nbs= p;        mul_1 =3D input("What's the first = number? ")

       &nbs= p;        mul_2 =3D input("What's the = second number? ")

       &nbs= p;        mul_4 =3D mul_1 * mul_2

       &nbs= p;        print mul_1, "multiplied = by", mul_2, "is equal to", mul_4

       &nbs= p;        wait()

       &nbs= p;    elif mulnum =3D=3D 3:

       &nbs= p;        mul_1 =3D input("What's the first = number? ")

       &nbs= p;        mul_2 =3D input("What's the = second number? ")

       &nbs= p;        mul_3 =3D input("What's the third = number? ")

        &nbs= p;       mul_4 =3D mul_1 * mul_2 * mul_3

       &nbs= p;        print mul_1, "multiplied = by", mul_2, "multiplied by", mul_3,

       &nbs= p;        print "is equal to", = mul_4

       &nbs= p;        wait()

       &nbs= p;    else:

       &nbs= p;        mulnum =3D = 1

    elif action =3D=3D = 4:

        = 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", div_4

        = wait()

    elif action =3D=3D = 5:

        exp_1 =3D input("What's the base = number? ")

        exp_2 =3D input("What's the = exponent? ")

        exp_3 =3D exp_1 ** exp_2

        = print exp_1, "to the power of", exp_2, = "is equal to", exp_3

        = wait()

    elif action =3D=3D = 9:

        = mask =3D 2

print "Thank you,", name

end =3D 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-- 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 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: 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
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?
 
Regards
 
Ares
------=_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: 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: Message-ID: [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: 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: 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: (Ian! verified it; it works. *grin*) ---------- Forwarded message ---------- Date: Sun, 28 Apr 2002 14:35:34 -0700 (PDT) From: Danny Yoo To: Ian! 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: 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) >>> 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 "", 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: Message-ID: 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: 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 Re: [Tutor] How can I do IP_MASQ by using = Python?
MGCP is Media Gateway Control Protocol. = IETF RFC=20 2705
http://www.iet= f.org/rfc/rfc2705.txt?number=3D2705
 

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

A MGCP=20 message is identified by the ALG using UDP port 2427 or 2727 as the = destination=20 port.  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.

Regards
 
Ares
----- Original Message ----- =
From:=20 dman
Sent: Monday, April = 29, 2002 3:05 AM
Subject: Re: [Tutor] = How can I do IP_MASQ by=20 using Python?

On Sun, Apr 28, 2002 at 03:22:40PM +0800, Ares Liu=20 wrote:
| I want to transfer MGCP packages = via NAT. Not=20 so much flux, so I think I
| can use python = to do it.=20 Does anyone can give me some advises?

I don't know what MGCP is, but all the times I've = seen the=20 terms
IPMASQ or NAT it is referring to the = IP stack of=20 a system.  The IP
stack is in the = kernel and=20 requires access to the kernel to adjust how
the=20 routing and NAT will operate.  With linux the netfilter = modules=20
provide the actual implementation and the userspace = tool=20 'iptables'
provides an interface for the = admin to=20 configure it.

Maybe if you can explain MGCP and what you want to = do with it=20 a bit
more I'll understand whether or not = python is=20 suitable for the task.

HTH,
-D

--

Python is executable pseudocode. Perl is executable = line=20 noise.
 
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg=20

------=_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: 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: References: 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" 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
Hi Folk,
I was toying with the idea = of producing=20 a suite of
matrix operations using list comprehensions. At one = point
I=20 needed to initialize a matrix so all elements were zero.
Three = possiblities=20 came to mind:
 
>>> c1 =3D = [[0]*2]*3
>>>=20 c1
[[0, 0], [0, 0], [0, 0]]
>>> c2 =3D = [[0,0]]*3
>>>=20 c2
[[0, 0], [0, 0], [0, 0]]
>>> c3 =3D=20 [[0,0],[0,0],[0,0]]
>>> c3
[[0, 0], [0, 0], [0,=20 0]]
>>> c1=3D=3Dc2=3D=3Dc3
1
>>> =
 
I believed these three matrices c1,c2 = and c3 were=20 equivalent,
but when used in the following simple matrix = multipication=20
algorithm it became evident c1 and c2 are not the 'same' as = c3.
 
>>>=20 a=3D[[1,2,3],[3,4,5],[5,6,7]]
>>>=20 b=3D[[1,1],[1,1],[1,1]]
>>> i1=3D3
>>> = j1=3D2
>>>=20 k1=3D3
>>> for i in range(i1):
 for j in=20 range(j1):
  #c[i][j]=3D0 #not necessary if c is a zero=20 matrix
  for k in=20 range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]
<= /DIV>
 
Test 1:
>>> c1 =3D=20 [[0]*2]*3
>>> c1
[[0, 0], [0, 0], [0, 0]]
>>> = c=3Dc1
>>> c
[[0, 0], [0, 0], [0, 0]]
>>> for = i in=20 range(i1):
 for j in=20 range(j1):
  #c[i][j]=3D0
  for k in=20 range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]
<= /DIV>
 
   
>>> = c
[[36, 36],=20 [36, 36], [36, 36]]
Test 2:
>>> c2 =3D = [[0,0]]*3
>>>=20 c2
[[0, 0], [0, 0], [0, 0]]
>>> c=3Dc2
>>> = c
[[0,=20 0], [0, 0], [0, 0]]
>>> for i in range(i1):
 for j = in=20 range(j1):
  #c[i][j]=3D0
  for k in=20 range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]
<= /DIV>
 
   
>>> = c
[[36, 36],=20 [36, 36], [36, 36]]
 
Test 3:
>>> c3 =3D=20 [[0,0],[0,0],[0,0]]
>>> c3
[[0, 0], [0, 0], [0,=20 0]]
>>> c=3Dc3
>>> c
[[0, 0], [0, 0], [0,=20 0]]
>>> for i in range(i1):
 for j in=20 range(j1):
  #c[i][j]=3D0
  for k in=20 range(k1):
   c[i][j]=3Dc[i][j]+a[i][k]*b[k][j]
<= /DIV>
 
   
>>> = c
[[6, 6],=20 [12, 12], [18, 18]]
>>>
 
It is only the matrix c3 which yields = the correct=20 result.
Can any of you gurus explain what is an anomaly to=20 me.
Thanks  Hugh
------=_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: 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: <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" To: 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 >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: 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: 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: References: 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: ; from jay.jordan@eds.com on Tue, Apr 30, 2002 at 11:23:46AM -0500 References: Message-ID: <20020430184355.A30445@pino.selwerd.nl> On 0, "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) 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: Message-ID: 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 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 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: 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 "", 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: 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 "", 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: <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/
>Hansel is using a linked list traversal= algorithm.  Here, it's the
>linkage --- the structural relationship= --- between the breadcrumbs
class="Three"