From bogus@does.not.exist.com Tue Dec 5 00:14:59 2000 From: bogus@does.not.exist.com () Date: Tue Dec 5 00:15:07 2000 Subject: No subject Message-ID: <199907250502.BAA05369@python.org> Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the web, visit http://www.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request@python.org You can reach the person managing the list at tutor-admin@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: PIF (fractalyze@iname.com) --__--__-- Message: 1 From: fractalyze@iname.com To: tutor@python.org Date: Sat, 24 Jul 1999 00:02:31 -0600 Subject: Re: [Tutor] PIF Reply-to: fractalyze@iname.com hey there josh - i had the same problem. if you are running python on win9x or something similar, you may want to try one of the following: a) open up a dos prompt b) at the dos prompt, type (without the quotes): "python the-py- file-you-want-to-run" when you do this, the error messages stay in the dos shell after python closes. i have made a win95(x?) file extension/association that does the same thing...check out my message at: http://x43.deja.com/[ST_rn=ps]/getdoc.xp?AN=503531232.1&CON TEXT=932745 826.1292763289&hitnum=0 (i'm not sure that link is going to work) if it doesn't, try this: go to http://www.deja.com go to power search search for: Subject: extension Author: Isidor Forum: comp.lang.python NOTE TO ANYONE ELSE READING THIS: i tried finding my message in the python-list "archives" at the python site, but it wasn't there. in fact, there are several (lots?) of messages missing from the archive. anyone know why? QUESTION: i have several newbie-related posts (i am a newbie) that i sent to comp.lang.python (tips/tools, not questions). is it ok/advisable/reasonable to cross-post them here? (E.g., reposting the message about win95(9x/NT?) file extensions/associations.) i hope that helps! take care isidor --__--__-- _______________________________________________ Tutor maillist - Tutor@python.org http://www.python.org/mailman/listinfo/tutor End of Tutor Digest _______________________________________________________________ Get Free Email and Do More On The Web. Visit http://www.msn.com From bogus@does.not.exist.com Tue Dec 5 00:14:59 2000 From: bogus@does.not.exist.com () Date: Tue Dec 5 00:15:10 2000 Subject: No subject Message-ID: <199909060503.BAA08939@python.org> Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the web, visit http://www.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request@python.org You can reach the person managing the list at tutor-admin@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. python vs VB (Hugh Marquis) 2. Re: python vs VB (Deirdre Saoirse) --__--__-- Message: 1 From: "Hugh Marquis" To: Date: Sun, 5 Sep 1999 12:22:20 -0400 boundary="----=_NextPart_000_001E_01BEF799.4CECD900" Subject: [Tutor] python vs VB This is a multi-part message in MIME format. ------=_NextPart_000_001E_01BEF799.4CECD900 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I want to begin programming and both Python and VB have been suggested = as good first languages. Although I realize you probably have some = biases could you comment on which might be better. Is Mark Lutz's book basic enough for a beginning programmer. Thanks Hugh Marquis=20 ------=_NextPart_000_001E_01BEF799.4CECD900 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I want to begin programming and both = Python and=20 VB have been suggested as good first languages.  Although I realize = you=20 probably have some biases could you comment on which might be=20 better.
 
Is Mark Lutz's book basic enough for = a beginning=20 programmer.
 
Thanks
 
Hugh = Marquis 
------=_NextPart_000_001E_01BEF799.4CECD900-- --__--__-- Message: 2 Date: Sun, 5 Sep 1999 13:08:53 -0700 (PDT) From: Deirdre Saoirse To: Hugh Marquis cc: tutor@python.org Subject: Re: [Tutor] python vs VB On Sun, 5 Sep 1999, Hugh Marquis wrote: > I want to begin programming and both Python and VB have been suggested > as good first languages. Although I realize you probably have some > biases could you comment on which might be better. A good programming language is ALWAYS portable. VB isn't. > Is Mark Lutz's book basic enough for a beginning programmer. Perhaps not, though we're trying to get another book going. -- _Deirdre * http://www.linuxcabal.net * http://www.deirdre.net "I must say that I was really happy to see _Linux for Dummies_ -- that's when you know you've arrived." -- Linus Torvalds --__--__-- _______________________________________________ Tutor maillist - Tutor@python.org http://www.python.org/mailman/listinfo/tutor End of Tutor Digest ______________________________________________________ Get Your Private, Free Email at http://www.hotmail.com From rhicks@rma.edu Tue Dec 5 00:14:59 2000 From: rhicks@rma.edu (rhicks@rma.edu) Date: Mon, 31 Jan 100 12:12:25 +0000 Subject: [Tutor] Windons Task tray Message-ID: <200001311713.MAA19985@smtp.rma.edu> Is it possible to minimize a python program to the task tray area of the taskbar in Windows95/98? Bob pop3.rma.edu From rhicks@rma.edu Tue Dec 5 00:14:59 2000 From: rhicks@rma.edu (rhicks@rma.edu) Date: Wed, 9 Feb 100 13:10:17 +0000 Subject: [Tutor] Dictionaries... Message-ID: <200002091811.NAA13567@smtp.rma.edu> On page 50 of "Learning Python" is makes the statement that dictionaries in Python are randomized in their order in order to provide quick lookup. I have talked to a programmer buddy and he doesn't know why this is. Why does an unordered list provide a quick lookup? Bob "It is never right to do wrong for a chance to do right..." pop3.rma.edu From clay_smith_is@hotmail.com Fri Dec 1 20:07:35 2000 From: clay_smith_is@hotmail.com (clay smith) Date: Fri, 01 Dec 2000 15:07:35 -0500 Subject: [Tutor] HELP!!!!!!!!!!:) Message-ID: I am a total programming newbie and i need help with Python...so 1) Where can i find a good FAQ concerning how to program Python (for newbies) 2) Can you make anything you want with Python? Or is it for web pages? I hope this is as basic as I'm going to get. Thanks, Clay Smith _____________________________________________________________________________________ Get more from the Web. FREE MSN Explorer download : http://explorer.msn.com From darrell@brogdon.net Fri Dec 1 20:22:41 2000 From: darrell@brogdon.net (Darrell Brogdon) Date: Fri, 01 Dec 2000 15:22:41 -0500 Subject: [Tutor] HELP!!!!!!!!!!:) References: Message-ID: <3A280891.A753686E@valinux.com> I believe there is a FAQ on the python.org web site. A good site for you to take a look at might be http://members.nbci.com/alan_gauld/tutor/tutindex.htm. As to item number 2, Python is a pretty flexible language from what I've seen so far and not just for web pages. I'm not a programming newbie but I am new to Python and so far I'm impressed. -Darrell clay smith wrote: > I am a total programming newbie and i need help with Python...so > > 1) Where can i find a good FAQ concerning how to program Python (for > newbies) > 2) Can you make anything you want with Python? Or is it for web pages? > > I hope this is as basic as I'm going to get. Thanks, > Clay Smith > > _____________________________________________________________________________________ > Get more from the Web. FREE MSN Explorer download : http://explorer.msn.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Sat Dec 2 02:44:58 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 1 Dec 2000 18:44:58 -0800 (PST) Subject: [Tutor] HELP!!!!!!!!!!:) In-Reply-To: <3A280891.A753686E@valinux.com> Message-ID: On Fri, 1 Dec 2000, Darrell Brogdon wrote: > I believe there is a FAQ on the python.org web site. A good site for > you to take a look at might be > http://members.nbci.com/alan_gauld/tutor/tutindex.htm. > > As to item number 2, Python is a pretty flexible language from what > I've seen so far and not just for web pages. I'm not a programming > newbie but I am new to Python and so far I'm impressed. Someone's even written a Solitare game in Python: http://wildsau.idv.uni-linz.ac.at/mfx/pysol/ But anyway, the tutorial above is really good. Also, if you have any programming questions, please feel to ask us. From devanshd@yahoo.com Fri Dec 1 19:16:38 2000 From: devanshd@yahoo.com (Devansh Dhutia) Date: Fri, 1 Dec 2000 13:16:38 -0600 Subject: [Tutor] (no subject) Message-ID: <003701c05bcb$3d0b18c0$5f1511ac@wartburg.edu> This is a multi-part message in MIME format. ------=_NextPart_000_0034_01C05B98.F089E760 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hi everyone, i have a small prob. i hvae a simulation to run n the following 3 lines = are where i m reading from an input file where i have the customer = database... i have a customer class n its something like this class customer: def __init__(self,card_num,pin,name,chk_bal,sav_bal,pic): self.card_num=3Dcard_num self.pin=3Dpin self.name=3Dname self.chk_bal=3Dchk_bal self.sav_bal=3Dsav_bal self.pic=3Dpic an example line in my input file is=20 customer(123456,1234,'Devansh Dhutia',111,222,list[11]) this is the section where i read the lines.... user=3Dcustdb.readline() user=3Deval(user) cust_list.append(user) and this is the error i get on the 2nd line.. Traceback (innermost last): File "", line 1, in ? File "A:\ATM\ATMsimB.py", line 297, in ? main() File "A:\ATM\ATMsimB.py", line 296, in main simulation() File "A:\ATM\ATMsimB.py", line 177, in simulation customervalidation(cardnumforverify,pinforverify) File "A:\ATM\ATMsimB.py", line 191, in customervalidation actualcard=3Deval(actualcard).getcard() File "", line 0, in ? TypeError: unsubscriptable object pls advise.. thanx Devansh Dhutia ------=_NextPart_000_0034_01C05B98.F089E760 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
hi everyone,
i have a small prob. i hvae a = simulation to run n=20 the following 3 lines are where i m reading from an input file where i = have the=20 customer database...
i have a customer class n its something = like=20 this
 
class customer:
    = def=20 __init__(self,card_num,pin,name,chk_bal,sav_bal,pic):
  &nbs= p;    =20 self.card_num=3Dcard_num
       =20 self.pin=3Dpin
       =20 self.name=3Dname
       =20 self.chk_bal=3Dchk_bal
       =20 self.sav_bal=3Dsav_bal
       =20 self.pic=3Dpic
an example line in my input file is =
customer(123456,1234,'Devansh=20 Dhutia',111,222,list[11])
 
this is the section where i read the=20 lines....
 
user=3Dcustdb.readline()
user=3Deval(user)
cust_list.appen= d(user)
 
and this is the error i get on the 2nd=20 line..
 
 
Traceback (innermost last):
  = File=20 "<string>", line 1, in ?
  File "A:\ATM\ATMsimB.py", line = 297, in=20 ?
    main()
  File "A:\ATM\ATMsimB.py", line = 296, in=20 main
    simulation()
  File = "A:\ATM\ATMsimB.py", line=20 177, in simulation
   =20 customervalidation(cardnumforverify,pinforverify)
  File=20 "A:\ATM\ATMsimB.py", line 191, in = customervalidation
   =20 actualcard=3Deval(actualcard).getcard()
  File "<string>", = line 0,=20 in ?
TypeError: unsubscriptable object
 
pls advise..
thanx
 
Devansh = Dhutia
------=_NextPart_000_0034_01C05B98.F089E760-- _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From garduino@rva.com.ar Sat Dec 2 14:43:30 2000 From: garduino@rva.com.ar (=?iso-8859-1?Q?Germ=E1n_S._Arduino?=) Date: Sat, 2 Dec 2000 11:43:30 -0300 Subject: [Tutor] Learn to Hack Message-ID: <002401c05c6e$55aaf8c0$60c915ac@chavo> This is a multi-part message in MIME format. ------=_NextPart_000_001F_01C05C55.17A5EEE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ------=_NextPart_000_001F_01C05C55.17A5EEE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 
------=_NextPart_000_001F_01C05C55.17A5EEE0-- From kalle@gnupung.net Sat Dec 2 15:35:40 2000 From: kalle@gnupung.net (Kalle Svensson) Date: Sat, 2 Dec 2000 16:35:40 +0100 Subject: [Tutor] (no subject) In-Reply-To: <003701c05bcb$3d0b18c0$5f1511ac@wartburg.edu>; from devanshd@yahoo.com on Fri, Dec 01, 2000 at 01:16:38PM -0600 References: <003701c05bcb$3d0b18c0$5f1511ac@wartburg.edu> Message-ID: <20001202163540.A817@gnupung.net> --pf9I7BMVVzbSWLtt Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Hi! Sez Devansh Dhutia: > Traceback (innermost last): > File "", line 1, in ? > File "A:\ATM\ATMsimB.py", line 297, in ? > main() > File "A:\ATM\ATMsimB.py", line 296, in main > simulation() > File "A:\ATM\ATMsimB.py", line 177, in simulation > customervalidation(cardnumforverify,pinforverify) > File "A:\ATM\ATMsimB.py", line 191, in customervalidation > actualcard=3Deval(actualcard).getcard() > File "", line 0, in ? > TypeError: unsubscriptable object The problem is in the string actualcard, eval(actualcard) raises an exception because it tries to subscript (access with index, like variable[1]) an object that cannot be subscripted. What is the value of actualcard? HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --pf9I7BMVVzbSWLtt Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6KRbMdNeA1787sd0RApXUAKCMorGQHHEGE6N38a3DxYQEViAmfwCfZERn g5kb1pD59j99H0uVgB75Opc= =++16 -----END PGP SIGNATURE----- --pf9I7BMVVzbSWLtt-- From Venugopal.JD@geind.ge.com Sat Dec 2 17:11:56 2000 From: Venugopal.JD@geind.ge.com (JD, Venugopal (CORP, CIM, MMC)) Date: Sat, 2 Dec 2000 22:41:56 +0530 Subject: [Tutor] help---- how do i create a file with todays date as the filename Message-ID: <1196B5CB33DED311A73700508B6FEB1E01FB33C3@ban03xbindge.geind.ge.com> hi, i a programming newbie and would like to know if there is any way i can create or rename a file through python so that the file name corresponds to todays date. thanks and regards venugopal.j.d From bobhicks@adelphia.net Sat Dec 2 18:26:00 2000 From: bobhicks@adelphia.net (Robert L Hicks) Date: Sat, 2 Dec 2000 13:26:00 -0500 Subject: [Tutor] a good place to start Message-ID: <20001202182607.ED1F41CC69@dinsdale.python.org> http://www.crosswinds.net/~agauld/ From spirou@carolo.com Sat Dec 2 20:29:02 2000 From: spirou@carolo.com (Denis) Date: Sat, 2 Dec 2000 21:29:02 +0100 Subject: [Tutor] Learn to Hack In-Reply-To: <002401c05c6e$55aaf8c0$60c915ac@chavo>; from garduino@rva.com.ar on Sat, Dec 02, 2000 at 11:43:30AM -0300 References: <002401c05c6e$55aaf8c0$60c915ac@chavo> Message-ID: <20001202212902.C22870@carolo.com> Le Sat, Dec 02, 2000 at 11:43:30AM -0300, Germ醤 S. Arduino pianota: > http://www.tuxedo.org/~esr/faqs/hacker-howto.html -- Denis FRERE P3B : Club Free-Pytho-Linuxien Caroloregien http://www.p3b.org Aragne : Internet - Reseaux - Formations http://www.aragne.com From dyoo@hkn.eecs.berkeley.edu Sun Dec 3 03:48:32 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 2 Dec 2000 19:48:32 -0800 (PST) Subject: [Tutor] (no subject) In-Reply-To: <003701c05bcb$3d0b18c0$5f1511ac@wartburg.edu> Message-ID: On Fri, 1 Dec 2000, Devansh Dhutia wrote: > an example line in my input file is > customer(123456,1234,'Devansh Dhutia',111,222,list[11]) > File "A:\ATM\ATMsimB.py", line 191, in customervalidation > actualcard=eval(actualcard).getcard() > File "", line 0, in ? > TypeError: unsubscriptable object I'd guess that "list[11]" isn't a list --- Python will give that same error. As a note, you may want to rename your "list" variable to something else: list() is a builtin function in Python! #### >>> list >>> list("this is a test") ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't'] #### It's very possible that your error comes from trying to subscript the function list(): ### >>> list[11] Traceback (most recent call last): File "", line 1, in ? TypeError: unsubscriptable object ### So perhaps you meant to say something like "cust_list[11]" or something. I'm not quite sure since I don't know too much about the context. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Dec 3 04:00:25 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 2 Dec 2000 20:00:25 -0800 (PST) Subject: [Tutor] help---- how do i create a file with todays date as the filename In-Reply-To: <1196B5CB33DED311A73700508B6FEB1E01FB33C3@ban03xbindge.geind.ge.com> Message-ID: On Sat, 2 Dec 2000, JD, Venugopal (CORP, CIM, MMC) wrote: > i a programming newbie and would like to know if there is any way i > can create or rename a file through python so that the file name > corresponds to todays date. Sure! There are a few tools that you can use to do this. One of them is the renaming function in the "os" module: os.rename(). Here's some sample usage: ### >>> import os >>> open("foobar.txt", "w") >>> os.rename("foobar.txt", "barfoo.txt") >>> # does that file exist? ... os.path.isfile("foobar.txt") 0 >>> os.path.isfile("barfoo.txt") 1 ### You can read a little more about os functions that deal with files and directories: http://python.org/doc/current/lib/os-file-dir.html Getting the time isn't too difficult either: the time module handles a lot of the dirty work for us. Take a look here: http://python.org/doc/current/lib/module-time.html For example: ### >>> import time >>> from time import time, localtime, strftime # time() gives us the number of milliseconds that have passed since the # "Epoch" # localtime() takes these milliseconds, and returns a tuple of # month,year,day,second,... lots of information. # strftime() takes this tuple, and a formatting string, and returns the # date in that form. >>> time_tuple = localtime(time()) >>> print strftime("%m%y%d", time_tuple) # Month, Year, Day as decimals 120002 ### You'll definitely want to look at the module documentation and play around with it. Also, if you're doing anything with file renaming, make some backups of those files, just in case. *grin* Good luck! From darrell@brogdon.net Sun Dec 3 04:46:08 2000 From: darrell@brogdon.net (Darrell Brogdon) Date: Sat, 02 Dec 2000 23:46:08 -0500 Subject: [Tutor] help---- how do i create a file with todays date as thefilename References: Message-ID: <3A29D010.111D2861@valinux.com> That raises an interesting question, isn't the following redundant? >>> import time >>> from time import time, localtime, strftime By that I mean, by entering 'import time' aren't you essentially doing the same thing as 'from time import time, localtime, strftime' except that with the latter you are importing specific classes? -Darrell Daniel Yoo wrote: > On Sat, 2 Dec 2000, JD, Venugopal (CORP, CIM, MMC) wrote: > > > i a programming newbie and would like to know if there is any way i > > can create or rename a file through python so that the file name > > corresponds to todays date. > > Sure! There are a few tools that you can use to do this. One of them is > the renaming function in the "os" module: os.rename(). Here's some sample > usage: > > ### > >>> import os > >>> open("foobar.txt", "w") > > >>> os.rename("foobar.txt", "barfoo.txt") > >>> # does that file exist? > ... os.path.isfile("foobar.txt") > 0 > >>> os.path.isfile("barfoo.txt") > 1 > ### > > You can read a little more about os functions that deal with files and > directories: > > http://python.org/doc/current/lib/os-file-dir.html > > Getting the time isn't too difficult either: the time module handles a lot > of the dirty work for us. Take a look here: > > http://python.org/doc/current/lib/module-time.html > > For example: > > ### > >>> import time > >>> from time import time, localtime, strftime > > # time() gives us the number of milliseconds that have passed since the > # "Epoch" > > # localtime() takes these milliseconds, and returns a tuple of > # month,year,day,second,... lots of information. > > # strftime() takes this tuple, and a formatting string, and returns the > # date in that form. > > >>> time_tuple = localtime(time()) > >>> print strftime("%m%y%d", time_tuple) # Month, Year, Day as decimals > 120002 > ### > > You'll definitely want to look at the module documentation and play around > with it. Also, if you're doing anything with file renaming, make some > backups of those files, just in case. *grin* > > Good luck! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Sun Dec 3 08:10:25 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 3 Dec 2000 00:10:25 -0800 (PST) Subject: [Tutor] help---- how do i create a file with todays date as thefilename In-Reply-To: <3A29D010.111D2861@valinux.com> Message-ID: On Sat, 2 Dec 2000, Darrell Brogdon wrote: > That raises an interesting question, isn't the following redundant? > > >>> import time > >>> from time import time, localtime, strftime > > By that I mean, by entering 'import time' aren't you essentially doing > the same thing as 'from time import time, localtime, strftime' except > that with the latter you are importing specific classes? Whoops. Yes, it's redundant. I should have edited my example more carefully. As I was typing in the interpreter, I realized that the expression: time.localtime(time.time()) would have looked really ugly, so I changed my mind and used the "from" statement. From mbc2@netdoor.com Mon Dec 4 14:54:17 2000 From: mbc2@netdoor.com (Brad Chandler) Date: Mon, 4 Dec 2000 08:54:17 -0600 Subject: [Tutor] How to detect an incoming phone call? Message-ID: <001701c05e02$1426b340$111c0d0a@spb.state.ms.us> I'd like to write a program that can detect an incoming phone call and then make some kind of sound. The reason behind this is that I only want to hear the phone ring during certain times of the day (i.e. no 2:00 am phone calls!). If I can get that to work, then later I'd also like to add some type of caller id capability, but first things first. I'm using Linux, USR 56k data/fax modem, and Python 2.0. How do I listen for an incoming call? I'm assuming there's a Linux program that will listen for an incoming call but how do I get my python program to work with that? Also, is there already a program that will do this? The closest thing I've found so far is a caller id program written in TCL called Marina, but I can't seem to get that to work. From johnp@reportlab.com Mon Dec 4 14:52:17 2000 From: johnp@reportlab.com (John Precedo) Date: Mon, 4 Dec 2000 14:52:17 -0000 Subject: [Tutor] HELP!!!!!!!!!!:) In-Reply-To: Message-ID: clay smith [clay_smith_is@hotmail.com] said: >I am a total programming newbie and i need help with Python...so > >1) Where can i find a good FAQ concerning how to program Python >(for newbies) >2) Can you make anything you want with Python? Or is it for web pages? > >I hope this is as basic as I'm going to get. Thanks, Darrell Brogdon [dbrogdon@valinux.com] replied: >I believe there is a FAQ on the python.org web site. A good site for you to take a look >at might be http://members.nbci.com/alan_gauld/tutor/tutindex.htm. Damn! You beat me to it! I was going to dig out the first tutorial on Python I ever read, but looking at the URL you gave, that's the one. I can confirm that it's a _very_ good tutorial for beginners. >As to item number 2, Python is a pretty flexible language from what I've seen so far and >not just for web pages. I'm not a programming newbie but I am new to Python and so far >I'm impressed. Hmm. Python is good for handling CGIs - that stands for Common Gateway Interface, and basically CGIs are the stuff that powers "active" web pages. It has quite a few good modules for that sort of stuff (not that I've ever messed with them!). But it is definitely a general language. Almost anything you could want to do, you can do in Python. It's not the best language for some things - if you want something that's very fast, for example, you'd be better off writing it in C or C++. But it's a good general language - they use it here where I work, as well as at a number of sports stadiums in Australia (to run scoreboards), at NASA's Johnson space centre and various other places that get mentioned a lot in books. Tutorials on the web: There is a good site for Python resources called the Vaults of Parnassus. This is the URL for their tutorials page. There are at least three links there to tutorials that appear to be the sort of thing you are looking for. http://www.vex.net/~x/parnassus/apyllo.py/935043691.636055170 These ones look good: Instant Hacking: Learn how to program with Python http://www.idi.ntnu.no/~mlh/python/programming.html Josh Cogliati's Non-Programmers Tutorial For Python http://www.honors.montana.edu/~jjc/easytut/easytut/ (Oh, and if you haven't yet installed Python, get the official tutorial from http://www.python.org/doc/ . It may be heavy going at first, but it is worth reading once, skipping anything you don't understand - just to get a general "feel" for Python as a language. Then go away and read any other tutorials you think can help, and come back to Guido's one when you think it will make more sense). Hope this helps John From dbrogdon@valinux.com Mon Dec 4 15:28:18 2000 From: dbrogdon@valinux.com (Darrell Brogdon) Date: Mon, 04 Dec 2000 10:28:18 -0500 Subject: [Tutor] HELP!!!!!!!!!!:) References: Message-ID: <3A2BB812.67C89BDA@valinux.com> --------------20174FC6F99DCB67F4D23096 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit John Precedo wrote: > Hmm. Python is good for handling CGIs - that stands for Common Gateway > Interface, and > basically CGIs are the stuff that powers "active" web pages. It has quite a > few good > modules for that sort of stuff (not that I've ever messed with them!). As far as web development goes, I personally prefer PHP but I hear Zope is very nice as well. I find it very helpful to be able to embed my server side code inside the HTML instead of having a bunch of print() statements everywhere. > But it is definitely a general language. Almost anything you could want to > do, you can > do in Python. It's not the best language for some things - if you want > something that's > very fast, for example, you'd be better off writing it in C or C++. But it's > a good general > language - they use it here where I work, as well as at a number of sports > stadiums in > Australia (to run scoreboards), at NASA's Johnson space centre and various > other places > that get mentioned a lot in books. > I agree that Python isn't nearly as fast as C or C++ but it is surprisingly fast for an interpreted language. I did a simple (I stress the word simple) test comparing it to PHP, Perl, Java, C, and Bash and with the exception of C It virtually beat out the rest of them by a head. -- --==[ Darrell Brogdon ] --==[ Web Developer - SourceForge ] --==[ http://darrell.brogdon.net ] "Keep your mouth shut and you'll always look like you know what you're talking about" --------------20174FC6F99DCB67F4D23096 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit John Precedo wrote:
Hmm. Python is good for handling CGIs - that stands for Common Gateway
Interface, and
basically CGIs are the stuff that powers "active" web pages. It has quite a
few good
modules for that sort of stuff (not that I've ever messed with them!).
As far as web development goes, I personally prefer PHP but I hear Zope is very nice as well.  I find it very helpful to be able to embed my server side code inside the HTML instead of having a bunch of print() statements everywhere.
But it is definitely a general language. Almost anything you could want to
do, you can
do in Python. It's not the best language for some things - if you want
something that's
very fast, for example, you'd be better off writing it in C or C++. But it's
a good general
language - they use it here where I work, as well as at a number of sports
stadiums in
Australia (to run scoreboards), at NASA's Johnson space centre and various
other places
that get mentioned a lot in books.
 
I agree that Python isn't nearly as fast as C or C++ but it is surprisingly fast for an interpreted language.  I did a simple (I stress the word simple) test comparing it to PHP, Perl, Java, C, and Bash and with the exception of C It virtually beat out the rest of them by a head.
 
-- 
--==[ Darrell Brogdon               ]
--==[ Web Developer - SourceForge   ]
--==[ http://darrell.brogdon.net    ]

"Keep your mouth shut and you'll always 
look like you know what you're talking about"
  --------------20174FC6F99DCB67F4D23096-- From srichter@cbu.edu Mon Dec 4 15:47:57 2000 From: srichter@cbu.edu (Stephan Richter) Date: Mon, 04 Dec 2000 09:47:57 -0600 Subject: [Tutor] HELP!!!!!!!!!!:) In-Reply-To: <3A2BB812.67C89BDA@valinux.com> References: Message-ID: <5.0.0.25.0.20001204094357.00a79710@198.78.130.6> >As far as web development goes, I personally prefer PHP but I hear Zope is >very nice as well. I find it very helpful to be able to embed my server >side code inside the HTML instead of having a bunch of print() statements >everywhere. Zope rules. It is very nice and the development time is amazing. The cool thing is, it is a small server that can serve for private use as well as for commercial sites. You should give it a try. It is a really nice piece of software, even though the initial learning curve is a little steep, but after that it is just "wow"! Amen. Well, a very biased and community-envolved Zope fanatic was speaking. :-) Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management cell: (901) 230-ZOPE From dbrogdon@valinux.com Mon Dec 4 16:35:38 2000 From: dbrogdon@valinux.com (Darrell Brogdon) Date: Mon, 04 Dec 2000 11:35:38 -0500 Subject: [Tutor] HELP!!!!!!!!!!:) References: <5.0.0.25.0.20001204094357.00a79710@198.78.130.6> Message-ID: <3A2BC7DA.A2D2B4CF@valinux.com> --------------2090029095B56893A3D5EBEA Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Nothing wrong with being biased towards something you believe in. :) I'll have to give Zope a try pretty soon. I will say that as far as systems stuff goes, where once I might use Perl I'll now use Python. Stephan Richter wrote: > >As far as web development goes, I personally prefer PHP but I hear Zope is > >very nice as well. I find it very helpful to be able to embed my server > >side code inside the HTML instead of having a bunch of print() statements > >everywhere. > > Zope rules. It is very nice and the development time is amazing. The cool > thing is, it is a small server that can serve for private use as well as > for commercial sites. You should give it a try. It is a really nice piece > of software, even though the initial learning curve is a little steep, but > after that it is just "wow"! > > Amen. > > Well, a very biased and community-envolved Zope fanatic was speaking. :-) > > Regards, > Stephan > > -- > Stephan Richter > CBU - Physics and Chemistry Student > Web2k - Web Design/Development & Technical Project Management > cell: (901) 230-ZOPE -- --==[ Darrell Brogdon ][ http://darrell.brogdon.net ] --==[ Web Developer - SourceForge ][ http://sourceforge.net ] --==[ VA Linux Systems, Inc. ][ http://www.valinux.com ] "Keep your mouth shut and you'll always look like you know what you're talking about" --------------2090029095B56893A3D5EBEA Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Nothing wrong with being biased towards something you believe in. :)  I'll have to give Zope a try pretty soon.

I will say that as far as systems stuff goes, where once I might use Perl I'll now use Python.

Stephan Richter wrote:

>As far as web development goes, I personally prefer PHP but I hear Zope is
>very nice as well.  I find it very helpful to be able to embed my server
>side code inside the HTML instead of having a bunch of print() statements
>everywhere.

Zope rules. It is very nice and the development time is amazing. The cool
thing is, it is a small server that can serve for private use as well as
for commercial sites. You should give it a try. It is a really nice piece
of software, even though the initial learning curve is a little steep, but
after that it is just "wow"!

Amen.

Well, a very biased and community-envolved Zope fanatic was speaking. :-)

Regards,
Stephan

--
Stephan Richter
CBU - Physics and Chemistry Student
Web2k - Web Design/Development & Technical Project Management
cell: (901) 230-ZOPE

-- 
--==[ Darrell Brogdon               ][ http://darrell.brogdon.net   ]
--==[ Web Developer - SourceForge   ][ http://sourceforge.net       ]
--==[ VA Linux Systems, Inc.        ][ http://www.valinux.com       ]

"Keep your mouth shut and you'll always 
look like you know what you're talking about"
  --------------2090029095B56893A3D5EBEA-- From timc@ans.net Mon Dec 4 17:07:57 2000 From: timc@ans.net (Tim Condit) Date: Mon, 4 Dec 2000 12:07:57 -0500 (EST) Subject: [Tutor] How to detect an incoming phone call? In-Reply-To: <001701c05e02$1426b340$111c0d0a@spb.state.ms.us> Message-ID: Hi, This is OT. More Linux than Python. Are you using the modem as a way of diverting the signal? (I'm terminology impaired; hope that makes sense. :) I'm trying to set up my Linux box at home as a dialup server, and just yesterday ran across part of the puzzle, anyway. [I apologize if this part is a bit confusing. I'm still trying to sort it out myself..] To get Linux to listen for an incoming call on a modem, you need to identify the modem (or more specifically it's port assignment) to Linux. Set one of the gettys (mgetty?) in /etc/inittab to point to your modem. It might be something like /dev/modem, which itself is a symbolic link to your modem's "real" name as listed in /dev directory. You only want the (port?) name, NOT the full pathname. For example, if your modem uses the second serial port, you'd enter 'ttyS1', not '/dev/ttyS1'. Use the example at the end of the /etc/inittab file as a hint. But be sure to back up that file first, and don't reboot your machine until you're done experimenting with the phone/modem! Probably nothing too drastic will happen, if you leave the rest of the file alone, but if you reset the runlevels or something in there, you may have trouble. Sorry, can't help you on the question of how to find your device name for the modem. It's probably not too difficult, though. If you're using it for dialout, you've probably got a chat script or similar in /etc (or maybe /etc/ppp/ ) directory that will identify the modem for you. That's not the whole job though, as your modem itself may need some configuration to tell it to accept incoming calls. That's vendor specific, I suspect. Here's a link to the Linux Dialin Server Setup Guide: http://www.linuxgazette.com/issue38/gentry.html HTH, Tim On Mon, 4 Dec 2000, Brad Chandler wrote: > I'd like to write a program that can detect an incoming phone call and then > make some kind of sound. The reason behind this is that I only want to hear > the phone ring during certain times of the day (i.e. no 2:00 am phone > calls!). If I can get that to work, then later I'd also like to add some > type of caller id capability, but first things first. > > I'm using Linux, USR 56k data/fax modem, and Python 2.0. How do I listen > for an incoming call? I'm assuming there's a Linux program that will listen > for an incoming call but how do I get my python program to work with that? > > Also, is there already a program that will do this? The closest thing I've > found so far is a caller id program written in TCL called Marina, but I > can't seem to get that to work. > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor > -- Tim Condit tcondit@uu.net UUNet Network Quality Services 734-214-7548 .. I said that the only thing that would change that is if we didn't report up the same chain of management .. he said that wasn't gonna happen .. and I said .. then I don't know what you're gonna do. From alan.gauld@bt.com Mon Dec 4 17:30:09 2000 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 4 Dec 2000 17:30:09 -0000 Subject: [Tutor] How to detect an incoming phone call? Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D453@mbtlipnt02.btlabs.bt.co.uk> > I'd like to write a program that can detect an incoming phone > call and then make some kind of sound. Now if you had Windoze that isn't too bad because many modems support TAPI or similar telephony API but I don't know of anything similar on Linux. It might be possible to get a JTAPI interface somewhere. > If I can get that to work, then later I'd also like > to add some type of caller id capability, If you do get that working I'd love to know how you did it. Seems a fairly ambitious project - unless someone knows of an easy way to do it that I'm unaware of. Alan g. From rmallett@rational.com Mon Dec 4 21:32:52 2000 From: rmallett@rational.com (Mallett, Roger) Date: Mon, 4 Dec 2000 13:32:52 -0800 Subject: [Tutor] changing value of variable in debug mode Message-ID: Is there a way to change the value of a *watch*ed variable while in a PythonWin debug session? I have attempted to do so through the watch window and the stack window but with no success. Roger Mallett From rmallett@rational.com Mon Dec 4 23:35:50 2000 From: rmallett@rational.com (Mallett, Roger) Date: Mon, 4 Dec 2000 15:35:50 -0800 Subject: [Tutor] non-typed variables AND naming conventions Message-ID: I am used to heavily typed languages. As I am working with python I am wondering when I can exercise the flexibility of a non-typed variable (outside of the interactive environment). I am tempted to revert to a naming convention that identifies variable types (as it is easier for me to read) but am hesitant believing that I'll soon enjoy the new found flexibility. Any wisdom on the subject? Roger Mallett From shaleh@valinux.com Mon Dec 4 23:50:32 2000 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Mon, 04 Dec 2000 15:50:32 -0800 (PST) Subject: [Tutor] non-typed variables AND naming conventions In-Reply-To: Message-ID: > I am tempted to revert to a naming convention that identifies variable types > (as it is easier for me to read) but am hesitant believing that I'll soon > enjoy the new found flexibility. Any wisdom on the subject? I just name the variable for what I am using it for: Namestring = 'Sean Perry' # or just Name = salary = 4.5 I find that a clear variable name tells me what it is used for, the type is not important. the gain I see most often in non typing is that a) i can change my mind, if I start off using a float and move to a class, most code need not change b) faster, I do not have to prototype or declare types most of my work has not needed a variable to be loosely typed, it is just a flexibility gain. From srichter@cbu.edu Tue Dec 5 03:55:41 2000 From: srichter@cbu.edu (Stephan Richter) Date: Mon, 04 Dec 2000 21:55:41 -0600 Subject: [Tutor] non-typed variables AND naming conventions In-Reply-To: References: Message-ID: <5.0.0.25.0.20001204214908.00a90b50@198.78.130.6> >most of my work has not needed a variable to be loosely typed, it is just a >flexibility gain. Well, here an example that Zope uses (code untested): When I call a function I have a optional parameter that can be a lsit of strings or if I just have one element a single string. In this case it would like this: def getValues(keys=[]): dict = {'a': 1, 'b': 2, 'c':3} if type(keys).__name__ == 'string': return (dict[keys],) else: help = () for key in keys: help = help + (dict[key],) return help Both times the function will return a tuple. so the function really does not care whether keys ends up being a string or a list. Regards, Stephan -- Stephan Richter CBU - Physics and Chemistry Student Web2k - Web Design/Development & Technical Project Management From dyoo@hkn.eecs.berkeley.edu Tue Dec 5 08:45:05 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 5 Dec 2000 00:45:05 -0800 (PST) Subject: [Tutor] Threads in Windows's IDLE don't work Message-ID: Dear Glen, First off, I want to apologize for the long delay in replying to this message; I should have done this sooner. About the threads: yes, when I try to run the program in IDLE, it breaks for me too. Apparently, trying to run a threading program on IDLE doesn't work. However, it does work if I run it manually from a Windows command window. This IDLE threading issue is actually a known problem! Take a look here: http://sourceforge.net/bugs/?group_id=5470&func=detailbug&bug_id=121963 The implementors are still trying to fix this one properly. Until then, their suggestion is that you run your thread stuff outside of IDLE. I know this is an unsatisfactory answer, but it sounds like it'll be a hard one for them to fix. From wheelege@tsn.cc Tue Dec 5 08:58:10 2000 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 5 Dec 2000 19:58:10 +1100 Subject: [Tutor] Threads in Windows's IDLE don't work References: Message-ID: <001601c05e99$7ee94d40$a410fea9@glen> Thanks for finally replying, I hope it gets fixed soon. It's good that it still works at the command line. Batch file here I come! :) Glen. From dyoo@hkn.eecs.berkeley.edu Tue Dec 5 07:12:17 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 4 Dec 2000 23:12:17 -0800 (PST) Subject: [Tutor] non-typed variables AND naming conventions In-Reply-To: Message-ID: On Mon, 4 Dec 2000, Mallett, Roger wrote: > I am used to heavily typed languages. > > As I am working with python I am wondering when I can exercise the > flexibility of a non-typed variable (outside of the interactive > environment). > > I am tempted to revert to a naming convention that identifies variable types > (as it is easier for me to read) but am hesitant believing that I'll soon > enjoy the new found flexibility. Any wisdom on the subject? One thing I find myself doing is making the variable name plural if it's some sort of list. Otherwise, it should be ok to use hungarian notation on your variable names, since it'll help you with typing issues. From hagerman@mac.com Tue Dec 5 13:32:59 2000 From: hagerman@mac.com (Craig Hagerman) Date: Tue, 05 Dec 2000 22:32:59 +0900 Subject: [Tutor] Errors using Simple.py for executables Message-ID: <200012051326.WAA10740@osa.att.ne.jp> I need help successfully creating an executable Python file (on Windows 98, using Python 1.5.2). I have been trying to do so using Gordon McMillan's "Simple.py". (For the record I have had no luck with Freeze or Squeeze either :( ) At first I thought that I had a problem with module dependencies, but I can't even get a simple HelloWorld program to turn into an executable. I will copy the error message below. I am not sure what is wrong but I hope that someone can point me in the right direction to get Simple working. Thanks in advance, Craig Hagerman The HelloWorld program : >>>print "Hello World" >>>print >>>print "Press any key to continue..." >>>raw_input() -------------------------------- Error Message when running %python Simple.py HelloWorld.py ---------------------------------- Creating HelloWorld.exe C:\Python\support\Run.exe -> HelloWorld.exe C:\WINDOWS/TEMP\~1969873-1 -> HelloWorld.exe Gathering components of Install_HelloWorld.exe Analyzing python dependencies of gen_install gen_install.py Traceback (innermost last): File "C:\Python\Builder.py", line 502, in ? main(opts, args) File "C:\Python\Builder.py", line 484, in main target.buildO File "C:\Python\Builder.py", line 83, in build self.gatherO File "C:\Python\Builder.py", line 381, in gather FullExeTarget.gather(self) File "C:\Python\Builder.py", line 290, in gather ArchiveTarget.gather(self) File "C:\Python\Builder.py", line 256, in gather CollectTarget.gather(self) File "C:\Python\Builder.py", line151, in gather self.toc.merge([resource.makeresource('python15.dll')]) File "C:\Python\Builder.py", line 19, in makeresource typ, nm, fullname = finder.identify(name,xtrapath) File "C:\Python\Builder.py", line 121, in identify raise ValueError, "%s not found" % name ValueError: python15.dll not found From jcm@bigskytel.com Tue Dec 5 16:02:30 2000 From: jcm@bigskytel.com (David Porter) Date: Tue, 5 Dec 2000 09:02:30 -0700 Subject: [Tutor] Errors using Simple.py for executables In-Reply-To: <200012051326.WAA10740@osa.att.ne.jp>; from hagerman@mac.com on Tue, Dec 05, 2000 at 10:32:59PM +0900 References: <200012051326.WAA10740@osa.att.ne.jp> Message-ID: <20001205090230.A12921@bigskytel.com> * Craig Hagerman : > I need help successfully creating an executable Python file (on Windows 98, > using Python 1.5.2). I have been trying to do so using Gordon McMillan's > "Simple.py". (For the record I have had no luck with Freeze or Squeeze > either :( ) I'll try, though I'm not using windows so I can't test any of this. > The HelloWorld program : > > >>>print "Hello World" > >>>print > >>>print "Press any key to continue..." > >>>raw_input() You can change the last two lines into one: raw_input("Press any key to continue...") > -------------------------------- > Error Message when running %python Simple.py HelloWorld.py > ---------------------------------- > > > Creating HelloWorld.exe > C:\Python\support\Run.exe -> HelloWorld.exe > C:\WINDOWS/TEMP\~1969873-1 -> HelloWorld.exe > Gathering components of Install_HelloWorld.exe > Analyzing python dependencies of gen_install gen_install.py > Traceback (innermost last): > File "C:\Python\Builder.py", line 502, in ? > main(opts, args) > File "C:\Python\Builder.py", line 484, in main > target.buildO > File "C:\Python\Builder.py", line 83, in build > self.gatherO > File "C:\Python\Builder.py", line 381, in gather > FullExeTarget.gather(self) > File "C:\Python\Builder.py", line 290, in gather > ArchiveTarget.gather(self) > File "C:\Python\Builder.py", line 256, in gather > CollectTarget.gather(self) > File "C:\Python\Builder.py", line151, in gather > self.toc.merge([resource.makeresource('python15.dll')]) > File "C:\Python\Builder.py", line 19, in makeresource > typ, nm, fullname = finder.identify(name,xtrapath) > File "C:\Python\Builder.py", line 121, in identify > raise ValueError, "%s not found" % name > ValueError: python15.dll not found It says that it can't find python15.dll. This is in fact python in the form of a shared library. If I remember correctly it should be installed in c:\windows\system. If it's not there, run a search for it on your system. Perhaps you should put a copy of it in c:\python\ and if that doesn't do anything try putting a copy in the same directory as helloworld.py. If that doesn't work, you'll have to wait for the people who actually know something about windows to respond... good luck, David From rmallett@rational.com Tue Dec 5 18:47:48 2000 From: rmallett@rational.com (Mallett, Roger) Date: Tue, 5 Dec 2000 10:47:48 -0800 Subject: [Tutor] Debuggers that permit you to change variable values during debug session Message-ID: I am currently working with PythonWin. I haven't found a way to modify variable values during a debug session. What Python debugger has such a feature? Roger Mallett -----Original Message----- From: Mallett, Roger [mailto:rmallett@Rational.Com] Sent: Monday, December 04, 2000 1:33 PM To: tutor@python.org Subject: [Tutor] changing value of variable in debug mode Is there a way to change the value of a *watch*ed variable while in a PythonWin debug session? I have attempted to do so through the watch window and the stack window but with no success. Roger Mallett _______________________________________________ Tutor maillist - Tutor@python.org http://www.python.org/mailman/listinfo/tutor From craig@osa.att.ne.jp Tue Dec 5 22:33:17 2000 From: craig@osa.att.ne.jp (Craig Hagerman) Date: Wed, 06 Dec 2000 07:33:17 +0900 Subject: [Tutor] Errors using Simple.py for executables Message-ID: <200012052226.HAA10799@osa.att.ne.jp> ---------- >From: David Porter >To: Python Tutor >Subject: Re: [Tutor] Errors using Simple.py for executables >Date: 2000, Dec 06 Wed 1:02 AM > > * Craig Hagerman : >> I need help successfully creating an executable Python file (on Windows 98, >> using Python 1.5.2). I have been trying to do so using Gordon McMillan's >> "Simple.py". (For the record I have had no luck with Freeze or Squeeze >> either :( ) > > I'll try, though I'm not using windows so I can't test any of this. > >> The HelloWorld program : >> >> >>>print "Hello World" >> >>>print >> >>>print "Press any key to continue..." >> >>>raw_input() > > You can change the last two lines into one: > > raw_input("Press any key to continue...") This is the HelloWorld program that is included with the Simple installation. -SNIP- >> ValueError: python15.dll not found > > It says that it can't find python15.dll. This is in fact python in the form > of a shared library. If I remember correctly it should be installed in > c:\windows\system. I checked and it python15.dll IS there (along with python14.dll and python20.dll since I have had those installed previously. I did an uninstall of those other pythons though.) >If it's not there, run a search for it on your system. > Perhaps you should put a copy of it in c:\python\ and if that doesn't do > anything try putting a copy in the same directory as helloworld.py. I will try this, but I think it won't help. Prior to the error message that I passed on the Simple.py program searched for python15.dll and reported that it successfully found it. Strange huh? Craig Hagerman From georges@acbm.qc.ca Wed Dec 6 02:21:53 2000 From: georges@acbm.qc.ca (Georges Gabereau) Date: Tue, 5 Dec 2000 21:21:53 -0500 Subject: [Tutor] little problem... Message-ID: Hey, This is my first post, go easy on me... :) I cannot figure out why this code does not work. command = input("irc>") command = string.split(command, ":", 5) newtext = command[1] print newtext If I enter "test:input", no quotes, it returns: Traceback (most recent call last): File "C:\Python2.0\Georges\IRCtest\client.py", line 38, in ? command = input("irc>") File "", line 1 test:input ^ SyntaxError: invalid syntax What's wrong? Shouldn't it split my input at the : and print "input"? Thanks, Georges From deirdre@deirdre.net Wed Dec 6 03:13:09 2000 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 5 Dec 2000 19:13:09 -0800 (PST) Subject: [Tutor] little problem... In-Reply-To: Message-ID: On Tue, 5 Dec 2000, Georges Gabereau wrote: > command = input("irc>") This is the wrong command to use. You want: command = raw_input("irc>") "input" evaluates what the user types. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "Our society has not yet gone so far as to place blind faith in machines. In almost all endeavors, humans routinely correct the errors of machines." - Florida Supreme Court From dsh8290@rit.edu Wed Dec 6 03:26:05 2000 From: dsh8290@rit.edu (D-Man) Date: Tue, 5 Dec 2000 22:26:05 -0500 Subject: [Tutor] little problem... In-Reply-To: ; from georges@acbm.qc.ca on Tue, Dec 05, 2000 at 21:21:53 -0500 References: Message-ID: <20001205222605.A19576@westsidecnc.rh.rit.edu> Just a guess, but you probably want to use raw_input, not input. The traceback you have shows that the call to the 'input' funcion failed. I haven't checked the docs, but it seems that it reads python code, thus the "syntax error" in your input. -D On Tue, 05 Dec 2000 21:21:53 Georges Gabereau wrote: | Hey, | | This is my first post, go easy on me... :) | | I cannot figure out why this code does not work. | | command = input("irc>") | command = string.split(command, ":", 5) | newtext = command[1] | print newtext | | If I enter "test:input", no quotes, it returns: | | Traceback (most recent call last): | File "C:\Python2.0\Georges\IRCtest\client.py", line 38, in ? | command = input("irc>") | File "", line 1 | test:input | ^ | SyntaxError: invalid syntax | | What's wrong? Shouldn't it split my input at the : and print "input"? | | Thanks, | | Georges | | _______________________________________________ | Tutor maillist - Tutor@python.org | http://www.python.org/mailman/listinfo/tutor | From georges@acbm.qc.ca Wed Dec 6 03:29:24 2000 From: georges@acbm.qc.ca (Georges Gabereau) Date: Tue, 5 Dec 2000 22:29:24 -0500 Subject: [Tutor] little problem... In-Reply-To: <20001205222605.A19576@westsidecnc.rh.rit.edu> Message-ID: thanks. I am now using raw_input() and it works the way I expect. Does anybody have any experince with irclib.py? http://joel.rosdahl.net/hacks/#irclib Georges -----Original Message----- From: D-Man [mailto:dsh8290@rit.edu] Sent: December 5, 2000 10:26 PM To: Georges Gabereau Cc: tutor@python.org Subject: Re: [Tutor] little problem... Just a guess, but you probably want to use raw_input, not input. The traceback you have shows that the call to the 'input' funcion failed. I haven't checked the docs, but it seems that it reads python code, thus the "syntax error" in your input. -D On Tue, 05 Dec 2000 21:21:53 Georges Gabereau wrote: | Hey, | | This is my first post, go easy on me... :) | | I cannot figure out why this code does not work. | | command = input("irc>") | command = string.split(command, ":", 5) | newtext = command[1] | print newtext | | If I enter "test:input", no quotes, it returns: | | Traceback (most recent call last): | File "C:\Python2.0\Georges\IRCtest\client.py", line 38, in ? | command = input("irc>") | File "", line 1 | test:input | ^ | SyntaxError: invalid syntax | | What's wrong? Shouldn't it split my input at the : and print "input"? | | Thanks, | | Georges | | _______________________________________________ | Tutor maillist - Tutor@python.org | http://www.python.org/mailman/listinfo/tutor | From abreu@penguinpowered.com Wed Dec 6 06:23:04 2000 From: abreu@penguinpowered.com (Jose Alberto Abreu) Date: Wed, 06 Dec 2000 00:23:04 -0600 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': Message-ID: <3A2DDB48.6D2B74EB@penguinpowered.com> Hello everybody! Im new to both Python and programming, so you can expect me to ask many questions in this list! ; ) Well... I made a (very simple) test module named prime.py that basically checks if a number is prime (duh!). The module works fine by itself, but now I am trying to make another script that will either tell if a given number is prime or which numbers from a list are primes. I think theres a problem in the line that reads the same as the title of this message, but I will include the whole script (sans the prime.py module, which is in the same directory): #!/usr/local/bin/python # Testing the module prime.py import prime print "This is a test script" x = "" while x != 'n' or 'N' or 'l' or 'L': x = raw_input ("Type 'L' for a list of primes or 'N' to test a single number: ") if x == 'N' or 'n': numbr = int(raw_input ("Type a number: ")) if prime.prime(numbr): print "Yeah, its a prime alright!" else: print "Nope, it aint no prime number" else: y = int(raw_input ("Type a number: ")) s=range(list) result = filter(prime.prime, s) print "The following numbers are primes: " print result Of course this is very very basic, but Im a bit stumped, and I cant find anything in my Python book (Teach Yourself Python in 24hrs, by Ivan Van Laningham) to help me out. -- 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170 Jose Alberto Abreu - abreu@penguinpowered.com | Futile is the labor of those who fatigue Bag detective and apprentice codecaster | themselves with calculations to square the | the circle - Michael Stifel (1544) 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170 From rmallett@rational.com Mon Dec 4 19:13:08 2000 From: rmallett@rational.com (Mallett, Roger) Date: Mon, 4 Dec 2000 11:13:08 -0800 Subject: [Tutor] stopping at a break point Message-ID: I am using PythonWin and have a break point set but can't yet figure out how to get the program to stop at the break point (it goes right on through it). To run the script I executed: File>Run> and set Debugging to "Step-through in the debugger". What appears to be a watch window displays along the left side. However, when I run the script from the interactive window it never stops at the break point. How can I get the script to stop at the break point? Roger Mallett From DOUGS@oceanic.com Wed Dec 6 08:41:56 2000 From: DOUGS@oceanic.com (Doug Stanfield) Date: Tue, 5 Dec 2000 22:41:56 -1000 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': Message-ID: <8457258D741DD411BD3D0050DA62365907A487@huina.oceanic.com> > Hello everybody! Hi. > Im new to both Python and programming, so you can expect me > to ask many > questions in this list! ; ) This is a great list for exactly that. We're all here to learn. > Well... I made a (very simple) test module named prime.py > that basically > checks if a number is prime (duh!). The module works fine by > itself, but > now I am trying to make another script that will either tell > if a given > number is prime or which numbers from a list are primes. > I think theres a problem in the line that reads the same as > the title of > this message, I think you're right. > but I will include the whole script (sans the prime.py > module, which is in the same directory): That's always a good idea. The other thing that will help a great deal is to include the text of the traceback that you get when it doesn't run correctly. That often has most of the information needed to figure things out. I'm not trying any of what follows with Python, so there is room for error here. This is just from the top of my head. > #!/usr/local/bin/python > # Testing the module prime.py > import prime > print "This is a test script" > x = "" > while x != 'n' or 'N' or 'l' or 'L': > x = raw_input ("Type 'L' for a list of primes or 'N' to > test a single > number: ") I'm just going to comment on this and skip the rest because it is what you've asked about. First the logic of your test is not consistant. Python needs four full comparisons. When you write: x != 'n' or 'N' or 'l' or 'L' Python may try to parse the first part and get it right, but can't figure out the rest. You're asking Python to make a decision based on x not equal to the letter 'n', or the truth of the letter 'N', or the truth of 'l', or 'L'. In other words, the last three are not being compared to x. You may be able to figure out how to correct this error from the above. I'd suggest there is another way to do what you want. It may or may not be considered more 'Pythonic', but it seems to be more obvious when coded (warning: untested code): print "This is a test script" x = "" while 1: if x in ('n','N','l','L'): break x = raw_input ("Type 'L' for a list of primes or 'N' to test a single number: ") > Of course this is very very basic, but Im a bit stumped, and > I cant find > anything in my Python book (Teach Yourself Python in 24hrs, > by Ivan Van > Laningham) to help me out. Thats a great book. I enjoyed it a lot, and got a lot from it. Hope I've helped. -Doug- From SBrunning@trisystems.co.uk Wed Dec 6 09:21:21 2000 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Wed, 6 Dec 2000 09:21:21 -0000 Subject: [Tutor] stopping at a break point Message-ID: <31575A892FF6D1118F5800600846864D5B154E@intrepid> > From: Mallett, Roger [SMTP:rmallett@rational.com] > How can I get the script to stop at the break point? Hit F9 to set the breakpoint(s), then run with debugging option "Run in the Debugger". Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From dman@westsidecnc.rh.rit.edu Wed Dec 6 14:25:27 2000 From: dman@westsidecnc.rh.rit.edu (D-Man) Date: Wed, 6 Dec 2000 09:25:27 -0500 (EST) Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': In-Reply-To: <8457258D741DD411BD3D0050DA62365907A487@huina.oceanic.com> from "Doug Stanfield" at Dec 05, 2000 10:41:56 PM Message-ID: <200012061425.eB6EPRM21096@westsidecnc.rh.rit.edu> Doug solved the problem correctly, however I feel that his solution is bad programming style and is harder to read than the alternative I will provide. [snip] > while 1: > if x in ('n','N','l','L'): > break # (some other processing snipped here) When reading this code, it appears that the loop is supposed to be infinite. I don't like loops like that. Then the loop termination condition is buried in the body of the loop with a 'break' statement. This is rather similar to using if's and goto's in BASIC or assembly to create a loop. Try this instead: while ( x not in ( 'n' , 'N' , 'l' , 'L' ) ) : # body of loop here I prefer this because you can see the loop termination condition in the loop's "declaration". (I also like parenthesis around the expression and spaces between symbols, but that is less important) An alternative could be : while ( string.upper( x ) not in ( 'N' , 'L' ) ) : # body of loop here I have often used the "toupper" operation when writing C code so I don't need as many equality comparisons (C doesn't have then "x in (list)" construct). Hope this helps, -D PS The Computer Science department at my school has some coding guidelines that forbid the use of 'break' and 'continue'. I had a class once where the professor was testing our understanding of C by writing similar loops ex: int i ; for( i = 0 ; i < 16 ; i++ ) { if ( i % 5 ) { printf( "%d\n" , i ) ; continue ; } else if ( i > 8 ) { break ; } printf( "End of loop\n" ) ; } Needless to say, this is very confusing and easy to make a mistake when tracing through it. From mbc2@netdoor.com Wed Dec 6 15:12:48 2000 From: mbc2@netdoor.com (Brad Chandler) Date: Wed, 6 Dec 2000 09:12:48 -0600 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': References: <200012061425.eB6EPRM21096@westsidecnc.rh.rit.edu> Message-ID: <002801c05f96$fe9e6360$111c0d0a@spb.state.ms.us> > while ( string.upper( x ) not in ( 'N' , 'L' ) ) : > # body of loop here I'm a beginner at all this, but I do think the above statement is much clearer. However, I don't think anyone has shown how the original statement should have looked. I know it helps me when I know why something doesn't work, and I think I also misunderstood the same thing at one time. The original statement: while x != 'n' or 'N' or 'l' or 'L': Should have been: while x != 'n' or x != 'N' or x != 'l' or x != 'L': Brad From FxItAL@aol.com Wed Dec 6 15:21:17 2000 From: FxItAL@aol.com (FxItAL@aol.com) Date: Wed, 6 Dec 2000 10:21:17 EST Subject: [Tutor] Time module Message-ID: <16.5aec3ff.275fb36d@aol.com> --part1_16.5aec3ff.275fb36d_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Hello All, I'm having trouble creating an executable file from my script and need to find the time module. If I search for "time.*" there are no files found but, if I use the command "from time import *" in IDLE there are no errors and "localtime(time())" returns an accurate value. Pease help me if you can. Python 2.0 on Windows ME Thanks Al --part1_16.5aec3ff.275fb36d_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit Hello All,

      I'm having trouble creating an executable file from my script and need
to find the time module. If I search for "time.*" there are no files found
but, if I use the command "from time import *" in IDLE there are no errors
and "localtime(time())" returns an accurate value. Pease help me if you can.

Python 2.0 on Windows ME

Thanks Al
--part1_16.5aec3ff.275fb36d_boundary-- From SBrunning@trisystems.co.uk Wed Dec 6 15:29:01 2000 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Wed, 6 Dec 2000 15:29:01 -0000 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': Message-ID: <31575A892FF6D1118F5800600846864D5B1556@intrepid> > From: Brad Chandler [SMTP:mbc2@netdoor.com] > The original statement: > while x != 'n' or 'N' or 'l' or 'L': > > Should have been: > while x != 'n' or x != 'N' or x != 'l' or x != 'L': No! while x != 'n' or x != 'N' or x != 'l' or x != 'L': is *exactly* equivalent to: while 1: - it will *always* be true, and will loop forever. I suspect that you mean: while x != 'n' and x != 'N' and x != 'l' and x != 'L': But as has been pointed out, the pythonic way of doing this is: while x not in ('n', 'N', 'l', 'L'): Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From scarblac@pino.selwerd.nl Wed Dec 6 15:36:00 2000 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 6 Dec 2000 16:36:00 +0100 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': In-Reply-To: <002801c05f96$fe9e6360$111c0d0a@spb.state.ms.us>; from mbc2@netdoor.com on Wed, Dec 06, 2000 at 09:12:48AM -0600 References: <200012061425.eB6EPRM21096@westsidecnc.rh.rit.edu> <002801c05f96$fe9e6360$111c0d0a@spb.state.ms.us> Message-ID: <20001206163600.A16732@pino.selwerd.nl> On Wed, Dec 06, 2000 at 09:12:48AM -0600, Brad Chandler wrote: > > while ( string.upper( x ) not in ( 'N' , 'L' ) ) : > > # body of loop here > > I'm a beginner at all this, but I do think the above statement is much > clearer. However, I don't think anyone has shown how the original statement > should have looked. I know it helps me when I know why something doesn't > work, and I think I also misunderstood the same thing at one time. > > The original statement: > while x != 'n' or 'N' or 'l' or 'L': > > Should have been: > while x != 'n' or x != 'N' or x != 'l' or x != 'L': Yes. Your first version means while (x != 'n') or ('N') or ('l') or ('L'): to python. Any non-empty string is true, so 'N' counts as true, and you have an infinite loop. My personal favorite spelling is while x not in 'N', 'n', 'L', 'l': The commas make the four strings into a tuple, and all those ( ( ) ) and spaces only confuse me :-). -- Remco Gerlich From arcege@shore.net Wed Dec 6 15:44:47 2000 From: arcege@shore.net (Michael P. Reilly) Date: Wed, 6 Dec 2000 10:44:47 -0500 (EST) Subject: [Tutor] Time module In-Reply-To: <16.5aec3ff.275fb36d@aol.com> from "FxItAL@aol.com" at Dec 06, 2000 10:21:17 AM Message-ID: <200012061544.KAA21445@northshore.shore.net> > Hello All, > > I'm having trouble creating an executable file from my script and need > to find the time module. If I search for "time.*" there are no files found > but, if I use the command "from time import *" in IDLE there are no errors > and "localtime(time())" returns an accurate value. Pease help me if you can. > > Python 2.0 on Windows ME > > Thanks Al The "time" module is going to be a builtin module, i.e. embedded in the python20.lib (when making the executable). You can find out which modules are builtin by searching in a list internal to the sys module: >>> import sys >>> 'time' in sys.builtin_module_names 1 >>> You can likely assume that any of the builtin modules will be abailable in frozen programs, I believe. -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From mbc2@netdoor.com Wed Dec 6 15:58:32 2000 From: mbc2@netdoor.com (Brad Chandler) Date: Wed, 6 Dec 2000 09:58:32 -0600 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': References: <31575A892FF6D1118F5800600846864D5B1556@intrepid> Message-ID: <003301c05f9d$61fc4200$111c0d0a@spb.state.ms.us> > while x != 'n' or x != 'N' or x != 'l' or x != 'L': > > is *exactly* equivalent to: > > while 1: > > - it will *always* be true, and will loop forever. I suspect that you mean: > > while x != 'n' and x != 'N' and x != 'l' and x != 'L': Yeah, that's right. Apparently, I'm still struggling with this. My point, though, was that there has to be a comparison with x after each 'and' or 'or', which is exactly what you stated in your first response. I was just trying to show it in code because there are other situations where the correct syntax is needed. Brad From scarblac@pino.selwerd.nl Wed Dec 6 15:59:12 2000 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 6 Dec 2000 16:59:12 +0100 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': In-Reply-To: <20001206163600.A16732@pino.selwerd.nl>; from scarblac@pino.selwerd.nl on Wed, Dec 06, 2000 at 04:36:00PM +0100 References: <200012061425.eB6EPRM21096@westsidecnc.rh.rit.edu> <002801c05f96$fe9e6360$111c0d0a@spb.state.ms.us> <20001206163600.A16732@pino.selwerd.nl> Message-ID: <20001206165912.A16766@pino.selwerd.nl> On Wed, Dec 06, 2000 at 04:36:00PM +0100, Remco Gerlich wrote: > > Should have been: > > while x != 'n' or x != 'N' or x != 'l' or x != 'L': > > Yes. Correcting myself: NO, as Simon Brunning said. Duh. Well, score a point for simpler versions ;) -- Remco Gerlich From dman@westsidecnc.rh.rit.edu Wed Dec 6 16:05:08 2000 From: dman@westsidecnc.rh.rit.edu (D-Man) Date: Wed, 6 Dec 2000 11:05:08 -0500 (EST) Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': In-Reply-To: <002801c05f96$fe9e6360$111c0d0a@spb.state.ms.us> from "Brad Chandler" at Dec 06, 2000 09:12:48 AM Message-ID: <200012061605.eB6G58T21411@westsidecnc.rh.rit.edu> > > > while ( string.upper( x ) not in ( 'N' , 'L' ) ) : > > # body of loop here > > I'm a beginner at all this, but I do think the above statement is much > clearer. However, I don't think anyone has shown how the original statement > should have looked. I know it helps me when I know why something doesn't > work, and I think I also misunderstood the same thing at one time. > > The original statement: > while x != 'n' or 'N' or 'l' or 'L': > > Should have been: > while x != 'n' or x != 'N' or x != 'l' or x != 'L': I use the 'toupper' function (in C) because of long expressions like the above. Python provides a simpler way using a list. while x not in ( 'N' , 'n' , 'L' , 'l' ) : ... That is equivalent to your correct expression. > > > Brad > -D From alan.gauld@bt.com Wed Dec 6 16:26:33 2000 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 6 Dec 2000 16:26:33 -0000 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D463@mbtlipnt02.btlabs.bt.co.uk> > Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': > I think theres a problem in the line that reads the same as > the title of this message, try this instead: while x not in 'nNlL': # do it here You method would require separate tests for each entry: while (x!='n') and (x != 'N) and.... Alan G. From alan.gauld@bt.com Wed Dec 6 16:31:42 2000 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 6 Dec 2000 16:31:42 -0000 Subject: [Tutor] while x != 'n' or 'N' or 'l' or 'L': Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D464@mbtlipnt02.btlabs.bt.co.uk> > The original statement: > while x != 'n' or 'N' or 'l' or 'L': > > Should have been: > while x != 'n' or x != 'N' or x != 'l' or x != 'L': Nope, theres a thing called De Morgans law that applies to logical expressions which says that to get the same result you need to swap or for and, thus: while (x != 'n') and (x != 'N') and (x != 'l') and (x != 'L'): In your version if x is 'n' then it would not (obviously!) be 'N' so the (x != 'N') test would be true and the while would continue... Alan g. From alan.gauld@bt.com Wed Dec 6 16:22:10 2000 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 6 Dec 2000 16:22:10 -0000 Subject: [Tutor] Debuggers that permit you to change variable values d uring debug session Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D462@mbtlipnt02.btlabs.bt.co.uk> > I am currently working with PythonWin. I haven't found a way > to modify variable values during a debug session. > What Python debugger has such a feature? pdb You can type arbitrary python comands into the debugger at the (pdb) prompt. I'm pretty sure IDLE exposes the pdb prompt but i'm not sure, I tend to just use raw pdb... Alan g. From SBrunning@trisystems.co.uk Wed Dec 6 16:58:42 2000 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Wed, 6 Dec 2000 16:58:42 -0000 Subject: [Tutor] Debuggers that permit you to change variable values d uring debug session Message-ID: <31575A892FF6D1118F5800600846864D5B155B@intrepid> > From: alan.gauld@bt.com [SMTP:alan.gauld@bt.com] > You can type arbitrary python comands into the > debugger at the (pdb) prompt. You can do this in PythonWin, too... Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From rmallett@rational.com Wed Dec 6 17:37:25 2000 From: rmallett@rational.com (Mallett, Roger) Date: Wed, 6 Dec 2000 09:37:25 -0800 Subject: [Tutor] stopping at a break point (WITHDRAWN) Message-ID: CANCEL THIS THREAD. This message was submitted two days ago (12/4/00) and just arrived this morning (12/6/00). I have since figured it out. Sorry for the inconvenience. Roger Mallett -----Original Message----- From: Mallett, Roger [mailto:rmallett@Rational.Com] Sent: Monday, December 04, 2000 11:13 AM To: tutor@python.org Subject: [Tutor] stopping at a break point I am using PythonWin and have a break point set but can't yet figure out how to get the program to stop at the break point (it goes right on through it). To run the script I executed: File>Run> and set Debugging to "Step-through in the debugger". What appears to be a watch window displays along the left side. However, when I run the script from the interactive window it never stops at the break point. How can I get the script to stop at the break point? Roger Mallett _______________________________________________ Tutor maillist - Tutor@python.org http://www.python.org/mailman/listinfo/tutor From rmallett@rational.com Mon Dec 4 19:39:52 2000 From: rmallett@rational.com (Mallett, Roger) Date: Mon, 4 Dec 2000 11:39:52 -0800 Subject: [Tutor] RE: stopping at a break point Message-ID: I have sorta figured out how to stop at breakpoints. The trouble was I ran the script from the interactive window rather than from the code window. I also selected "Step-through in the debugger" when I should have selected "Run in the debugger". On top of all of that I added the following code, but I don't understand what _main__ really is and why it causes the code to work. Here is my ugly snippet that enables me run the code in the debugger so that I can stop at break point. Can someone please tell me why it works so I can understand it and clean it up? if __name__ == '__main__': Main() else: Main() Roger Mallett > -----Original Message----- > From: Mallett, Roger > Sent: Monday, December 04, 2000 11:18 AM > To: 'tutor@python.org' > Subject: stopping at a break point > > I am using PythonWin and have a break point set but can't yet figure out > how to get the program to stop at the break point (it goes right on > through it). > > To run the script I executed: File>Run> and set Debugging to > "Step-through in the debugger". What appears to be a watch window > displays along the left side. However, when I run the script from the > interactive window it never stops at the break point. > > How can I get the script to stop at the break point? > > Roger Mallett From rmallett@rational.com Wed Dec 6 23:52:31 2000 From: rmallett@rational.com (Mallett, Roger) Date: Wed, 6 Dec 2000 15:52:31 -0800 Subject: [Tutor] Debuggers that permit you to change variable values d uring debug session Message-ID: Thanks to both Alan and Simon for taking a shot at my question. There answer has compelled me to describe the problem more completely as follows: I attempted to modify a variable using the interactive window. However, the modification did not affect the value on the stack. For example, below are three lines of code and the interactive session that I experienced. A breakpoint was set at line3. When line2 executed, the stack showed its counter = 0, which is also what I experienced in line4 & line5. However, when I modified the value of the counter (line6) (while still at the breakpoint), the value of counter only changed in the interactive window (line7 & line8), but did not change the value on the stack. Evidence that the value on the stack did not change was demonstrated when line3 was executed and the value of counter as 5 rather than 6 (line9 & line10). A display of 5 means that line6 had no real affect on the variable as it was being operated on in the script. Is it possible to modify values on the stack from within the debug session? line1 def Main(): line2 counter = 0 line3 counter = counter + 5 line4 [Dbg]>>> counter line5 0 line6 [Dbg]>>> counter = counter + 1 line7 [Dbg]>>> counter line8 1 line9 [Dbg]>>> counter line10 5 line11 [Dbg]>>> -----Original Message----- From: Simon Brunning [mailto:SBrunning@trisystems.co.uk] Sent: Wednesday, December 06, 2000 8:59 AM To: 'alan.gauld@bt.com'; rmallett@Rational.Com; tutor@python.org Subject: RE: [Tutor] Debuggers that permit you to change variable values d uring debug session > From: alan.gauld@bt.com [SMTP:alan.gauld@bt.com] > You can type arbitrary python comands into the > debugger at the (pdb) prompt. You can do this in PythonWin, too... Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From rael@oreilly.com Thu Dec 7 02:03:05 2000 From: rael@oreilly.com (Rael Dornfest) Date: Wed, 6 Dec 2000 18:03:05 -0800 (PST) Subject: [Tutor] Canonical Message-ID: Howdy, I was wondering what the canonical way of dealing with the following problem in Python is: I have a tuple of tuples (specifically, a tuple of rows from a database). ( ('a', 'b'), ('1', '2'), ... ) I want to manipulate the 2nd element in each 2nd level tuple (ie. 'b', '2', and so on). I could do some hackery with nested for loops, but this quickly gets pretty ugly given that I'm playing with tuples, not lists. Is this a job for map or filter or a combo of the two? Any help would be greatly appreciated. Rael From SBrunning@trisystems.co.uk Thu Dec 7 09:14:56 2000 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Thu, 7 Dec 2000 09:14:56 -0000 Subject: [Tutor] Canonical Message-ID: <31575A892FF6D1118F5800600846864D5B1561@intrepid> > From: Rael Dornfest [SMTP:rael@oreilly.com] > I have a tuple of tuples (specifically, a tuple of rows from a database). > > ( ('a', 'b'), ('1', '2'), ... ) > > I want to manipulate the 2nd element in each 2nd level tuple (ie. 'b', > '2', and so on). Try something like: for firstval, secondval in mytuple: print secondval Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From SBrunning@trisystems.co.uk Thu Dec 7 09:28:30 2000 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Thu, 7 Dec 2000 09:28:30 -0000 Subject: [Tutor] Debuggers that permit you to change variable values d uring debug session Message-ID: <31575A892FF6D1118F5800600846864D5B1563@intrepid> > From: Mallett, Roger [SMTP:rmallett@rational.com] > I attempted to modify a variable using the interactive window. However, > the > modification did not affect the value on the stack. > > For example, below are three lines of code and the interactive session > that > I experienced. A breakpoint was set at line3. When line2 executed, the > stack showed its counter = 0, which is also what I experienced in line4 & > line5. However, when I modified the value of the counter (line6) (while > still at the breakpoint), the value of counter only changed in the > interactive window (line7 & line8), but did not change the value on the > stack. Evidence that the value on the stack did not change was > demonstrated > when line3 was executed and the value of counter as 5 rather than 6 (line9 > & > line10). A display of 5 means that line6 had no real affect on the > variable > as it was being operated on in the script. > > Is it possible to modify values on the stack from within the debug > session? > > > line1 def Main(): > line2 counter = 0 > line3 counter = counter + 5 > > > > line4 [Dbg]>>> counter > line5 0 > line6 [Dbg]>>> counter = counter + 1 > line7 [Dbg]>>> counter > line8 1 > line9 [Dbg]>>> counter > line10 5 > line11 [Dbg]>>> This worked fine for me: [Dbg]>>> counter 0 [Dbg]>>> counter = 2 [Dbg]>>> counter 7 [Dbg]>>> What OS/Python release/PythonWin build are you at? Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From SBrunning@trisystems.co.uk Thu Dec 7 09:30:34 2000 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Thu, 7 Dec 2000 09:30:34 -0000 Subject: [Tutor] RE: stopping at a break point Message-ID: <31575A892FF6D1118F5800600846864D5B1564@intrepid> > From: Mallett, Roger [SMTP:rmallett@rational.com] > Here is my ugly snippet that enables me run the code in the debugger so > that > I can stop at break point. Can someone please tell me why it works so I > can > understand it and clean it up? > > > if __name__ == '__main__': > Main() > else: > Main() This is the usual way of getting your script to behave differently depending upon whether the script is imported, or run directly. __name__ is '__main__' if the module is being run directly (i.e. You typed 'Python mymodule.py' at the command line in order to run it, or some such). Hitting the run button on the PythonWin toolbar runs you module in this way. Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From arcege@shore.net Thu Dec 7 13:07:38 2000 From: arcege@shore.net (Michael P. Reilly) Date: Thu, 7 Dec 2000 08:07:38 -0500 (EST) Subject: [Tutor] Canonical In-Reply-To: from "Rael Dornfest" at Dec 06, 2000 06:03:05 PM Message-ID: <200012071307.IAA26152@northshore.shore.net> > > Howdy, > > I was wondering what the canonical way of dealing with the following > problem in Python is: > > I have a tuple of tuples (specifically, a tuple of rows from a database). > > ( ('a', 'b'), ('1', '2'), ... ) > > I want to manipulate the 2nd element in each 2nd level tuple (ie. 'b', > '2', and so on). > > I could do some hackery with nested for loops, but this quickly gets > pretty ugly given that I'm playing with tuples, not lists. > > Is this a job for map or filter or a combo of the two? You could convert it all to a list of lists: >>> a = ( ( 'a', 'b' ), ( '1', '2' ), ( 'i', 'ii' ) ) >>> al = map(list, a) >>> al [['a', 'b'], ['1', '2'], ['i', 'ii']] >>> # do some things, changing al itself >>> a = tuple( map(tuple, al) ) But that could be overkill depending on your needs, instead just convert to one list of tuples and replace the elements: >>> al = list(a) >>> for i in range(len(al)): ... record = al[i] ... # do some things, maybe resulting in a new value of record ... if record is not al[i]: # it changed ... al[i] = record ... >>> a = tuple(a) If you are not converting back to tuple afterward, the it could be just as easy to convert the first time to a list of lists. -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From ddj@EUnet.yu Thu Dec 7 16:10:19 2000 From: ddj@EUnet.yu (DRagan) Date: Thu, 07 Dec 2000 17:10:19 +0100 Subject: [Tutor] A question? Message-ID: <3A2FB66B.781965C4@eunet.yu> Hi, I just try to figure out how to change the size of basic widget and any other frame: This is an example: ... fApp=Frame(height=100,width=100,bg="green",bd=20) fFile = Frame(fApp,height=10,width=30) ... The results is the same with or without frame options height and width ! I will preciate any suggestion! best regards Dragan linux/python1.5.2 From rmallett@rational.com Thu Dec 7 17:09:26 2000 From: rmallett@rational.com (Mallett, Roger) Date: Thu, 7 Dec 2000 09:09:26 -0800 Subject: [Tutor] Debuggers that permit you to change variable values d uring debug session Message-ID: Concerning changing values of variables during a debug session, Simon stated: >This worked fine for me: >[Dbg]>>> counter >0 >[Dbg]>>> counter = 2 >[Dbg]>>> counter >7 >[Dbg]>>> > >What OS/Python release/PythonWin build are you at? My configuration is as follows: OS: Win2K SP1 Version # from the About Box: ActivePython build 202 From the Interactive Window: PythonWin 2.0 (#8, Oct 19,2000, 11:30:05) It is interesting to me that you obtained the results I expected to get but didn't. After receiving your response, I checked the ActiveState site and build 202 is the latest build. I attempted to redownload for a reinstall but the site was not responding, so I'll wait till later. I am now curious as to what version you are using after all, if you are using the same version I am, then there is certainty that my installation is bad and a reinstall in necessary, otherwise,...). Roger Mallett -----Original Message----- From: Simon Brunning [mailto:SBrunning@trisystems.co.uk] Sent: Thursday, December 07, 2000 1:29 AM To: 'Mallett, Roger'; tutor@python.org Subject: RE: [Tutor] Debuggers that permit you to change variable values d uring debug session > From: Mallett, Roger [SMTP:rmallett@rational.com] > I attempted to modify a variable using the interactive >window. However, the modification did not affect the >value on the stack. > > For example, below are three lines of code and the > interactive session that I experienced. A breakpoint > was set at line3. When line2 executed, the stack > showed its counter = 0, which is also what I experienced > in line4 & line5. However, when I modified the value > of the counter (line6) (while still at the breakpoint), > the value of counter only changed in the interactive > window (line7 & line8), but did not change the value > on the stack. Evidence that the value on the stack > did not change was demonstrated when line3 was > executed and the value of counter as 5 rather than 6 > (line9 & line10). A display of 5 means that line6 > had no real affect on the variable as it was being > operated on in the script. > > Is it possible to modify values on the stack from > within the debug session? > > > line1 def Main(): > line2 counter = 0 > line3 counter = counter + 5 > > > > line4 [Dbg]>>> counter > line5 0 > line6 [Dbg]>>> counter = counter + 1 > line7 [Dbg]>>> counter > line8 1 > line9 [Dbg]>>> counter > line10 5 > line11 [Dbg]>>> This worked fine for me: [Dbg]>>> counter 0 [Dbg]>>> counter = 2 [Dbg]>>> counter 7 [Dbg]>>> What OS/Python release/PythonWin build are you at? Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From SBrunning@trisystems.co.uk Fri Dec 8 08:57:54 2000 From: SBrunning@trisystems.co.uk (Simon Brunning) Date: Fri, 8 Dec 2000 08:57:54 -0000 Subject: [Tutor] Debuggers that permit you to change variable values d uring debug session Message-ID: <31575A892FF6D1118F5800600846864D5B1586@intrepid> > From: Mallett, Roger [SMTP:rmallett@rational.com] > My configuration is as follows: > OS: Win2K SP1 > Version # from the About Box: ActivePython build 202 > From the Interactive Window: PythonWin 2.0 (#8, Oct 19,2000, > 11:30:05) > > It is interesting to me that you obtained the results I expected to get > but > didn't. > > After receiving your response, I checked the ActiveState site and build > 202 > is the latest build. I attempted to redownload for a reinstall but the > site > was not responding, so I'll wait till later. > > I am now curious as to what version you are using after all, if you are > using the same version I am, then there is certainty that my installation > is > bad and a reinstall in necessary, otherwise,...). WinNT 4, SP5. Python 2.0 #8 Win32All build 135 Cheers, Simon Brunning TriSystems Ltd. sbrunning@trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From lupakisyo@hotmail.com Fri Dec 8 13:23:38 2000 From: lupakisyo@hotmail.com (scholastica musokwa) Date: Fri, 08 Dec 2000 13:23:38 Subject: [Tutor] C++ functions in python....using calldll Message-ID: How do I make use of the calldll foreign function interface function called "call_foreign_function(function_address, in_args_format_string,result_args_format_string,argument_tuple)" to call a C++ function that returns void and has 2 input parameters-an integer and an inter pointer _____________________________________________________________________________________ Get more from the Web. FREE MSN Explorer download : http://explorer.msn.com From lupakisyo@hotmail.com Fri Dec 8 13:47:29 2000 From: lupakisyo@hotmail.com (scholastica musokwa) Date: Fri, 08 Dec 2000 13:47:29 Subject: [Tutor] Using C++ functions in python by making use of calldll Message-ID: 營 would like documentation on the using the calldll foreign funtion interface. In particular, I am having problems filling in the arguments of the calldll.call_foreign_function(function_address, in_args_format_string, result_format_string, argument_tuple) ,function. Could you explain the what the arguments of this function refer to? I would aslo like you to elaborate more on sections 4.7.1 to 4.7.3 of the "Python tutorials" available on on the python.org web page. (i) explain the difference between the two f funbctions defined in much simpler terms than those used in the tutorial. (ii)explain the "non-keyword argunment following keyword error undr section 4.7.2. (iii) Explain the last part of section 4.7.2. This involves using parameters of the form "**name" and "*name". _____________________________________________________________________________________ Get more from the Web. FREE MSN Explorer download : http://explorer.msn.com From bobhicks@adelphia.net Fri Dec 8 23:05:29 2000 From: bobhicks@adelphia.net (Robert Hicks) Date: Fri, 8 Dec 2000 23:05:29 +0000 Subject: [Tutor] Dependency problems Message-ID: <00120823052900.11062@localhost.localdomain> I would like to upgrade to Python 2.0 on my Mandrake 7.2 system. I get several dependency problems (libstc++, tkinter, etc.) when I use the beopen rpm from python.org. Is this just me? -- Robert Hicks "It is never right to do wrong for a chance to do right." From dsh8290@rit.edu Sat Dec 9 06:09:24 2000 From: dsh8290@rit.edu (D-Man) Date: Sat, 9 Dec 2000 01:09:24 -0500 Subject: [Tutor] Dependency problems In-Reply-To: <00120823052900.11062@localhost.localdomain>; from bobhicks@adelphia.net on Fri, Dec 08, 2000 at 18:05:29 -0500 References: <00120823052900.11062@localhost.localdomain> Message-ID: <20001209010924.C31063@westsidecnc.rh.rit.edu> Try getting the srpm and rebuilding it ( $ rpm --rebuild name.srpm ) You probably just have a different version that has different .so files than the one they compiled against. -D On Fri, 08 Dec 2000 18:05:29 Robert Hicks wrote: | I would like to upgrade to Python 2.0 on my Mandrake 7.2 system. I get | several dependency problems (libstc++, tkinter, etc.) when I use the beopen | rpm from python.org. Is this just me? | -- | Robert Hicks | | "It is never right to do wrong for a chance to do right." | | _______________________________________________ | Tutor maillist - Tutor@python.org | http://www.python.org/mailman/listinfo/tutor | From bobhicks@adelphia.net Mon Dec 11 07:36:32 2000 From: bobhicks@adelphia.net (Robert Hicks) Date: Mon, 11 Dec 2000 07:36:32 +0000 Subject: [Tutor] Dependency problems Message-ID: <00120823052900.11062@localhost.localdomain> I would like to upgrade to Python 2.0 on my Mandrake 7.2 system. I get several dependency problems (libstc++, tkinter, etc.) when I use the beopen rpm from python.org. Is this just me? -- Robert Hicks "It is never right to do wrong for a chance to do right." From dsh8290@rit.edu Mon Dec 11 13:29:25 2000 From: dsh8290@rit.edu (D-Man) Date: Mon, 11 Dec 2000 08:29:25 -0500 Subject: [Tutor] Dependency problems In-Reply-To: <00120823052900.11062@localhost.localdomain>; from bobhicks@adelphia.net on Mon, Dec 11, 2000 at 02:36:32 -0500 References: <00120823052900.11062@localhost.localdomain> Message-ID: <20001211082925.E11006@westsidecnc.rh.rit.edu> It probably means that you have different versions on your system than the system they compiled it on. My recommendation is to get the srpm, then rpm --rebuild Python.srpm . If you get errors such as LONG_BIT being misdefined, let me know. It's a problem w/ RH7 systems on 32-bit architectures, I don't know if Mandrake has that problem. (I hope RH was the only one crazy enough to make such a dist) -D On Mon, 11 Dec 2000 02:36:32 Robert Hicks wrote: | I would like to upgrade to Python 2.0 on my Mandrake 7.2 system. I get | several dependency problems (libstc++, tkinter, etc.) when I use the beopen | rpm from python.org. Is this just me? | -- | Robert Hicks | | "It is never right to do wrong for a chance to do right." | | _______________________________________________ | Tutor maillist - Tutor@python.org | http://www.python.org/mailman/listinfo/tutor | From peterc@brosystems.com Mon Dec 11 18:36:04 2000 From: peterc@brosystems.com (peterc) Date: Mon, 11 Dec 2000 18:36:04 -0000 Subject: [Tutor] Database DBI Format problem Message-ID: Hi I am currently using Python to open an oracle8i db and read its contents into a DB2 datadase. The date fields from the oracle DB are exported in this format dbidate('2000-Nov-23 00:00:00') this will not read back into the new db because of the dbidate() function surrounding it. does anybody know of a way to stop the DCOracle module from exporting date like this ? Thanks in Advance Peter Church From georg.simon@bnmsp.de Tue Dec 12 10:58:14 2000 From: georg.simon@bnmsp.de (Georg Simon) Date: Tue, 12 Dec 2000 11:58:14 +0100 Subject: [Tutor] DOS box only works a few times References: <007901c04168$dbba5580$a410fea9@glen> Message-ID: <3A3604D0.676B2F74@bnmsp.de> Since I am learning not only Python but Tkinter too, I am not able to run my programs more than a few times. >From IDLE I write the following example to the hard disk. ------------------------------------- from Tkinter import * root = Tk() w = Label(root, text="Hello, world!") w.pack() root.mainloop() ------------------------------------- Then I open the DOS box, type p and Enter for my batch file p.bat and wait for the Tkinter window. The Tkinter window I close with Alt+F4. The DOS prompt appears and I start again entering p . After 2 to 7 repetitions ( count not reproducable ) the DOS prompt no longer appears but only the DOS cursor. The DOS box is unable to receive any keystrokes. Similar results I get with three different computers, Windows 95 and Windows 98, up to 128 MB RAM, and different Tkinter examples. An empty example like ------------------------------------- from Tkinter import * root = Tk() root.mainloop() ------------------------------------- seems to be more dangerous. Georg Simon From mbc2@netdoor.com Tue Dec 12 17:33:14 2000 From: mbc2@netdoor.com (Brad Chandler) Date: Tue, 12 Dec 2000 11:33:14 -0600 Subject: [Tutor] Should I create a Class for this? Message-ID: <002301c06461$9b4a0a60$111c0d0a@spb.state.ms.us> Where I work, we have a report which performs a number of calculations on each employee to determine the exact amounts of his salary and fringe benefits. I've put all of these calculations into a python file, defining each as a separate function. There are approximately 67 functions and about 50 constant variables that I've defined at the top of the file. What is the best way to organize these functions so that I can easily reuse them in different programs? Should I create a class and put them in it. I've never created a class before so I'm not exactly sure how to go about it. As it is right now, I can just import the file and access the functions. What would be the advantage of creating a class for this? Brad From shaleh@valinux.com Tue Dec 12 18:47:23 2000 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Tue, 12 Dec 2000 10:47:23 -0800 (PST) Subject: [Tutor] Should I create a Class for this? In-Reply-To: <002301c06461$9b4a0a60$111c0d0a@spb.state.ms.us> Message-ID: > What is the best way to organize these functions so that I can easily reuse > them in different programs? Should I create a class and put them in it. > I've never created a class before so I'm not exactly sure how to go about > it. As it is right now, I can just import the file and access the > functions. What would be the advantage of creating a class for this? > go read a book on Object Oriented design. If you do not have a vocabularly, you can not talk about a topic. No more than I can discuss legal issues (-: This really boils down to 'what is an object' and 'do i have objects?'. Once you can answer those questions for yourself, the implementation is not that hard to work out. From scarblac@pino.selwerd.nl Tue Dec 12 19:02:01 2000 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 12 Dec 2000 20:02:01 +0100 Subject: [Tutor] Should I create a Class for this? In-Reply-To: <002301c06461$9b4a0a60$111c0d0a@spb.state.ms.us>; from mbc2@netdoor.com on Tue, Dec 12, 2000 at 11:33:14AM -0600 References: <002301c06461$9b4a0a60$111c0d0a@spb.state.ms.us> Message-ID: <20001212200201.A8471@pino.selwerd.nl> On Tue, Dec 12, 2000 at 11:33:14AM -0600, Brad Chandler wrote: > Where I work, we have a report which performs a number of calculations on > each employee to determine the exact amounts of his salary and fringe > benefits. I've put all of these calculations into a python file, defining > each as a separate function. There are approximately 67 functions and about > 50 constant variables that I've defined at the top of the file. > > What is the best way to organize these functions so that I can easily reuse > them in different programs? Should I create a class and put them in it. > I've never created a class before so I'm not exactly sure how to go about > it. As it is right now, I can just import the file and access the > functions. What would be the advantage of creating a class for this? It depends, it's not easy to tell what the best way is, from this. When you code in classes, the *data* comes central. If all those functions act on the same data (say, an employee number and his base salary), it may be easier to make a class with that data, and add the functions as methods. A class is a representation of a block of data that should be seen as one piece, and the things you can do with that data. But if the functions all do unrelated things, there is no reason to put them in a class. And above all, if it works now, there is probably no reason to change it into OO for the sake of OO :). What kind of functions do you have? Do you feel the way it works now is logical? -- Remco Gerlich From scott@zenplex.com Tue Dec 12 20:11:26 2000 From: scott@zenplex.com (Scott C) Date: Tue, 12 Dec 2000 15:11:26 -0500 Subject: [Tutor] newbie: Serial I/O question Message-ID: <00121215112607.07689@scoot.zenplex.com> Hello All, I'd like to monitor my serial I/O port. My platform is Linux. I've seen a serial module for windows is there any for Linux?? Or is this not something I should be doing with Python? Thanks Scott From arcege@shore.net Tue Dec 12 21:53:21 2000 From: arcege@shore.net (Michael P. Reilly) Date: Tue, 12 Dec 2000 16:53:21 -0500 (EST) Subject: [Tutor] newbie: Serial I/O question In-Reply-To: <00121215112607.07689@scoot.zenplex.com> from "Scott C" at Dec 12, 2000 03:11:26 PM Message-ID: <200012122153.QAA25956@northshore.shore.net> > Hello All, I'd like to monitor my serial I/O port. My platform is Linux. > I've seen a serial module for windows is there any for Linux?? Or is this > not something I should be doing with Python? What kind of "monitoring" do you want to do? Detecting when the serial port is in use? Read the data coming through the port? If you want to handle the port itself, the simplest means is to open the device file (e.g. /dev/ttyS0), set the terminal settings (with the termios/TERMIOS modules) and read/write the data. You can also use Expect, or Python Expect module/extensions; this will allow you to program intelligent "chat" sessions for talking to such devices. If you just want to see when the device is in use, then you need to look at the lock files for your flavor of Linux (often in /var/locks/). Good luck. -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From scott@zenplex.com Tue Dec 12 22:20:04 2000 From: scott@zenplex.com (Scott C) Date: Tue, 12 Dec 2000 17:20:04 -0500 Subject: [Tutor] newbie: Serial I/O question In-Reply-To: <200012122153.QAA25956@northshore.shore.net> References: <200012122153.QAA25956@northshore.shore.net> Message-ID: <0012121720040B.07689@scoot.zenplex.com> On Tuesday 12 December 2000 16:53, Michael P. Reilly wrote: > > Hello All, I'd like to monitor my serial I/O port. My platform is > > Linux. I've seen a serial module for windows is there any for Linux?? Or > > is this not something I should be doing with Python? > > What kind of "monitoring" do you want to do? Detecting when the serial > port is in use? Read the data coming through the port? > > If you want to handle the port itself, the simplest means is to open > the device file (e.g. /dev/ttyS0), set the terminal settings (with the > termios/TERMIOS modules) and read/write the data. You can also use > Expect, or Python Expect module/extensions; this will allow you to > program intelligent "chat" sessions for talking to such devices. > > If you just want to see when the device is in use, then you need to > look at the lock files for your flavor of Linux (often in > /var/locks/). > > Good luck. > > -Arcege I guess I was not very detailed was I. I have a device that measures conductivity of a liquid used for printing presses. This info is very vital to print quilty and needs to be monitored on a daily basis. What I've been doing is looking at devices that hook up to a pc serial port. Once hooked up I'd like to gather my needed info and dump it too a web page if at all possible. Anyway thats a quick and dirty explanation. Thanks for the info, this may be over my head but I'm looking forward to a challenge. Thanks Scott From dman@westsidecnc.rh.rit.edu Tue Dec 12 23:03:54 2000 From: dman@westsidecnc.rh.rit.edu (D-Man) Date: Tue, 12 Dec 2000 18:03:54 -0500 (EST) Subject: [Tutor] Should I create a Class for this? In-Reply-To: <20001212200201.A8471@pino.selwerd.nl> from "Remco Gerlich" at Dec 12, 2000 08:02:01 PM Message-ID: <200012122303.eBCN3sK16695@westsidecnc.rh.rit.edu> In Python, a module is very similar to an object (except it isn't an object). You may already be using OO design principles without being aware of it. OO is good as it promotes encapsulation, but I agree that there's no need to change the existing stuff if it is already designed well. HTH, -D From dman@westsidecnc.rh.rit.edu Tue Dec 12 23:06:52 2000 From: dman@westsidecnc.rh.rit.edu (D-Man) Date: Tue, 12 Dec 2000 18:06:52 -0500 (EST) Subject: [Tutor] newbie: Serial I/O question In-Reply-To: <0012121720040B.07689@scoot.zenplex.com> from "Scott C" at Dec 12, 2000 05:20:04 PM Message-ID: <200012122306.eBCN6qx16719@westsidecnc.rh.rit.edu> It sounds like you should be able to do this if you a) know how to communicate with the hardware (it's protocol) and b) have access to a web server's filesystem. I don't know about the first, but since you are running Linux, you could have a web server on it. -D > > I guess I was not very detailed was I. I have a device that measures > conductivity of a liquid used for printing presses. This info is very vital > to print quilty and needs to be monitored on a daily basis. What I've been > doing is looking at devices that hook up to a pc serial port. Once hooked up > I'd like to gather my needed info and dump it too a web page if at all > possible. Anyway thats a quick and dirty explanation. > Thanks for the info, this may be over my head but I'm looking forward to a > challenge. > Thanks Scott > From mbc2@netdoor.com Tue Dec 12 23:38:55 2000 From: mbc2@netdoor.com (Brad Chandler) Date: Tue, 12 Dec 2000 17:38:55 -0600 Subject: [Tutor] Should I create a Class for this? References: <002301c06461$9b4a0a60$111c0d0a@spb.state.ms.us> <20001212200201.A8471@pino.selwerd.nl> Message-ID: <001a01c06494$b13a4fa0$111c0d0a@spb.state.ms.us> ----- Original Message ----- From: "Remco Gerlich" > When you code in classes, the *data* comes central. If all those functions > act on the same data (say, an employee number and his base salary), it may > be easier to make a class with that data, and add the functions as methods. > A class is a representation of a block of data that should be seen as one > piece, and the things you can do with that data. Well, the data comes from a database. Each row is a separate position and contains around 30 fields. The functions are for calculations such as retirement, social security, life insurance, etc... Each takes fields from the database as arguments and returns a number. At the end, the result of each function is added together to get the total fringe benefits. The same fields are used for multiple functions. I guess I would see the position as the object. > What kind of functions do you have? Do you feel the way it works now > is logical? I'll include an example below. I've read most of a book on C++ which describes OO and I've read the section of the Python Tutorial which describes classes. I've just never made the leap from theory to practice and I'm having trouble grasping the idea. I haven't had that "A ha" moment yet. I guess I'm just curious about how to implement these calculations now that they're written. I think that I will have to feed a row of data from the database to a function and have it return the fringe benefits amount to me. Typically, I'll only need that one number returned, but I wanted to make it as flexible as possible so that if I needed to access one of the other functions directly, I would be able to do so. Is this the proper place for a class? Example functions: #part-time percent def parttimepercent (hours,months): if hours==0: h=40 else: h=hours if months==0: m=12 else: m=months return (h*m)/480 #Social Security def Socialsec (basesalary, ssrate, ssmax): if basesalary<=ssmax: x=round((basesalary*ssrate),2) else: x=ssmax*ssrate return x From tim.one@home.com Wed Dec 13 03:25:24 2000 From: tim.one@home.com (Tim Peters) Date: Tue, 12 Dec 2000 22:25:24 -0500 Subject: [Tutor] DOS box only works a few times In-Reply-To: <3A3604D0.676B2F74@bnmsp.de> Message-ID: [posted and mailed] This is a known bug, and is not in Python (it's in Tcl/Tk), but nobody yet understands it fully: http://sourceforge.net/bugs/?group_id=5470&func=detailbug&bug_id=116289 Note that you didn't tell us what was in your p.bat, which is the only interesting information . A workaround is to use pythonw.exe instead of python.exe (and if you have python.exe, you also have pythonw.exe, although you may not have noticed it before). > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of > Georg Simon > Sent: Tuesday, December 12, 2000 5:58 AM > To: tutor@python.org > Subject: [Tutor] DOS box only works a few times > > > Since I am learning not only Python but Tkinter too, I am not able to > run my programs more than a few times. > From IDLE I write the following example to the hard disk. > ------------------------------------- > from Tkinter import * > > root = Tk() > > w = Label(root, text="Hello, world!") > w.pack() > > root.mainloop() > ------------------------------------- > Then I open the DOS box, type p and Enter for my batch file p.bat and > wait for the Tkinter window. The Tkinter window I close with Alt+F4. The > DOS prompt appears and I start again entering p . After 2 to 7 > repetitions ( count not reproducable ) the DOS prompt no longer appears > but only the DOS cursor. The DOS box is unable to receive any > keystrokes. > Similar results I get with three different computers, Windows 95 and > Windows 98, up to 128 MB RAM, and different Tkinter examples. An empty > example like > ------------------------------------- > from Tkinter import * > > root = Tk() > > root.mainloop() > ------------------------------------- > seems to be more dangerous. > > Georg Simon > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Wed Dec 13 04:48:53 2000 From: dsh8290@rit.edu (D-Man) Date: Tue, 12 Dec 2000 23:48:53 -0500 Subject: [Tutor] Should I create a Class for this? In-Reply-To: <001a01c06494$b13a4fa0$111c0d0a@spb.state.ms.us>; from mbc2@netdoor.com on Tue, Dec 12, 2000 at 18:38:55 -0500 References: <002301c06461$9b4a0a60$111c0d0a@spb.state.ms.us> <20001212200201.A8471@pino.selwerd.nl> <001a01c06494$b13a4fa0$111c0d0a@spb.state.ms.us> Message-ID: <20001212234853.D17575@westsidecnc.rh.rit.edu> Here's how a class might be useful: You create a class called Employee. It's constructor takes some argument, like maybe a row in a table. The ctor (short for constructor) will then interpret the data in the row and initialize some instance variables, such as hours, months, salary, etc. The functions would be members of the class. Thus they have access to instance variables, which are shared by all the functions of the same object. (note I said object, not class becuase they are instance, not class variables). Then the functions, such as the parttimepercent function you gave would not take any arguments. It already has the data it needs in the class. ex: # being cheap in the ctor here and making the client parse the database stuff class Employee : def __init__( self , hours , months ) : if ( hours == 0 ) : # should this be an error instead of a default? # it's up to what you want the calculation to mean self.hours = 40 else : self.hours = hours if ( months == 0 ) : # same here about the error self.months = 12 else : self.months = days def part_time_percent( self ) : return (self.hours * self.months ) / 480 # end class Employee # this is the main() emp = Employee( 40 , 5 ) # ok, he only worked 1 week :-) print emp.part_time_percent() I will also point out that Python doesn't enforce encapsulation. However, I feel that encapsulation is very important and write code as if it did. C++ and Java support it through the 'private' keyword. Eiffel won't let a client assign to a data member even if you try to make it public. Does this help at all? -D On Tue, 12 Dec 2000 18:38:55 Brad Chandler wrote: | ----- Original Message ----- | From: "Remco Gerlich" | | I'll include an example below. I've read most of a book on C++ which | describes OO and I've read the section of the Python Tutorial which | describes classes. I've just never made the leap from theory to practice | and I'm having trouble grasping the idea. I haven't had that "A ha" moment | yet. | | I guess I'm just curious about how to implement these calculations now that | they're written. I think that I will have to feed a row of data from the | database to a function and have it return the fringe benefits amount to me. | Typically, I'll only need that one number returned, but I wanted to make it | as flexible as possible so that if I needed to access one of the other | functions directly, I would be able to do so. Is this the proper place for | a class? | | Example functions: | | #part-time percent | def parttimepercent (hours,months): | if hours==0: | h=40 | else: | h=hours | | if months==0: | m=12 | else: | m=months | | return (h*m)/480 | | #Social Security | def Socialsec (basesalary, ssrate, ssmax): | if basesalary<=ssmax: | x=round((basesalary*ssrate),2) | else: | x=ssmax*ssrate | | return x | | From arcege@shore.net Wed Dec 13 12:39:29 2000 From: arcege@shore.net (Michael P. Reilly) Date: Wed, 13 Dec 2000 07:39:29 -0500 (EST) Subject: [Tutor] newbie: Serial I/O question In-Reply-To: <0012121720040B.07689@scoot.zenplex.com> from "Scott C" at Dec 12, 2000 05:20:04 PM Message-ID: <200012131239.HAA01536@northshore.shore.net> > I guess I was not very detailed was I. I have a device that measures > conductivity of a liquid used for printing presses. This info is very vital > to print quilty and needs to be monitored on a daily basis. What I've been > doing is looking at devices that hook up to a pc serial port. Once hooked up > I'd like to gather my needed info and dump it too a web page if at all > possible. Anyway thats a quick and dirty explanation. > Thanks for the info, this may be over my head but I'm looking forward to a > challenge. > Thanks Scott It doesn't sound like you will be writing to the device, which simplifies things a bit. Most of the challenge is probably based on the protocol with the serial device. Python has the "struct" module to convert binary structures (taken from the serial line) into Python data, and the "termios" module can manage the serial port itself. open serial device file set device speed and modes (likely want RAW mode and 9600 baud) do forever: read data (probably a fixed size) from serial line convert data into Python objects for analysis write HTML document to temp file move temp file into writable web directory, with appropriate name (optional) sleep for some time before we need to read again The sleeping is optional because the read should "block" until data is ready. But if it doesn't block and an exception is raised, then you will want to sleep instead of continually going thru a read-exception- retry cycle which would eat up unnecessary CPU. Other things you could (might need to) do: * You probably also want to add some routines to clean old HTML files. * Also that you will want to run this program not as root, but as some other account; try to get the permissions on the web directory so they are writable for whatever account you use, and that the serial device file is as well. Good luck. :) -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From mbc2@netdoor.com Thu Dec 14 22:51:40 2000 From: mbc2@netdoor.com (Brad Chandler) Date: Thu, 14 Dec 2000 16:51:40 -0600 Subject: [Tutor] Should I create a Class for this? References: <002301c06461$9b4a0a60$111c0d0a@spb.state.ms.us> <20001212200201.A8471@pino.selwerd.nl> <001a01c06494$b13a4fa0$111c0d0a@spb.state.ms.us> <20001212234853.D17575@westsidecnc.rh.rit.edu> Message-ID: <000c01c06620$6c56fa40$111c0d0a@spb.state.ms.us> Well, I finally got everthing converted into a Position class. Thanks to everyone who gave suggestions. I think I understand classes a little better now. I can now create a position object by sending a database row to the class like this: employee = projectclass.Position(db[0]) As an example of what I did, This: #Social Security def Socialsec (basesalary, ssrate, ssmax): if basesalary<=ssmax: x=round((basesalary*ssrate),2) else: x=ssmax*ssrate return x became this: #Social Security def Socialsec (self): if self.basesalary<=self.ssmax: x=round((self.basesalary*self.ssrate),2) else: x=self.ssmax*self.ssrate return x From geoffbays@mindspring.com Fri Dec 15 03:27:27 2000 From: geoffbays@mindspring.com (Geoffrey Bays) Date: Thu, 14 Dec 2000 19:27:27 -0800 Subject: [Tutor] setting pythonpath fro python 2.0 Message-ID: <4.3.2.7.0.20001214191809.00aa01b0@pop.mindspring.com> HI! I've been reading the tutor messages for awhile and writing teensy little programs. I have downloaded 2.0, but when trying to import a module, the interpreter will not find it. (on Win98 system) It says: "No module named whatever." Saving a file from notepad, I am not getting the little green python icon when I save a .py file. I am guessing that the pythonpath is not set correctly. I uninstalled Python 1.52. How do I get into DOS and set the path? I tried adding .py file extensions to be opened with python.exe in Windows, but this did not work. I am attached to my little programs, so any help would be appreciated.. P.S. Why did all the hackers vote for Gore? Because they like Al--Gore--Rhythms!! From tbrauch@mindless.com Fri Dec 15 02:27:09 2000 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Thu, 14 Dec 2000 21:27:09 -0500 Subject: [Tutor] Viewing Directories Message-ID: <3A39817D.3DE43DB4@mindless.com> Is there anyway to view the contents of a folder in Windows 95/98 using Python? Ideally I would actually like to read the names of files in a folder and write the names to a file. Tim Brauch From jcm@bigskytel.com Fri Dec 15 03:58:02 2000 From: jcm@bigskytel.com (David Porter) Date: Thu, 14 Dec 2000 20:58:02 -0700 Subject: [Tutor] Viewing Directories In-Reply-To: <3A39817D.3DE43DB4@mindless.com>; from tbrauch@mindless.com on Thu, Dec 14, 2000 at 09:27:09PM -0500 References: <3A39817D.3DE43DB4@mindless.com> Message-ID: <20001214205801.A11434@bigskytel.com> * Timothy M. Brauch : > Is there anyway to view the contents of a folder in Windows 95/98 using > Python? import os d = os.listdir('c:/dirname') print d > Ideally I would actually like to read the names of files in a folder and > write the names to a file. import os, string d = os.listdir('c:/dirname') f = open('c:/myfile.txt', 'w') f.write(string.join(d, '\n') Note that if you use backslashes (\) in paths, you need to escape them with another backslash, e.g., c:\\dirname . David From dvoitenko@qode.com Fri Dec 15 16:14:23 2000 From: dvoitenko@qode.com (Voitenko, Denis) Date: Fri, 15 Dec 2000 11:14:23 -0500 Subject: [Tutor] Can't use NNTP? Message-ID: <0FF17853157CD31197E100902784B34B7A1C2A@FILESERVER1> 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_01C066B2.165D8194 Content-Type: text/plain; charset="iso-8859-1" I am trying to connect to an NNTP server as follows: import nntplib news = NNTP('news.man.torun.pl') # news.man.torun.pl is a public server and at this point I get an error: Traceback (innermost last): File "", line 1, in ? NameError: NNTP >>> what is wrong? ------_=_NextPart_001_01C066B2.165D8194 Content-Type: text/html; charset="iso-8859-1" Can't use NNTP?

I am trying to connect to an NNTP server as follows:

import nntplib
news = NNTP('news.man.torun.pl') # news.man.torun.pl is a public server

and at this point I get an error:

Traceback (innermost last):
  File "<interactive input>", line 1, in ?
NameError: NNTP
>>>

what is wrong?

------_=_NextPart_001_01C066B2.165D8194-- From scarblac@pino.selwerd.nl Fri Dec 15 16:31:10 2000 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 15 Dec 2000 17:31:10 +0100 Subject: [Tutor] Can't use NNTP? In-Reply-To: <0FF17853157CD31197E100902784B34B7A1C2A@FILESERVER1>; from dvoitenko@qode.com on Fri, Dec 15, 2000 at 11:14:23AM -0500 References: <0FF17853157CD31197E100902784B34B7A1C2A@FILESERVER1> Message-ID: <20001215173110.A514@pino.selwerd.nl> On Fri, Dec 15, 2000 at 11:14:23AM -0500, Voitenko, Denis wrote: > I am trying to connect to an NNTP server as follows: > > import nntplib > news = NNTP('news.man.torun.pl') # news.man.torun.pl is a public server > > and at this point I get an error: > > Traceback (innermost last): > File "", line 1, in ? > NameError: NNTP > >>> > > what is wrong? Something really simple: it should read news = nntplib.NNTP('news.man.torun.pl') You import a module, then you can call things inside it with 'modulename.element'. -- Remco Gerlich From Venugopal.JD@geind.ge.com Fri Dec 15 19:15:05 2000 From: Venugopal.JD@geind.ge.com (JD, Venugopal (CORP, CIM, OMC)) Date: Sat, 16 Dec 2000 00:45:05 +0530 Subject: [Tutor] pinging from python Message-ID: <4DE51758E7CDD411A78700508B6FEB1E4128D4@ban03xbindge.geind.ge.com> hi, is it possible to ping to a host using python and redirect the output to a comma seperated value flat file. regards venugopal From deirdre@deirdre.net Fri Dec 15 20:22:15 2000 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Fri, 15 Dec 2000 12:22:15 -0800 (PST) Subject: [Tutor] pinging from python In-Reply-To: <4DE51758E7CDD411A78700508B6FEB1E4128D4@ban03xbindge.geind.ge.com> Message-ID: On Sat, 16 Dec 2000, JD, Venugopal (CORP, CIM, OMC) wrote: > is it possible to ping to a host using python and redirect the output > to a comma seperated value flat file. First of all, this is a good way to make enemies -- ping *can* be used as a hostile denial-of-service. Please don't use it this way. Yes, there are several ways of doing this: 1) On Unix, you can redirect the status of an external command -- see the commands module. 2) You can re-write the c-based "ping" program in python. Source code for ping is available in numerous places, including with most Linux distributions. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "Our society has not yet gone so far as to place blind faith in machines. In almost all endeavors, humans routinely correct the errors of machines." - Florida Supreme Court From MUSAJADAKISS@aol.com Sat Dec 16 12:16:05 2000 From: MUSAJADAKISS@aol.com (MUSAJADAKISS@aol.com) Date: Sat, 16 Dec 2000 07:16:05 EST Subject: [Tutor] help Message-ID: <70.605bf0d.276cb705@aol.com> please can you help me in completing this to search for a route using a* algorithim the file will be in text written and stored in notepad plase i will be glad if it is done as soon as you can thank you very much Amsterdam: Berlin,650 Brussels,197 Calais,367 Cologne,256 Edinburgh,1093 Hamburg,447 Paris,510 Athens: Sofia,828 Belfast: Cork,416 Dublin,167 Kilkenny,277 Berlin: Edinburgh,1696 Hamburg,285 Prague,345 Rostock,222 Stuttgart,629 Warsaw,606 Budapest: Burcharest,852 Prague,537 Sofia,790 Vienna,242 Cork: Kilkenny,148 Dublin: Cork,259 Kilkenny,119 Edinburgh,346 Edinburgh: Copenhagen,479 Hamburg: Rostock,175 Stuttgart,659 Istanbul: Athens,1145 Burcharest,690 Sofia,550 London: Brussels,333 Dublin,430 Cologne,508 Edinburgh,608 Paris,399 Madrid: Bercelona,617 Lisbon,651 Paris,1280 Munich: Berlin,594 Cologne,580 Frankfurt,398 Paris,810 Prague,388 Vienna,430 Oslo: Copenhagen,590 Hamburg,900 stocholm,530 Paris: Brussels,320 Cologne,495 Prague: Frankfurt,512 Hamburg,652 Oslo,1350 Warsaw,616 Vienna,295 Rome: Athens,1140 Milan,606 Vienna: Berlin,640 Warsaw,727 Warsaw: Moscow,1245 Zurich: Milan,292 Munich,303 Paris,592 Vienna,743 this is the pprogramme the hueristic distance is not measured but you can use any distance you want import sys, os import string ## global vars : citysign = ':' NL = '\n' alphanum = string.letters + string.digits ## Main program # def main(): "TUBEREAD : Main line!" global citysign, NL args = sys.argv[:] ## gets command-line arguments na = len(args) print args[0],"[version 1.0]" print "command-line args. =",na if na < 2: print "normal usage: python tuberead.py " args.append(raw_input("please give input textfile name: ")) na = len(args) textname = args[1] textfile = open(textname,"r") if textfile == None: print "Can't open file:",textname lc = 0 ; sc = 0 lines = {} ## empty dictionary (station names) citylist = [] ## empty list (line names) thisline = "Zonk" citydic = {} while 1: textline = textfile.readline() if not textline: break name = string.capwords(string.strip(textline)) sc = sc + 1 if citysign in name: newline = 1 print "city = ", name thiscity = string.replace(name,citysign,'') if not citydic.has_key(thiscity): citydic[thiscity] = [] ## citylist.append(thiscity) else: x = string.split(name,',') ##print x c = x[0] ##print c if not citydic.has_key(c): lc = lc + 1 citydic[c] = [] d = eval(x[1]) t1 = (c,d) citydic[thiscity].append(t1) ## also append symmetric link : t2 = (thiscity,d) citydic[c].append(t2) citylist = citydic.keys() citylist.sort() print citylist print print len(citylist),"distinct cities read from textfile." print ## print citydic ## I/O from user while 1: sn = raw_input("Enter city name: ") sn = string.strip(sn) if len(sn) < 1: break ## user hits CRLF to quit loop sd = raw_input("Enter destination city name: ") if len(sd) < 1: break ## user hits CRLF to quit loop sl = citydic.get(sn,[]) ra = len(sl) st = citydic.get(sd,[]) mu = len(st) print sn,sl,ra print sd,st,mu return 0 ## do search ## show result to user ## Call main and attempt to honour exit status: try: main() except KeyboardInterrupt: sys.exit(1) From rmallett@rational.com Mon Dec 18 22:03:30 2000 From: rmallett@rational.com (Mallett, Roger) Date: Mon, 18 Dec 2000 14:03:30 -0800 Subject: [Tutor] building callable function names on the fly Message-ID: I would like to know if function names can be build on the fly and then the newly built function named called. For example: L1: for marker in MARKER_LIST: L2: if index_for_marker = my_htm_string.find(marker) > -1: L3: func_name = 'Process_' + Marker L4: my_processed_htm_string = func_name(my_htm_string) L5: def Process_1():... L6: def Process_2().... etc. L3/L4 is the question here. It is obviously incorrect, but I would like to know what the correct way would be. I could use a bunch of *elif* statements (one for each element in MARKER_LIST), but I would like to build the name of the function to be called so that I have less lines to manage. In other words, if marker = '1', then I'd like to call Process_1, however, if marker = '2' then I'd like to call Process_2. Can such be done? Roger Mallett From kalle@gnupung.net Mon Dec 18 22:40:05 2000 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 18 Dec 2000 23:40:05 +0100 Subject: [Tutor] building callable function names on the fly In-Reply-To: ; from rmallett@rational.com on Mon, Dec 18, 2000 at 02:03:30PM -0800 References: Message-ID: <20001218234005.A1798@gnupung.net> --J/dobhs11T7y2rNN Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Roger Mallett: > I would like to know if function names can be build on the fly and then t= he > newly built function named called. >=20 > For example: >=20 > L1: for marker in MARKER_LIST: > L2: if index_for_marker =3D my_htm_string.find(marker) > -= 1: > L3: func_name =3D 'Process_' + Marker =20 > L4: my_processed_htm_string =3D func_name(my_htm_string) >=20 > L5: def Process_1():... > L6: def Process_2().... etc. There are several ways to do something like that. You could use the built-in function eval(), for example: =2E.. func_name =3D "Process_" + Marker my_processed_string =3D eval(func_name + "(my_htm_string)") =2E.. Now, I don't like eval very much, so I'd suggest another strategy, a list or dictionary of functions: def Process_1(arg): ... def Process_2(arg): ... funcs =3D [Process_1, Process_2] # No parens, just the names... for marker in MARKER_LIST: if index_for_marker =3D my_htm_string.find(marker) > -1: my_processed_string =3D funcs[marker](my_htm_string) This requires that marker is a valid index, perhaps you have to make it an integer or something. Or you could replace the list with a dictionary. The important thing to remember is that functions can be passed around, stored in lists or anything else you might come up with, just like any other objec= t. HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --J/dobhs11T7y2rNN Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6PpJFdNeA1787sd0RAll8AJ94KZ+vNR0ak4kS/dZ1KU4nPchkMACeK/Fv 4ffKS6DDbop/hvL+a5eNyrA= =qVsD -----END PGP SIGNATURE----- --J/dobhs11T7y2rNN-- From doug@postsmart.net Tue Dec 19 02:58:44 2000 From: doug@postsmart.net (Doug Ball) Date: Mon, 18 Dec 2000 20:58:44 -0600 Subject: [Tutor] Mulit-threading for windows Message-ID: <001401c06967$99e2cee0$8a00000a@darwin.net> This is a multi-part message in MIME format. ------=_NextPart_000_0011_01C06935.4F1F2C00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all: I am new to this list and am very excited to be learning python. Can any of you point me to where I might find out about multi-threading = in a windows environment ( FAQ had some stuff about Linux but I didn't = see anything about windows).=20 Thank you in advice! Doug ------=_NextPart_000_0011_01C06935.4F1F2C00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi all:
 
I am new to this list and am very = excited to be=20 learning python.
 
Can any of you point me to where I = might find out=20 about multi-threading in a windows environment ( FAQ had some stuff = about Linux=20 but I didn't see anything about windows).
 
Thank you in advice!
 
Doug
------=_NextPart_000_0011_01C06935.4F1F2C00-- From dyoo@hkn.eecs.berkeley.edu Tue Dec 19 07:19:39 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 18 Dec 2000 23:19:39 -0800 (PST) Subject: [Tutor] Mulit-threading for windows In-Reply-To: <001401c06967$99e2cee0$8a00000a@darwin.net> Message-ID: On Mon, 18 Dec 2000, Doug Ball wrote: > Can any of you point me to where I might find out about > multi-threading in a windows environment ( FAQ had some stuff about > Linux but I didn't see anything about windows). There shouldn't be much difference between the Linux and Windows stuff with multithreading; the os specific stuff should be hidden beneath the interface of the "threading" module. Do you have any specific questions about threads? One thing you should be careful about, though, is that threads don't work nicely with Tkinter (and especially IDLE) --- so don't try to test your threading code within IDLE, or else bad things happen. (This is explained in: http://sourceforge.net/bugs/?group_id=5470&func=detailbug&bug_id=121963 ) If you have any questions, please feel free to ask them. From wheelege@tsn.cc Tue Dec 19 09:27:03 2000 From: wheelege@tsn.cc (wheelege) Date: Tue, 19 Dec 2000 20:27:03 +1100 Subject: [Tutor] Mulit-threading for windows References: Message-ID: <007101c0699d$d9a62460$a410fea9@glen> ----- Original > One thing you should be careful about, though, is that threads don't work > nicely with Tkinter (and especially IDLE) --- so don't try to test your > threading code within IDLE, or else bad things happen. > > (This is explained in: > http://sourceforge.net/bugs/?group_id=5470&func=detailbug&bug_id=121963 > ) > I know all about that :) From rishi@musicurry.com Tue Dec 19 10:00:59 2000 From: rishi@musicurry.com (Rishi Maker) Date: Tue, 19 Dec 2000 15:30:59 +0530 Subject: [Tutor] threads Message-ID: <20001219153058.A32057@musicurry.com> Hi!!! I am sorry if this question is trivial ... i want to have a global variable accross different threads will python consider it as in java 'volatile' also i am looking for another java statement in python 'synchronized' does python have a corresponding statement .... -- --------------------------------------------------------------------------- Signature Follows :- Rishi Maker |------------Quote Of The Mail----------------| Senior Developer |Xerox your lunch and file it under "sex | rishi@musicurry.com |offenders"! | Tel-Res : 91-22-5374892 | | Tel-Off : 91-22-4603751/52 | | ICQ-UIN : 56551784 | | www.rishimaker.com | | ------------------------------------------------------------------------------- From dsh8290@rit.edu Tue Dec 19 16:37:32 2000 From: dsh8290@rit.edu (D-Man) Date: Tue, 19 Dec 2000 11:37:32 -0500 Subject: [Tutor] threads In-Reply-To: <20001219153058.A32057@musicurry.com>; from rishi@musicurry.com on Tue, Dec 19, 2000 at 03:30:59PM +0530 References: <20001219153058.A32057@musicurry.com> Message-ID: <20001219113732.A15062@westsidecnc.rh.rit.edu> AFAIK Python doesn't do any optimizations (like a C compiler would) that necessitate a 'volatile' keyword. Everything is considered as volatile. I haven't done any thread stuff in Python so I don't know if there is a need for "declaring" things as synchronized. You might just need to acquire/relase a lock, but I really don't know. HTH, -D On Tue, Dec 19, 2000 at 03:30:59PM +0530, Rishi Maker wrote: > > Hi!!! > I am sorry if this question is trivial ... > i want to have a global variable accross different threads > will python consider it as in java 'volatile' > also i am looking for another java statement in python 'synchronized' > does python have a corresponding statement .... > > -- > --------------------------------------------------------------------------- > Signature Follows :- > > Rishi Maker |------------Quote Of The Mail----------------| > Senior Developer |Xerox your lunch and file it under "sex | > rishi@musicurry.com |offenders"! | > Tel-Res : 91-22-5374892 | | > Tel-Off : 91-22-4603751/52 | | > ICQ-UIN : 56551784 | | > www.rishimaker.com | | > ------------------------------------------------------------------------------- > From kalle@gnupung.net Tue Dec 19 23:48:48 2000 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 20 Dec 2000 00:48:48 +0100 Subject: [Tutor] threads In-Reply-To: <20001219153058.A32057@musicurry.com>; from rishi@musicurry.com on Tue, Dec 19, 2000 at 03:30:59PM +0530 References: <20001219153058.A32057@musicurry.com> Message-ID: <20001220004847.C2700@gnupung.net> --4jXrM3lyYWu4nBt5 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Rishi Maker: >=20 > Hi!!! > I am sorry if this question is trivial ...=20 No problems, I for one like trivial questions. They're much more easy to answer (at least almost) correctly! [snip] > also i am looking for another java statement in python 'synchronized' > does python have a corresponding statement .... No, I'm afraid not. I believe you can use threading.RLock to achieve the same effect: [Disclaimer: I'm not sure about how 'synchronized' works, and I'm not very experienced with python threads either.] import threading, time lock =3D threading.RLock() def syncfunc(t): lock.acquire() for i in range(2): time.sleep(0.1) print t.getName(), i lock.release() class MyThread(threading.Thread): def run(self): for i in range(2): syncfunc(self) time.sleep(0.1) t1 =3D MyThread() t2 =3D MyThread() t1.start() t2.start() will give you a nice result: Thread-1 0 Thread-1 1 Thread-2 0 Thread-2 1 Thread-1 0 Thread-1 1 Thread-2 0 Thread-2 1 Without the lock, you should get: Thread-1 0 Thread-2 0 Thread-1 1 Thread-2 1 Thread-1 0 Thread-2 0 Thread-1 1 Thread-2 1 Also note that a threading.Lock object would have been enough in this example, but the RLock is more advanced. Read the 'threading' module docs = to learn about the difference, and what other threading tools you have at your disposal in Python. Good luck! Peace, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --4jXrM3lyYWu4nBt5 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6P/PfdNeA1787sd0RAvn5AKCpn/hFwu2iDV2lb/vQD4aCk32XjQCghYtn wNNUSPoRkovARUi61EuMeQw= =YX3r -----END PGP SIGNATURE----- --4jXrM3lyYWu4nBt5-- From darrell@brogdon.net Wed Dec 20 00:06:14 2000 From: darrell@brogdon.net (Darrell Brogdon) Date: Tue, 19 Dec 2000 19:06:14 -0500 Subject: [Tutor] valueOf() equivalent Message-ID: <3A3FF7F6.90105@brogdon.net> Is there a Python equivalent to the Java "valueOf()" method? For example, I want to be able to determine the value of 'tmp_var' in the following function: test_variable = 2 def myTestFunction(tmp_var, count_var): if( tmp_var == count_var ): print "Match!" else: print "No match" myTestFunction('test_variable', 5) From kalle@gnupung.net Wed Dec 20 00:27:17 2000 From: kalle@gnupung.net (Kalle Svensson) Date: Wed, 20 Dec 2000 01:27:17 +0100 Subject: [Tutor] valueOf() equivalent In-Reply-To: <3A3FF7F6.90105@brogdon.net>; from darrell@brogdon.net on Tue, Dec 19, 2000 at 07:06:14PM -0500 References: <3A3FF7F6.90105@brogdon.net> Message-ID: <20001220012717.D2700@gnupung.net> --3Gf/FFewwPeBMqCJ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Darrell Brogdon: > Is there a Python equivalent to the Java "valueOf()" method? For=20 > example, I want to be able to determine the value of 'tmp_var' in the=20 > following function: >=20 > test_variable =3D 2 >=20 > def myTestFunction(tmp_var, count_var): > if( tmp_var =3D=3D count_var ): > print "Match!" > else: > print "No match" >=20 > myTestFunction('test_variable', 5) I'm not sure I understand what you mean (don't remember much Java), but maybe the built-in function eval() is what you're looking for? test_variable =3D 2 if eval("test_variable") =3D=3D 2: print "Yes." else: print "No." will print Yes. But whenever I feel tempted to use eval, I rethink my program instead. I don't feel clean after using eval... A bunch of functions you might be interested in are int, float and str. int("20") =3D=3D 20 float("10.0") =3D=3D 10.0 # Maybe, you never know with floats... str(10) =3D=3D "10" The above example would become: test_variable =3D 2 if int(test_variable) =3D=3D 2: print "Yes." else: print "No." HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --3Gf/FFewwPeBMqCJ Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6P/zkdNeA1787sd0RAqZYAJ44IQ9UrpUUn52Q30qIlbIlLr4w7gCfZwtZ mV7hbnejz+40tuQjuZZLam4= =xRe6 -----END PGP SIGNATURE----- --3Gf/FFewwPeBMqCJ-- From darrell@brogdon.net Wed Dec 20 03:28:09 2000 From: darrell@brogdon.net (Darrell Brogdon) Date: Tue, 19 Dec 2000 22:28:09 -0500 Subject: [Tutor] valueOf() equivalent References: <3A3FF7F6.90105@brogdon.net> <20001220012717.D2700@gnupung.net> Message-ID: <3A402749.7070605@brogdon.net> Well, in Java you have the valueOf() method which, as its name sounds, will tell you the value of a member (variable). So in my example I could say: print tmp_var.valueOf() ...if Python were to have a valueOf() function. Here's a more complete example that may better explain what I'm trying to do: class myTestClass: test_variable = 2 def __init__(self): self.myTestFunc(self.test_variable, 4) def myTestFunc(self, my_var, var_val): my_test_var = my_var my_test_var = my_test_var + 1 if my_test_var < var_val: print "Yes." eval('self.my_var') = my_test_var # <-- I know this won't work but this is why I need a "valueOf()" equivalent. else: print "No." my_test = myTestClass() If you're familiar with PHP, this can be considered using a variable variable (http://php.net/manual/language.variables.variable.php). -Darrell Kalle Svensson wrote: > Sez Darrell Brogdon: > >> Is there a Python equivalent to the Java "valueOf()" method? For >> example, I want to be able to determine the value of 'tmp_var' in the >> following function: >> >> test_variable = 2 >> >> def myTestFunction(tmp_var, count_var): >> if( tmp_var == count_var ): >> print "Match!" >> else: >> print "No match" >> >> myTestFunction('test_variable', 5) > > I'm not sure I understand what you mean (don't remember much Java), but > maybe the built-in function eval() is what you're looking for? > > test_variable = 2 > if eval("test_variable") == 2: > print "Yes." > else: > print "No." > > will print Yes. > > But whenever I feel tempted to use eval, I rethink my program instead. I > don't feel clean after using eval... > > A bunch of functions you might be interested in are int, float and str. > int("20") == 20 > float("10.0") == 10.0 # Maybe, you never know with floats... > str(10) == "10" > > The above example would become: > > test_variable = 2 > if int(test_variable) == 2: > print "Yes." > else: > print "No." > > HTH, > Kalle From dyoo@hkn.eecs.berkeley.edu Wed Dec 20 06:10:36 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 19 Dec 2000 22:10:36 -0800 (PST) Subject: [Tutor] valueOf() equivalent In-Reply-To: <3A402749.7070605@brogdon.net> Message-ID: On Tue, 19 Dec 2000, Darrell Brogdon wrote: > Well, in Java you have the valueOf() method which, as its name sounds, > will tell you the value of a member (variable). So in my example I > could say: > > print tmp_var.valueOf() > > ...if Python were to have a valueOf() function. I think you're referring to Java's class wrappers over the primitive data types (integers, doubles, floats, chars...) Although Python's integers are objects (reference counted and all), you can just get the value of them by using the variable --- they're "primitive" in this sense. However, if you really want to use them, there are class wrappers for these types: UserList (class wrapper over lists): http://python.org/doc/current/lib/module-UserList.html UserDict (class wrapper over dictionaries): http://python.org/doc/current/lib/module-UserList.html UserString (class wrapper over strings): http://python.org/doc/current/lib/module-UserString.html In these three, you'd use the .data member to get at the value of the object. However, you will most likely not need to use these classes --- they're there if you want to extend their functionality through inheritence. Instead, just treat numbers and strings as primitives, and you should be ok. > eval('self.my_var') = my_test_var # <-- I know this won't > work but this is why I need a "valueOf()" equivalent. I believe you can do this with: self.my_var = my_test_var Just stick it in there. There's no need to use a valueOf(), since Python variables have no static type to worry about --- class instances are dynamic enough that you can just start stuffing extra variables into them. For example: ### class EmptyClass: pass x = EmptyClass() x.var1 = 42 x.name = 'Darrell' ### should be legal (as long as I didn't misspell anythign... *grin*) > If you're familiar with PHP, this can be considered using a variable > variable (http://php.net/manual/language.variables.variable.php). Reading through the php manual, this idea of "variable-named" variables sounds like you want to use either eval() for expressions or exec() for statements. Your statement above, then, could be expressed like this: exec("self.my_var = my_test_var") (But of course, if you were going to write this, you would do the more direct statement. I'm assuming you want to do some really dynamic code, perhaps by dynamically generating a statement out of a string?) If you're interested with dynamic variable stuff, take a look here: http://python.org/doc/current/lib/built-in-funcs.html The functions getattr() and setattr() should be very interesting to you: they let you add arbitrary "attributes" into a class instance, using a normal string as a name. So you can do stuff like: setattr(self, "my_" + "var", my_test_var) setattr(self, "my_" + "var", eval("my_test_var")) although it makes me feel a bit nervous seeing this sort of programming with wild abandon. > >> myTestFunction('test_variable', 5) To make this work, you'd do: myTestFunction(eval('test_variable'), 5) because the string 'test_variable' needs to be evaluated somehow --- otherwise, you're just passing the string 'test_variable' to your myTestFunction(). However, there are probably more direct ways of writing your program; you may find you don't need to use as many dynamically named variables. Tell us what you're writing, and we can make suggestions on Python idioms for doing something equivalent. I hope some if this made sense. If you have more questions or clarifications, please feel free to ask. From Nate Bargmann Thu Dec 21 03:29:25 2000 From: Nate Bargmann (Nate Bargmann) Date: Wed, 20 Dec 2000 21:29:25 -0600 Subject: [Tutor] Using a list as function argument? Message-ID: <20001220212925.A366@nomad.n0nb.ampr.org> Hi all. I'm wanting to write a function that utilizes several arguments. As I intend to read the arguments out of a file, they are already in a list variable. I would like to pass this list to a function, do my processing and then return a list to the calling routine which I can use. I'm just getting starting in Python and I really didn't find an answer in the Python tutorial, the FAQ at python.org or in the TYP book. Thanks, - Nate >> -- Wireless | Amateur Radio Station N0NB | "None can love freedom Internet | n0nb@networksplus.net | heartily, but good Location | Wichita, Kansas USA EM17hs | men; the rest love not Wichita area exams; ham radio; Linux info @ | freedom, but license." http://www.qsl.net/n0nb/ | -- John Milton From bxuef@freemail.sx.cn Thu Dec 21 04:02:55 2000 From: bxuef@freemail.sx.cn (bxuef@freemail.sx.cn) Date: Thu, 21 Dec 2000 12:02:55 +0800 (CST) Subject: [Tutor] please help Message-ID: Hi, I am just thinking about taking Python as my first programming language for serious learning, but some distrusts with its applicability prevent me from fully applying myself to it. Would you kindly help clear up some of my doubts about Python? 1. I want to use IIS 4.0 for my webserver, can I use scripts compiled by Python in it? 2. What about the ASP? If I want to use ASP, can I use Python to do such jobs like user authentication? How well can Python be used in Web programming on Windows platform? 3. I used VB in the past and you can make a '.exe' file after compiling. But how can I actually execute the Python program in Windows? It seems that I can not make a .exe file for it to execute. It is dependent on the interpreter? 4. If I really sit my self to Python, does it reward equally for the same effort in learning C? In the aspect of the quality of programs. Thank you in advance for answering my questions. An eager learner waiting for reply (By the way, if I begin my serious learning process, I will translate the tutorial into Chinese.) ----------------------------------------------------------- 欢迎使用山西电信免费电子邮件系统 。 如有问题,请与 webmaster@freemail.sx.cn 联系。 谢谢您的使用! From dyoo@hkn.eecs.berkeley.edu Thu Dec 21 10:47:39 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Thu, 21 Dec 2000 02:47:39 -0800 (PST) Subject: [Tutor] Using a list as function argument? In-Reply-To: <20001220212925.A366@nomad.n0nb.ampr.org> Message-ID: On Wed, 20 Dec 2000, Nate Bargmann wrote: > I'm wanting to write a function that utilizes several arguments. As I > intend to read the arguments out of a file, they are already in a list > variable. I would like to pass this list to a function, do my > processing and then return a list to the calling routine which I can > use. I'm just getting starting in Python and I really didn't find an > answer in the Python tutorial, the FAQ at python.org or in the TYP book. Let's try to write a function that, given a list of numbers, returns back a list of those numbers doubled. Here's a small interpreter session: ### >>> def doubleNumbers(numbers): ... results = [] # we'll collect our results in here ... for x in numbers: ... results.append(x + x) ... return results ... >>> doubleNumbers([1, 2, 3, 4, 5]) [2, 4, 6, 8, 10] >>> doubleNumbers("testing") ['tt', 'ee', 'ss', 'tt', 'ii', 'nn', 'gg'] ### So our doubleNumbers function can work on lists of numbers. The surprising thing is that it works on any kind of "sequence" --- anything that we can do a for-loop around. Just wanted to play around with it... *grin* So basically, you can make an empty list, and collect your results into it by using its append() function. This is the skeleton that I use when I want to process lists. Hope this helps! From dsh8290@rit.edu Thu Dec 21 13:54:06 2000 From: dsh8290@rit.edu (D-Man) Date: Thu, 21 Dec 2000 08:54:06 -0500 Subject: [Tutor] Using a list as function argument? In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Thu, Dec 21, 2000 at 02:47:39AM -0800 References: <20001220212925.A366@nomad.n0nb.ampr.org> Message-ID: <20001221085406.B1673@westsidecnc.rh.rit.edu> On Thu, Dec 21, 2000 at 02:47:39AM -0800, Daniel Yoo wrote: > Let's try to write a function that, given a list of numbers, returns back > a list of those numbers doubled. Here's a small interpreter session: > > ### > >>> def doubleNumbers(numbers): > ... results = [] # we'll collect our results in here > ... for x in numbers: > ... results.append(x + x) > ... return results > ... > >>> doubleNumbers([1, 2, 3, 4, 5]) > [2, 4, 6, 8, 10] > >>> doubleNumbers("testing") > ['tt', 'ee', 'ss', 'tt', 'ii', 'nn', 'gg'] > ### > > So our doubleNumbers function can work on lists of numbers. The > surprising thing is that it works on any kind of "sequence" --- anything > that we can do a for-loop around. Just wanted to play around with it... > *grin* > > So basically, you can make an empty list, and collect your results into it > by using its append() function. This is the skeleton that I use when I > want to process lists. Hope this helps! > Depending on your purpose in writing this, you could do: for i in range( len( numbers ) ) : numbers[i] += numbers[i] # this only works in Python 2.0 # numbers[i] = numbers[i] + numbers[i] # this will work in older pythons This sort of thing can be dangerous though since the argument is modified. It is generally considered cleaner to return the result instead like in Daniel's example. -D From Nate Bargmann Thu Dec 21 14:09:03 2000 From: Nate Bargmann (Nate Bargmann) Date: Thu, 21 Dec 2000 08:09:03 -0600 Subject: [Tutor] Using a list as function argument? In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Thu, Dec 21, 2000 at 02:47:39AM -0800 References: <20001220212925.A366@nomad.n0nb.ampr.org> Message-ID: <20001221080903.A460@nomad.n0nb.ampr.org> Thanks Daniel. I do appreciate the tip in your example. Turns out I actually had it working, but was mis-interpreting the program output! Thanks again. - Nate >> -- Wireless | Amateur Radio Station N0NB | "None can love freedom Internet | n0nb@networksplus.net | heartily, but good Location | Wichita, Kansas USA EM17hs | men; the rest love not Wichita area exams; ham radio; Linux info @ | freedom, but license." http://www.qsl.net/n0nb/ | -- John Milton From darrell@brogdon.net Fri Dec 22 02:39:39 2000 From: darrell@brogdon.net (Darrell Brogdon) Date: Thu, 21 Dec 2000 21:39:39 -0500 Subject: [Tutor] valueOf() equivalent References: Message-ID: <3A42BEEB.4090109@brogdon.net> Thanks for the help. In working on my code I found I didn't need to do this after all. But the suggestions were helpful and provided good insight. Another unrelated question though: Is there a requirement to close an "os.popen()" connection? I've checked the docs and haven't found anything. If not then is it safe to assume that Python automatically closes these connections when the script ends? I just want to make sure I'm not leaving a bunch of open connections in my script. Daniel Yoo wrote: > On Tue, 19 Dec 2000, Darrell Brogdon wrote: > > >> Well, in Java you have the valueOf() method which, as its name sounds, >> will tell you the value of a member (variable). So in my example I >> could say: >> >> print tmp_var.valueOf() >> >> ...if Python were to have a valueOf() function. > > I think you're referring to Java's class wrappers over the primitive data > types (integers, doubles, floats, chars...) > > Although Python's integers are objects (reference counted and all), you > can just get the value of them by using the variable --- they're > "primitive" in this sense. However, if you really want to use them, there > are class wrappers for these types: > > UserList (class wrapper over lists): > http://python.org/doc/current/lib/module-UserList.html > > UserDict (class wrapper over dictionaries): > http://python.org/doc/current/lib/module-UserList.html > > UserString (class wrapper over strings): > http://python.org/doc/current/lib/module-UserString.html > > In these three, you'd use the .data member to get at the value of the > object. However, you will most likely not need to use these classes --- > they're there if you want to extend their functionality through > inheritence. Instead, just treat numbers and strings as primitives, and > you should be ok. > > > >> eval('self.my_var') = my_test_var # <-- I know this won't >> work but this is why I need a "valueOf()" equivalent. > > > I believe you can do this with: > > self.my_var = my_test_var > > Just stick it in there. There's no need to use a valueOf(), since Python > variables have no static type to worry about --- class instances are > dynamic enough that you can just start stuffing extra variables into > them. For example: > > ### > class EmptyClass: pass > > x = EmptyClass() > x.var1 = 42 > x.name = 'Darrell' > ### > > should be legal (as long as I didn't misspell anythign... *grin*) > > > >> If you're familiar with PHP, this can be considered using a variable >> variable (http://php.net/manual/language.variables.variable.php). > > Reading through the php manual, this idea of "variable-named" variables > sounds like you want to use either eval() for expressions or exec() for > statements. Your statement above, then, could be expressed like this: > > exec("self.my_var = my_test_var") > > (But of course, if you were going to write this, you would do the more > direct statement. I'm assuming you want to do some really dynamic code, > perhaps by dynamically generating a statement out of a string?) > > > If you're interested with dynamic variable stuff, take a look here: > > http://python.org/doc/current/lib/built-in-funcs.html > > The functions getattr() and setattr() should be very interesting to > you: they let you add arbitrary "attributes" into a class instance, using > a normal string as a name. So you can do stuff like: > > setattr(self, "my_" + "var", my_test_var) > setattr(self, "my_" + "var", eval("my_test_var")) > > although it makes me feel a bit nervous seeing this sort of programming > with wild abandon. > > > >>>> myTestFunction('test_variable', 5) >>> > To make this work, you'd do: > > myTestFunction(eval('test_variable'), 5) > > because the string 'test_variable' needs to be evaluated somehow --- > otherwise, you're just passing the string 'test_variable' to your > myTestFunction(). > > However, there are probably more direct ways of writing your program; you > may find you don't need to use as many dynamically named variables. Tell > us what you're writing, and we can make suggestions on Python idioms for > doing something equivalent. > > > I hope some if this made sense. If you have more questions or > clarifications, please feel free to ask. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor -- Darrell Brogdon http://darrell.brogdon.net From dsh8290@rit.edu Fri Dec 22 05:05:46 2000 From: dsh8290@rit.edu (D-Man) Date: Fri, 22 Dec 2000 00:05:46 -0500 Subject: [Tutor] Closing handles (was valueOf() equivalent) In-Reply-To: <3A42BEEB.4090109@brogdon.net>; from darrell@brogdon.net on Thu, Dec 21, 2000 at 09:39:39PM -0500 References: <3A42BEEB.4090109@brogdon.net> Message-ID: <20001222000546.B22858@westsidecnc.rh.rit.edu> Since python is interpreted, the interpreter provides you with all the benefits of a smart run-time system. The interpreter will close all file handles (and I imagine network connections too) before terminating. Even if you are working in C, file handles are closed by the system upon exit. I don't know about the handles on a popen() connection, though. In any case it's still good practice to explicitly close all file handles and network connections before exiting. HTH, -D On Thu, Dec 21, 2000 at 09:39:39PM -0500, Darrell Brogdon wrote: > Thanks for the help. In working on my code I found I didn't need to do > this after all. But the suggestions were helpful and provided good insight. > > Another unrelated question though: Is there a requirement to close an > "os.popen()" connection? I've checked the docs and haven't found > anything. If not then is it safe to assume that Python automatically > closes these connections when the script ends? I just want to make sure > I'm not leaving a bunch of open connections in my script. > From klchua@apis.dhl.com Fri Dec 22 10:16:42 2000 From: klchua@apis.dhl.com (Chua Kia Loong) Date: Fri, 22 Dec 2000 18:16:42 +0800 Subject: [Tutor] Compile python to executable binary? Message-ID: <3A432A0A.6D786A65@apis.dhl.com> --------------E894351F247065A9A90246D6 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Hi, (1) I am wonder can *.py scripts be compile to excutable binary file? If yes, (2) What are the steps that need to taken for compilation. (3) With the compiled binary file, can it be run in the mechine which does not have python installed? Thank you. -- Regards, /Chua Kia Loong Email: klchua@apis.dhl.com Asia Pacific Information Services, DHL Worldwide Express, Kuala Lumpur. --------------E894351F247065A9A90246D6 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit
Hi,
(1) I am wonder can *.py scripts be compile to excutable binary file?
If yes,
(2) What are the steps that need to taken for compilation.
(3) With the compiled binary file, can it be run in the mechine which does not have python installed?


Thank you.


-- 

Regards,
/Chua Kia Loong
Email: klchua@apis.dhl.com
Asia Pacific Information Services, 
DHL Worldwide Express, Kuala Lumpur.
  --------------E894351F247065A9A90246D6-- From darrell@brogdon.net Fri Dec 22 15:38:57 2000 From: darrell@brogdon.net (Darrell Brogdon) Date: Fri, 22 Dec 2000 10:38:57 -0500 Subject: [Tutor] Closing handles (was valueOf() equivalent) References: <3A42BEEB.4090109@brogdon.net> <20001222000546.B22858@westsidecnc.rh.rit.edu> Message-ID: <3A437591.8000903@brogdon.net> D-Man wrote: > In any case it's still good practice to explicitly close all file handles and > network connections before exiting. Ok so, uh, how do I close a connection that has been opened with 'os.popen()'? I was reasonably confident that Python would close the connection for me but I always try to close anything I open in my code just to be sure. -- Darrell Brogdon http://darrell.brogdon.net From dbrogdon@valinux.com Fri Dec 22 15:44:52 2000 From: dbrogdon@valinux.com (Darrell Brogdon) Date: Fri, 22 Dec 2000 10:44:52 -0500 Subject: [Tutor] pinging from python References: Message-ID: <3A4376F4.2010408@valinux.com> For future reference: fp = os.popen('ping -c 4 yahoo.com') ping_results = fp.read() I'm not sure how to explicitly close this connection yet (see the "valueOf() equivalent" thread) Deirdre Saoirse wrote: > On Sat, 16 Dec 2000, JD, Venugopal (CORP, CIM, OMC) wrote: > > >> is it possible to ping to a host using python and redirect the output >> to a comma seperated value flat file. > > First of all, this is a good way to make enemies -- ping *can* be used as > a hostile denial-of-service. Please don't use it this way. > > Yes, there are several ways of doing this: > > 1) On Unix, you can redirect the status of an external command -- see the > commands module. > > 2) You can re-write the c-based "ping" program in python. Source code for > ping is available in numerous places, including with most Linux > distributions. > -- Darrell Brogdon http://darrell.brogdon.net Web Developer - SourceForge http://sourceforge.net VA Linux Systems, Inc. http://www.valinux.com From dsh8290@rit.edu Fri Dec 22 15:57:51 2000 From: dsh8290@rit.edu (D-Man) Date: Fri, 22 Dec 2000 10:57:51 -0500 Subject: [Tutor] pinging from python In-Reply-To: <3A4376F4.2010408@valinux.com>; from dbrogdon@valinux.com on Fri, Dec 22, 2000 at 10:44:52AM -0500 References: <3A4376F4.2010408@valinux.com> Message-ID: <20001222105751.A24495@westsidecnc.rh.rit.edu> popen returns a file object, right? If so: On Fri, Dec 22, 2000 at 10:44:52AM -0500, Darrell Brogdon wrote: > For future reference: > > fp = os.popen('ping -c 4 yahoo.com') > ping_results = fp.read() fp.close() HTH, -D From dsh8290@rit.edu Fri Dec 22 16:01:20 2000 From: dsh8290@rit.edu (D-Man) Date: Fri, 22 Dec 2000 11:01:20 -0500 Subject: [Tutor] Compile python to executable binary? In-Reply-To: <3A432A0A.6D786A65@apis.dhl.com>; from klchua@apis.dhl.com on Fri, Dec 22, 2000 at 06:16:42PM +0800 References: <3A432A0A.6D786A65@apis.dhl.com> Message-ID: <20001222110120.B24495@westsidecnc.rh.rit.edu> I can't answer all of the questions, but you can run your app without a separate interpreter installed on the machine *if* 1) You package an interpreter with your installer (basically you provide it for them) or 2) You package an interpreter with your program. Maybe make a little C program that embeds the interpreter and runs your scripts. alternatively, 3) You make or find a compiler that will turn python code into native machine code. or 4) You make a machine that executes python byte-code directly (IBM and Sun started such a project for Java but discontinued it when the VM's got fast enough) HTH, -D On Fri, Dec 22, 2000 at 06:16:42PM +0800, Chua Kia Loong wrote: > Hi, > > (1) I am wonder can *.py scripts be compile to excutable binary file? > > If yes, > > (2) What are the steps that need to taken for compilation. > > (3) With the compiled binary file, can it be run in the mechine which does not have python installed? > > Thank you. > > -- > > Regards, > /Chua Kia Loong > Email: klchua@apis.dhl.com > Asia Pacific Information Services, > DHL Worldwide Express, Kuala Lumpur. > From arcege@shore.net Fri Dec 22 16:56:48 2000 From: arcege@shore.net (Michael P. Reilly) Date: Fri, 22 Dec 2000 11:56:48 -0500 (EST) Subject: [Tutor] Closing handles (was valueOf() equivalent) In-Reply-To: <3A437591.8000903@brogdon.net> from "Darrell Brogdon" at Dec 22, 2000 10:38:57 AM Message-ID: <200012221656.LAA07013@northshore.shore.net> > > D-Man wrote: > > > In any case it's still good practice to explicitly close all file handles and > > network connections before exiting. > > Ok so, uh, how do I close a connection that has been opened with > 'os.popen()'? > > I was reasonably confident that Python would close the connection for me > but I always try to close anything I open in my code just to be sure. There is another value of closing a popen'd connection. Every program has an "exit status" code, which is sometimes very useful. This exit code is retrieved (as per os.wait) when you close the returned file object. >>> f = os.popen('finger %s@localhost' % username, 'r') >>> finger_output = f.read() >>> status = f.close() >>> if status is not None: # close() (and the related wait()) returns ... # None instead of the usual 0 ... >>> # the finger failed >>> raise SystemError( "finger failed", os.WEXITSTATUS(status) ) Then you can use the os.WEXITSTATUS, os.WIFEXITED, os.WIFSIGNALED, os.WIFSTOPPED, os.WSTOPSIG and os.WTERMSIG functions. There are other issues (specifically relating to UNIX systems) but those are just details and shouldn't matter that much for basic operations. -Arcege References: 1. Python Language Reference, section 6.1.2 File Object Creation 2. Python Language Reference, section 6.1.5 Process Management -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From rear@sirius.com Fri Dec 22 19:22:44 2000 From: rear@sirius.com (Bob) Date: Fri, 22 Dec 2000 11:22:44 -0800 Subject: [Tutor] Beginner's Question Message-ID: <00122211250809.12381@gandalf> I am setting out to learn python. I have some books, those from O'Reilly and the Quick Pythom Book, and I have found the online tutorials, and done Josh Cogliati's. I need to know where to go from here, I guess. But what I *really* need are programming projects matched to what I have learned so far. Any suggestions, either projects or textbooks? I work in Linux, by the way. -- Bob Rea =09Freedom is only privilege extended =09=09unless enjoyed by one and all =09=09--Billy Bragg rear@sirius.com rrea@askjeeves.com http://www.sirius.com/~rear From dsh8290@rit.edu Fri Dec 22 20:02:03 2000 From: dsh8290@rit.edu (D-Man) Date: Fri, 22 Dec 2000 15:02:03 -0500 Subject: [Tutor] Beginner's Question In-Reply-To: <00122211250809.12381@gandalf>; from rear@sirius.com on Fri, Dec 22, 2000 at 11:22:44AM -0800 References: <00122211250809.12381@gandalf> Message-ID: <20001222150203.A25499@westsidecnc.rh.rit.edu> It sounds as if you have succeeded in getting through all those tutorials and books. Yes, a project is the important thing to really learning a language or library or whatever. I would suggest checking at Sourceforge (www.sourceforge.net) and find some project using python that interests you. Study what the project is supposed to do, how it does it and volunteer to help continue it. HTH, -D On Fri, Dec 22, 2000 at 11:22:44AM -0800, Bob wrote: > I am setting out to learn python. I have some books, those from > O'Reilly and the Quick Pythom Book, and I have found the online > tutorials, and done Josh Cogliati's. I need to know where to go from > here, I guess. But what I *really* need are programming projects > matched to what I have learned so far. Any suggestions, either > projects or textbooks? > > I work in Linux, by the way. > > -- Bob Rea > > Freedom is only privilege extended > unless enjoyed by one and all > --Billy Bragg > > rear@sirius.com rrea@askjeeves.com http://www.sirius.com/~rear > From shaleh@valinux.com Fri Dec 22 20:03:55 2000 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Fri, 22 Dec 2000 12:03:55 -0800 (PST) Subject: [Tutor] Beginner's Question In-Reply-To: <00122211250809.12381@gandalf> Message-ID: On 22-Dec-2000 Bob wrote: > I am setting out to learn python. I have some books, those from > O'Reilly and the Quick Pythom Book, and I have found the online > tutorials, and done Josh Cogliati's. I need to know where to go from > here, I guess. But what I *really* need are programming projects > matched to what I have learned so far. Any suggestions, either > projects or textbooks? > > I work in Linux, by the way. > simple ideas for starting any new language: rewrite something small you already use in the new language. For instance, reimplement cat or grep. You need not fully implement them, just feel like you can do it without reaching for the book every other line. write scripts to help you in every day life. Nothing fancy, just things to make life easier. 30 minutes of python coding can remove 2 minutes of a repetitive task which saves time in the long run. find something written in python and either add features or fix a bug. try to answer questions here on the list. By teaching, you learn. From c.gruschow@prodigy.net Fri Dec 22 20:26:03 2000 From: c.gruschow@prodigy.net (Charles Gruschow, Jr.) Date: Fri, 22 Dec 2000 14:26:03 -0600 Subject: [Tutor] I haven't touched nor played with Python in quite awhile, but I had a ? about serial ports. Message-ID: <000901c06c55$68e79000$7fdf6520@gruschow> I haven't touched nor played with Python in quite awhile, but I had a ? about serial ports. Can Python send and receive signals from a serial port? Like for a serial port device of some sort. Or for actuator motors in robotics. Someday I wanted to experiment with robotics, but that's someday. Well, anyway how would you do this with Python? Or do you need something else? Out of curiousity, if there are examples for an actuator motor that would be cool too. Thank you, Charles W. Gruschow, Jr. c.gruschow@prodigy.net From deirdre@deirdre.net Fri Dec 22 20:40:35 2000 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Fri, 22 Dec 2000 12:40:35 -0800 (PST) Subject: [Tutor] I haven't touched nor played with Python in quite awhile, but I had a ? about serial ports. In-Reply-To: <000901c06c55$68e79000$7fdf6520@gruschow> Message-ID: How it is done depends a bit on the OS, but in most OSes, it's a device you stuff data into and listen to. In other words, it's one of those things that seems complex until you do it. But the fundamentals are indeed there. Again, the specifics *do* depend on the OS, which you didn't specify. On Fri, 22 Dec 2000, Charles Gruschow, Jr. wrote: > I haven't touched nor played with Python in quite awhile, but I had a > ? about serial ports. > > Can Python send and receive signals from a serial port? Like for a > serial port device of some sort. Or for actuator motors in robotics. > Someday I wanted to experiment with robotics, but that's someday. > > Well, anyway how would you do this with Python? Or do you need > something else? > > Out of curiousity, if there are examples for an actuator motor that > would be cool too. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "Our society has not yet gone so far as to place blind faith in machines. In almost all endeavors, humans routinely correct the errors of machines." - Florida Supreme Court From c.gruschow@prodigy.net Fri Dec 22 20:48:31 2000 From: c.gruschow@prodigy.net (Charles Gruschow, Jr.) Date: Fri, 22 Dec 2000 14:48:31 -0600 Subject: [Tutor] with my ? posted today I meant Windows 98 and Python 1.5.2 about the serial port programming Message-ID: <003201c06c58$8c4dba80$7fdf6520@gruschow> with my ? posted today I meant Windows 98 and Python 1.5.2 about the serial port programming Thank you Charles W. Gruschow, Jr. c.gruschow@prodigy.net From rmallett@rational.com Sat Dec 23 00:18:23 2000 From: rmallett@rational.com (Mallett, Roger) Date: Fri, 22 Dec 2000 16:18:23 -0800 Subject: [Tutor] Scope and values in a list Message-ID: I am having problems with a *for* loop picking up the *modified* value of a list and would therefore like some to better understand SCOPE. My basic problem is for n in myList: ... then in a deeply nested *if* I modified the values of the list: myList = newList The change to the list consists of eliminating some elements from the list Looking at the STACK VIEW, I can observe the modifications taking place to the list; however, when the loop comes back around and *n* is assigned a new value it still seems to have access to the original list. How might I make such changes? (Note: I don't seem to experience this problem when working in the interactive window, but then again, I am not using such a deeply nested set of statements. Any help is greatly appreciated. Roger Mallett From jgodbier@yahoo.com.au Sat Dec 23 01:11:15 2000 From: jgodbier@yahoo.com.au (=?iso-8859-1?q?jeremy?=) Date: Sat, 23 Dec 2000 12:11:15 +1100 (EST) Subject: [Tutor] merry christmas to you all Message-ID: <20001223011115.7693.qmail@web3704.mail.yahoo.com> thanks for all the nerdy talk throughout the year people :) take it easy in the festive season and have a smashing new year regards jeremy _____________________________________________________________________________ http://au.classifieds.yahoo.com/au/car/ - Yahoo! Cars - Buy, sell or finance a car.. From rael@oreilly.com Sat Dec 23 01:31:12 2000 From: rael@oreilly.com (Rael Dornfest) Date: Fri, 22 Dec 2000 17:31:12 -0800 (PST) Subject: [Tutor] merry christmas to you all In-Reply-To: <20001223011115.7693.qmail@web3704.mail.yahoo.com> Message-ID: Howdy, I've only just joined this list, but have certainly learned by lurking. Expect gobs of questions from me in the new year ;-) Oh, and some answers too, I expect. Have a Merry Christman, Happy Channukkah, and Happy (and Safe!) New Year. Rael On Sat, 23 Dec 2000, [iso-8859-1] jeremy wrote: > thanks for all the nerdy talk throughout the year > people :) > > take it easy in the festive season and have a smashing > new year From cpsoct@lycos.com Sun Dec 24 08:43:09 2000 From: cpsoct@lycos.com (kevin parks) Date: Sun, 24 Dec 2000 17:43:09 +0900 Subject: [Tutor] text editors for python on mac & import Message-ID: what is the best text editor to use for python on the macintosh. I would love to have a python aware editor with sytax coloring, etc. Is there some way to turn this on in the IDLE or are mac users left behind once again. I looked at alpha, which is great for tcl, but it seems not to have a python mode. I am just beginning with python and am very happy to learn it. It is very cool. but i also wonder, is it not possible to use the full path for import as in: import /foo/bar/mystuff * I was unable to do this, is it no allowed? cheers, kevin seoul, korea cpsoct@lycos.com Get FREE Email/Voicemail with 15MB at Lycos Communications at http://comm.lycos.com From deirdre@deirdre.net Sun Dec 24 09:11:06 2000 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Sun, 24 Dec 2000 01:11:06 -0800 (PST) Subject: [Tutor] text editors for python on mac & import In-Reply-To: Message-ID: On Sun, 24 Dec 2000, kevin parks wrote: > what is the best text editor to use for python on the macintosh. I > would love to have a python aware editor with sytax coloring, etc. Is > there some way to turn this on in the IDLE or are mac users left > behind once again. I looked at alpha, which is great for tcl, but it > seems not to have a python mode. BBEdit is the single best editor on the Mac. I don't know if the current version does syntax highlighting for Python, but I'm hoping it will soon if it doesn't already. At work, I use NEdit on Linux, which does (but which I've always considered a poor cousin to BBEdit). BBEdit has a commercial and a free (as in beer, not as in "free software") version. It can be found at http://www.barebones.com/ I'm just glad I finally know enough about Unix to finally use all its features. ;) I just moved back to MacOS for my desktop OS, so I suspect I'll be going through this again. > I am just beginning with python and am very happy to learn it. It is > very cool. > > but i also wonder, is it not possible to use the full path for import > as in: > > import /foo/bar/mystuff * > > I was unable to do this, is it no allowed? There's two parts to this answer. Yes, it is allowed, but...you did it incorrectly on two counts: 1) The correct procedure generally is listed on http://www.python.org/doc/2.0b1/lib/node240.html import sys sys.path.insert(0, "/usr/home/joe/lib/python") sys.path.insert(0, "/usr/local/lib/python") In other words, you add the paths to the list of directories to search; to do this, you must first import sys and add the paths before anything you import that's not in an expected place. 2) On the Mac, you need to use the correct OS separator. Only MacOS X running in native mode would use slashes; the directory separator on a Mac is a colon. See: http://www.python.org/doc/2.0b1/lib/os-path.html (I'm using MacOS X Public Beta now and I *love* it -- still a bit unstable, but life on the edge is fun!) -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "Our society has not yet gone so far as to place blind faith in machines. In almost all endeavors, humans routinely correct the errors of machines." - Florida Supreme Court From dsh8290@rit.edu Sun Dec 24 20:22:48 2000 From: dsh8290@rit.edu (D-Man) Date: Sun, 24 Dec 2000 15:22:48 -0500 Subject: [Tutor] text editors for python on mac & import In-Reply-To: ; from cpsoct@lycos.com on Sun, Dec 24, 2000 at 05:43:09PM +0900 References: Message-ID: <20001224152248.C2648@westsidecnc.rh.rit.edu> vim is the best text editor! (though we don't need to start an editor war here) Vim is available and runs on many systems (and is open source), but I don't know if anyone has packaged it for the mac yet. -D From dyoo@hkn.eecs.berkeley.edu Mon Dec 25 02:52:07 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 24 Dec 2000 18:52:07 -0800 (PST) Subject: [Tutor] Scope and values in a list In-Reply-To: Message-ID: On Fri, 22 Dec 2000, Mallett, Roger wrote: > I am having problems with a *for* loop picking up the *modified* value of a > list and would therefore like some to better understand SCOPE. [warning --- this message is long and wanders a bit] Before we do anything, let's test something out: ### >>> L1 = [1, 2, 3, 4] >>> L2 = L1 >>> L2[0] = 'one' >>> L2 ['one', 2, 3, 4] >>> L1 ['one', 2, 3, 4] ### Whenever we direct another variable to a preexisting list, it's as if we are giving the list a different name or alias --- it's still the same list, so when we make changes to the list, it'll look as if we modified both of them. Diagramically, it looks like this: L1 -------> [1, 2, 3, 4] ^ L2 ---------| On the other hand: ### >>> L1 = [1, 2, 3, 4] >>> L2 = L1 >>> L2 = ['one', 'two', 'three', 'four'] >>> L1 [1, 2, 3, 4] >>> L2 ['one', 'two', 'three', 'four'] ### Here we see that when we redirect L2 to a new list, L1 still points to the old one. This looks like the diagram: L1 -------> [1, 2, 3, 4] L2 -------> ['one', 'two', 'three', 'four'] With that background out of the way, let's try a few examples to see if we can trigger your scoping problem. First: ### Case #1 >>> mylist = list(range(10)) >>> for x in mylist: ... mylist.append(x) ... # waited for about 3 seconds, realized it was # an infinite loop, and Ctrl-C'ed it Traceback (innermost last): File "", line 2, in ? KeyboardInterrupt >>> len(mylist) 800885 ### So it does appear that you can modify a list in-place. So that's probably not what you did. Let's try another example: ### Case #2 >>> L = list(range(2)) >>> for x in L: ... L = list(range(5)) ... >>> print L [0, 1, 2, 3, 4] ### So that also seems to work. That doesn't trigger the behavior you reported. (At least, not at first glance. In actuality, it does, but we don't see it.) Let's try something else. ### Case #3 >>> L = list(range(2)) >>> for x in L: ... print x ... L = list(range(len(L) * 2)) ... 0 1 ### Ah ha! There's that weird scoping problem. We expected to see another infinite loop, since L's length was supposed to double through each loop iteration. What's happening? The statement "for x in L" is slightly special in the sense that Python really keeps track of that list: you can think of it as Python giving the list some sort of anonymous variable name, which it uses later to access each list element. So if we do something like this: L = [1, 2, 3, 4] for x in L: ... the diagram of what Python sees looks like this: L ------------> [1, 2, 3, 4] ^ | anonymous_name --| After it gives an anonymous variable naming to the list, it'll grab each element using the anonymous variable. Why all this indirection? This model might seem a little awkward, but it helps to explain what happens in the second and third cases. In order to do a for loop, Python will try to grab elements until it hits an IndexError. In the first case, since we kept adding new elements to the same list, we never hit rock bottom --- it keeps going. We're making internal changes to the same list, and that explains the first case's infinite loop. What's happening in the second? Let's take a look again: ### Case #2 >>> L = list(range(2)) >>> for x in L: ... L = list(range(5)) ... >>> print L [0, 1, 2, 3, 4] ### Well, it's redirecting L to a new list. What's crucial to notice is that the for loop is still iterating through the list [0, 1] --- once it knows which list to iterate over, it doesn't look at where L is redirected to. And that's what the third case shows us: ### Case #3 >>> L = list(range(2)) >>> for x in L: ... print x ... L = list(range(len(L) * 2)) ... 0 1 ### We see that the for loop goes through the elements [0, 1], but it doubles the length of L each time through the loop. In fact, let's print out L to make sure that this is what just happened: ### >>> L [0, 1, 2, 3, 4, 5, 6, 7] ### This might make more sense if we slightly reword what Python might do to perform a for-loop: ### for x in L: ... # body of the loop ### could conceivable be rewritten as: ### non_conflicting_list_name = L non_conflicting_list_index = 0 try: while 1: x = non_conflicting_list_name[non_conflicting_list_index] ... # body of the loop non_conflicting_list_index += 1 except IndexError: pass ### *pant pant* Now THAT was long-winded. The above might not even be how Python does things, but this model explains what might be happening underneath the surface. Anyway, experiment with it a little more. You might find a nicer way of explaining what's happening --- it so, please post it up. *grin* Good luck! From cpsoct@lycos.com Mon Dec 25 13:21:38 2000 From: cpsoct@lycos.com (kevin parks) Date: Mon, 25 Dec 2000 22:21:38 +0900 Subject: [Tutor] information hiding = interface & documntation hiding Message-ID: information hiding is supposed to olny hide the implementation, not the interface! But unfortunately, the interfac for a piece of code is mysterious to me. There are tons of modules, packages, proceedures, objects, classes, and function that come with the python distribution and also to be fond on the net. The problem is knowing what input they expect and what the output is. Only the people who program them seem to know this and there is often little or no documentation to b found. Additionally there are often dependencies to be known about and often not to be found. I would really like help with this. This whole OOP thing is such a farce sometimes. The whole idea is that you are supposed to be able to mak use of code thatyo didn't (or in my case couldn't) implement yourself. I am not an algorythms guy and i don't want to reinvent the wheel. i would like to use all the code inthe python image, but getting to know what is in the image and how to use it is so hard. What tools does python have for this? If any? How cani know if my code names are unque orif my funcs are overiding somthing that aleady exsits. In TCL one just types a nam in the the shll. if there is a proc of that name it comes up and the interface is often tere too. For example, i saw there was a markov.py file in the standard distribution, but i have no idea how to use it, when i try to compile it it barfs on me. Sory to such a dumb question, but i am really excited about python, but confused about how to use much of the code that i encounter. cheers, kevin parks seoul, korea Get FREE Email/Voicemail with 15MB at Lycos Communications at http://comm.lycos.com From alan.gauld@freenet.co.uk Tue Dec 26 15:27:40 2000 From: alan.gauld@freenet.co.uk (Alan Gauld) Date: Tue, 26 Dec 2000 15:27:40 +0000 Subject: [Tutor] valueOf() eqivalent Message-ID: <3.0.1.32.20001226152740.006f0b80@mail.freenet.co.uk> > Is there a Python equivalent to the Java "valueOf()" method? First there is no single valueOf() method in Java rather it is part of the object protocol there being one static method per type. The direct equivalent in python are the conversion functions: str() int() etc. Usually you don't need them as often as you need valueOf() in Java because of Pythons intelligent dynamic typing. > I want to be able to determine the value of 'tmp_var' in > the following function: > >test_variable = 2 > >def myTestFunction(tmp_var, count_var): > if( tmp_var == count_var ): > print "Match!" > else: > print "No match" > >myTestFunction('test_variable', 5) Assuming those are backquotes above to convert 2(a number) to "2"(a string) you can convert back again with: if int(tmp_var) == count_var If you don't know the type of count_var you could do something like: count_t = type(count_var) if count_t == type(1): # integer tmp2 = int(tmp_var) elif count_t == type("s"): # string tmp2 = str(tmp_var) elif count_t == type(1.0): # float tmp2 = float(tmp_var) etc... then if tmp2 == count_var: ... I suspect there's a cleverer way of doing this using Python's introspection capabilities but I leave the exprerts to tell us how :-) Alan g. From cruciatuz Tue Dec 26 15:42:57 2000 From: cruciatuz (cruciatuz) Date: Tue, 26 Dec 2000 16:42:57 +0100 Subject: [Tutor] vim for macintosh Message-ID: <13814802354.20001226164257@gmx.de> Hello Tutor, Since i am using vim under windows and unix and i like it's powerful and easy-to-use features and ... argh! no editor war here. I agree ;) Just check out: http://www.vim.org/macs.html , ok? good :) + ---------------------------------- + | Best regards: Cruciatuz_AH | + ---------------------------------- + | AKA: Stefan Antoni | + ---------------------------------- + | ICQ: 72292815 | | web (d2-clan): www.cruciatuz.de | | PGP-Key: AVAILABLE | + ---------------------------------- + 16:40 / Dienstag, 26. Dezember 2000 From rmallett@rational.com Tue Dec 26 16:49:33 2000 From: rmallett@rational.com (Mallett, Roger) Date: Tue, 26 Dec 2000 08:49:33 -0800 Subject: [Tutor] Scope and values in a list Message-ID: <78D9B26221DBD411B7EE00D0B73EB0EA06660B@cupex2.rational.com> Remco, Alright, being that > When you do "myList = newList", > that old list isn't changed at > all, rather myList now refers to > a new list. AND being that: "since everything in Python is a reference, and the variable doesn't hold any value but is a name for an object", then why does x display its newly assigned value (10...19) once the *for* loop has complete (see output below)? Seems that myList does indeed take on the new value, but that the "i" in the *for* loop is using a snapshot of the myList object to iterate (and not actually using myList). Is that true? I appreciate the response you gave, it was very helpful. The problem has bothering me for a couple of days as I've been attempting to figure it out without writing a hack. Now that I know exactly what is happening, I can create a proper fix. >>> x = range(10) >>> for i in x: ... x = range(10,20) ... print i, ... 0 1 2 3 4 5 6 7 8 9 >>> x [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> Roger Mallett -----Original Message----- From: Remco Gerlich [mailto:scarblac@pino.selwerd.nl] Sent: Saturday, December 23, 2000 12:16 AM To: Mallett, Roger Subject: Re: [Tutor] Scope and values in a list On Fri, Dec 22, 2000 at 04:18:23PM -0800, Mallett, Roger wrote: > I am having problems with a *for* loop picking up the *modified* value of a > list and would therefore like some to better understand SCOPE. > > My basic problem is > > > for n in myList: > ... > then in a deeply nested *if* > I modified the values of the list: myList = > newList > > The change to the list consists of eliminating some elements from the list > > Looking at the STACK VIEW, I can observe the modifications taking place to > the list; however, when the loop comes back around and *n* is assigned a new > value it still seems to have access to the original list. The for loop looks up myList at the start of the loop, and starts looping over the list that it refers to at that moment. When you do "myList = newList", that old list isn't changed at all, rather myList now refers to a new list. So the for loop shouldn't be influenced by that. So >>> x = range(10) >>> for i in x: ... x = range(10,20) ... print i Simply prints 0 to 9. Keep in mind that everything is a reference in Python; a variable doesn't hold any value but is a name for an object instead. The for loop uses the name to lookup the object at its start, then doesn't care about the name anymore. So that explains this effect. However, it is a BAD IDEA to change the list you are looping over in a for loop even if it did work. For instance, you could delete items in the list, or make it larger, and the way the for loop behaves is UNDEFINED. Don't do it. Instead, make a new list, put your results in that, and copy it back into myList after the loop. I hope this helps. If you still have trouble, show us what you're doing :) -- Remco Gerlich From jons@reachone.com Tue Dec 26 19:36:48 2000 From: jons@reachone.com (Jonathan Akers) Date: Tue, 26 Dec 2000 11:36:48 -0800 Subject: [Tutor] :) Message-ID: <3A48F350.3455B91C@reachone.com> I would like to join your mailing list. From deirdre@deirdre.net Tue Dec 26 20:35:19 2000 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 26 Dec 2000 12:35:19 -0800 (PST) Subject: [Tutor] :) In-Reply-To: <3A48F350.3455B91C@reachone.com> Message-ID: On Tue, 26 Dec 2000, Jonathan Akers wrote: > I would like to join your mailing list. You did. Welcome! -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "Our society has not yet gone so far as to place blind faith in machines. In almost all endeavors, humans routinely correct the errors of machines." - Florida Supreme Court From c.gruschow@prodigy.net Tue Dec 26 21:23:04 2000 From: c.gruschow@prodigy.net (Charles Gruschow, Jr.) Date: Tue, 26 Dec 2000 15:23:04 -0600 Subject: [Tutor] with win'98, python 1.5.2, how do you use serial ports with Python? I asked this several days ago but got no reply Message-ID: <001d01c06f82$0a036480$9cdf6520@gruschow> This is a multi-part message in MIME format. ------=_NextPart_000_001A_01C06F4F.BE226AC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable with win'98, python 1.5.2, how do you use serial ports with Python? I = asked this several days ago but got no reply like with actuator motors in robotics for example any serial port example i am curious about too ------=_NextPart_000_001A_01C06F4F.BE226AC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

with win'98, python 1.5.2, how do you use serial ports with Python? I = asked=20 this several days ago but got no reply

like with actuator motors in robotics for example

any serial port example i am curious about too

 

------=_NextPart_000_001A_01C06F4F.BE226AC0-- From scarblac@pino.selwerd.nl Wed Dec 27 01:09:40 2000 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 27 Dec 2000 02:09:40 +0100 Subject: [Tutor] Scope and values in a list In-Reply-To: <78D9B26221DBD411B7EE00D0B73EB0EA06660B@cupex2.rational.com>; from rmallett@rational.com on Tue, Dec 26, 2000 at 08:49:33AM -0800 References: <78D9B26221DBD411B7EE00D0B73EB0EA06660B@cupex2.rational.com> Message-ID: <20001227020940.A16224@pino.selwerd.nl> Sometimes I over-explain the "everything is a reference" thing and it's late at night now so I'm overdoing it more than usual I think, but maybe it's helpful. I consider this the key point of Python and its worth being hit with a hammer for a few times to make sure it's understood ;-). On Tue, Dec 26, 2000 at 08:49:33AM -0800, Mallett, Roger wrote: > Alright, being that > > When you do "myList = newList", > > that old list isn't changed at > > all, rather myList now refers to > > a new list. > > AND being that: "since everything in Python is a reference, and the variable > doesn't hold any value but is a name for an object", > > then why does x display its newly assigned value (10...19) once the *for* > loop has complete (see output below)? Since 'x' is now a name for that new list. But the 'for' loop only looks up the name 'x' once (when it starts), so it is using the old list. > Seems that myList does indeed take on > the new value, but that the "i" in the *for* loop is using a snapshot of the > myList object to iterate (and not actually using myList). Is that true? Depends how you mean that. It's not making a copy of the list, or something like that. The for loop looks up the reference at the beginning of the loop; then it keeps the reference to the list and loops through it. It doesn't care what happens to the name "myList" after it starts. Let's show it step by step (arrows mean "refers to"): > >>> x = range(10) The situation is now: x -------> [List A, containing 0...9] > >>> for i in x: x ----+--> [List A, containing 0...9] for loop -/ > ... x = range(10,20) for loop -----> [List A, containing 0...9] x ------------> [Some new list B, containing 10...19] (the assignment makes x refer to something new, but nothing more; in particular the for loop still uses the old reference) (next loop through the for:) for loop -----> [List A, containing 0...9] [List B, 10...19, not used anymore, will be freed] x ------------> [Some new list C, containing 10...19] (etc) > ... print i, > ... > 0 1 2 3 4 5 6 7 8 9 > >>> x x -----------> [List K or so, the last one that was made, 10...19] (the rest have been freed because nothing referred to them anymore) > [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] Whatever. Time to sleep. Remco Gerlich From dyoo@hkn.eecs.berkeley.edu Wed Dec 27 02:34:37 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 26 Dec 2000 18:34:37 -0800 (PST) Subject: [Tutor] information hiding = interface & documntation hiding In-Reply-To: Message-ID: On Mon, 25 Dec 2000, kevin parks wrote: > information hiding is supposed to olny hide the implementation, not > the interface! But unfortunately, the interfac for a piece of code is > mysterious to me. There are tons of modules, packages, proceedures, Each module has documentation with it. For example, if we wanted to know more about the "string" module, we'd look at the Library Reference at: http://python.org/doc/current/lib/lib.html If you look through, you'll find a link that says "String Services", and under that, the string module documentation. http://python.org/doc/current/lib/module-string.html Also, the interpreter is wonderful when you want to figure out how a module works. Let's show a sample interpreter session: ### >>> import string >>> dir(string) ['__builtins__', '__doc__', '__file__', '__name__', '_idmap', '_idmapL', '_lower ', '_re', '_safe_env', '_swapcase', '_upper', 'atof', 'atof_error', 'atoi', 'ato i_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'di gits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinf ields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdig its', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitfields', ' strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill'] >>> # let's figure out how to use swapcase ... >>> print string.swapcase.__doc__ swapcase(s) -> string Return a copy of the string s with upper case characters converted to lowercase and vice versa. >>> string.swapcase("This is a test.") 'tHIS IS A TEST.' ### The big thing to notice is that, for properly documented functions, you can print out its "docstring" --- a small summary that describes basic use and the argument types. Every function usually has a .__doc__ attribute that you can print out. > objects, classes, and function that come with the python distribution > and also to be fond on the net. The problem is knowing what input they > expect and what the output is. Only the people who program them seem > to know this and there is often little or no documentation to b found. Learning the features of any standard library comes with experience and practice. You may want to talk to other Python programmers to find out what modules they find useful. For example, I usually use "string", "re", and "math", because I focus on doing string manipulation and playing with math. When I want to do stuff like downloading URL's, I use "urllib". However, your focus may be different --- a good thing to do is to browse through the titles on the Library Reference, and see what catches your eye. > Additionally there are often dependencies to be known about and often > not to be found. I would really like help with this. This whole OOP > thing is such a farce sometimes. The whole idea is that you are > supposed to be able to mak use of code thatyo didn't (or in my case > couldn't) implement yourself. I am not an algorythms guy and i don't > want to reinvent the wheel. i would like to use all the code inthe > python image, but getting to know what is in the image and how to use > it is so hard. What tools does python have for this? If any? How cani Well, you have us. *grin* Also, the documentation isn't as bad as you may think --- again, take a look at the Library Reference. If there's anything that seems weird, ask us; there's bound to be someone else who's played around with the same module. > know if my code names are unque orif my funcs are overiding somthing > that aleady exsits. In TCL one just types a nam in the the shll. if > there is a proc of that name it comes up and the interface is often > tere too. For example, i saw there was a markov.py file in the That should work. Try it from the interpreter --- you should be able to see what names are defined for you. More directly, you can use the dir() function to see what variables and functions are available. About markov.py --- I have no idea; I haven't looked into it yet. It doesn't appear to be part of the standard library, so your best bet is to look in markov.py itself. As a note, you do NOT have to memorize the whole standard library. There's not going to be a test on it. *grin* Just concentrate on the stuff that you want to use, and you should do ok. From cpsoct@lycos.com Wed Dec 27 10:35:51 2000 From: cpsoct@lycos.com (kevin parks) Date: Wed, 27 Dec 2000 19:35:51 +0900 Subject: [Tutor] (No Subject) Message-ID: What i am trying to do is perhaps easy for seasoned pythonites, but confronted with a new langauge and a wonderful new array of data types i am a bit baffled as to how to best approach it. I suppose that what i need is a some kind of dictionary and tuple to function as a classic table look up type structure. It is very hard to decribe the problem abstractly so i will just deal with exactly what it is i am trying to do and hope that someone here can get their head around the problem. I have a set of sound samples that are set at discreet values. However i want to use them any tuning scheme. So what i have is an algorhythm that figures out the frequency that i want based on some tuning mombo-jumbo that i wrote. What i need now is to use that frequency (the desired frequency) as a key or index and to do the following: 1. find the frequnce in the list below that is closest. 2. return that frequency and the name of the associated sample. e.g.: if i arrive at a frequency of 31.001 Hz, the code should look up and see that 32.703 is my closest available sample base frequency. It should return that number along with the name of the sample 'sh.forte C_1' so that i now have the desired frequency (31.001), the base frequency (32.703) and the sample name ('sh.forte C_1') which i can then use to calulate a transposition factor (31.001/32.703). What is the best way to do this? In my old language i would use a look-up table to choose the base freq. and then a table with a step function to choose the sample. so that all frequncies from 0-27.500 chose sample1, all frequncies from 27.500 to 32.703 choose sample2, etc. (we want the samples to be responsible for the frequncies, up to and including it as we usually want to transpose down to get our note, as up sounds "micky mouse"). { 'sh.forte A_0' : 27.500 , 'sh.forte C_1' : 32.703 , 'sh.forte D#1' : 38.891 , 'sh.forte F#1' : 46.249 , 'sh.forte A_1' : 55.000 , 'sh.forte C_2' : 65.406 , 'sh.forte D#2' : 77.782 , 'sh.forte F#2' : 92.499 , 'sh.forte A_2' : 110.000 , 'sh.forte C_3' : 130.813 , 'sh.forte D#3' : 155.563 , 'sh.forte F#3' : 184.997 , 'sh.forte A_3' : 220.000 , 'sh.forte C_4' : 261.626 , 'sh.forte D#4' : 311.127, 'sh.forte F#4' : 369.994 , 'sh.forte A_4' : 440.000 , 'sh.forte C_5' : 523.251 , 'sh.forte D#5' : 622.254 , 'sh.forte F#5' : 739.989 , 'sh.forte A_5' : 880.000 , 'sh.forte C_6' : 1046.502 , 'sh.forte D#6' : 1244.508 , 'sh.forte F#6' : 1479.978 , 'sh.forte A_6' : 1760.000 , 'sh.forte C_7' : 2093.005 , 'sh.forte D#7' : 2489.016 , 'sh.forte F#7' : 2959.955 , 'sh.forte A_7' : 3520.000 , 'sh.forte C_8' : 4186.009 } Sorry this is so long winded, i tried to explain the problem as simply as i could. i am just certain this is easier to do with python's built in structures, but can't quite get my head around it just yet. best, kevin parks seoul, korea Get FREE Email/Voicemail with 15MB at Lycos Communications at http://comm.lycos.com From tim.one@home.com Wed Dec 27 23:51:03 2000 From: tim.one@home.com (Tim Peters) Date: Wed, 27 Dec 2000 18:51:03 -0500 Subject: [Tutor] (No Subject) In-Reply-To: Message-ID: [kevin parks] > What i am trying to do is perhaps easy for seasoned pythonites, > but confronted with a new langauge and a wonderful new array of > data types i am a bit baffled as to how to best approach it. I > suppose that what i need is a some kind of dictionary and tuple > to function as a classic table look up type structure. It is very > hard to decribe the problem abstractly so i will just deal with > exactly what it is i am trying to do and hope that someone here > can get their head around the problem. First rule: when you don't know what you're doing, abstraction is what you *need*, not what you need to avoid. We can get the program started right away. Start with a class to represent your data structure: class Tuner: pass There, you've made great progress already . You know you want to add data pairs to it, but don't know how you're going to represent them. Fine! *Assume* Tuner has an add(name, freq) method, and write code to initialize a Tuner instance: t = Tuner() t.add('sh.forte A_0', 27.500) t.add('sh.forte C_1', 32.703) t.add('sh.forte D#1', 38.891) t.add('sh.forte F#1', 46.249) t.add('sh.forte A_1', 55.000) t.add('sh.forte C_2', 65.406) t.add('sh.forte D#2', 77.782) t.add('sh.forte F#2', 92.499) t.add('sh.forte A_2', 110.000) t.add('sh.forte C_3', 130.813) t.add('sh.forte D#3', 155.563) t.add('sh.forte F#3', 184.997) t.add('sh.forte A_3', 220.000) t.add('sh.forte C_4', 261.626) t.add('sh.forte D#4', 311.127) t.add('sh.forte F#4', 369.994) t.add('sh.forte A_4', 440.000) t.add('sh.forte C_5', 523.251) t.add('sh.forte D#5', 622.254) t.add('sh.forte F#5', 739.989) t.add('sh.forte A_5', 880.000) t.add('sh.forte C_6', 1046.502) t.add('sh.forte D#6', 1244.508) t.add('sh.forte F#6', 1479.978) t.add('sh.forte A_6', 1760.000) t.add('sh.forte C_7', 2093.005) t.add('sh.forte D#7', 2489.016) t.add('sh.forte F#7', 2959.955) t.add('sh.forte A_7', 3520.000) t.add('sh.forte C_8', 4186.009) No matter what you decide later, you'll never have to change a line of that, because the mere name "add" doesn't commit you to any particular representation. Since you're going to be looking for frequencies later, a list sorted by frequency is a very reasonable structure. We can keep another list of names, in the same order. At this point it would be very helpful if you already knew about the std bisect module, but I do so you don't have to . I'll also add a .dump() method while I'm at it: from bisect import bisect class Tuner: def __init__(self): self.names = [] self.freqs = [] def add(self, name, freq): i = bisect(self.freqs, freq) self.freqs.insert(i, freq) self.names.insert(i, name) # exercise: should this code check to see whether # freq was added before? and if so, what then? # complain? complain but only if the name on this # call isn't the same as the name it saw before? # don't complain, but silently ignore the new value? # don't complain, but silently ignore the old value? def dump(self): for i in range(len(self.freqs)): print self.names[i], self.freqs[i] Now you have enough code to run something: stick that above the masses of "t.add()" lines, and stick t.dump() at the end. Run it to make sure it works. > I have a set of sound samples that are set at discreet values. > However i want to use them any tuning scheme. So what i have is > an algorhythm that figures out the frequency that i want based on > some tuning mombo-jumbo that i wrote. > > What i need now is to use that frequency (the desired frequency) > as a key or index and to do the following: > > 1. find the frequnce in the list below that is closest. > 2. return that frequency and the name of the associated sample. > e.g.: if i arrive at a frequency of 31.001 Hz, the code should > look up and see that 32.703 is my closest available sample base > frequency. This was very confusing, because while 32.703 is the closest value to 31.001 in your data, 32.703 is not "below" 31.001, so your point #2 appears to contradict your point #1. Later on you made a big deal about how important it was to be below, so I'll assume your example was simply wrong and that you really meant to say that looking up 31.001 should return 27.5 instead. Note that if you think I'm being unreasonable, don't argue about it : it really doesn't matter! Simply change the implementation of the lookup method to do what you want: def lookup(self, freq): """freq -> (base freq, base name). Return the (base freq, base name) pair whose base freq is the largest of all base freqs less than or equal to freq. Raise ValueError if there is no base freq <= freq. """ i = bisect(self.freqs, freq) if i == 0: raise ValueError("no base freq <= %g" % freq) return self.freqs[i-1], self.names[i-1] # exercise: is it reasonable to raise ValueError, or # would it be better to return self.freqs[0] in that # case despite that self.freqs[0] > freq? Add that to the class, jump into interactive mode, and give it a try: >>> t.lookup(31.001) (27.5, 'sh.forte A_0') >>> t.lookup(32) (27.5, 'sh.forte A_0') >>> t.lookup(27.5) (27.5, 'sh.forte A_0') >>> t.lookup(27) Traceback (innermost last): File "", line 1, in ? t.lookup(27) File "C:/Python20/forte.py", line 27, in lookup raise ValueError("no base freq <= %g" % freq) ValueError: no base freq <= 27 >>> t.lookup(27000000) (4186.009, 'sh.forte C_8') >>> t.lookup(221) (220.0, 'sh.forte A_3') >>> Looks pretty good! > What is the best way to do this? Well, you would have to define "best" first. It's more important to learn how to use classes to make your life easier. Take away the comments and the exercises in the above, and each method is only a few lines of code: you can switch to a different form of representation quickly, and all the code *using* the .lookup() and .add() methods doesn't have to change at all. This is important, because whatever you mean by "best" today, you'll probably change your mind next week. classes-help-you-live-with-that-you-almost-never-know-what-you're- doing-for-sure-ly y'rs - tim From bxuef@freemail.sx.cn Fri Dec 29 02:04:10 2000 From: bxuef@freemail.sx.cn (bxuef@freemail.sx.cn) Date: Fri, 29 Dec 2000 10:04:10 +0800 (CST) Subject: [Tutor] Where to find example source codes? Message-ID: Dear everyone, It is said that the best way of learning a programing language is that you read some example souces and write some by your own. My question is where can I download some good source codes of Python as resources of learning? thank you! ----------------------------------------------------------- 欢迎使用山西电信免费电子邮件系统 。 如有问题,请与 webmaster@freemail.sx.cn 联系。 谢谢您的使用! From bxuef@freemail.sx.cn Fri Dec 29 02:04:37 2000 From: bxuef@freemail.sx.cn (bxuef@freemail.sx.cn) Date: Fri, 29 Dec 2000 10:04:37 +0800 (CST) Subject: [Tutor] Where to find example source codes? Message-ID: Dear everyone, It is said that the best way of learning a programing language is that you read some example souces and write some by your own. My question is where can I download some good source codes of Python as resources of learning? thank you! Do you have any other suggestions for a newbie of python? ----------------------------------------------------------- 欢迎使用山西电信免费电子邮件系统 。 如有问题,请与 webmaster@freemail.sx.cn 联系。 谢谢您的使用! From shaleh@valinux.com Fri Dec 29 16:37:51 2000 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Fri, 29 Dec 2000 08:37:51 -0800 (PST) Subject: [Tutor] Where to find example source codes? In-Reply-To: Message-ID: On 29-Dec-2000 bxuef@freemail.sx.cn wrote: > Dear everyone, > > It is said that the best way of learning a programing language is that you > read some example souces and write some by your own. > My question is where can I download some good source codes of Python as > resources of learning? > thank you! > hit freshmeat or sourceforge. Search for python. sourceforge even sorts projects based on language used. From tim.one@home.com Fri Dec 29 21:00:41 2000 From: tim.one@home.com (Tim Peters) Date: Fri, 29 Dec 2000 16:00:41 -0500 Subject: [Tutor] Where to find example source codes? In-Reply-To: Message-ID: [posted & mailed] > It is said that the best way of learning a programing language > is that you read some example souces and write some by your own. I'll agree with that! > My question is where can I download some good source codes of > Python as resources of learning? One idea: Python comes with almost 5 megabytes of Python code, spread across hundreds of .py files: much of the Python standard library is written in Python, and there are a variety of tools and demos too. So browse your installation tree, pick an area of the library that *interests* you (or a tool, etc), and study that. Change it! See what happens. And get very, very friendly with interactive mode: "just trying things" is much easier in Python than in most other languages, and the immediate feedback is a great aid to initial learning. It's an even better aid after initial learning . From mbc2@netdoor.com Fri Dec 29 23:17:35 2000 From: mbc2@netdoor.com (Brad Chandler) Date: Fri, 29 Dec 2000 17:17:35 -0600 Subject: [Tutor] Class inheiritance question Message-ID: <000701c071ed$8727e360$111c0d0a@spb.state.ms.us> I have created a sub class called Positionrlgn of a base class called Position. I've redefinded one of the functions successfully, but now I need to redefine a variable. How do I redefine a value which is set in the __init__ function. For example, my base class starts like this: class Position: def __init__(self, dbrow): self.currentsalary=dbrow[0] my sub class starts like this: class Positionrlgn(projectclass.Position): #currentsalary needs to be redefined here. Can I modify the __init__ function so that only the one value is altered and the rest are left intact? From jcm@bigskytel.com Sat Dec 30 10:27:17 2000 From: jcm@bigskytel.com (David Porter) Date: Sat, 30 Dec 2000 03:27:17 -0700 Subject: [Tutor] Where to find example source codes? In-Reply-To: ; from bxuef@freemail.sx.cn on Fri, Dec 29, 2000 at 10:04:37AM +0800 References: Message-ID: <20001230032717.A13591@bigskytel.com> * bxuef@freemail.sx.cn : > It is said that the best way of learning a programing language is that > you read some example souces and write some by your own. My question is > where can I download some good source codes of Python as resources of > learning? thank you! There are a lot of places I'm sure. Here's one, though it's getting a bit old: http://strout.net/python/tidbits.html Check out the Vaults for programs that interest you (though many may deal with complex parts of Python you need not know at first they are still fun to play with and to illustrate the potential of Python): http://www.vex.net/parnassus/apyllo.py > Do you have any other suggestions for a newbie of python? I suggest reading an intro tutorial or two(*). This will give you a framework to place the code you read into. Also, it will help you avoid blind spots. I highly recommend that you use the python interpreter while studying other people's code and while reading tutorials. For me, reading something shows me that it can be done; experimenting with it in the interpreter shows me in greater detail how it IS done. If I've done something in practice, I also have a much lower chance of forgetting it. (*) A great beginner's tutorial is Alan Gauld's "Learning to Program", at http://www.crosswinds.net/~agauld/ . After that, a more in depth coverage of Python is given by the Standard Tutorial at http://www.python.org/doc/current/tut/tut.html . David From abreu@penguinpowered.com Sat Dec 30 17:04:25 2000 From: abreu@penguinpowered.com (Jose Alberto Abreu) Date: Sat, 30 Dec 2000 11:04:25 -0600 Subject: [Tutor] Beginner's Question References: <00122211250809.12381@gandalf> Message-ID: <3A4E1599.28CBD14A@penguinpowered.com> Bob wrote: > > I am setting out to learn python. I have some books, those from > O'Reilly and the Quick Pythom Book, and I have found the online > tutorials, and done Josh Cogliati's. I need to know where to go from > here, I guess. But what I *really* need are programming projects > matched to what I have learned so far. Any suggestions, either > projects or textbooks? > > I work in Linux, by the way. > > -- Bob Rea > I would recomment the Python Essential Reference by David M. Beazley... This is the book that made my life with Python a lot easier... You still have to download the Python 2.0 library reference from the website (the book uses 5.2's), but the differences are not that much. -- 3.14159265358979323846264338327950288419716939937 Jose Alberto Abreu - abreu@penguinpowered.com 3.14159265358979323846264338327950288419716939937 From abreu@penguinpowered.com Sat Dec 30 17:16:13 2000 From: abreu@penguinpowered.com (Jose Alberto Abreu) Date: Sat, 30 Dec 2000 11:16:13 -0600 Subject: [Tutor] Compile python to executable binary? References: <3A432A0A.6D786A65@apis.dhl.com> <20001222110120.B24495@westsidecnc.rh.rit.edu> Message-ID: <3A4E185D.3894580@penguinpowered.com> D-Man wrote: > > I can't answer all of the questions, but you can run your app without > a separate interpreter installed on the machine *if* > > 1) You package an interpreter with your installer > (basically you provide it for them) But how do you do that: put the interpreter, the required modules and your code on a couple of .exe's or perhaps using installshield (in the case of Windows, for example). Distributing python programs for Linux is much easier, as almost all linux distributions will install (at least) python 1.5, but trying to get the average Windows user to go and download and install python so that they can run your code is not realistic. > or > > 2) You package an interpreter with your program. Maybe make a > little C program that embeds the interpreter and runs your scripts. Is there an opensourced thing that does this? -- 3.14159265358979323846264338327950288419716939937 Jose Alberto Abreu - abreu@penguinpowered.com 3.14159265358979323846264338327950288419716939937 From MUSAJADAKISS@aol.com Sat Dec 30 18:48:15 2000 From: MUSAJADAKISS@aol.com (MUSAJADAKISS@aol.com) Date: Sat, 30 Dec 2000 13:48:15 EST Subject: [Tutor] please!!!!!!!!!!!!!! Message-ID: <3d.5787381.277f87ef@aol.com> can you help me in debugging this to do an a* search although there is no heuristic distance measured but just put any figure there on the textfile pleasee happy newyear """An implementation of A*. Given a start state and a goal state, as well as a heuristic function h(m), return the shortest path between start and goal. In the algorithm, we keep a priority queue, and continuously look at the element with the lowest heuristic cost f(m). We define f(m) = g(m) + h(m), where g(m) is the cost from the start state to m, and h(m) is the heuristic from m to the goal state. """ def myMin(L, f): """Return the index of the minimal element, using f to calculate the cost.""" if len(L) == 0: return None index = 0 minCost = f(L[index]) for i in range(1, len(L)): if f(L[i]) < minCost: index = i mincost = f(L[i]) return index class Node: def __init__(self, name, distance_func): self.name = name self.distance_func = distance_func self.predecessor = None self.neighbors = [] def f(self): return self.g() + self.h() def g(self): if self.getPred() in [None, self]: return 0 return (self.distance_func(self, self.getPred()) + self.getPred().g()) def h(self): return 0 # the heuristic cost from self to the goal def __str__(self): return self.name def __repr__(self): return str(self) def getName(self): return self.name def getPred(self): return self.predecessor def setPred(self, value): self.predecessor = value def getNeighbors(self): return self.neighbors def setNeighbors(self, neighbors): self.neighbors = neighbors class DistanceDictWrapper: def __init__(self, dict): self.dict = dict def __call__(self, m, n): """Return the distance between m and n. Since distance is symmetric, we'll try from m->n, or n->m""" if m == n: return 0 if self.dict.has_key((m.name, n.name)): return self.dict[(m.name, n.name)] if self.dict.has_key((n.name, m.name)): return self.dict[(n.name, m.name)] return None def aStarSearch(nodes, start, goal): start.predecessor = start pqueue = [start] while 1: next_choice_index = myMin(pqueue, lambda n: n.f()) next_choice = pqueue[next_choice_index] ## print "queue:", pqueue # debug ## print "choosing", next_choice, next_choice.f() # debug del pqueue[next_choice_index] if next_choice == goal: break _updatePqueue(next_choice, pqueue) path = _resultHelper(nodes, start, goal) _resetPredLinks(nodes) return path def zeroFunc(): return 0 def _resultHelper(nodes, start, goal): result = [goal] node = goal while node != start: node = node.predecessor result.append(node) result.reverse() return result def _resetPredLinks(nodes): for x in nodes: x.setPred(None) def _updatePqueue(parent, pqueue): children = parent.getNeighbors() for x in children: if (x.predecessor is None or parent.g() + x.distance_func(parent, x) < x.g()): x.predecessor = parent pqueue.append(x) def main(): "TUBEREAD : Main line!" global citysign, NL args = sys.argv[:] ## gets command-line arguments na = len(args) print args[0],"[version 1.0]" print "command-line args. =",na if na < 2: print "normal usage: python tuberead.py " args.append(raw_input("please give input textfile name: ")) na = len(args) textname = args[1] textfile = open(textname,"r") if textfile == None: print "Can't open file:",textname lc = 0 ; sc = 0 lines = {} ## empty dictionary (station names) citylist = [] ## empty list (line names) thisline = "Zonk" citydic = {} while 1: textline = textfile.readline() if not textline: break name = string.capwords(string.strip(textline)) sc = sc + 1 if citysign in name: newline = 1 print "city = ", name thiscity = string.replace(name,citysign,'') if not citydic.has_key(thiscity): citydic[thiscity] = [] ## citylist.append(thiscity) else: x = string.split(name,',') ##print x c = x[0] ##print c if not citydic.has_key(c): lc = lc + 1 citydic[c] = [] d = eval(x[1]) t1 = (c,d) citydic[thiscity].append(t1) ## also append symmetric link : t2 = (thiscity,d) citydic[c].append(t2) citylist = citydic.keys() citylist.sort() print citylist print print print len(citylist),"distinct cities read." print ##print citydic while 1: sn = raw_input("Enter city name: ") sn = string.strip(sn) if len(sn) < 1: break ## user hits CRLF to quit loop sd = raw_input("Enter destination city name: ") if len(sd) < 1: break ## user hits CRLF to quit loop sl = citydic.get(sn,[]) ra = len(sl) st = citydic.get(sd,[]) mu = len(st) print sn,sl,ra print sd,st,mu citylist = textfile.readline() dfunc = DistanceDictWrapper(citylist) sq = Node(sn, dfunc) sq.setNeighbors([sn,sd]) node = {} print aStarSearch(sq,sn,node) return 0 if __name__ == '__main__': try: main() except KeyboardInterrupt: sys.exit(1) this is the textfile just put any second figure as the hueristic distance Amsterdam:123 Berlin,650 Brussels,197 Calais,367 Cologne,256 Edinburgh,1093 Hamburg,447 Paris,510 Athens:123,124 Sofia,828,857 Belfast: cork,416 Dublin,167 Kilkenny,277 Berlin: Edinburgh,1696 Hamburg,285 Prague,345 Rostock,222 Stuttgart,629 Warsaw,606 Budapest: Burcharest,852 Prague,537 Sofia,790 Vienna,242 Cork: Kilkenny,148 Dublin: Cork,259 Kilkenny,119 Edinburgh,346 Edinburgh: Copenhagen,479 Hamburg: Rostock,175 Stuttgart,659 Istanbul: Athens,1145 Burcharest,690 Sofia,550 London: Brussele,333 Dublin,430 Cologne,508 Edinburgh,608 Paris,399 Madrid: Bercelona,617 Lisbon,651 Paris,1280 Munich: Berlin,594 Cologne,580 Frankfurt,398 Paris,810 Parague,388 Vienna,430 Oslo: Copenhagen,590 Hamburg,900 stocholm,530 Paris: Brussels,320 Cologne,495 Prague: Frankfurt,512 Hamburg,652 Oslo,1350 Warsaw,616 Vienna,295 Rome: Athens,1140 Milan,606 Vienna: Berlin,640 Warsaw,727 Warsaw: Moscow,1245 Zurich: Milan,292 Munich,303 Paris,592 Vienna,743 From MUSAJADAKISS@aol.com Sat Dec 30 18:48:41 2000 From: MUSAJADAKISS@aol.com (MUSAJADAKISS@aol.com) Date: Sat, 30 Dec 2000 13:48:41 EST Subject: [Tutor] help Message-ID: can you help me in debugging this to do an a* search although there is no heuristic distance measured but just put any figure there on the textfile pleasee happy newyear """An implementation of A*. Given a start state and a goal state, as well as a heuristic function h(m), return the shortest path between start and goal. In the algorithm, we keep a priority queue, and continuously look at the element with the lowest heuristic cost f(m). We define f(m) = g(m) + h(m), where g(m) is the cost from the start state to m, and h(m) is the heuristic from m to the goal state. """ def myMin(L, f): """Return the index of the minimal element, using f to calculate the cost.""" if len(L) == 0: return None index = 0 minCost = f(L[index]) for i in range(1, len(L)): if f(L[i]) < minCost: index = i mincost = f(L[i]) return index class Node: def __init__(self, name, distance_func): self.name = name self.distance_func = distance_func self.predecessor = None self.neighbors = [] def f(self): return self.g() + self.h() def g(self): if self.getPred() in [None, self]: return 0 return (self.distance_func(self, self.getPred()) + self.getPred().g()) def h(self): return 0 # the heuristic cost from self to the goal def __str__(self): return self.name def __repr__(self): return str(self) def getName(self): return self.name def getPred(self): return self.predecessor def setPred(self, value): self.predecessor = value def getNeighbors(self): return self.neighbors def setNeighbors(self, neighbors): self.neighbors = neighbors class DistanceDictWrapper: def __init__(self, dict): self.dict = dict def __call__(self, m, n): """Return the distance between m and n. Since distance is symmetric, we'll try from m->n, or n->m""" if m == n: return 0 if self.dict.has_key((m.name, n.name)): return self.dict[(m.name, n.name)] if self.dict.has_key((n.name, m.name)): return self.dict[(n.name, m.name)] return None def aStarSearch(nodes, start, goal): start.predecessor = start pqueue = [start] while 1: next_choice_index = myMin(pqueue, lambda n: n.f()) next_choice = pqueue[next_choice_index] ## print "queue:", pqueue # debug ## print "choosing", next_choice, next_choice.f() # debug del pqueue[next_choice_index] if next_choice == goal: break _updatePqueue(next_choice, pqueue) path = _resultHelper(nodes, start, goal) _resetPredLinks(nodes) return path def zeroFunc(): return 0 def _resultHelper(nodes, start, goal): result = [goal] node = goal while node != start: node = node.predecessor result.append(node) result.reverse() return result def _resetPredLinks(nodes): for x in nodes: x.setPred(None) def _updatePqueue(parent, pqueue): children = parent.getNeighbors() for x in children: if (x.predecessor is None or parent.g() + x.distance_func(parent, x) < x.g()): x.predecessor = parent pqueue.append(x) def main(): "TUBEREAD : Main line!" global citysign, NL args = sys.argv[:] ## gets command-line arguments na = len(args) print args[0],"[version 1.0]" print "command-line args. =",na if na < 2: print "normal usage: python tuberead.py " args.append(raw_input("please give input textfile name: ")) na = len(args) textname = args[1] textfile = open(textname,"r") if textfile == None: print "Can't open file:",textname lc = 0 ; sc = 0 lines = {} ## empty dictionary (station names) citylist = [] ## empty list (line names) thisline = "Zonk" citydic = {} while 1: textline = textfile.readline() if not textline: break name = string.capwords(string.strip(textline)) sc = sc + 1 if citysign in name: newline = 1 print "city = ", name thiscity = string.replace(name,citysign,'') if not citydic.has_key(thiscity): citydic[thiscity] = [] ## citylist.append(thiscity) else: x = string.split(name,',') ##print x c = x[0] ##print c if not citydic.has_key(c): lc = lc + 1 citydic[c] = [] d = eval(x[1]) t1 = (c,d) citydic[thiscity].append(t1) ## also append symmetric link : t2 = (thiscity,d) citydic[c].append(t2) citylist = citydic.keys() citylist.sort() print citylist print print print len(citylist),"distinct cities read." print ##print citydic while 1: sn = raw_input("Enter city name: ") sn = string.strip(sn) if len(sn) < 1: break ## user hits CRLF to quit loop sd = raw_input("Enter destination city name: ") if len(sd) < 1: break ## user hits CRLF to quit loop sl = citydic.get(sn,[]) ra = len(sl) st = citydic.get(sd,[]) mu = len(st) print sn,sl,ra print sd,st,mu citylist = textfile.readline() dfunc = DistanceDictWrapper(citylist) sq = Node(sn, dfunc) sq.setNeighbors([sn,sd]) node = {} print aStarSearch(sq,sn,node) return 0 if __name__ == '__main__': try: main() except KeyboardInterrupt: sys.exit(1) this is the textfile just put any second figure as the hueristic distance Amsterdam:123 Berlin,650 Brussels,197 Calais,367 Cologne,256 Edinburgh,1093 Hamburg,447 Paris,510 Athens:123,124 Sofia,828,857 Belfast: cork,416 Dublin,167 Kilkenny,277 Berlin: Edinburgh,1696 Hamburg,285 Prague,345 Rostock,222 Stuttgart,629 Warsaw,606 Budapest: Burcharest,852 Prague,537 Sofia,790 Vienna,242 Cork: Kilkenny,148 Dublin: Cork,259 Kilkenny,119 Edinburgh,346 Edinburgh: Copenhagen,479 Hamburg: Rostock,175 Stuttgart,659 Istanbul: Athens,1145 Burcharest,690 Sofia,550 London: Brussele,333 Dublin,430 Cologne,508 Edinburgh,608 Paris,399 Madrid: Bercelona,617 Lisbon,651 Paris,1280 Munich: Berlin,594 Cologne,580 Frankfurt,398 Paris,810 Parague,388 Vienna,430 Oslo: Copenhagen,590 Hamburg,900 stocholm,530 Paris: Brussels,320 Cologne,495 Prague: Frankfurt,512 Hamburg,652 Oslo,1350 Warsaw,616 Vienna,295 Rome: Athens,1140 Milan,606 Vienna: Berlin,640 Warsaw,727 Warsaw: Moscow,1245 Zurich: Milan,292 Munich,303 Paris,592 Vienna,743 From dsh8290@rit.edu Sun Dec 31 04:34:25 2000 From: dsh8290@rit.edu (D-Man) Date: Sat, 30 Dec 2000 23:34:25 -0500 Subject: [Tutor] Compile python to executable binary? In-Reply-To: <3A4E185D.3894580@penguinpowered.com>; from abreu@penguinpowered.com on Sat, Dec 30, 2000 at 11:16:13AM -0600 References: <3A432A0A.6D786A65@apis.dhl.com> <20001222110120.B24495@westsidecnc.rh.rit.edu> <3A4E185D.3894580@penguinpowered.com> Message-ID: <20001230233425.B19500@westsidecnc.rh.rit.edu> On Sat, Dec 30, 2000 at 11:16:13AM -0600, Jose Alberto Abreu wrote: > D-Man wrote: > > > > I can't answer all of the questions, but you can run your app without > > a separate interpreter installed on the machine *if* > > > > 1) You package an interpreter with your installer > > (basically you provide it for them) > > But how do you do that: put the interpreter, the required modules and > your code on a couple of .exe's or perhaps using installshield (in the > case of Windows, for example). I don't know anything about configuring InstallShield, but I would expect that it would allow you to make an installer for python and have it install python as part of the install process. Maybe just include it in a tarball (or zip file, winzip can read tarballs too) and tell the users to install it first? > > Distributing python programs for Linux is much easier, as almost all > linux distributions will install (at least) python 1.5, but trying to > get the average Windows user to go and download and install python so > that they can run your code is not realistic. > > > or > > > > 2) You package an interpreter with your program. Maybe make a > > little C program that embeds the interpreter and runs your scripts. > > Is there an opensourced thing that does this? I think this would have to be a custom sort of thing. Maybe not. Someone was mentioning byte-compiling his scripts, then putting the byte-code in a static C array and embedding the interpreter and handing it those arrays to execute. I don't remember if that person was on this list or python-list. There's also a utility called "freeze" that is distributed by MacMillian publisher I think (or maybe just by an author who has been published by them). Search the archives for mention of it. I haven't made any distributeable packages yet so I don't have any real-world experience to draw from. HTH, -D From dyoo@hkn.eecs.berkeley.edu Sun Dec 31 04:37:12 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 30 Dec 2000 20:37:12 -0800 (PST) Subject: [Tutor] (No Subject) In-Reply-To: Message-ID: On Wed, 27 Dec 2000, kevin parks wrote: > 1. find the frequnce in the list below that is closest. > 2. return that frequency and the name of the associated sample. > e.g.: if i arrive at a frequency of 31.001 Hz, the code should look up and see that 32.703 is my closest available sample base frequency. It should return that number along with the name of the sample 'sh.forte C_1' so that i now have the desired frequency (31.001), the base frequency (32.703) and the sample name ('sh.forte C_1') which i can then use to calulate a transposition factor (31.001/32.703). > > What is the best way to do this? In my old language i would use a > look-up table to choose the base freq. and then a table with a step > function to choose the sample. so that all frequncies from 0-27.500 Hmmm... You can use a stepping function. You might have run into the problem of looking up a nonexisting dictionary value: >>> dict = {3 : 'foo', 5: 'bar'} >>> dict[1] Traceback (innermost last): File "", line 1, in ? KeyError: 1 This occurs because Python assumes that a mistake has been made --- usually, keys should match exactly. If a key is invalid, Python will raise KeyError. What we can do to avoid KeyError is to first check if your dictionary has a key using the dict's has_key() method: if dict.has_key(something): # then doing dict[something] is safe So your function could look like this: ### def selectSample(dict, frequency, step_size): while not dict.has_key(frequency): frequency = frequency + step_size return dict[frequency] ### So the above function will use the step_size to find the "ceil" of the frequency you pass it. However, you might also consider filling in the gaps of your lookup table itself --- if you do that in your initialization, then you won't need to do so much work throughout the rest of your program. Your table will be much larger, true, but it might save some time. There are proabbly many solutions to your problem. Using dictionaries will speed things along. > { 'sh.forte A_0' : 27.500 , 'sh.forte C_1' : 32.703 , 'sh.forte D#1' : > 38.891 , 'sh.forte F#1' : 46.249 , 'sh.forte A_1' : 55.000 , 'sh.forte [lots of stuff cut] This looks almost ok, but may work better if the frequencies are keys, and the samples are values. So, it might be something like: { 27.500 : 'sh.forte A_0', 32.703 : 'sh.forte C_1', ... } Otherwise, you'll lose the advantages of the dictionary --- dictionaries make it very easy to find a value if we know the key. However, going the other way around is a bit expensive. Good luck! From dyoo@hkn.eecs.berkeley.edu Sun Dec 31 04:48:10 2000 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 30 Dec 2000 20:48:10 -0800 (PST) Subject: [Tutor] Where to find example source codes? In-Reply-To: Message-ID: On Fri, 29 Dec 2000, Sean 'Shaleh' Perry wrote: > where can I download some good source codes of Python > > hit freshmeat or sourceforge. Search for python. sourceforge even > sorts projects based on language used. Also, the Vaults of Parnassus indices Python programs: http://www.vex.net/parnassus From pursang@interact.net.au Sun Dec 31 10:01:43 2000 From: pursang@interact.net.au (John Murray) Date: Sun, 31 Dec 2000 21:01:43 +1100 Subject: [Tutor] Where to find example source codes. Message-ID: <00123121220400.01627@localhost.localdomain> > It is said that the best way of learning a programing language > is that you read some example souces and write some by your own. This reminds me of something I've been thinking about for a while, ie; should we be making our individual python project's code available to each other? There must be quite a few scripts in various stages of completion spread throughout the tutor subscribers. As a newbie (to programming as well as python), I would normally be embarrassed about releasing my hideously amateurish code, though I would have no problems sharing it with other list members. Ugly as my code may be, some of it has actually proven to be useful, so surely others here have written useful stuff as well. Making projects available to each other would give those without a project something to get into, and who knows, some stuff might get developed to the point of public release. What do you think? Sorry to sound like an open source evangelist........... Happy New Year Johnno From cpsoct@lycos.com Sun Dec 31 13:28:47 2000 From: cpsoct@lycos.com (kevin parks) Date: Sun, 31 Dec 2000 22:28:47 +0900 Subject: [Tutor] Re: flattening and clumping lists Message-ID: I would love to know how to flatten a list. For example if i write the following code to make a palendrome # mirror.py -- [1,2,3] returns [1,2,3,2,1] # how to make it return [1,2,3,2,1,2,3,2,1] # this should really be a tuple so that it is preserved. l=[1, 2, 3, 4, 5, 6, 7] foo=l[:-1] #copy list, excluding last element foo.reverse() #flip it l.append(foo) #stick it on the end of the other list #we need to flatten it some how in to a single list print l ------- snip ------ but i get in return a list with the appended list tacked on as a single element like: [1, 2, 3, 4, 5, 6, 7, [6, 5, 4, 3, 2, 1]] I thought that there was a thing where you could say flatten(l), but i'll be damned if i can find it now. additionally i would like to make a single list into a list of sublists with a random number of elements with a list like this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i might get: [[1], [2], [3, 4, 5], [6, 7], [8,9,10]] but i would need to know how to flatten and clump lists first to be able to do this. I am trying to make some list processing funcs (or eventually classes). I also wonder if such funcs already exists. I found a few that were on the "Vaults" page, but not as much as i'd thought of the flavors i was a seeking. I have many in mind, but am trying to just take a few baby steps to start with. cheers & happy new year, kevin parks, seoul, korea Get FREE Email/Voicemail with 15MB at Lycos Communications at http://comm.lycos.com From W.W.vandenBroek Sun Dec 31 14:06:02 2000 From: W.W.vandenBroek (W.W.vandenBroek) Date: Sun, 31 Dec 2000 15:06:02 +0100 Subject: [Tutor] list problem In-Reply-To: <20001216170109.9FD19E94E@mail.python.org> References: <20001216170109.9FD19E94E@mail.python.org> Message-ID: <00123115060200.02657@vdbroekw> Hi all, Trying to make a little "program" for myself, i am working my way through: "Teach yourself python..". Found out that mathematical subject are the topics to begin with in simple programming. I am a psychiatrist so i am used to associative thinking and pattern recognition instead of logical thinking so bare with me please. As a psychiatrist i am doing some research. I wanted to program some simple statistics, like finding the median of a list or a mean, range and quartiles. Lists are probably useful in this, so started making a list in a file: list.txt: l= [n, n1, n2,.....] Next tried to make a program with a sorted list as output #!/usr/local/bin/python x = open("list.txt", "rb") x.read () x.sort () print x Tried different options cannot figure out the problem. Can somebody please enlighten me or point me in a direction, thanks walter W.W. van den Broek e-mail: vandenbroek@psyd.azr.nl AZR-Dijkzigt fax: 010-4633217 afdeling psychiatrie tel: 010-4639222 Postbus 2040 e-mail vdbroekw@wxs.nl (thuis) 3000 CA Rotterdam homepage: http://home.planet.nl/~vdbroekw From dsh8290@rit.edu Sun Dec 31 17:52:05 2000 From: dsh8290@rit.edu (D-Man) Date: Sun, 31 Dec 2000 12:52:05 -0500 Subject: [Tutor] Class inheiritance question In-Reply-To: <000701c071ed$8727e360$111c0d0a@spb.state.ms.us>; from mbc2@netdoor.com on Fri, Dec 29, 2000 at 05:17:35PM -0600 References: <000701c071ed$8727e360$111c0d0a@spb.state.ms.us> Message-ID: <20001231125205.A27300@westsidecnc.rh.rit.edu> Yes! That's where the power of iheritance and polymorphism lie. On Fri, Dec 29, 2000 at 05:17:35PM -0600, Brad Chandler wrote: > I have created a sub class called Positionrlgn of a base class called > Position. I've redefinded one of the functions successfully, but now I need > to redefine a variable. How do I redefine a value which is set in the > __init__ function. > > For example, my base class starts like this: > > class Position: > def __init__(self, dbrow): > self.currentsalary=dbrow[0] > > my sub class starts like this: > > class Positionrlgn(projectclass.Position): def __init__( sef , dbrow ) : # first call the parent's ctor # this will set currentsalary and everything else as # before Position.__init__( self , dbrow ) # now change current salary to whatever the new value # should be self.currentsalary = 2000000 > > Can I modify the __init__ function so that only the one value is altered and > the rest are left intact? -D From dsh8290@rit.edu Sun Dec 31 18:03:57 2000 From: dsh8290@rit.edu (D-Man) Date: Sun, 31 Dec 2000 13:03:57 -0500 Subject: [Tutor] list problem In-Reply-To: <00123115060200.02657@vdbroekw>; from vdbroekw@wxs.nl on Sun, Dec 31, 2000 at 03:06:02PM +0100 References: <20001216170109.9FD19E94E@mail.python.org> <00123115060200.02657@vdbroekw> Message-ID: <20001231130357.B27300@westsidecnc.rh.rit.edu> On Sun, Dec 31, 2000 at 03:06:02PM +0100, W.W.van den Broek wrote: > Hi all, > Trying to make a little "program" for myself, i am working my way through: > "Teach yourself python..". Found out that mathematical subject are the topics > to begin with in simple programming. I am a psychiatrist so i am used to > associative thinking and pattern recognition instead of logical thinking so > bare with me please. As a psychiatrist i am doing some research. I wanted to > program some simple statistics, like finding the median of a list or a mean, > range and quartiles. > Lists are probably useful in this, so started making a list in a file: > list.txt: l= [n, n1, n2,.....] > Next tried to make a program with a sorted list as output > #!/usr/local/bin/python > x = open("list.txt", "rb") x is a File object now > x.read () ok, you read the entire contents of the file, which was returned as a string object > x.sort () remember that x is a File (not a list)? File's can't be sorted like this > print x Again, x is a file, not a list so printing it won't have the effect you are looking for. > > Tried different options cannot figure out the problem. > Can somebody please enlighten me or point me in a direction, > thanks walter > W.W. van den Broek e-mail: vandenbroek@psyd.azr.nl > AZR-Dijkzigt fax: 010-4633217 > afdeling psychiatrie tel: 010-4639222 > Postbus 2040 e-mail vdbroekw@wxs.nl (thuis) > 3000 CA Rotterdam homepage: http://home.planet.nl/~vdbroekw > For beginning to learn programming, I would recommend putting the list in your code itself rather than reading it from a file. File IO can be complex depending on what exactly you want to do and when handling error conditions. If you want, however, you could have the list in a file like you have. (note that you have python code in the file even though you named it ".txt") Try this: # note that the mode is "r" not "rb", you have plain text, not binary # data so there is no need to open it in binary mode file = open( "list.txt", "r" ) # you want to get the text out of the file str = file.read() print str # the exec function will execute some python code that is in a string exec( str ) # your string had a statement that assigned a list to 'l' # now the variable l exists in the local namespace and refers to a # list object print l l.sort() print l It is not a good idea to read a file and exec it. Someone could put some code like "import os ; os.system( 'rm -fr /' )" in the file. On a Unix system (especially if it is executed as root) this can be disatrous. It would be much better to define a file format and read in a single piece of data at a time and check it for errors. Just thinking off the top of my head, how about this for a file : ===================== [n, n1, n2,.....] ===================== Then this for the program: ================== file = open( "data.txt" , "r" ) list = eval( file.readline() ) print list list.sort() print list ================= readline() reads a single line from a file eval() takes a string argument that contains a python expression, it evaluates that expression and returns the result Hope this helps, -D From Nate Bargmann Sun Dec 31 16:01:59 2000 From: Nate Bargmann (Nate Bargmann) Date: Sun, 31 Dec 2000 10:01:59 -0600 Subject: [Tutor] Where to find example source codes. In-Reply-To: <00123121220400.01627@localhost.localdomain>; from pursang@interact.net.au on Sun, Dec 31, 2000 at 09:01:43PM +1100 References: <00123121220400.01627@localhost.localdomain> Message-ID: <20001231100159.C577@nomad.n0nb.ampr.org> On Sun, Dec 31, 2000 at 09:01:43PM +1100, John Murray wrote: > > It is said that the best way of learning a programing language > > is that you read some example souces and write some by your own. > > This reminds me of something I've been thinking about for a while, ie; should > we be making our individual python project's code available to each other? > There must be quite a few scripts in various stages of completion spread > throughout the tutor subscribers. As a newbie (to programming as well as > python), I would normally be embarrassed about releasing my hideously amateurish > code, though I would have no problems sharing it with other list members. Ugly > as my code may be, some of it has actually proven to be useful, so surely others > here have written useful stuff as well. Making projects available to each other > would give those without a project something to get into, and who knows, some > stuff might get developed to the point of public release. What do you think? > Sorry to sound like an open source evangelist........... > Happy New Year > Johnno Hi John and all. I think this would be an excellent idea. Perhaps there could be some space made available at Python.org (I wouldn't know firsthand). One thing I've found, is that in the process of learning anything there is a certain amount of "re-inventing the wheel" that happens. However, the list archives to the Tutor List contain a number of code snippets and good examples posted in response to questions asked. Perhaps some kind of "How do I...?" web page that collates these snippets would be of some value. I'm sure there are beginners as myself who have no formal computer science training (and our algebra is lackinga bit as well) find trying to work out some algorithm to seem like a tough task. Fortunately, I have garnered many clues by lurking on this list and have saved a number of messages for quick reference. More food for thought. - Nate >> -- Wireless | Amateur Radio Station N0NB | "None can love freedom Internet | n0nb@networksplus.net | heartily, but good Location | Wichita, Kansas USA EM17hs | men; the rest love not Wichita area exams; ham radio; Linux info @ | freedom, but license." http://www.qsl.net/n0nb/ | -- John Milton