From bwinton at latte.ca Tue Jun 1 16:05:45 2004 From: bwinton at latte.ca (Blake Winton) Date: Tue Jun 1 16:06:05 2004 Subject: [Tutor] list comprehension question In-Reply-To: Message-ID: <003501c44813$d9c918f0$6401a8c0@phantomfiber.com> > I have two lists of keys that I have from creating edge > dictionaries for the altered and original mesh, then > using list comprehension to find the unique edges. > giving, for instance, the following. > > ListAUniqueEdges = {(1,5), (2,6), (3,7), (8,9)} > ListBUniqueEdges = {(2,7), (3,5), (1,6), (10,11)} Just one question, you have those listed as dictionaries, but I've found it easier to work with if I converted them to lists. i.e.: ListAUniqueEdges = [(1,5), (2,6), (3,7), (8,9)] ListBUniqueEdges = [(2,7), (3,5), (1,6), (10,11)] Was that a typo? > I need to create two dictionaries from the above, showing > how the edges from lista relate to those in listb and vice > versa, ie the resulting Dict would be > > DictA = {(1,5): {(1,6), (3,5)}, (2,6): {(2,7), (1,6)}, > (3,7): {(3,5), (2,7)}, (8,9):{}} > > is there some elegant way to do this, I think it should > be doable via list comprehension, but for some reason I > can't think of the solution right now, and the power of > google isn't helping... I can do it with a list comprehension, but I'ld like to see what you came up with first... Later, Blake. From martin at hardcoder.dk Tue Jun 1 16:48:06 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Tue Jun 1 16:50:51 2004 Subject: [Tutor] Problems with references Message-ID: <40BCEB86.3080603@hardcoder.dk> Hello This is a question on how references work with Python. I have several objects, which use the same class definition. Within this class definition, there is an attribute of the type dictionary. During the run of the application, this dictionary, will be slowly filled up with references to other objects. I would expect that the dictionary attribute will not be the same accross the objects. But everytime i add an object to one dictionary, it is also added to all the other dictionary. When I compare the addresses in the memory for the objects, I can only conclude that they are not the same. Here is an sample of when i put the references into the dictionaries: def examineParticipations(self): for id, participation in self.Participations.iteritems(): # lets first figure out what type it is connection1ObjectType = self.findDiaObject(participation.connection1) connection2ObjectType = self.findDiaObject(participation.connection2) # attr ======================================================= if connection1ObjectType == "attribute": connection1Object = self.Attributes[participation.connection1] # attr ----------------------------------------------------------------------------------------------- if connection2ObjectType == "entity": connection2Object = self.Entities[participation.connection2] connection2Object.attributes[participation.connection1] = connection1Object Now for the question: Why is a references added into one dictionary attribute also added to all other dictionary attributes, in objects of teh the same class definition, when one would expect that they where different dictionaries? regards Martin Hjort Eriksen From pythonTutor at venix.com Tue Jun 1 17:29:49 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Jun 1 17:30:00 2004 Subject: [Tutor] Problems with references In-Reply-To: <40BCEB86.3080603@hardcoder.dk> References: <40BCEB86.3080603@hardcoder.dk> Message-ID: <1086125389.2097.125.camel@laptop.venix.com> I assume that you made the dictionary a class variable. Class variables are common to the class. When they are immutable such as strings or numbers, the CHANGED values will be per instance (when assigned to self). This is a handy way to provide default values within a class. (I simply typed this in. There could be minor typos) class A: foo = 3 def change_foo(self): print self.foo # 3 self.foo = 10 print self.foo # 10 print A.foo # 3 unless class variable is explicitly changed Since the dictionary is mutable, all changes are shared among instances. To have separate dictionaries for each instance move the dictionary creation to the __init__ method and delete the class variable from the source. If the dictionary is NOT a class variable, please let us know. Then it will take further investigation. On Tue, 2004-06-01 at 16:48, Martin Hjort Eriksen wrote: > Hello > > This is a question on how references work with Python. > > I have several objects, which use the same class definition. Within this > class definition, there is an attribute of the type dictionary. During > the run of the application, this dictionary, will be slowly filled up > with references to other objects. > > I would expect that the dictionary attribute will not be the same > accross the objects. But everytime i add an object to one dictionary, it > is also added to all the other dictionary. > > When I compare the addresses in the memory for the objects, I can only > conclude that they are not the same. > > Here is an sample of when i put the references into the dictionaries: > > def examineParticipations(self): > for id, participation in self.Participations.iteritems(): > # lets first figure out what type it is > connection1ObjectType = > self.findDiaObject(participation.connection1) > connection2ObjectType = > self.findDiaObject(participation.connection2) > > # attr ======================================================= > if connection1ObjectType == "attribute": > connection1Object = > self.Attributes[participation.connection1] > # attr > ----------------------------------------------------------------------------------------------- > if connection2ObjectType == "entity": > connection2Object = > self.Entities[participation.connection2] > > connection2Object.attributes[participation.connection1] = connection1Object > > > Now for the question: > Why is a references added into one dictionary attribute also added to > all other dictionary attributes, in objects of teh the same class > definition, when one would expect that they where different dictionaries? > > regards > > Martin Hjort Eriksen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Tue Jun 1 18:32:53 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jun 1 18:32:59 2004 Subject: [Tutor] Problems with references In-Reply-To: <40BCEB86.3080603@hardcoder.dk> Message-ID: On Tue, 1 Jun 2004, Martin Hjort Eriksen wrote: > This is a question on how references work with Python. > > I have several objects, which use the same class definition. Within this > class definition, there is an attribute of the type dictionary. During > the run of the application, this dictionary, will be slowly filled up > with references to other objects. Hi Martin, Let's look at two possible implementations of a class with an attribute: ### class FirstExample: names = [] def __init__(self): pass def add(self, name): self.names.append(name) def report(self): for n in names: print n class SecondExample: def __init__(self): self.names = [] def add(self, name): self.names.append(name) def report(self): for n in names: print n ### Does your class definition resemble either one of these? The difference between the two here is that the FirstExample uses a shared "names" class attribute. The SecondExample uses an instance-specific "names" attribute that's created anew for each instance. My guess is that the FirstExample's approach fits your problem description, but then, I guess wildly. *grin* Please tell us a few more details on your class. A small, simplified example of the problem with source code will help us a lot, since then we can duplicate the same problem. Good luck to you! From tommusgrove__ at hotmail.com Tue Jun 1 18:43:45 2004 From: tommusgrove__ at hotmail.com (Tom Musgrove) Date: Tue Jun 1 18:43:50 2004 Subject: [Tutor] list comprehension question Message-ID: >Was that a typo? Hi Blake, it was indeed a typo, new to the whole python thing... Here is the solution I came up with >>>ListAUniqueEdges = [(1,5), (2,6), (3,7), (8,9)] >>>ListBUniqueEdges = [(2,7), (3,5), (1,6), (10,11)] >>>NewDict = {} >>>for k,v in ListAUniqueEdges: >>> listTemp = [] >>> for m,n in ListBUniqueEdges: >>> if((k==m)or(k==n)or(v==m)or(v==n)): #seems there should be a better >>>method here >>> if (listTemp == []) : >>> listTemp = [(m,n)] >>> else: >>> listTemp.extend([(m,n)]) >>> NewDict[(k,v)] = listTemp >>> >>>NewDict {(3,7): [(2,7), (3,5)], (2,6): [(2,7), (1,6)], (8,9): [], (1,5):[(3,5), (1,6)]} >>> So, it seems to work ok I'd be interested if there is a 'better' or more elegant way. Especially the if((k==m)or(k==n)or(v==m)or(v==n)) (I tried (k or v) == (m or n) but didn't give the result I'd hoped for...) >I can do it with a list comprehension, but I'ld like to see >what you came up with first... > >Later, >Blake. > _________________________________________________________________ MSN Toolbar provides one-click access to Hotmail from any Web page – FREE download! http://toolbar.msn.click-url.com/go/onm00200413ave/direct/01/ From bwinton at latte.ca Tue Jun 1 20:58:22 2004 From: bwinton at latte.ca (Blake Winton) Date: Tue Jun 1 21:15:23 2004 Subject: [Tutor] list comprehension question In-Reply-To: References: Message-ID: <20040602005822.GA42480@latte.ca> On Tue, Jun 01, 2004 at 10:43:45PM +0000, Tom Musgrove wrote: > >Was that a typo? > Hi Blake, it was indeed a typo, new to the whole python thing... No worries, just checking. > Here is the solution I came up with > >>>ListAUniqueEdges = [(1,5), (2,6), (3,7), (8,9)] > >>>ListBUniqueEdges = [(2,7), (3,5), (1,6), (10,11)] > >>>NewDict = {} > >>>for k,v in ListAUniqueEdges: > >>> listTemp = [] > >>> for m,n in ListBUniqueEdges: > >>> if((k==m)or(k==n)or(v==m)or(v==n)): > >>> if (listTemp == []) : > >>> listTemp = [(m,n)] > >>> else: > >>> listTemp.extend([(m,n)]) > >>> NewDict[(k,v)] = listTemp > >>> > >>>NewDict > {(3,7): [(2,7), (3,5)], (2,6): [(2,7), (1,6)], (8,9): [], (1,5):[(3,5), > (1,6)]} > >>> > So, it seems to work ok > > I'd be interested if there is a 'better' or more elegant way. Especially > the > if((k==m)or(k==n)or(v==m)or(v==n)) > (I tried (k or v) == (m or n) but didn't give the result I'd hoped for...) Yeah. How about: if k in (m,n) or v in (m,n): ? If you use the "in" trick, you don't really need to split out the tuples in ListBUniqueEdges, so you can shorten it to for x in ListBUniqueEdges: if k in x or v in x: I feel that there should be something a little nicer, but I'm not entirely sure what it is. Is there any way of taking advantage of the fact that the pairs are in some order? I think there should be, but I can't see it... (I kind of want to write: if (k,v) in (m,n): but I know that's not going to work, and I don't think it should work, particularly. Still, it would be nice.) > >I can do it with a list comprehension, but I'ld like to see > >what you came up with first... The other trick I used was the dict() method, which takes a list of tuples and turns them into a dictionary. i.e. >>> dict([(1,2),(3,4)]) {1: 2, 3: 4} And finally, here's my list comprehension (a one-liner, even!) : dict( [((a,b),[x for x in ListBUniqueEdges if a in x or b in x]) for a,b in ListAUniqueEdges] ) and the output: {(3, 7): [(2, 7), (3, 5)], (2, 6): [(2, 7), (1, 6)], (8, 9): [], (1, 5): [(3, 5), (1, 6)]} I don't think it's particularly more readable than your solution, though. Later, Blake. From Dragonfirebane at aol.com Tue Jun 1 21:46:25 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 1 21:46:35 2004 Subject: [Tutor] (no subject) Message-ID: Skipped content of type multipart/alternative-------------- next part -------------- 1. Allow creation of accounts with unique id's (based on birthday [ddmmyyyy] times pi times 1000 times 'time.time()' % 100000000) CHECK 2. Allow these accounts to be manipulated (deposits, withdrawals, transfers to existing accounts, and transfers to new accounts) 3. Allow account info (including account id, balance, date of opening, date of last use, a log of transactions, time since opening, and time since last use (but NOT the password)) to be saved. 4. Allow retrieval of this saved information only when the CORRECT password for the account id is entered. 5. Allow a directory of stored account id's to be visible without a password (but NOT their balances). 6. Allow compound interest to take effect compounded quarterly at 3 percent. 7. Allow the bank to charge a .5% commission on all transactions. 8. *optional* Allow the bank to hold a certain amount of money (expressly from aforementioned fees) to be used in loans at 25% interest compounded semi-annually, with payments to be made once a month. 9. Allow each user to be assigned a certain amount of money to begin with, based on the number of vowels in their name times 'time.time()' to the power of pi split into at most 6 digits. IN PROGRESS -------------- next part -------------- def newuser(): new = raw_input("Are you a new user [y/n]? ") while new not in 'yYnN': new = raw_input(""" Please enter 'y' for yes or 'n' for no. Are you a new user? """) if new in 'yY': startmon = raw_input("Please enter your first and last name [------ ------]. ") vowsearch = re.compile('[aeiou]*', re.IGNORECASE) print re.search(vowsearch, startmon).group() def newacc(): newac = raw_input("Would you like to create a new account [y/n]? ") while newac not in 'yYnN': newac = raw_input(""" Please enter 'y' for yes or 'n' for no. Would you like to create a new acount? """) if newac in 'yY': newacid = int(raw_input("Please enter your birthday [ddmmyyyy]. ")) newacid = 3141.5962 * newacid newacid = newacid * time.time() newacid = newacid % 100000000 initbal = int(raw_input("How much money would you like to put in your account? ")) print "Account number %d created with $%d in it." % (newacid, initbal) return newacid import time import re newuser() newacc() From gew75 at hotmail.com Tue Jun 1 22:18:00 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Tue Jun 1 22:18:10 2004 Subject: [Tutor] (no subject) References: Message-ID: Hi Dragonfirebane, > I'm having some trouble understanding the use of the re module in searches, etc. > What I am trying to do in the attached code is get the user's first and last name > with a maximum of 6 characters each (I don't know how to get only the first six > characters of each name (first, last). I'll probably divide that into one for each > name to make it easier) and find the number of vowels in it. I am utterly confused > regarding how to do this . . . any help would be appreciated. Well, for such a simple task I would not use the re module. Regular expressions can be hard to understand, and especially for someone who is relatively new to programming. More intuitive is to roll your own! The standard string object has plenty of builtin functionality. If you want to only get names of maximum 6 characters, then use a while loop with len(name) as a check. For example: name = raw_input("Please enter your name > ") while len(name) > 6: print "Six characters maximum. Please try again." name = raw_input("Please enter your name > ") Or if you want to get the first six characters of the input string, use a slice. For example: >>> name = "Jimbiusmongius" >>> shortname = name[:6] >>> shortname 'Jimbiu' To find the number of vowels in a name, try something like : >>> vowels = ['a', 'e', 'i', 'o', 'u'] >>> name = "Alista" >>> for letter in name: .. if letter.lower() in vowels: .. vowelcount = vowelcount + 1 >>> vowelcount 3 The reason .lower() is required is to ensure that the name contains no uppercase letters, which are not present in our vowels list, since uppercase and lowercase are not the same according to python. HTH, Glen From tommusgrove__ at hotmail.com Tue Jun 1 22:25:02 2004 From: tommusgrove__ at hotmail.com (Tom Musgrove) Date: Tue Jun 1 22:25:07 2004 Subject: [Tutor] list comprehension question Message-ID: Thanks, I think I'll stick with my code, but replace the k,v with vertA and vertB, and m,n with edge for a slight readability improvement. I can't believe I forgot about the in thing - duh! I guess I'm just not used to seeing it in a programming context. Tom M. _________________________________________________________________ Stop worrying about overloading your inbox - get MSN Hotmail Extra Storage! http://join.msn.click-url.com/go/onm00200362ave/direct/01/ From gew75 at hotmail.com Tue Jun 1 23:54:46 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Tue Jun 1 23:55:00 2004 Subject: [Tutor] (no subject) References: Message-ID: Yes it would, but I am lazy so tried to save a little typing :). Glen ----- Original Message ----- From: Dragonfirebane@aol.com To: gew75@hotmail.com Sent: Wednesday, June 02, 2004 12:35 PM Subject: Re: [Tutor] (no subject) Thanks. Wouldn't it also be possible to add 'A','E','I','O','U' to vowels so that capital vowels are caught as well, removing the need for a case-sensitive match? In a message dated 6/1/2004 10:18:20 PM Eastern Standard Time, gew75@hotmail.com writes: Hi Dragonfirebane, > I'm having some trouble understanding the use of the re module in searches, etc. > What I am trying to do in the attached code is get the user's first and last name > with a maximum of 6 characters each (I don't know how to get only the first six > characters of each name (first, last). I'll probably divide that into one for each > name to make it easier) and find the number of vowels in it. I am utterly confused > regarding how to do this . . . any help would be appreciated. Well, for such a simple task I would not use the re module. Regular expressions can be hard to understand, and especially for someone who is relatively new to programming. More intuitive is to roll your own! The standard string object has plenty of builtin functionality. If you want to only get names of maximum 6 characters, then use a while loop with len(name) as a check. For example: name = raw_input("Please enter your name > ") while len(name) > 6: print "Six characters maximum. Please try again." name = raw_input("Please enter your name > ") Or if you want to get the first six characters of the input string, use a slice. For example: >>> name = "Jimbiusmongius" >>> shortname = name[:6] >>> shortname 'Jimbiu' To find the number of vowels in a name, try something like : >>> vowels = ['a', 'e', 'i', 'o', 'u'] >>> name = "Alista" >>> for letter in name: . if letter.lower() in vowels: . vowelcount = vowelcount + 1 >>> vowelcount 3 The reason .lower() is required is to ensure that the name contains no uppercase letters, which are not present in our vowels list, since uppercase and lowercase are not the same according to python. HTH, Glen From bobhe at telkomsa.net Wed Jun 2 01:42:31 2004 From: bobhe at telkomsa.net (Bob Heasman) Date: Wed Jun 2 01:41:54 2004 Subject: [Tutor] Comparing two lines of print Message-ID: <40BD68C7.20006@telkomsa.net> First of all thanks to those who have assisted me thus far!!!!! I am trying to write a simple program which compares a line taken from a file with one which I have typed into a script. Herewith the script :- #!/usr/bin/python # Window analyser # To select a phrase and send a cmd to the parallel port # print "\a" print "\nReading one line at a time." text_file = open("window2", "r") print text_file.readline() # [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] #This a is copy of the line which # is supposed to be compared with the next line down. if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] print "UA6ADV, beam heading 000 deg. Activate relay #1" # elif phrase == "[PORT 6 (PTCPACTOR) - 19 - F3KT-0]": # print "F3KT, beam heading 350 deg. Activate relay #2" # elif phrase == "[PORT 6 (PTCPACTOR) - 19 - HS0ZDZ-0]": # print "HS0ZDZ-0, beam heading 67 deg. Activate relay #3" # else: # print "\n\n\t\tPhrase does not match. Return to 000 deg. Relay #1" raw_input("\n\nPress the enter key to exit.") ******************************* When I attempt to run this script I get a syntax error:- [root@penguin bob]# ./readfile.py File "./readfile.py", line 14 if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] ^ SyntaxError: invalid syntax **************************** I just cannot figure out why this is happening. HELP. Cheers Bob From chidorex-pytutor at yahoo.com Wed Jun 2 01:54:15 2004 From: chidorex-pytutor at yahoo.com (Rex) Date: Wed Jun 2 01:54:20 2004 Subject: [Tutor] Comparing two lines of print In-Reply-To: <40BD68C7.20006@telkomsa.net> Message-ID: <20040602055415.35825.qmail@web13425.mail.yahoo.com> I'm not a Python expert at all, but in this case, your error comes from missing the capturing quotes and the final colon. You do have these on the subsequent elifs: if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] should be if text_file.readline() == "[PORT 6 (PTCPACTOR) - 19 - UA6ADV-0]": Best regards, Rex --- Bob Heasman wrote: > First of all thanks to those who have assisted me thus far!!!!! > > I am trying to write a simple program which compares a line taken > from a > file with one which I have typed into a script. > > Herewith the script :- > > > > > #!/usr/bin/python > # Window analyser > # To select a phrase and send a cmd to the parallel port > > > > # print "\a" > print "\nReading one line at a time." > > > > text_file = open("window2", "r") > > > > print text_file.readline() > > > > # [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] #This a is copy of the line > which > # is supposed to be compared with the next line down. > > > > if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] > print "UA6ADV, beam heading 000 deg. Activate relay #1" > > > > # elif phrase == "[PORT 6 (PTCPACTOR) - 19 - F3KT-0]": > # print "F3KT, beam heading 350 deg. Activate relay #2" > > > > # elif phrase == "[PORT 6 (PTCPACTOR) - 19 - HS0ZDZ-0]": > # print "HS0ZDZ-0, beam heading 67 deg. Activate relay #3" > > > > # else: > # print "\n\n\t\tPhrase does not match. Return to 000 deg. Relay > #1" > > > > raw_input("\n\nPress the enter key to exit.") > > > ******************************* > > When I attempt to run this script I get a syntax error:- > > [root@penguin bob]# ./readfile.py > File "./readfile.py", line 14 > if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] > ^ > SyntaxError: invalid syntax > > **************************** > > I just cannot figure out why this is happening. HELP. > > Cheers > > Bob > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Wed Jun 2 02:55:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 2 02:54:47 2004 Subject: [Tutor] gui tks and encodings References: <200405312114.i4VLEZ7l033048@smtp.enternet.hu> Message-ID: <011b01c4486e$935992e0$6401a8c0@xp> > but could you tell me why do i always get 0, 0, 0, 0 for > > print text_widget.bbox('insert') ? Not without knowing more about what's inside the text box. The manual says of bbox: ---------- Return a list of 4 numbers giving x,y,width and height (relative to the widget) of the visible area occupied by the character at the index. If the character is not visible an empty list is returned ---------- So if there were no characters in the text box you would indeed get 0,0,0,0. But if you insert some characters and move the insert into the middle of them, then you should get a different result. HTH, Alan G. From martin at hardcoder.dk Wed Jun 2 03:01:20 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Wed Jun 2 03:04:07 2004 Subject: [Tutor] Problems with references In-Reply-To: References: Message-ID: <40BD7B40.5090007@hardcoder.dk> >Hi Martin, > > >Let's look at two possible implementations of a class with an attribute: > >### >class FirstExample: > names = [] > def __init__(self): > pass > def add(self, name): > self.names.append(name) > def report(self): > for n in names: > print n > > >class SecondExample: > def __init__(self): > self.names = [] > def add(self, name): > self.names.append(name) > def report(self): > for n in names: > print n >### > >Does your class definition resemble either one of these? > >The difference between the two here is that the FirstExample uses a shared >"names" class attribute. The SecondExample uses an instance-specific >"names" attribute that's created anew for each instance. > > >My guess is that the FirstExample's approach fits your problem >description, but then, I guess wildly. *grin* > >Please tell us a few more details on your class. A small, simplified >example of the problem with source code will help us a lot, since then we >can duplicate the same problem. > >Good luck to you! > > > > > Hello Danny Thank you very much..that helped, my program now reacts the way I want. I understand what is going on in your explenation, but there is still one funny thing that I still do not understand. This is how part of the class definition looked like, before I edited according to your recomendations: class DiaObjectEntity: # attributes of the entity attributes = {} # keys of the entity keys = [] # wheater or not it is a weak entity weak = 0 # the name of the entity name = "" def __init__(self, DiaId): self.DiaId = DiaId I moved the generation of the attribute "attributes" down into the __init__ method, and now they are instance specific, instead of shared. The funny thing however is the attribute name. Eventhough it is defined like the above, the content is still instence specific, and not shared. Meaning, that I have given each instance an unique name, at some point efter the instantiation, and that name is only hold for that instance, and is not given to the other instances. /Martin From alan.gauld at blueyonder.co.uk Wed Jun 2 03:14:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 2 03:14:10 2004 Subject: [Tutor] Problems with references References: <40BCEB86.3080603@hardcoder.dk> Message-ID: <012401c44871$48af2a40$6401a8c0@xp> > I have several objects, which use the same class definition. I assume you mean they are all instances of the same class? Not that they have a reference to the class? > class definition, there is an attribute of the type dictionary. > > I would expect that the dictionary attribute will not be the same > accross the objects. If the dictionary is defined as a class attribute it will be shared across instances. That is what class attributes are for. If you want it to be per instance you need to define it within the __init__ method. If OTOH you are holding a reference to the class within other objects then again the objects will all point at the same class object and share the dictionarey. All three scenarios are illustrated below: class C: sharedDict = {} # class attribute shared by all instances def __init__(self): self.uniqueDict = {} # this is unique per insance def printDicts(self) print self.sharedDict print self.uniqueDict class D: def __init__(self): self.c_ref = C # reference to the class def printDict: print self.c_ref.sharedDict c = C() d = C() c.sharedDict[1] = 'one' c.uniqueDict[1] = 'ONE' c.printDict() d.printDict() d.sharedDict[1] = 'CHANGED IT!" d.uniqueDict[1] = "WON" c.printDict() d.printDict() e = D() e.printDict() > Here is an sample of when i put the references into the dictionaries: > > def examineParticipations(self): > for id, participation in self.Participations.iteritems(): > # lets first figure out what type it is > connection1ObjectType = > self.findDiaObject(participation.connection1) > connection2ObjectType = > self.findDiaObject(participation.connection2) > > # attr ======================================================= > if connection1ObjectType == "attribute": > connection1Object = > self.Attributes[participation.connection1] > # attr Off topic, but looking at this code I can't help thinking it doesn't look very object like... Couldn't the connectionObjects themselves figure out what to do? Rather than have a 'if type==XXX' statement? Such statements are very rarely needed in OO designs and are a common maintenance headache in the future. On of the big bendefits of OO is to avoid those types of if statements. But without more understanding of what the various objects do I can't be sure, so maybe you do need to do it that way. > Why is a references added into one dictionary attribute also added to > all other dictionary attributes, in objects of teh the same class > definition, when one would expect that they where different dictionaries? Hopefully my example above has demonstrated that - assuming that my guess is right and you have created them as class attributes. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Wed Jun 2 03:18:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 2 03:17:58 2004 Subject: [Tutor] list comprehension question References: Message-ID: <012d01c44871$d11560c0$6401a8c0@xp> I'll leave someone else to dop the list comprehension answer but... > I'd be interested if there is a 'better' or more elegant way. Especially > the > > if((k==m)or(k==n)or(v==m)or(v==n)) Personally I'd do: if k in (m,n) or v in (m,n) Alan G. From martin at hardcoder.dk Wed Jun 2 03:41:59 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Wed Jun 2 03:44:55 2004 Subject: [Tutor] Problems with references In-Reply-To: <012401c44871$48af2a40$6401a8c0@xp> References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp> Message-ID: <40BD84C7.4010709@hardcoder.dk> Thank you very much for your answer. >If the dictionary is defined as a class attribute it will be >shared across instances. That is what class attributes are for. > > > That depends in what language you are working. > >Off topic, but looking at this code I can't help thinking it >doesn't look very object like... Couldn't the connectionObjects >themselves figure out what to do? Rather than have a 'if type==XXX' >statement? Such statements are very rarely needed in OO designs >and are a common maintenance headache in the future. On of the >big bendefits of OO is to avoid those types of if statements. > >But without more understanding of what the various objects do >I can't be sure, so maybe you do need to do it that way. > > > You are totally right, and normally I would not work in this way. The problem is that this is the first time I work with Python, and I am still learning all the little quirks of the language. Later versions of this program will be better designed. /Martin From orbitz at ezabel.com Wed Jun 2 04:43:12 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Wed Jun 2 04:44:23 2004 Subject: [Tutor] Comparing two lines of print In-Reply-To: <40BD68C7.20006@telkomsa.net> References: <40BD68C7.20006@telkomsa.net> Message-ID: <20040602044312.2ad4b80d.orbitz@ezabel.com> Just take the time to compare what you have with all the other elif lines. When you hit a snag just take a deep breath and look at the code for awhile and think about what you are trying to do. On Wed, 02 Jun 2004 07:42:31 +0200 Bob Heasman wrote: > First of all thanks to those who have assisted me thus far!!!!! > > I am trying to write a simple program which compares a line taken from a > file with one which I have typed into a script. > > Herewith the script :- > > > > > #!/usr/bin/python > # Window analyser > # To select a phrase and send a cmd to the parallel port > > > > # print "\a" > print "\nReading one line at a time." > > > > text_file = open("window2", "r") > > > > print text_file.readline() > > > > # [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] #This a is copy of the line which > # is supposed to be compared with the next line down. > > > > if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] > print "UA6ADV, beam heading 000 deg. Activate relay #1" > > > > # elif phrase == "[PORT 6 (PTCPACTOR) - 19 - F3KT-0]": > # print "F3KT, beam heading 350 deg. Activate relay #2" > > > > # elif phrase == "[PORT 6 (PTCPACTOR) - 19 - HS0ZDZ-0]": > # print "HS0ZDZ-0, beam heading 67 deg. Activate relay #3" > > > > # else: > # print "\n\n\t\tPhrase does not match. Return to 000 deg. Relay #1" > > > > raw_input("\n\nPress the enter key to exit.") > > > ******************************* > > When I attempt to run this script I get a syntax error:- > > [root@penguin bob]# ./readfile.py > File "./readfile.py", line 14 > if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] > ^ > SyntaxError: invalid syntax > > **************************** > > I just cannot figure out why this is happening. HELP. > > Cheers > > Bob > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Wed Jun 2 05:17:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 2 05:16:41 2004 Subject: [Tutor] Problems with references References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp> <40BD84C7.4010709@hardcoder.dk> Message-ID: <013e01c44882$6342ff60$6401a8c0@xp> > >If the dictionary is defined as a class attribute it will be > >shared across instances. That is what class attributes are for. > That depends in what language you are working. Nope, that is a basic tenet of OOP. The only language dependent feature is how class attributes are implemented. For example in C++ and Java they are prefixed with ''static', in Smalltalk they are defined within a separate pane of the class browser (they have a unique syntax too but I can't remember it! :-) and in Objective-C they are prefixed by '+' rather than the '-' used for instance members. But the idea of class attributes is the same in all OOP languages. Sorry to be picky, but for the sake of other newbies who might be reading, the distinction is important :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Wed Jun 2 05:23:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 2 05:22:55 2004 Subject: [Tutor] Comparing two lines of print References: <40BD68C7.20006@telkomsa.net> Message-ID: <016001c44883$41f16030$6401a8c0@xp> > When I attempt to run this script I get a syntax error:- > > [root@penguin bob]# ./readfile.py > File "./readfile.py", line 14 > if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] > ^ > SyntaxError: invalid syntax You are comparing a string (from raw_input()) with a list. I assume you need quotes around the [PORT....-0] stuff? Alan G From martin at hardcoder.dk Wed Jun 2 05:37:16 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Wed Jun 2 05:40:08 2004 Subject: [Tutor] Problems with references In-Reply-To: <013e01c44882$6342ff60$6401a8c0@xp> References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp> <40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> Message-ID: <40BD9FCC.9090904@hardcoder.dk> >Nope, that is a basic tenet of OOP. The only language dependent >feature is how class attributes are implemented. For example >in C++ and Java they are prefixed with ''static', > > agreed....and in php5 it is also prefixed with a static. But I do disagree that the basic idea that attributes should be shared across objects. The basic idea of objects, is that they can take different states. These states are described through the attributes that the object has. This requires that the attributes are not shared between instances. But in some cases it is necessary that you have the ability to share attributes, but that should be rather rare, since the best practice is that each object is as much as possible encapsulated from everything else. /Martin From bobhe at telkomsa.net Wed Jun 2 09:00:05 2004 From: bobhe at telkomsa.net (Bob Heasman) Date: Wed Jun 2 08:59:34 2004 Subject: [Tutor] Comparing two lines of print In-Reply-To: <016001c44883$41f16030$6401a8c0@xp> References: <40BD68C7.20006@telkomsa.net> <016001c44883$41f16030$6401a8c0@xp> Message-ID: <40BDCF55.9010909@telkomsa.net> Alan Gauld wrote: >>When I attempt to run this script I get a syntax error:- >> >>[root@penguin bob]# ./readfile.py >> File "./readfile.py", line 14 >> if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] >> ^ >>SyntaxError: invalid syntax > > > You are comparing a string (from raw_input()) with a list. > I assume you need quotes around the [PORT....-0] stuff? > > Alan G > > > Hello Alan, Yes I now see what is happening. When I had the quotes in it appeared to be ignoring two lines of code. Now I see that it IS comparing them and, due to the quotes, it says they are not the same. Sorry, I am so new to this game I cannot see the wood for the trees. Phew, back to the drawing board. Regards. Bob From dr_mirror at freemail.hu Wed Jun 2 09:39:46 2004 From: dr_mirror at freemail.hu (dr_mirror@freemail.hu) Date: Wed Jun 2 09:39:55 2004 Subject: [Tutor] gui tks and encodings Message-ID: <200406021339.i52DdkJ8020050@smtp.enternet.hu> " So if there were no characters in the text box you would indeed get 0,0,0,0. But if you insert some characters and move the insert into the middle of them, then you should get a different result. " yes i know i should, but i don't. the widget is full of characters and i move the cursor to the middle, this has always been the way i tried. this bbox method does not seem to care about it. i would be happy if somebody had an evidence that it actually works at all. tm From Janssen at rz.uni-frankfurt.de Wed Jun 2 10:28:39 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Wed Jun 2 10:28:54 2004 Subject: [Tutor] Comparing two lines of print In-Reply-To: <40BDCF55.9010909@telkomsa.net> References: <40BD68C7.20006@telkomsa.net> <016001c44883$41f16030$6401a8c0@xp> <40BDCF55.9010909@telkomsa.net> Message-ID: On Wed, 2 Jun 2004, Bob Heasman wrote: > Alan Gauld wrote: > >>When I attempt to run this script I get a syntax error:- > >> > >>[root@penguin bob]# ./readfile.py > >> File "./readfile.py", line 14 > >> if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] > >> ^ > >>SyntaxError: invalid syntax > > > > > > You are comparing a string (from raw_input()) with a list. > > I assume you need quotes around the [PORT....-0] stuff? > > > > Alan G > > > > > > > Hello Alan, > > Yes I now see what is happening. When I had the quotes in it appeared > to be ignoring two lines of code. Now I see that it IS comparing them > and, due to the quotes, it says they are not the same. it's very likly due to the trailing newline: lines captured with raw_input have a newline (because you type ENTER). Run this: """ inp = raw_input("Type Enter: ") print repr(inp) """ the "repr" shows the newline in raw representation: "\n". Michael From dyoo at hkn.eecs.berkeley.edu Wed Jun 2 14:29:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jun 2 14:29:42 2004 Subject: [Tutor] Comparing two lines of print In-Reply-To: <40BDCF55.9010909@telkomsa.net> Message-ID: On Wed, 2 Jun 2004, Bob Heasman wrote: > Alan Gauld wrote: > >>When I attempt to run this script I get a syntax error:- > >> > >>[root@penguin bob]# ./readfile.py > >> File "./readfile.py", line 14 > >> if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0] > >> ^ > >>SyntaxError: invalid syntax > > > > > > You are comparing a string (from raw_input()) with a list. > > I assume you need quotes around the [PORT....-0] stuff? > > > > > > Hello Alan, > > Yes I now see what is happening. When I had the quotes in it appeared to > be ignoring two lines of code. Now I see that it IS comparing them and, > due to the quotes, it says they are not the same. Hi Bob, Let's elaborate on this point a little. When we say things like: ### >>> msg = "hello world" ### then the 'msg' itself won't have quotes embedded in it. The value of the name 'msg' is the string hello world (The indentation, too, isn't part of the string, but is there just to set it off from my explanation.) The quotes allow us to tell Python that we're defining a "string literal". This is a detail that matters, since the following: ### >>> "hello" + " world" == "hello world" True ### is True, even though we can see four quote characters on the left side, and only two quote characters on the right side. And so is: ### >>> 'hello world' == "hello world" True ### The quote characters are really for us, to tell the Python system: "Ok, I'm defining a string constant. Anything between the quote characters should be treated as a string." We could live without using string literals, since we can construct string values based on the individual ASCII character values: ### >>> chr(104) + chr(101) + chr(108) + chr(108) + chr(111) + chr(32) + \ ... chr(119) + chr(111) + chr(114) + chr(108) + chr(100) 'hello world' ### but this is just... well... painful. *grin* Anyway, getting back to the subject: the quote characters themselves are probably not the reason why the expression: text_file.readline() == "[PORT 6 (PTCPACTOR) - 19 - UA6ADV-0]" is evaluating to False. Instead, it's better to assume, for the moment, that the value of text_file.readline() isn't exactly equal to that other string value, and to find out why. So keep the quotes there: removing them, just because the comparison was failing, was a wrong turn. *grin* Michael Janssen's suggestion to make sure that the "newline" character '\n' isn't interfering with the comparison, on the other hand, sounds right. Hope this helps! From alan.gauld at blueyonder.co.uk Wed Jun 2 14:54:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 2 14:54:27 2004 Subject: [Tutor] Problems with references References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> Message-ID: <019101c448d3$0394a8b0$6401a8c0@xp> > >Nope, that is a basic tenet of OOP. The only language dependent > >feature is how class attributes are implemented. For example > >in C++ and Java they are prefixed with ''static', > > > > But I do disagree that the basic idea that attributes should be shared > across objects. Class attributes are shared by definition, thats what makes them class attributes - they belong to the class rather than the instance. > The basic idea of objects, is that they can take different states. Absolutely but objects are not classes. (Although classes are objects but thats getting too far into meta theory for this list I suspect!) Instances have their attributes and they are unique to the instance. Classes have their attributes andthey are unique to the class and shared by the instances of that class. If that were not true basic OOP would not work since OOP relies on the ability to create instances which utilises the class constructor which in turn is an attribute (or more specifically a method) of the class. Indeed all methods are attributes of the class shared by the instances. (Python is one of the few OOP languages which allows you to define attributes in the instances which are not in the class, but again that's verging into the esoteric) > These states are described through the attributes that > the object has. This requires that the attributes are not shared between > instances. [irrelevant aside: In fact it doesn't, it can be represented by a single state attribute (which in turn can be stored by the class itself). Some early OOP languages investigated such an approach but it was very inefficient. ] > But in some cases it is necessary that you have the ability > to share attributes, but that should be rather rare, In practice, in most large scale systems there will be class attributes around somewhere, and indeed in Smalltalk it is common practice to define a few class attributes for almost every new class. In any system where persistence is implemented (storing objects between program invocations) it is common to implement class attributes and methods to manage the instances (keep a count or object pool/cache for example, or to implement an object search mechanism). However, I do agree that classs methods are far more common that class attributes. > practice is that each object is as much as possible encapsulated from > everything else. Yes, but class attributes have very little to do with objects (except the class objects themselves) and everything to do with the class. So anything you need to know about the class rather than the object should be stored in a class attribute. Alan G. From alan.gauld at blueyonder.co.uk Wed Jun 2 15:02:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 2 15:02:58 2004 Subject: [Tutor] gui tks and encodings References: <200406021339.i52DdkJ8020050@smtp.enternet.hu> Message-ID: <019601c448d4$34284ee0$6401a8c0@xp> > >But if you insert some characters and move the insert into the > >middle of them, then you should get a different result. " > > yes i know i should, but i don't. the widget is full of characters > and i move the cursor to the middle, this has always been the way i tried. >>> tk = Tk() >>> t = Text() >>> t.pack() >>> def printBbox(): ... print 'bbox returned: ', t.bbox(INSERT) ... >>> b = Button(text="BBOX", command = printBbox) >>> b.pack() >>> tk.mainloop() bbox returned: (3, 3, 480, 13) bbox returned: (61, 3, 6, 13) bbox returned: (92, 29, 6, 13) bbox returned: (260, 3, 6, 13) Seems to work OK for me. Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Jun 2 15:10:53 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jun 2 15:11:03 2004 Subject: [Tutor] Problems with references In-Reply-To: <40BD7B40.5090007@hardcoder.dk> Message-ID: > I understand what is going on in your explenation, but there is still > one funny thing that I still do not understand. > > This is how part of the class definition looked like, before I edited > according to your recomendations: > > class DiaObjectEntity: > # attributes of the entity > attributes = {} > > # keys of the entity > keys = [] > > # wheater or not it is a weak entity > weak = 0 > > # the name of the entity > name = "" > > def __init__(self, DiaId): > self.DiaId = DiaId > > > I moved the generation of the attribute "attributes" down into the > __init__ method, and now they are instance specific, instead of shared. Hi Martin, I'm glad it's starting to come together a little beetter. *grin* So what does the class definition look like, now? > The funny thing however is the attribute name. Eventhough it is defined > like the above, the content is still instence specific, and not shared. > Meaning, that I have given each instance an unique name, at some point > efter the instantiation, and that name is only hold for that instance, > and is not given to the other instances. Hmmm. Ok, let me guess the situation again. Do you mean something like this? ### class Person: name = "Foobar" def __init__(self): pass def greet(self): print self.name, "greets you with great joy" def rename(self, newName): self.name = newName ### [Advance warning: we'll see that the code above is actually not such a hot idea to write.] Let's see what happens here: ### >>> class Person: ... name = "Foobar" ... def __init__(self): ... pass ... def greet(self): ... print self.name, "greets you with great joy" ... def rename(self, newName): ... self.name = newName ... >>> p1 = Person() >>> p1.greet() Foobar greets you with great joy >>> p2 = Person() >>> p2.rename("Martin") >>> p2.greet() Martin greets you with great joy >>> p1.greet() Foobar greets you with great joy ### If you're doing something like this, don't! *grin* What's happening here is a mixture of class and instance attribute stuff, and it's potentially confusing. The class defined above, ### class Person: name = "Foobar" def __init__(self): pass def greet(self): print self.name, "greets you with great joy" def rename(self, newName): self.name = newName ### is very bug-prone, because it first defines a class attribute named 'name', but also allows one to use an instance attribute named 'name'. Any new Person that's instantiated here doesn't yet have a instance attribute to make it unique, so when we call greet(), we get the class attribute value: ### >>> p1 = Person() >>> p1.greet() Foobar greets you with great joy ### But when we rename a person, we end up adding a new instance attribute to our Person. Instance attributes, if defined, will shadow class attributes: ### >>> p2 = Person() >>> p2.rename("Martin") >>> p2.greet() Martin greets you with great joy ### And the real reason this is really not a good situation is because our method, greet(), def greet(self): print self.name, "greets you with great joy" has two different behaviors here, depending if rename() had been called previously. greet() will print out the class attribute if that instance attribute hadn't been defined yet, but will print out the instance attribute if one is defined for the instance. Beginners will often try to use class attributes to define default values for attributes. However, it's probably a better idea to set those defaults up in the initializer: ### class Person: def __init__(self): self.name = "Foobar" def greet(self): print self.name, "greets you with great joy" def rename(self, newName): self.name = newName ### and avoid the whole class-vs-instance attribute mess. In fact, I'd recommend avoiding class attributes altogether... well, at least for a while. *grin* If you have Java/C++ experience, and if you're familiar with things like: /*** Pseudo-Java ***/ class Person { String name; Person(String name) { this.name = name; } } /******/ then the appropriate translation of this into Python is: ### class Person: def __init__(self, name): self.name = name ### and there's no need to declare the attributes of a Person elsewhere. Class attributes follow a similar model to the way we use local variables in Python: we just assign to them to define them. Good luck to you! From martin at hardcoder.dk Wed Jun 2 19:05:42 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Wed Jun 2 19:08:10 2004 Subject: [Tutor] Problems with references In-Reply-To: <019101c448d3$0394a8b0$6401a8c0@xp> References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> <019101c448d3$0394a8b0$6401a8c0@xp> Message-ID: <40BE5D46.8090105@hardcoder.dk> Alan....either we both totally agree but we cannot understand each other, or we have been going to two very different schools of thought. :) I think instead of commenting on your comments on my comments...etc. I will just come with a short summary of the basics, from what I have been tought in the ways of OOP. Hopefully it can help to clear any misunderstandings between us. ;) As a starter, you have classes and objects. The class definitions are a blueprints on how the objects should be built, and these deifinitions are usualy not interesting when they are not instantiated. The basic purpose of class definitions is to provide blueprints for the objects. But of course all rules have an exception, meaning that sometimes it can be necessary to have a class definition that never will be instantiated, where the different part will be called staticly. But to work in the best OOP maner, this should be kept to a minimum. Well it even lies in the name...Object Oriented Programming. To understand the difference between the class and object, we can use one of the classic examples...a sail boat, or to be more precise, the sail of a sail boat. Roughly the different states of a sail can be the size, whether or not it is op or down, what color it is and so forth. These different states of the sail will be described through the attributes of the object, and theses attributes are defined in the class. Multiple instances of the class, means different sails. This idea of modeling is the basic idea of OOP, and this modeling has as a basic idea, that the attributes should not be shared. This leads back to what it was that i origanally objected in one of your e-mails, that the idea of attributes is that they should be shared. "If the dictionary is defined as a class attribute it will be shared across instances. That is what class attributes are for." Hope my writing clears any misunderstandings in my position. :) regards Martin Eriksen From glingl at aon.at Wed Jun 2 20:51:47 2004 From: glingl at aon.at (Gregor Lingl) Date: Wed Jun 2 20:51:05 2004 Subject: [Tutor] Problems with references In-Reply-To: <40BE5D46.8090105@hardcoder.dk> References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> <019101c448d3$0394a8b0$6401a8c0@xp> <40BE5D46.8090105@hardcoder.dk> Message-ID: <40BE7623.6020204@aon.at> > > > This leads back to what it was that i origanally objected in one of > your e-mails, that the idea of attributes is that they should be shared. > Do you agree, that there are two kinds of attributes in Python: instance attributes and class attributes? The latter are not shared beween objects (instances) of the same class, whereas the former are. What do you think, that "class attributes are for"? And keep in mind: you need not use them, if you don't like them ;-) Gregor > "If the dictionary is defined as a class attribute it will be > shared across instances. That is what class attributes are for." > > Hope my writing clears any misunderstandings in my position. :) > > regards > > Martin Eriksen > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From cwaigl at free.fr Wed Jun 2 21:51:05 2004 From: cwaigl at free.fr (Chris F Waigl) Date: Wed Jun 2 21:50:44 2004 Subject: [Tutor] New to list & first steps in Python Message-ID: <200406030351.05426.cwaigl@free.fr> I am thrilled to find that there is a list where beginners can find guidance. Thanks for taking the time to help! I'm interested in natural language processing, and chose Python as a programming language. I'm working my way through various tutorials right now, but I've only just begun. I've also changed over from W98 to Debian GNU/Linux and am not yet familiar with the modules installed on my box with Python 2.3. I use Idle, which I find very convenient. Right now I'm mostly interested in not adopting bad habits -- learning "good" style from the very beginning. In a different life, I used C for number-crunching type programming (solving equations and the like), but I never particularly enjoyed it. Here's my first script not copied from a tutorial. It works, so the only question is, should I have done something differently? (Well, it's so short, there's not much to _do_.) from random import * # or "... import choice" ? adj1 = [] adj2 = [] nouns = [] file = open("ElisabethInsults", "r") for line in file.readlines(): words = line.split() adj1.append(words[0]) adj2.append(words[1]) nouns.append(words[2]) print "Thou", choice(adj1), choice (adj2), choice(nouns) + "!" file.close() ElisabethInsults is a file containing three rows, 2 x adjectives, 1 x nouns, of derogatory words taken from Shakespeare. (If you're interested, it's here: http://kastalia.free.fr/misc/ElisabethInsults ) The script creates a random insult, e.g. "Thou clouted onion-eyed pigeon-egg!" I'm planning to put together something like a very simple tokenizer, something that reads in a text, counts sentences and words, handles all the punctuation correctly, tells me something about word frequencies and the presence or absence of grammatical structures I might be interested in. I'm certainly going to run into a lot of problems soon. Any comments and recommendations are warmly encouraged. Best, Christine From alan.gauld at blueyonder.co.uk Thu Jun 3 03:38:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 3 03:38:53 2004 Subject: [Tutor] Problems with references References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> <019101c448d3$0394a8b0$6401a8c0@xp> <40BE5D46.8090105@hardcoder.dk> Message-ID: <001701c4493d$d2a13730$6401a8c0@xp> > Alan....either we both totally agree but we cannot understand each > other, or we have been going to two very different schools of thought. :) Possibly different schools :-) What you are describing below is the fairly basic version of OOP as typically implemented in languages like C++/Java etc. It relegates the class to being a kind of cookie cutter with no interesting behaviour of itself. The longer you use objects the more you come to realize that this is an inadequate model. The early OOP languages (Lisp, Smalltalk, Actor etc) all recognised that classes had behaviour and attributes of their own. In fact in Smalltalk, where everything is an object, it was recognised that classes were objects too - they were instances of the class 'class'. (classes are objects, in the same way that functions are objects, in Python too) The purpose of class objects is amongst, other things, to act as factory objects. Thus constructors are class methods - you send the create message to the class, not to the instance - the instance doesn't exist yet! Similarly if you have a large collection of instances of a particular class which are not related to each other in an explicit collection, you may want to find out how many instances currently exist - that is something that the class knows - it created them after all... Another class responsibility would be to find a particular instance out of the pool of objects In a large database environment you may want to create an object from scratch, or to instantiate one from a database given an ID. The two different creation mechanisms are again the responsibility of the class. Related to this is the idea of type convertion, you may want to convert a piece of text to RichText, so the RichText class provides constructors that can take an ASCIItext object, a Postscript object, an HTMLobject etc. In a network application a process wants to send a message to a particular instance of a class, it can do so by directing the message to the class object in the receiving process which in turn locates the instance and forwards the message - acting as a proxy for all received messages for its instances. Languages like C++ implement class behaviour using static methods and attributes, which is an adequate if slightly inelegant way of doing so. Lisp, Smalltalk and Objective-C have explicit provision for class methods. Python lies somewhere in between with similar implementation to C++ but with some of the extra capabilities of Smalltalk. For example you can create an attribute that refers to the class - you can't do that in C++ For example: ################ class A: pass class B: pass classes = [A,B] instances = [] for cls in classes: # create 5 instances of each for n in range(5): instances.append(cls()) for obj in instances: print type(obj) ################## You can find some more about this in Guido's paper in the new type system and meta classes, but beware its a confusing read! Also the excellent book "Putting Meta Classes to Work" by Foreman and Danforth. > As a starter, you have classes and objects. The class definitions are a > blueprints on how the objects should be built, and these deifinitions > are usualy not interesting when they are not instantiated. Mostly that is right, except that the class is what is used to instantiate the instances... > purpose of class definitions is to provide blueprints for the objects. And to manage the instances once created, if necessary. > But of course all rules have an exception, meaning that sometimes it can > be necessary to have a class definition that never will be instantiated, > where the different part will be called staticly. But this is very rare and usually an example of bad design or an attempt to hide what is really a set of related functions - Java is rivven with this kind of horror. > best OOP maner, this should be kept to a minimum. Well it even lies in > the name...Object Oriented Programming. Absolutely. But classes are ojects too :-) > To understand the difference between the class and object, we can use > one of the classic examples...a sail boat, or to be more precise, the > sail of a sail boat. OK, Now consider that sail boat being an ocean going schooner. It has dozens of sales, including spares in case of accidents at sea. The captain wants to find a specific instance of sail - the pink one with green stripes, say. What object does he ask to find that instance? It could be the cupboard where the sails are kept, or ot could be the ship to ask all the cupboards - but it should also ask the masts since it might be aloft already - oh yes and maybe ask the sailmaker who is repairing a rip.... or he could just ask the sail class.... > Roughly the different states of a sail can be the > size, whether or not it is op or down, what color it is and so forth. Yes, absolutely. And the different states of *the sail* class (as opposed to *a sail object*) are whether any sails exist, whether new sails can be created (the singleton pattern is usually most easily implemented through class methods!) etc. > class. Multiple instances of the class, means different sails. This idea > of modeling is the basic idea of OOP, and this modeling has as a basic > idea, that the attributes should not be shared. Absolutely correct. Instance attributes are unique to each instance. Class attributes are shared across all instances. For example the set of characters that may be permitted in a string object could be stored in the string class, rather than every instance having to carry its own copy around. > This leads back to what it was that i origanally objected in one of your > e-mails, that the idea of attributes is that they should be shared. And the difference between class attributes and instance attributes and the fundamental importance of the distinction. This is why I was so picky about it, thee is a very real but subtle difference which many newbie OOP programmers find confusing. [ It might help to have a play with a Smalltalk class browser - Squeak or Dolphin are free to download. There you can explore the built in classes and see the kinds of thing that smalltalk defines as class attributes and methods. ] Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From vijaykumar at linuxmail.org Thu Jun 3 05:42:28 2004 From: vijaykumar at linuxmail.org (Vijay Kumar Bagavath Singh) Date: Thu Jun 3 05:42:43 2004 Subject: [Tutor] New to list & first steps in Python Message-ID: <20040603094228.498C121B32F@ws5-6.us4.outblaze.com> The best thing about python is that you get to write very little code for even the most complicated thing. Check out this super compressed code, that acheives the same result? from random import choice fil = file("/tmp/ElisabethInsults.txt", "r") adj1, adj2, nouns = zip(*[line.split() for line in fil]) print "Thou", choice(adj1), choice (adj2), choice(nouns) + "!" fil.close() To understand this program you will have to understand 1) List comprehension 2) Unpacking argument lists 3) Zip function 4) Multiple assignment List comprehesion is a short hand for creating complicated lists. The following example illustrates list comprehension. >>> [i*2 for i in range(0, 10)] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] The arguments to a function can be passed on in a single tuple or list. The tuple/list has to be preceded by a * for the unpacking to happen. The following example illustrates unpacking of argument lists. >>> range(0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> arg=(0,10) >>> range(*arg) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The zip function(added in Python 2.0): This function returns a list of tuples, where the I-th tuple contains the I-th element from each of the argument sequences. >>> numbers = [1, 2, 3, 4] >>> alpha = ['a', 'b', 'c', 'd'] >>> zip(numbers, alpha) [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] >>> z = zip(numbers,alpha) z = zip(numbers,alpha) Using unpacking of argument lists in zip function results in inverse operation of the zip function. >>> zip(*z) [(1, 2, 3, 4), ('a', 'b', 'c', 'd')] Following is an example of multiple assignment >>> a, b, c = 1, 2, 3 >>> print a, b, c 1 2 3 With recent versions of Python(2.2 and above) you can use file("filename", "r") to open files instead of open("filename", "r") also "r" is the default mode so you could use file("filename") With recent versions of Python(2.2 and above) you can use for line in fil instead of for line in fil.readlines() Regards, Vijay > Date: Thu, 3 Jun 2004 03:51:05 +0200 > From: Chris F Waigl > Subject: [Tutor] New to list & first steps in Python > To: Python Tutor > Message-ID: <200406030351.05426.cwaigl@free.fr> > Content-Type: text/plain; charset="us-ascii" > > I am thrilled to find that there is a list where beginners can find > guidance. Thanks for taking the time to help! > > I'm interested in natural language processing, and chose Python as a > programming language. I'm working my way through various tutorials > right now, but I've only just begun. I've also changed over from W98 to > Debian GNU/Linux and am not yet familiar with the modules installed on > my box with Python 2.3. I use Idle, which I find very convenient. > > Right now I'm mostly interested in not adopting bad habits -- learning > "good" style from the very beginning. In a different life, I used C for > number-crunching type programming (solving equations and the like), but > I never particularly enjoyed it. > > Here's my first script not copied from a tutorial. It works, so the only > question is, should I have done something differently? (Well, it's so > short, there's not much to _do_.) > > from random import * # or "... import choice" ? > adj1 = [] > adj2 = [] > nouns = [] > file = open("ElisabethInsults", "r") > for line in file.readlines(): > words = line.split() > adj1.append(words[0]) > adj2.append(words[1]) > nouns.append(words[2]) > print "Thou", choice(adj1), choice (adj2), choice(nouns) + "!" > file.close() > > ElisabethInsults is a file containing three rows, 2 x adjectives, 1 x > nouns, of derogatory words taken from Shakespeare. (If you're > interested, it's here: http://kastalia.free.fr/misc/ElisabethInsults ) > The script creates a random insult, e.g. > "Thou clouted onion-eyed pigeon-egg!" > > I'm planning to put together something like a very simple tokenizer, > something that reads in a text, counts sentences and words, handles all > the punctuation correctly, tells me something about word frequencies > and the presence or absence of grammatical structures I might be > interested in. I'm certainly going to run into a lot of problems soon. > > Any comments and recommendations are warmly encouraged. > > Best, > Christine > -- ______________________________________________ Check out the latest SMS services @ http://www.linuxmail.org This allows you to send and receive SMS through your mailbox. Powered by Outblaze From martin at hardcoder.dk Thu Jun 3 06:25:13 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Thu Jun 3 06:27:56 2004 Subject: [Tutor] Problems with references In-Reply-To: <001701c4493d$d2a13730$6401a8c0@xp> References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> <019101c448d3$0394a8b0$6401a8c0@xp> <40BE5D46.8090105@hardcoder.dk> <001701c4493d$d2a13730$6401a8c0@xp> Message-ID: <40BEFC89.50502@hardcoder.dk> >Possibly different schools :-) > > > We are... :) Now it all makes sense to me, thank you very much. I had no idea that OOP also worked in that direction. 2 small questions if it is ok... 1. "self" is that a reference to the class or an instance of the object? 2. Since that there are different paradigms within the OOP framework, which one is the most "correct"? (I know it is a wierd question.) /Martin >What you are describing below is the fairly basic version >of OOP as typically implemented in languages like C++/Java etc. >It relegates the class to being a kind of cookie cutter with >no interesting behaviour of itself. The longer you use objects >the more you come to realize that this is an inadequate model. > >The early OOP languages (Lisp, Smalltalk, Actor etc) all >recognised that classes had behaviour and attributes of their >own. In fact in Smalltalk, where everything is an object, it was >recognised that classes were objects too - they were instances >of the class 'class'. (classes are objects, in the same way >that functions are objects, in Python too) > >The purpose of class objects is amongst, other things, to act >as factory objects. Thus constructors are class methods - you >send the create message to the class, not to the instance >- the instance doesn't exist yet! > >Similarly if you have a large collection of instances of a >particular class which are not related to each other in an explicit >collection, you may want to find out how many instances currently >exist - that is something that the class knows - it created them >after all... Another class responsibility would be to find a >particular instance out of the pool of objects > >In a large database environment you may want to create an object >from scratch, or to instantiate one from a database given an ID. >The two different creation mechanisms are again the responsibility >of the class. Related to this is the idea of type convertion, >you may want to convert a piece of text to RichText, so the >RichText class provides constructors that can take an ASCIItext >object, a Postscript object, an HTMLobject etc. > >In a network application a process wants to send a message to a >particular instance of a class, it can do so by directing the >message to the class object in the receiving process which in >turn locates the instance and forwards the message - acting >as a proxy for all received messages for its instances. > >Languages like C++ implement class behaviour using static methods >and attributes, which is an adequate if slightly inelegant way of >doing so. Lisp, Smalltalk and Objective-C have explicit provision >for class methods. Python lies somewhere in between with similar >implementation to C++ but with some of the extra capabilities of >Smalltalk. For example you can create an attribute that refers >to the class - you can't do that in C++ > >For example: >################ >class A: pass >class B: pass > >classes = [A,B] >instances = [] >for cls in classes: > # create 5 instances of each > for n in range(5): > instances.append(cls()) > >for obj in instances: print type(obj) >################## > >You can find some more about this in Guido's paper in the new >type system and meta classes, but beware its a confusing read! >Also the excellent book "Putting Meta Classes to Work" by >Foreman and Danforth. > > > >>As a starter, you have classes and objects. The class definitions >> >> >are a > > >>blueprints on how the objects should be built, and these >> >> >deifinitions > > >>are usualy not interesting when they are not instantiated. >> >> > >Mostly that is right, except that the class is what is used to >instantiate the instances... > > > >>purpose of class definitions is to provide blueprints for the >> >> >objects. > >And to manage the instances once created, if necessary. > > > >>But of course all rules have an exception, meaning that sometimes it >> >> >can > > >>be necessary to have a class definition that never will be >> >> >instantiated, > > >>where the different part will be called staticly. >> >> > >But this is very rare and usually an example of bad design or an >attempt to hide what is really a set of related functions >- Java is rivven with this kind of horror. > > > >>best OOP maner, this should be kept to a minimum. Well it even lies >> >> >in > > >>the name...Object Oriented Programming. >> >> > >Absolutely. But classes are ojects too :-) > > > >>To understand the difference between the class and object, we can >> >> >use > > >>one of the classic examples...a sail boat, or to be more precise, >> >> >the > > >>sail of a sail boat. >> >> > >OK, Now consider that sail boat being an ocean going schooner. >It has dozens of sales, including spares in case of accidents at >sea. The captain wants to find a specific instance of sail >- the pink one with green stripes, say. What object does he >ask to find that instance? It could be the cupboard where >the sails are kept, or ot could be the ship to ask all the >cupboards - but it should also ask the masts since it might >be aloft already - oh yes and maybe ask the sailmaker who >is repairing a rip.... or he could just ask the sail class.... > > > >>Roughly the different states of a sail can be the >>size, whether or not it is op or down, what color it is and so >> >> >forth. > >Yes, absolutely. And the different states of *the sail* class >(as opposed to *a sail object*) are whether any sails exist, >whether new sails can be created (the singleton pattern is >usually most easily implemented through class methods!) etc. > > > >>class. Multiple instances of the class, means different sails. This >> >> >idea > > >>of modeling is the basic idea of OOP, and this modeling has as a >> >> >basic > > >>idea, that the attributes should not be shared. >> >> > >Absolutely correct. Instance attributes are unique to each instance. >Class attributes are shared across all instances. For example the >set of characters that may be permitted in a string object could >be stored in the string class, rather than every instance having >to carry its own copy around. > > > >>This leads back to what it was that i origanally objected in one of >> >> >your > > >>e-mails, that the idea of attributes is that they should be shared. >> >> > >And the difference between class attributes and instance attributes >and the fundamental importance of the distinction. This is why I was >so picky about it, thee is a very real but subtle difference which >many newbie OOP programmers find confusing. > >[ It might help to have a play with a Smalltalk class browser >- Squeak or Dolphin are free to download. There you can explore >the built in classes and see the kinds of thing that smalltalk >defines as class attributes and methods. ] > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > From martin at hardcoder.dk Thu Jun 3 06:30:14 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Thu Jun 3 06:32:53 2004 Subject: [Tutor] Problems with references In-Reply-To: <40BEFC89.50502@hardcoder.dk> References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> <019101c448d3$0394a8b0$6401a8c0@xp> <40BE5D46.8090105@hardcoder.dk> <001701c4493d$d2a13730$6401a8c0@xp> <40BEFC89.50502@hardcoder.dk> Message-ID: <40BEFDB6.3030807@hardcoder.dk> Sorry sorry... let me refrase 1. "self" is that a reference to the class or an instance of the class? 2. Since that there are different paradigms within the OOP framework, which one is the most "correct"? (I know it is a wierd question.) /Martin From Janssen at rz.uni-frankfurt.de Thu Jun 3 06:36:21 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jun 3 06:36:38 2004 Subject: [Tutor] Comparing two lines of print In-Reply-To: References: <40BD68C7.20006@telkomsa.net> <016001c44883$41f16030$6401a8c0@xp> <40BDCF55.9010909@telkomsa.net> Message-ID: [self correcting me] On Wed, 2 Jun 2004, Michael Janssen wrote: > it's very likly due to the trailing newline: lines captured with > raw_input have a newline (because you type ENTER). as Bob has claimed in private mail, he didn't use raw_input. With further investigations I have found out that "lines captured with raw_input" doesn't have a newline. So to say, the part after the colon is rather silly ;-) Perhaps I should have run my testcode myself. OTOH line read in with the readline-method are likly to have a newline (the last line in a file might be without newline). The reported problem comparing lines with strings might be due to this. Michael From alan.gauld at blueyonder.co.uk Thu Jun 3 08:02:41 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 3 08:02:38 2004 Subject: [Tutor] Problems with references References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> <019101c448d3$0394a8b0$6401a8c0@xp> <40BE5D46.8090105@hardcoder.dk> <001701c4493d$d2a13730$6401a8c0@xp> <40BEFC89.50502@hardcoder.dk> Message-ID: <003001c44962$ac7cf6f0$6401a8c0@xp> > >Possibly different schools :-) > > We are... :) > > Now it all makes sense to me, thank you very much. I had no idea that > OOP also worked in that direction. > > 2 small questions if it is ok... > > 1. "self" is that a reference to the class or an instance of the object? Depends on the language, but in Python self in a classmethod means the class, self in an instance method means the runtime instance: >>> class C: ... def f(self): ... self.x = 42 ... f = classmethod(f) ... def g(self): self.y = 27 ... >>> C.x Traceback (most recent call last): File "", line 1, in ? AttributeError: class C has no attribute 'x' >>> C.f() >>> C.x 42 >>> c = C() >>> c.x 42 >>> c.g() >>> print c.x, c.y 42 27 >>> > 2. Since that there are different paradigms within the OOP framework, > which one is the most "correct"? (I know it is a wierd question.) There is only one paradigm for class attributes and methods, its just a matter of how well supported it is in different languages. C++/Java support it partially, Python, Lisp, Java etc support it well. Delphi supports it slightly beter than C++ but not as well as Smalltalk etc. Lisp/CLOS probably support the full theoretical OOP model best. Alan G. From alan.gauld at blueyonder.co.uk Thu Jun 3 08:07:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 3 08:07:12 2004 Subject: [Tutor] Problems with references References: <40BCEB86.3080603@hardcoder.dk> <012401c44871$48af2a40$6401a8c0@xp><40BD84C7.4010709@hardcoder.dk> <013e01c44882$6342ff60$6401a8c0@xp> <40BD9FCC.9090904@hardcoder.dk> <019101c448d3$0394a8b0$6401a8c0@xp> <40BE5D46.8090105@hardcoder.dk> <001701c4493d$d2a13730$6401a8c0@xp> <40BEFC89.50502@hardcoder.dk> <40BEFDB6.3030807@hardcoder.dk> Message-ID: <003501c44963$52f0f6d0$6401a8c0@xp> > let me rephrase > > 1. "self" is that a reference to the class or an instance of the class? OK, I'll rephrase too. In a class method self refers to the class object itself. In an instance method it refers to the runtime instance of the class in which it is defined. > 2. Since that there are different paradigms within the OOP framework, > which one is the most "correct"? (I know it is a wierd question.) The real problem lies in the broken way in which C++ and its derivitives define a class. They treat a class as a weird mix of type definition and namespace rather than as a full blown object in its own right. Adding static methods/attributes to the class namespace only partially solves the problem. IMHO of course, Bjarne Stroustrup may disagree :-) Alan G. From wilson at visi.com Thu Jun 3 10:11:15 2004 From: wilson at visi.com (Tim Wilson) Date: Thu Jun 3 10:11:14 2004 Subject: [Tutor] Tricky parsing problem Message-ID: Hey everyone, I've got a stack of old MS Word document that need to be converted to HTML. Unfortunately, Word's HTML export is not an option because the document's are essentially large outlines and the original author didn't use Word's outlining features, but created the outlines manually using spaces for indenting. As a result, the HTML output from Word doesn't use HTML ordered lists. We can export as plain text, of course, but the documents can be fairly complex and it's a time-intensive task to manually create all the proper HTML. Naturally, I thought of using a Python script to process these files and create the nested outline structure. If you're interested, a typical document can be viewed at http://www.hopkins.k12.mn.us/pages/district/policies/iplcy/iiaa.htm in all its ugliness. As you can see if you view the source, the structure of the document is a real mess. Can anyone recommend a module that might have some features that would assist in this task? Any general programming principles that would be good to keep in mind? -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From lumbricus at gmx.net Thu Jun 3 10:15:19 2004 From: lumbricus at gmx.net (Joerg Woelke) Date: Thu Jun 3 10:22:31 2004 Subject: [Tutor] Tricky parsing problem In-Reply-To: References: Message-ID: <20040603141519.GB1375@linux.local> On Thu, Jun 03, 2004 at 09:11:15AM -0500, Tim Wilson wrote: > Hey everyone, Hello! [ snip ] > Naturally, I thought of using a Python script to process these files and > create the nested outline structure. If you're interested, a typical > document can be viewed at > http://www.hopkins.k12.mn.us/pages/district/policies/iplcy/iiaa.htm in all > its ugliness. As you can see if you view the source, the structure of the > document is a real mess. > > Can anyone recommend a module that might have some features that would > assist in this task? Easyest is to use Wordview: "http://wvware.sourceforge.net/" > Any general programming principles that would be good to keep in mind? > > -Tim HTH and Greetings, J"o! From wilson at visi.com Thu Jun 3 10:31:39 2004 From: wilson at visi.com (Tim Wilson) Date: Thu Jun 3 10:31:35 2004 Subject: [Tutor] Tricky parsing problem In-Reply-To: <20040603141519.GB1375@linux.local> Message-ID: On 6/3/04 9:15 AM, "Joerg Woelke" wrote: > Easyest is to use Wordview: > "http://wvware.sourceforge.net/" I thought of that too, but I don't think it will help in this case because of the haphazard way in which the original Word document was created. The original author created the outline forms completely manually by inserting the roman numerals and letters and using spaces for the indentation. Perhaps I'm not giving the Wordview authors enough credit, but I assumed that it wouldn't be possible to infer the proper outline structure from a such a brain-dead document. -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From nick at javacat.f2s.com Thu Jun 3 12:32:16 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Jun 3 12:32:18 2004 Subject: FW: [Tutor] New to list & first steps in Python Message-ID: My apologies to Vijay, who accidentally sent my original reply to instead of to the list. -----Original Message----- From: Nick Lunt [mailto:nick@javacat.f2s.com] Sent: 03 June 2004 10:52 To: Vijay Kumar Bagavath Singh Subject: RE: [Tutor] New to list & first steps in Python Im not the starter of this thread, but many thanks Vijay for taking the time to explain those concepts. Regards Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Vijay Kumar Bagavath Singh Sent: 03 June 2004 10:42 To: tutor@python.org Subject: [Tutor] New to list & first steps in Python The best thing about python is that you get to write very little code for even the most complicated thing. Check out this super compressed code, that acheives the same result? from random import choice fil = file("/tmp/ElisabethInsults.txt", "r") adj1, adj2, nouns = zip(*[line.split() for line in fil]) print "Thou", choice(adj1), choice (adj2), choice(nouns) + "!" fil.close() To understand this program you will have to understand 1) List comprehension 2) Unpacking argument lists 3) Zip function 4) Multiple assignment List comprehesion is a short hand for creating complicated lists. The following example illustrates list comprehension. >>> [i*2 for i in range(0, 10)] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] The arguments to a function can be passed on in a single tuple or list. The tuple/list has to be preceded by a * for the unpacking to happen. The following example illustrates unpacking of argument lists. >>> range(0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> arg=(0,10) >>> range(*arg) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The zip function(added in Python 2.0): This function returns a list of tuples, where the I-th tuple contains the I-th element from each of the argument sequences. >>> numbers = [1, 2, 3, 4] >>> alpha = ['a', 'b', 'c', 'd'] >>> zip(numbers, alpha) [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] >>> z = zip(numbers,alpha) z = zip(numbers,alpha) Using unpacking of argument lists in zip function results in inverse operation of the zip function. >>> zip(*z) [(1, 2, 3, 4), ('a', 'b', 'c', 'd')] Following is an example of multiple assignment >>> a, b, c = 1, 2, 3 >>> print a, b, c 1 2 3 With recent versions of Python(2.2 and above) you can use file("filename", "r") to open files instead of open("filename", "r") also "r" is the default mode so you could use file("filename") With recent versions of Python(2.2 and above) you can use for line in fil instead of for line in fil.readlines() Regards, Vijay > Date: Thu, 3 Jun 2004 03:51:05 +0200 > From: Chris F Waigl > Subject: [Tutor] New to list & first steps in Python > To: Python Tutor > Message-ID: <200406030351.05426.cwaigl@free.fr> > Content-Type: text/plain; charset="us-ascii" > > I am thrilled to find that there is a list where beginners can find > guidance. Thanks for taking the time to help! > > I'm interested in natural language processing, and chose Python as a > programming language. I'm working my way through various tutorials > right now, but I've only just begun. I've also changed over from W98 to > Debian GNU/Linux and am not yet familiar with the modules installed on > my box with Python 2.3. I use Idle, which I find very convenient. > > Right now I'm mostly interested in not adopting bad habits -- learning > "good" style from the very beginning. In a different life, I used C for > number-crunching type programming (solving equations and the like), but > I never particularly enjoyed it. > > Here's my first script not copied from a tutorial. It works, so the only > question is, should I have done something differently? (Well, it's so > short, there's not much to _do_.) > > from random import * # or "... import choice" ? > adj1 = [] > adj2 = [] > nouns = [] > file = open("ElisabethInsults", "r") > for line in file.readlines(): > words = line.split() > adj1.append(words[0]) > adj2.append(words[1]) > nouns.append(words[2]) > print "Thou", choice(adj1), choice (adj2), choice(nouns) + "!" > file.close() > > ElisabethInsults is a file containing three rows, 2 x adjectives, 1 x > nouns, of derogatory words taken from Shakespeare. (If you're > interested, it's here: http://kastalia.free.fr/misc/ElisabethInsults ) > The script creates a random insult, e.g. > "Thou clouted onion-eyed pigeon-egg!" > > I'm planning to put together something like a very simple tokenizer, > something that reads in a text, counts sentences and words, handles all > the punctuation correctly, tells me something about word frequencies > and the presence or absence of grammatical structures I might be > interested in. I'm certainly going to run into a lot of problems soon. > > Any comments and recommendations are warmly encouraged. > > Best, > Christine > -- ______________________________________________ Check out the latest SMS services @ http://www.linuxmail.org This allows you to send and receive SMS through your mailbox. Powered by Outblaze _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From michele.alzetta at aliceposta.it Thu Jun 3 12:39:13 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Thu Jun 3 12:37:03 2004 Subject: [Tutor] How to control list input ? In-Reply-To: <40AE32C6000B35B4@vsmtp5alice.tin.it> (added by postmaster@aliceposta.it) References: <40AE32C6000B35B4@vsmtp5alice.tin.it> (added by postmaster@aliceposta.it) Message-ID: <1086280753.10408.7.camel@localhost> For a program I'm fooling about with I created the following class (still largely incomplete): class Template: def __init__(self,doctdbname): self.doctor = shelve.open(doctdbname, writeback = True) def addDoctor(self, doctname, doctlist): self.doctor[doctname] = doctlist def printDoctor(self, doctname): self.doctor[doctname] def alterDoctor(self, doctname, index1, index2, newvalue): self.doctor[doctname][index1][index2] = newvalue For my purposes doctlist can't be just any arbitrary list of lists; it will have to be made of a precise number of elements, that musn't be hardcoded but definable; how do you suggest I try coding a) a way in which to define what the structure of my list ought to be like and b) a way of checking the input to make sure it corresponds ? -- Michele From jfabiani at yolo.com Thu Jun 3 13:30:11 2004 From: jfabiani at yolo.com (John Fabiani) Date: Thu Jun 3 13:30:32 2004 Subject: [Tutor] Qpixmaps Message-ID: <40BF6023.9020203@yolo.com> Hi, I using PyQt as my GUI. When I build a app from the QT designer and add menu's and toolbars the designer creates a bitmap of the icons for the app. As follows fileopen = [ '16 13 5 1', '. c #040404', '# c #808304', 'a c None', 'b c #f3f704', 'c c #f3f7f3', 'aaaaaaaaa...aaaa', 'aaaaaaaa.aaa.a.a', 'aaaaaaaaaaaaa..a', 'a...aaaaaaaa...a', '.bcb.......aaaaa', '.cbcbcbcbc.aaaaa', '.bcbcbcbcb.aaaaa', '.cbcb...........', '.bcb.#########.a', '.cb.#########.aa', '.b.#########.aaa', '..#########.aaaa', '...........aaaaa' ] I think I understand that this a description of a bitmap and is painted (displayed) using QPixmap(). My question is how was the fileopen (a list) bitmap created. Are there any tools that convert from a bmp file or some other file type to what is used by PyQt? It seems that wxPython uses something similar. Thanks John From dyoo at hkn.eecs.berkeley.edu Thu Jun 3 14:57:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 3 14:58:28 2004 Subject: [Tutor] New to list & first steps in Python In-Reply-To: <200406030351.05426.cwaigl@free.fr> Message-ID: On Thu, 3 Jun 2004, Chris F Waigl wrote: > from random import * # or "... import choice" ? > adj1 = [] > adj2 = [] > nouns = [] > file = open("ElisabethInsults", "r") > for line in file.readlines(): > words = line.split() > adj1.append(words[0]) > adj2.append(words[1]) > nouns.append(words[2]) > print "Thou", choice(adj1), choice (adj2), choice(nouns) + "!" > file.close() Hi Chris, This looks fine. You may want to avoid using the 'from foo import *' statement. I agree that explicitely pulling out the 'choice' function is better: ### from random import choice ### There's a section on the official Python tutorial that talks about the reasons why it's a good idea to avoid it: http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000 One other improvement is to use direct iteration across file objects: we can avoid calling the readlines() method. > file = open("ElisabethInsults", "r") > for line in file.readlines(): > words = line.split() > adj1.append(words[0]) > adj2.append(words[1]) > nouns.append(words[2]) Python supports iteration directly across file objects, so this can be simplified to: ### file = open("ElisabethInsults", "r") for line in file: words = line.split() adj1.append(words[0]) adj2.append(words[1]) nouns.append(words[2]) ### That is, the file looks almost like a 'sequence' of lines. In Python terminology, it's an 'iterable', which means that the for loop works on it directly. By avoiding readlines(), we dodge loading the whole ElisabethInsults file into memory at once. There are a few things in Python that are iterables, including strings, files, and lists. > ElisabethInsults is a file containing three rows, 2 x adjectives, 1 x > nouns, of derogatory words taken from Shakespeare. (If you're > interested, it's here: http://kastalia.free.fr/misc/ElisabethInsults ) > The script creates a random insult, e.g. "Thou clouted onion-eyed > pigeon-egg!" Awesome. Your program looks very clear; I like it. Keep the questions coming! *grin* Good luck to you! From magnus at thinkware.se Thu Jun 3 15:08:38 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 3 15:08:45 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSG93IHRvIGNvbnRyb2wgbGlzdCBpbnB1dCA/?= Message-ID: > For my purposes doctlist can't be just any arbitrary list of lists; it > will have to be made of a precise number of elements, that musn't be > hardcoded but definable; So it's not a list! > how do you suggest I try coding a) a way in > which to define what the structure of my list ought to be like and b) a > way of checking the input to make sure it corresponds ? Don't use a list. Use a class. If you want to be able to access attributes in your instance objects as if they were list members, just implement the __getitem__ method. >>> class ListLike: def __init__(self, name, address, phone): self.name=name self.address=address self.phone=phone def __getitem__(self, i): return [self.name, self.address, self.phone][i] >>> a = ListLike('Santa Claus', 'North Pole', 123) >>> for i in a: print i Santa Claus North Pole 123 -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Dragonfirebane at aol.com Thu Jun 3 17:32:54 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Thu Jun 3 17:33:03 2004 Subject: [Tutor] random number equations . . . Message-ID: <7e.4ffb990d.2df0f306@aol.com> I don't want to write my own equations for creating random numbers (based on 'time.time()'), but i need random numbers to create account id's and assign starting money in the program segment below . . . i would use [import random *] but i'm not sure which section of random is a random number generator or the syntax necessary to apply it. Any help would be appreciated. def newuser(): new = raw_input("Are you a new user [y/n]? ") while new not in 'yYnN': new = raw_input(""" Please enter 'y' for yes or 'n' for no. Are you a new user? """) if new in 'yY': import math vowelcount = 0 name = raw_input("Please enter your first name. ") name = name[:6] namel = raw_input("Please enter your last name. ") namel = namel[:6] name = name + ' ' + namel vowels = ['a','e','i','o','u','A','E','I','O','U'] for letter in name: if letter in vowels: vowelcount = vowelcount + 1 global startmon global tim tim = time.time() % 100000 startmon = vowelcount * tim startmon = math.sqrt(startmon) * 3141.5962 startmon = str(startmon)[:7] startmon = int(float(startmon)) print "Welcome, %s. You have $%d to use in BankSim 1.0." % (name, startmon) def newacc(): global newac newac = raw_input("Would you like to create a new account [y/n]? ") while newac not in 'yYnN': newac = raw_input(""" Please enter 'y' for yes or 'n' for no. Would you like to create a new acount [y/n]? """) if newac in 'yY': import math global newacid newacid = int(raw_input("Please enter your birthday [ddmmyyyy]. ")) newacid = newacid * tim newacid = math.sqrt(newacid) * 314.15692 newacid = str(newacid)[:6] newacid = int(float(newacid)) initbal = int(raw_input("How much money would you like to put in your account? ")) print "Account number %d created with $%d in it." % (newacid, initbal) mon = startmon - initbal print "You now have $%d in account %d and $%d out of the bank." % (initbal, newacid, mon) Thanks, Orri -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040603/56f8ff95/attachment.html From gew75 at hotmail.com Thu Jun 3 17:42:42 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Thu Jun 3 17:42:53 2004 Subject: [Tutor] random number equations . . . References: <7e.4ffb990d.2df0f306@aol.com> Message-ID: Well, the random module is pretty easy to use. Here is a an example: >>> import random >>> l = [] >>> for i in range(10): .. l.append(int(random.random()*10)) .. >>> l [4, 2, 0, 3, 7, 8, 5, 9, 9, 8] >>> random.random() gives a floating point number between 0 and 1, so I just multiplied it by 10 to get from 0-10 then cast it to an integer with int(). To get a more accurate representation (since int() truncates the argument) you could use int(round(...)) instead. HTH, Glen ----- Original Message ----- From: Dragonfirebane@aol.com To: tutor@python.org Sent: Friday, June 04, 2004 7:32 AM Subject: [Tutor] random number equations . . . I don't want to write my own equations for creating random numbers (based on 'time.time()'), but i need random numbers to create account id's and assign starting money in the program segment below . . . i would use [import random *] but i'm not sure which section of random is a random number generator or the syntax necessary to apply it. Any help would be appreciated. def newuser(): new = raw_input("Are you a new user [y/n]? ") while new not in 'yYnN': new = raw_input(""" Please enter 'y' for yes or 'n' for no. Are you a new user? """) if new in 'yY': import math vowelcount = 0 name = raw_input("Please enter your first name. ") name = name[:6] namel = raw_input("Please enter your last name. ") namel = namel[:6] name = name + ' ' + namel vowels = ['a','e','i','o','u','A','E','I','O','U'] for letter in name: if letter in vowels: vowelcount = vowelcount + 1 global startmon global tim tim = time.time() % 100000 startmon = vowelcount * tim startmon = math.sqrt(startmon) * 3141.5962 startmon = str(startmon)[:7] startmon = int(float(startmon)) print "Welcome, %s. You have $%d to use in BankSim 1.0." % (name, startmon) def newacc(): global newac newac = raw_input("Would you like to create a new account [y/n]? ") while newac not in 'yYnN': newac = raw_input(""" Please enter 'y' for yes or 'n' for no. Would you like to create a new acount [y/n]? """) if newac in 'yY': import math global newacid newacid = int(raw_input("Please enter your birthday [ddmmyyyy]. ")) newacid = newacid * tim newacid = math.sqrt(newacid) * 314.15692 newacid = str(newacid)[:6] newacid = int(float(newacid)) initbal = int(raw_input("How much money would you like to put in your account? ")) print "Account number %d created with $%d in it." % (newacid, initbal) mon = startmon - initbal print "You now have $%d in account %d and $%d out of the bank." % (initbal, newacid, mon) Thanks, Orri _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From gew75 at hotmail.com Thu Jun 3 17:52:39 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Thu Jun 3 17:52:46 2004 Subject: [Tutor] How to control list input ? References: <40AE32C6000B35B4@vsmtp5alice.tin.it>(added by postmaster@aliceposta.it) <1086280753.10408.7.camel@localhost> Message-ID: Hi Michele, You can use len(..) to check then length of a list, eg if len(l) == 10: .. else: raise "LengthError" Easier on the eyes is: if len(l) != 10: raise ... There is no real need for you to strictly define the structure of your list. Just make sure you check the input for any errors. Always know what your functions are getting as input arguments. In other words, say you were looking for a list of lists, three lists, of lengths 3, 9 and 27. Then something like: # l is the list of lists if len(l) != 3 and len(l[0]) != 3 and len(l[1]) != 9 and len(l[2]) != 27: raise ... Better would be to write some kind of list-structure-checking function. But let's leave that as an exercise ;). HTH, Glen ----- Original Message ----- From: "Michele Alzetta" To: "Python Tutor" Sent: Friday, June 04, 2004 2:39 AM Subject: [Tutor] How to control list input ? > For a program I'm fooling about with I created the following class > (still largely incomplete): > > class Template: > > def __init__(self,doctdbname): > self.doctor = shelve.open(doctdbname, writeback = True) > > def addDoctor(self, doctname, doctlist): > self.doctor[doctname] = doctlist > > def printDoctor(self, doctname): > self.doctor[doctname] > > def alterDoctor(self, doctname, index1, index2, newvalue): > self.doctor[doctname][index1][index2] = newvalue > > For my purposes doctlist can't be just any arbitrary list of lists; it > will have to be made of a precise number of elements, that musn't be > hardcoded but definable; how do you suggest I try coding a) a way in > which to define what the structure of my list ought to be like and b) a > way of checking the input to make sure it corresponds ? > > -- > Michele > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Dragonfirebane at aol.com Thu Jun 3 17:52:55 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Thu Jun 3 17:53:17 2004 Subject: [Tutor] random number equations . . . Message-ID: In a message dated 6/3/2004 5:43:27 PM Eastern Standard Time, gew75@hotmail.com writes: Thanks. Would this: def newuser(): new = raw_input("Are you a new user [y/n]? ") while new not in 'yYnN': new = raw_input(""" Please enter 'y' for yes or 'n' for no. Are you a new user? """) if new in 'yY': import math vowelcount = 0 global rannum = [] name = raw_input("Please enter your first name. ") name = name[:6] namel = raw_input("Please enter your last name. ") namel = namel[:6] name = name + ' ' + namel vowels = ['a','e','i','o','u','A','E','I','O','U'] for letter in name: if letter in vowels: vowelcount = vowelcount + 1 global startmon for i in range(10): rannum.append.int(round(random.random() * 1000000)) startmon = vowelcount * rannum[0] startmon = str(startmon)[:7] startmon = int(float(startmon)) print "Welcome, %s. You have $%d to use in BankSim 1.0." % (name, startmon) def newacc(): global newac newac = raw_input("Would you like to create a new account [y/n]? ") while newac not in 'yYnN': newac = raw_input(""" Please enter 'y' for yes or 'n' for no. Would you like to create a new acount [y/n]? """) if newac in 'yY': import math global newacid newacid = int(raw_input("Please enter your birthday [ddmmyyyy]. ")) newacid = newacid * rannum[5] newacid = str(newacid)[:6] newacid = int(float(newacid)) initbal = int(raw_input("How much money would you like to put in your account? ")) print "Account number %d created with $%d in it." % (newacid, initbal) mon = startmon - initbal print "You now have $%d in account %d and $%d out of the bank." % (initbal, newacid, mon) work using your example? (The relevant portion is bolded). Thanks again, Orri Well, the random module is pretty easy to use. Here is a an example: >>> import random >>> l = [] >>> for i in range(10): .. l.append(int(random.random()*10)) .. >>> l [4, 2, 0, 3, 7, 8, 5, 9, 9, 8] >>> random.random() gives a floating point number between 0 and 1, so I just multiplied it by 10 to get from 0-10 then cast it to an integer with int(). To get a more accurate representation (since int() truncates the argument) you could use int(round(...)) instead. HTH, Glen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040603/65216e53/attachment.html From gew75 at hotmail.com Thu Jun 3 17:57:39 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Thu Jun 3 17:57:48 2004 Subject: [Tutor] random number equations . . . References: Message-ID: Yep. Although, I'm not sure what you want to do with them, but that will generate ten random numbers in your desired range. If you have any other questions, just send them along. Glen ----- Original Message ----- From: Dragonfirebane@aol.com To: gew75@hotmail.com Cc: tutor@python.org Sent: Friday, June 04, 2004 7:52 AM Subject: Re: [Tutor] random number equations . . . In a message dated 6/3/2004 5:43:27 PM Eastern Standard Time, gew75@hotmail.com writes: Thanks. Would this: def newuser(): new = raw_input("Are you a new user [y/n]? ") while new not in 'yYnN': new = raw_input(""" Please enter 'y' for yes or 'n' for no. Are you a new user? """) if new in 'yY': import math vowelcount = 0 global rannum = [] name = raw_input("Please enter your first name. ") name = name[:6] namel = raw_input("Please enter your last name. ") namel = namel[:6] name = name + ' ' + namel vowels = ['a','e','i','o','u','A','E','I','O','U'] for letter in name: if letter in vowels: vowelcount = vowelcount + 1 global startmon for i in range(10): rannum.append.int(round(random.random() * 1000000)) startmon = vowelcount * rannum[0] startmon = str(startmon)[:7] startmon = int(float(startmon)) print "Welcome, %s. You have $%d to use in BankSim 1.0." % (name, startmon) def newacc(): global newac newac = raw_input("Would you like to create a new account [y/n]? ") while newac not in 'yYnN': newac = raw_input(""" Please enter 'y' for yes or 'n' for no. Would you like to create a new acount [y/n]? """) if newac in 'yY': import math global newacid newacid = int(raw_input("Please enter your birthday [ddmmyyyy]. ")) newacid = newacid * rannum[5] newacid = str(newacid)[:6] newacid = int(float(newacid)) initbal = int(raw_input("How much money would you like to put in your account? ")) print "Account number %d created with $%d in it." % (newacid, initbal) mon = startmon - initbal print "You now have $%d in account %d and $%d out of the bank." % (initbal, newacid, mon) work using your example? (The relevant portion is bolded). Thanks again, Orri Well, the random module is pretty easy to use. Here is a an example: >>> import random >>> l = [] >>> for i in range(10): . l.append(int(random.random()*10)) . >>> l [4, 2, 0, 3, 7, 8, 5, 9, 9, 8] >>> random.random() gives a floating point number between 0 and 1, so I just multiplied it by 10 to get from 0-10 then cast it to an integer with int(). To get a more accurate representation (since int() truncates the argument) you could use int(round(...)) instead. HTH, Glen From Dragonfirebane at aol.com Thu Jun 3 18:00:33 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Thu Jun 3 18:00:57 2004 Subject: [Tutor] random number equations . . . Message-ID: <1e2.2242b681.2df0f981@aol.com> I was thinking of using the random number generator to randomly choose a number from the 10 numbers, but i think that would be a bit excessive. However, i might need more random numbers later (hence {global rannum =[]}), so i figure i might as well leave all ten there. In a message dated 6/3/2004 5:58:31 PM Eastern Standard Time, gew75@hotmail.com writes: Yep. Although, I'm not sure what you want to do with them, but that will generate ten random numbers in your desired range. If you have any other questions, just send them along. Glen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040603/4372b614/attachment.html From alan.gauld at blueyonder.co.uk Thu Jun 3 18:02:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 3 18:02:01 2004 Subject: [Tutor] How to control list input ? References: <40AE32C6000B35B4@vsmtp5alice.tin.it>(added by postmaster@aliceposta.it) <1086280753.10408.7.camel@localhost> Message-ID: <008701c449b6$6d131860$6401a8c0@xp> > class Template: > def __init__(self,doctdbname): > def addDoctor(self, doctname, doctlist): > def printDoctor(self, doctname): > def alterDoctor(self, doctname, index1, index2, newvalue): > self.doctor[doctname][index1][index2] = newvalue > > For my purposes doctlist can't be just any arbitrary list of lists; it > will have to be made of a precise number of elements, that musn't be > hardcoded but definable; how do you suggest I try coding a) a way in > which to define what the structure of my list ought to be like and b) a > way of checking the input to make sure it corresponds ? I'd solve both issues by using dictionaries insteadof lists. Then instead of trying to figure out the two index values, just pass in the names of the attributes you want - which your code doesn't give any clues about! - and use them as keys. Alan G. From gew75 at hotmail.com Thu Jun 3 18:04:12 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Thu Jun 3 18:04:19 2004 Subject: [Tutor] random number equations . . . References: <1e2.2242b681.2df0f981@aol.com> Message-ID: Well, as a suggestion, instead of using the global declaration you could write a little function which returned a randum number in some range on demand. >>> def gimmeRandomInRange(rng): .. return int(round(random.random()*rng)) .. >>> gimmeRandomInRange(100) 99 >>> for i in range(100): .. print gimmeRandomInRange(1000) .. 910 664 466 186 600 930 528 65 392 .. Of course you could just use the random.randint() function, but none of these are as fun as writing your own ;). Glen ----- Original Message ----- From: Dragonfirebane@aol.com To: gew75@hotmail.com Cc: tutor@python.org Sent: Friday, June 04, 2004 8:00 AM Subject: Re: [Tutor] random number equations . . . I was thinking of using the random number generator to randomly choose a number from the 10 numbers, but i think that would be a bit excessive. However, i might need more random numbers later (hence {global rannum =[]}), so i figure i might as well leave all ten there. In a message dated 6/3/2004 5:58:31 PM Eastern Standard Time, gew75@hotmail.com writes: Yep. Although, I'm not sure what you want to do with them, but that will generate ten random numbers in your desired range. If you have any other questions, just send them along. Glen From alan.gauld at blueyonder.co.uk Thu Jun 3 18:28:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 3 18:28:01 2004 Subject: [Tutor] random number equations . . . References: <7e.4ffb990d.2df0f306@aol.com> Message-ID: <009501c449ba$0f320ea0$6401a8c0@xp> Some comments on general style. I'd move the newuser() function part further down, it's usually a bad idea to mix user selection with processing. > def newuser(): > new = raw_input("Are you a new user [y/n]? ") > while new not in 'yYnN': > new = raw_input(""" > Please enter 'y' for yes or 'n' for no. > Are you a new user? """) > if new in 'yY': newuser() def newuser(): > import math > vowelcount = 0 > name = raw_input("Please enter your first name. ") > name = name[:6] > namel = raw_input("Please enter your last name. ") > namel = namel[:6] > name = name + ' ' + namel > vowels = ['a','e','i','o','u','A','E','I','O','U'] vowels = "aeiouAEIOU" # don't need a list > for letter in name: > if letter in vowels: > vowelcount = vowelcount + 1 > global startmon > global tim Do these need to be global? If so its probably better practice to define them outside the function - easier to find in future - rather than rely on the global statement creating them by default from within the function. > tim = time.time() % 100000 > startmon = vowelcount * tim > startmon = math.sqrt(startmon) * 3141.5962 > startmon = str(startmon)[:7] > startmon = int(float(startmon)) This duplicates the code for newacid below, so you could make it into a function: def makeCodedValue(seed): global tim # I'll assume you really do mean this... val = seed * tim val = math.sqrt(startmon) * 3141.5962 val = str(startmon)[:7] val = int(float(startmon)) return value Then call it like: startmon = makeCodedValue( vowelcount ) and newacid = makeCodedValue( birthday ) Then if you change the algorithm its only done in one place. > print "Welcome, %s. You have $%d to use in BankSim 1.0." % (name, > startmon) Much the same applies to newacc(): > def newacc(): move this down... > global newac Does this need to be global, I don't think its used anywhere else? Global variables are usually something to avoid if possible. > newac = raw_input("Would you like to create a new account [y/n]? ") > while newac not in 'yYnN': > newac = raw_input(""" > Please enter 'y' for yes or 'n' for no. > Would you like to create a new acount [y/n]? """) > if newac in 'yY': newacc() def newacc(): > import math > global newacid > birthday = int(raw_input("Please enter your birthday [ddmmyyyy]. ")) > newacid = newacc( birthday ) > initbal = int(raw_input("How much money would you like to put in your > account? ")) > print "Account number %d created with $%d in it." % (newacid, initbal) > mon = startmon - initbal > print "You now have $%d in account %d and $%d out of the bank." % > (initbal, newacid, mon) Then I'd put all the early user input stuff with the while loops in either two separate functions or a single function, depending on how you expect to use them. Even better would be to try to move all of the user input stuiff outside and have the functions only do the calculations, that way it will be much easier if you decide to write a GUI inteface someday. Just some thoughts, Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Jun 3 18:39:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 3 18:39:47 2004 Subject: [Tutor] random number equations . . . In-Reply-To: Message-ID: On Fri, 4 Jun 2004, Glen Wheeler wrote: > > Well, as a suggestion, instead of using the global declaration you could > write a little function which returned a randum number in some range on > demand. > > >>> def gimmeRandomInRange(rng): > .. return int(round(random.random()*rng)) > .. > >>> gimmeRandomInRange(100) > 99 > >>> for i in range(100): > .. print gimmeRandomInRange(1000) > .. > 910 > 664 > 466 > 186 > 600 > 930 > 528 > 65 > 392 > .. > > Of course you could just use the random.randint() function, but none > of these are as fun as writing your own ;). Hi Glen, But whenever we're dealing with probability, it's often a good idea to reuse what other folks have already done. *grin* This kind of selection function already exists in random.randrange(): http://www.python.org/doc/lib/module-random.html#l2h-1147 The problem with gimmeRandomInRange() is that it's biased. It's easier to see what this means if we use a small range. Let's see what happens when we use it for a range between 0 and 2, inclusive: ### >>> def distribution(numbers): ... """Calculates a distribution of the numbers.""" ... counts = {} ... for n in numbers: ... counts[n] = counts.get(n, 0) + 1 ... return counts ... >>> distribution([gimmeRandomInRange(2) for i in range(1000)]) {0: 238, 1: 523, 2: 239} ### There's a big hump near one! Why is that? Why are the numbers biased biased around 1? If we draw things out: A B C |--------(---------------)-------| 0 0.5 1 1.5 2 our number line splits into three regions A, B, and C. The behavior of the round()ing causes region B to be larger than the other two. But random.randrange() doesn't suffer this defect: ### >>> distribution([random.randrange(0, 3) for i in range(1000)]) {0: 343, 1: 344, 2: 313} ### The 'random' module has many helper functions that we should use. They're there because it's all too easy not to take into consideration some of the subtle problems with random number generation. Hope this helps! From glingl at aon.at Thu Jun 3 18:53:27 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Jun 3 18:52:41 2004 Subject: [Tutor] random number equations . . . In-Reply-To: <7e.4ffb990d.2df0f306@aol.com> References: <7e.4ffb990d.2df0f306@aol.com> Message-ID: <40BFABE7.9080500@aon.at> Dragonfirebane@aol.com schrieb: > I don't want to write my own equations for creating random numbers > (based on 'time.time()'), but i need random numbers to create account > id's and assign starting money in the program segment below . . . i > would use [import random *] but i'm not sure which section of random > is a random number generator or the syntax necessary to apply it. Any > help would be appreciated. > There are two or three functions in module random, which you could use, if you didn't want to build your own: >>> from random import randrange # works similar to range >>> for i in range(20): print randrange(4), 1 1 0 3 2 1 3 2 0 0 1 1 3 3 0 1 1 0 0 2 >>> for i in range(20): print randrange(5,9), 5 7 8 5 8 7 8 7 7 6 6 8 5 7 7 5 8 8 5 6 >>> from random import randint >>> for i in range(20): print randint(0,4), # needs start and endpoint(inclusive) of interval 3 0 3 3 2 2 4 4 1 1 3 0 4 1 4 3 2 1 3 2 >>> for i in range(20): print randint(1,6), # dice 3 5 3 3 2 2 5 5 2 1 1 1 6 2 6 5 3 6 4 4 >>> from random import choice # from any sequence type, e.g. strings >>> for i in range(20): print choice("abcdefghijklmnopqrstuvwxyz"), p h f b a o p l n q z y k f n c k r v l >>> for i in range(20): print choice("abcdefghijklmnopqrstuvwxyz".upper()), V Y R I T Q K O E A S V E T F V Q M M Q >>> You may find docs here: http://docs.python.org/lib/module-random.html Regards, Gregor From gew75 at hotmail.com Thu Jun 3 19:18:29 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Thu Jun 3 19:18:36 2004 Subject: [Tutor] random number equations . . . References: Message-ID: Hi Danny, You are of course correct! My purpose in showing the usage of creating one's own random numbers from random.random() is for understanding and flexibility. I guess if I was to write a ``proper'' myRandRange(..) function I'd probably add 1 to the range then truncate. Actually, let's try that: >>> def myRandRange(n): .. return int((random.random()*(n+1))) >>> distribution([myRandRange(2) for i in range(1000)]) {0: 320, 1: 331, 2: 349} Seems to work ok. Bias is one reason why someone may *want* to use their own function for this kind of purpose. I know that in several of my applications, I wish to generate random numbers based on a custom distribution, so I have this set up in a function. Now before you go off and point me to the docs, I do know that the random module has builtin distributions, and do know how to express distributions as functions of other standard distributions. But not every single distribution can be expressed as such, and it is easier to debug when you know exactly what is going on. I guess my ``teach the basics first'' philosophy shows through in a bad way sometimes. -- Glen ----- Original Message ----- From: "Danny Yoo" To: "Glen Wheeler" Cc: ; Sent: Friday, June 04, 2004 8:39 AM Subject: Re: [Tutor] random number equations . . . > > Hi Glen, > > But whenever we're dealing with probability, it's often a good idea to > reuse what other folks have already done. *grin* > > > This kind of selection function already exists in random.randrange(): > > http://www.python.org/doc/lib/module-random.html#l2h-1147 > > > The problem with gimmeRandomInRange() is that it's biased. It's easier to > see what this means if we use a small range. Let's see what happens when > we use it for a range between 0 and 2, inclusive: > > ### > >>> def distribution(numbers): > ... """Calculates a distribution of the numbers.""" > ... counts = {} > ... for n in numbers: > ... counts[n] = counts.get(n, 0) + 1 > ... return counts > ... > >>> distribution([gimmeRandomInRange(2) for i in range(1000)]) > {0: 238, 1: 523, 2: 239} > ### > > > There's a big hump near one! > > > Why is that? Why are the numbers biased biased around 1? If we draw > things out: > > A B C > |--------(---------------)-------| > 0 0.5 1 1.5 2 > > > our number line splits into three regions A, B, and C. The behavior of > the round()ing causes region B to be larger than the other two. > > > But random.randrange() doesn't suffer this defect: > > ### > >>> distribution([random.randrange(0, 3) for i in range(1000)]) > {0: 343, 1: 344, 2: 313} > ### > > > The 'random' module has many helper functions that we should use. > They're there because it's all too easy not to take into consideration > some of the subtle problems with random number generation. > > > > Hope this helps! > > From vijaykumar at linuxmail.org Thu Jun 3 23:10:39 2004 From: vijaykumar at linuxmail.org (Vijay Kumar Bagavath Singh) Date: Thu Jun 3 23:10:47 2004 Subject: [Tutor] Qpixmaps Message-ID: <20040604031039.7210E3983FB@ws5-1.us4.outblaze.com> This is not specific to Python or PyQt. The pixmap created by QT designer is in the XPM format. You can use Gimp, ImageMagick and most of the other bitmap tools in GNU/Linux to create such XPMs. If you have ImageMagick installed, you can convert bmp files to xpm using convert myfile.bmp myfile.xpm Vijay ----- Original Message ----- > Date: Thu, 03 Jun 2004 10:30:11 -0700 > From: John Fabiani > Subject: [Tutor] Qpixmaps > To: Python tutor help > Message-ID: <40BF6023.9020203@yolo.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hi, > I using PyQt as my GUI. When I build a app from the QT designer and add > menu's and toolbars the designer creates a bitmap of the icons for the > app. As follows > fileopen = [ > '16 13 5 1', > '. c #040404', > '# c #808304', > 'a c None', > 'b c #f3f704', > 'c c #f3f7f3', > 'aaaaaaaaa...aaaa', > 'aaaaaaaa.aaa.a.a', > 'aaaaaaaaaaaaa..a', > 'a...aaaaaaaa...a', > '.bcb.......aaaaa', > '.cbcbcbcbc.aaaaa', > '.bcbcbcbcb.aaaaa', > '.cbcb...........', > '.bcb.#########.a', > '.cb.#########.aa', > '.b.#########.aaa', > '..#########.aaaa', > '...........aaaaa' > ] > > I think I understand that this a description of a bitmap and is painted > (displayed) using QPixmap(). My question is how was the fileopen (a > list) bitmap created. Are there any tools that convert from a bmp file > or some other file type to what is used by PyQt? It seems that > wxPython uses something similar. > > Thanks > John -- ______________________________________________ Check out the latest SMS services @ http://www.linuxmail.org This allows you to send and receive SMS through your mailbox. Powered by Outblaze From rantek at pacific.net.sg Fri Jun 4 04:12:50 2004 From: rantek at pacific.net.sg (rantek@pacific.net.sg) Date: Fri Jun 4 04:13:04 2004 Subject: [Tutor] random number equations . . . Message-ID: <20040604081250.BFHD8220.maxwell6.pacific.net.sg@[203.120.90.194]> Wouldn't using fixed point representation (32bit) improve the accuracy? Bill > > From: "Glen Wheeler" > Date: Fri 04/06/2004 7:18 AM GMT+08:00 > To: "Danny Yoo" > CC: Dragonfirebane@aol.com, tutor@python.org > Subject: Re: [Tutor] random number equations . . . > > > Hi Danny, > > You are of course correct! My purpose in showing the usage of creating > one's own random numbers from random.random() is for understanding and > flexibility. I guess if I was to write a ``proper'' myRandRange(..) > function I'd probably add 1 to the range then truncate. Actually, let's try > that: > > >>> def myRandRange(n): > .. return int((random.random()*(n+1))) > >>> distribution([myRandRange(2) for i in range(1000)]) > {0: 320, 1: 331, 2: 349} > > Seems to work ok. > Bias is one reason why someone may *want* to use their own function for > this kind of purpose. I know that in several of my applications, I wish to > generate random numbers based on a custom distribution, so I have this set > up in a function. > Now before you go off and point me to the docs, I do know that the random > module has builtin distributions, and do know how to express distributions > as functions of other standard distributions. But not every single > distribution can be expressed as such, and it is easier to debug when you > know exactly what is going on. > I guess my ``teach the basics first'' philosophy shows through in a bad > way sometimes. > > -- > Glen > > ----- Original Message ----- > From: "Danny Yoo" > To: "Glen Wheeler" > Cc: ; > Sent: Friday, June 04, 2004 8:39 AM > Subject: Re: [Tutor] random number equations . . . > > > > > > Hi Glen, > > > > But whenever we're dealing with probability, it's often a good idea to > > reuse what other folks have already done. *grin* > > > > > > This kind of selection function already exists in random.randrange(): > > > > http://www.python.org/doc/lib/module-random.html#l2h-1147 > > > > > > The problem with gimmeRandomInRange() is that it's biased. It's easier to > > see what this means if we use a small range. Let's see what happens when > > we use it for a range between 0 and 2, inclusive: > > > > ### > > >>> def distribution(numbers): > > ... """Calculates a distribution of the numbers.""" > > ... counts = {} > > ... for n in numbers: > > ... counts[n] = counts.get(n, 0) + 1 > > ... return counts > > ... > > >>> distribution([gimmeRandomInRange(2) for i in range(1000)]) > > {0: 238, 1: 523, 2: 239} > > ### > > > > > > There's a big hump near one! > > > > > > Why is that? Why are the numbers biased biased around 1? If we draw > > things out: > > > > A B C > > |--------(---------------)-------| > > 0 0.5 1 1.5 2 > > > > > > our number line splits into three regions A, B, and C. The behavior of > > the round()ing causes region B to be larger than the other two. > > > > > > But random.randrange() doesn't suffer this defect: > > > > ### > > >>> distribution([random.randrange(0, 3) for i in range(1000)]) > > {0: 343, 1: 344, 2: 313} > > ### > > > > > > The 'random' module has many helper functions that we should use. > > They're there because it's all too easy not to take into consideration > > some of the subtle problems with random number generation. > > > > > > > > Hope this helps! > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From michele.alzetta at aliceposta.it Fri Jun 4 05:28:46 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Fri Jun 4 05:26:40 2004 Subject: [Tutor] How to control list input ? Message-ID: <1086341326.13373.60.camel@localhost> Many thanks for the answers I've received so far. (I see that I probably have to explain the nature of my problem better. Footnote for those who are interested). What my code actually attempts to do is create a template as a series of dictionaries which get saved to disk (with the shelve module): import shelve class Template: def __init__(self,doctdbname,abdbname,schemadbname,shdbname): self.doctor = shelve.open(doctdbname, writeback = True) self.ability = shelve.open(abdbname, writeback = True) self.schematype = shelve.open(schemadbname, writeback = True) self.shifttype = shelve.open(shdbname, writeback = True) def various functions to insert, delete, obtain elements from my dicts I thought that the dictionaries would be like this: Name || key || value ----------------------------------------- doctor || doctor name || list of lists containing the data to take into account when assigning the doc to a shift: hours worked weekly, abilities, days set off by rules, off days etc. etc. ability || name of ability || list of doctors having that ability schema || name of shift || days of week in which the shift exists (e.g. emergency || start time end time abilities required ward duty mornings) shift || label of each || doctor finally assigned: || single specific shift || my output ! || i.e. 0306-08-14-int-PN Actually, maybe some of these are redundant. I'll find out coding along .... We were talking about how to control list input for the list of lists saved as a value in my doctor dictionary; one suggestion was to make this a class, not a list of lists: - is it possible for a dictionary to save a class as a value ? Would this actually make sense in this case ? Someone also suggests using dictionaries instead of lists: - is it possible for a dictionary to save another dictionary as a value ? Another solution proposed (maybe the simplest ?) is to write a list structure checking function. Any comments and suggestions appreciated ! -- Michele --------------------------------------------------------------------- Footnote: --------------------------------------------------------------------- ER doctors have hectic lives and weird shifts. Preparation of a month's shift schedule takes up entire afternoons, and no matter how many of us check the schedule you always end up discovering somebody is supposed to be in two places contemporaneously. So I thought a good way of learning python might be to try to make a Python Emergency Physician Scheduler which: allows one to create and save a template of what the shifts are like (in the emergency department at a given moment there are up to 5 different doctors on duty doing different things); the template also takes into account that different types of shifts require different abilities; that some doctors can be assigned to any shift whereas others may not be assigned to certain types of shift because they do not have certain abilities; it takes into account that different doctors have different working hours, and that some have more days holiday left over than others too. The program should be capable of acquiring a list of rules (doc A must be allowed these 3 days off because he's at a Congress, doc B must be home every wednesday evening, docs C and D are willing to do 2 consecutive 6 hour shifts of a certain type, doc E must not work nights, doc F prefers working afternoons raher than mornings but will of course do both etc etc). It must then fill in my template for the current month, by assigning a doctor to each shift while taking into account working hours, rules and incompatiblities (for instance one cannot do two consecutive long shifts, after a night shift he must be allowed at least 24hours rest, one cannot be contemporaneously on duty in two shifts etc). NB it is not possible to have a regular pattern in our shifts (can't say for instance each does 2 mornings, 2 afternoons, 2 nights then 3 days off). Eventually a tidy schedule sheet would be the output (in pdf format, for instance), and the the whole thing would have to run in a GUI. At the moment I'm forgetting about the output part (import reportlab ?) and the GUI part (wxwindows ?), I would like to concentrate on creating a few classes and functions to deal with some of the basic problems. The actual quantity of data involved isn't very high, so I would like to avoid databases. List comprehensions, import time, import calendar seem to be the things to study for now ... From Cantkirby at aol.com Fri Jun 4 11:38:33 2004 From: Cantkirby at aol.com (Cantkirby@aol.com) Date: Fri Jun 4 11:38:47 2004 Subject: [Tutor] How create a grade book Message-ID: Hi My name is cliff, I have just began to use python from the intactive screen. I wrote a small program that ran fine. Now I want to write a program that accept use input and perform calculations. Specifically, I want to write a grade book that conisist of student name, grade, subjects, average, date, and objective. However, I don't know how to connect pyton to visual basic by COM. I tried to set a com server and I have had no luck. Is it because i'm using the XP operating system. Also, If you have any example code for setting-up a database file or which do you recommend using with python. I have many more questions but I think this is a load. Please, Please respond because I really want to learn this language. Thanks Cliff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040604/0621e9c2/attachment.html From project5 at redrival.net Fri Jun 4 12:23:46 2004 From: project5 at redrival.net (Andrei) Date: Fri Jun 4 12:24:00 2004 Subject: [Tutor] Re: How create a grade book References: Message-ID: Cantkirby@aol.com wrote on Fri, 4 Jun 2004 11:38:33 EDT: > Hi My name is cliff, Hi Cliff, > I have just began to use python from the intactive screen. I wrote a small > program that ran fine. Now I want to write a program that accept use input and > perform calculations. Specifically, I want to write a grade book that > conisist of student name, grade, subjects, average, date, and objective. However, I Sounds doable. > don't know how to connect pyton to visual basic by COM. I tried to set a com What does VB have to do with anything? Just looking for ways to make your life hard? :) Perhaps you don't know that Python has other ways of being used, not just the interactive screen. You can use it just fine for GUI development too. > server and I have had no luck. Is it because i'm using the XP operating > system. Also, If you have any example code for setting-up a database file or > which do you recommend using with python. I have many more questions but I think You could use the built-in bsddb module. It's very fast and easy to use (you can basically approach it like a Python dictionary). > this is a load. Please, Please respond because I really want to learn this > language. Thanks Cliff Paragraph 7.13.1 of the Python 2.3 docs contain a simple, but sufficient example of using the bsddb module. Note that it is possible to store just about anythin as value, not just strings, by using the pickle.dumps() and pickle.loads() methods. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From magnus at thinkware.se Fri Jun 4 12:59:37 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Fri Jun 4 12:59:44 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSG93IGNyZWF0ZSBhIGdyYWRlIGJvb2s=?= Message-ID: Hi Cliff, > I have just began to use python from the intactive screen. I wrote a small > program that ran fine. Now I want to write a program that accept use input and > perform calculations. Specifically, I want to write a grade book that > conisist of student name, grade, subjects, average, date, and objective. However, I > don't know how to connect pyton to visual basic by COM. I don't think COM will make that any easier, but you *can* certainly make Python work with COM. You need some kind of interface though. Plain Python doesn't interact with COM. The most COMmon way is to use the win32all extensions. The Python download page for Windows link to them. (It's included if you use ActiveState Python). Here is some excerpts of code from a program that writes stuff in an Excel sheet. You need to add some data in the variables etc to make it work. import win32com.client .. xl = win32com.client.Dispatch('Excel.Application') xl.Workbooks.Open(xls_fn) xl.Visible = True .. for sheetNo in range(MIN_SHEET,MAX_SHEET+1): sheet = xl.Worksheets[sheetNo-1] sheet.Activate() for row in range(MIN_ROW, MAX_ROW+1): for col in range(MIN_COL,MAX_COL+1): if xl.Worksheets[0].Cells(row,col).Value: values = persons.get((sheetNo, row, col), 'X') sheet.Cells(row, col).Value = values[:65000] else: sheet.Cells(row, col).Value = '.' This was the closest example I had at hand. I don't really have time to write you a proper, working example now. I hope you can read through the noise and extract something intelligent from it. There's a book called "Python Programming on Win32" which explains the issues well, and a mailing list available through http://mail.python.org/mailman/listinfo/python-win32 Another option is to use ctypes: http://starship.python.net/crew/theller/ctypes/ but I don't know how mature that is. > I tried to set a com > server and I have had no luck. Is it because i'm using the XP operating > system. Well, if you used Linux, you wouldn't even try, so perhaps? ;) Seriously, this *should* work on XP. It's very difficult to for anyone to see what you are doing wrong if you don't show us your code. > Also, If you have any example code for setting-up a database file or > which do you recommend using with python. I have many more questions but I think If you come to the EuroPython Conference at Chalmers University of Technology in G?teborg, Sweden next week, you can listen to my talk about database programming on Wednesday morning. :) Or if you can't I should be able to provide you with my presentaion as a PDF by then, but it's not quite done yet. I'll try to remember to post them on my site and to announce it here. > this is a load. Please, Please respond because I really want to learn this > language. Thanks Cliff If you are familiar with SQL, you could start with pysqlite. See http://pysqlite.sourceforge.net/ You can get some examples of its use at http://pysqlite.sourceforge.net/manual.html If you want to access some database through ODBC you probably want mxODBC. See http://www.egenix.com/files/python/mxODBC.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Fri Jun 4 13:59:31 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jun 4 13:59:43 2004 Subject: [Tutor] random number equations . . . In-Reply-To: <20040604081250.BFHD8220.maxwell6.pacific.net.sg@[203.120.90.194]> Message-ID: On Fri, 4 Jun 2004 rantek@pacific.net.sg wrote: > Wouldn't using fixed point representation (32bit) improve the accuracy? Hi Bill, Fixed point representation would make the calculations more exact, but numeric accuracy isn't the reason for the bias in the old gimmeRandomInRange() function. For reference, here's the definition of gimmeRandomInRange() again: ### def gimmeRandomInRange(n): """Returns a random number between 0 and n, inclusive.""" return int(round(random.random() * n)) ### Ideally, we'd like to get all numbers between '0' and 'n'. I'm assuming, that we want every number to be equally likely to be chosen. We can visualize the expression "random.random() * n" almost as a function that randomly chooses a point on the number line. I like concrete examples, so let's do this for n=2 again. (------------------------------------) 0 2 The round()ing function take a number on the number line, and forces it either up or down into an integer. Here's another small diagram of how round divides the number line into regions from 0 to 2. [0] [1] [2] (--------)(----------------)(--------) 0 0.5 1 1.5 2 The bias comes from the observation that the region for [0] and the region for [2] is simply smaller than the region for [1]. If we start choosing random points on this line, we're more likely to fall into region [1] than the other regions. If we don't do the rounding, and just do the truncation, then we're splitting the number line into something like this: [0] [1] (-----------------)(-----------------) 0 1 2 The regions are of equal size, and so it's more uniform. But there are only two regions now. That's why Glen modified the expression to: int(random.random() * (n + 1)) [0] [1] [2] (-----------------)(-----------------)(-----------------) 0 1 2 3 > > I guess my ``teach the basics first'' philosophy shows through in a > > bad way sometimes. No, no, basics are fine. And it's great that we're having this discussion, since I'm sure folks wanted to see how random.random(), and multiplication can be used to get random numbers. I'm just trying to make sure folks see why using round() causes a slight nonuniformity around the edges. *grin* Hope this helps! From alan.gauld at blueyonder.co.uk Fri Jun 4 14:07:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jun 4 14:07:29 2004 Subject: [Tutor] How to control list input ? References: <1086341326.13373.60.camel@localhost> Message-ID: <00d801c44a5e$ddabc6a0$6401a8c0@xp> > I thought that the dictionaries would be like this: > > Name || key || value > ----------------------------------------- Actually you just described a relational data schema. You would almost certainly be better off moving to a proper relatinal database such as MySQL, Postgres or SqlLite. In the long term it will be much easier to work with. > - is it possible for a dictionary to save a class as a value ? Would > this actually make sense in this case ? Yes, and more usefully instances of classes. > Someone also suggests using dictionaries instead of lists: > > - is it possible for a dictionary to save another dictionary as a > value ? Yes, you can store any object as a value. Its quite common to have nested dictionaries: D = { "first" : { "second" : { "third" : 3, "fourth" : 4 }, "fifth" : { "sixth" : 6, "seventh" : 7 } }, "eight" : { "short" : 0}, } print D['first']['fifth']['seventh'] print D['eighth']['short'] etc... You will find more on this in the section on collection types within the Raw Materials topic in my new tutor HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From michele.alzetta at aliceposta.it Fri Jun 4 14:31:04 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Fri Jun 4 14:33:21 2004 Subject: [Tutor] working with time spans ? Message-ID: <1086373863.16113.8.camel@localhost> I've taken a look at modules datetime and calendar, but they don't seem to have what I need (or maybe I ca't see it); I would like to be able to do something like this: say this moment is 11 a.m. of 11 september 2002 and the timespan 'a' I'm examining is from 1 to 30 september 2002 whereas timespan 'b' is from 12 to 15 september 2002: thismoment in atimespan True thismoment in btimespan False Any suggestions ? -- Michele From alan.gauld at blueyonder.co.uk Fri Jun 4 14:39:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jun 4 14:39:03 2004 Subject: [Tutor] How create a grade book References: Message-ID: <00e001c44a63$46f781e0$6401a8c0@xp> > I have just began to use python from the intactive screen. I wrote a small > program that ran fine. Great start. > Now I want to write a program that accept use input and > perform calculations. Specifically, I want to write a grade book that > conisist of student name, grade, subjects, average, date, and objective. Thats OK, no problem doing that in Python. If you go to my tutorial (or any of the others for that mnatter!) you will find the following topics useful: Simple Sequences - performing calculations Talking to the User - getting input The Raw Materials - how to store your data within the program Handling Files - how to save your data to disk between executions > don't know how to connect pyton to visual basic by COM. Why do you think you need to do that? You can get Python to talk to COM directly via the winall extensions (standard from Activestate's version of Python or a separate download from official Python). But I don't think you even need to go near COM here unless your data already exists in a COM enabled application? > Is it because i'm using the XP operating system. No, Python and XP play together just fine. Try my tutorial pages as outlined above, there is a simple address book application started in "Raw Materials" and finished in "Handling Files" that might seem similar to what you want. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Fri Jun 4 16:49:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jun 4 16:49:42 2004 Subject: [Tutor] working with time spans ? In-Reply-To: <1086373863.16113.8.camel@localhost> Message-ID: On Fri, 4 Jun 2004, Michele Alzetta wrote: > I've taken a look at modules datetime and calendar, but they don't seem > to have what I need (or maybe I ca't see it); I would like to be able to > do something like this: > > say this moment is 11 a.m. of 11 september 2002 and the timespan 'a' I'm > examining is from 1 to 30 september 2002 whereas timespan 'b' is from 12 > to 15 september 2002: > thismoment in atimespan > True > > thismoment in btimespan > False Hi Michele, I don't see time spans explicitely defined in the datetime module, but we should be able to do something like this: ### >>> start, end = (datetime.date(month=9, day=1, year=2002), ... datetime.date(month=9, day=30, year=2002)) >>> >>> someOtherDate = datetime.date(month=9, day=11, year=2002) >>> >>> start <= someOtherDate <= end True >>> start <= end <= someOtherDate False ### And if we really wanted to, we can define a Span object that supports the 'in' containment operator, given two endpoints. ### >>> class Span: ... def __init__(self, a, b): ... self.a, self.b = a, b ... def __contains__(self, x): ... return self.a <= x <= self.b ... >>> s = Span(5, 6) >>> 4 in s False >>> 5 in s True >>> 5.5 in s True >>> 6 in s True >>> 7 in s False ### This should work on endpoints that are dates, too. Hope this helps! From michele.alzetta at aliceposta.it Fri Jun 4 18:50:57 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Fri Jun 4 18:48:37 2004 Subject: [Tutor] working with time spans ? In-Reply-To: <1086385426.16441.2.camel@localhost> References: <1086385426.16441.2.camel@localhost> Message-ID: <1086389457.16484.12.camel@localhost> Thanks to Danny Yoo's suggestion I got to this, might be interesting: from time import mktime class TimeSpan(object): def __init__(self, startimetuple, endtimetuple): self.starttime = mktime(startimetuple) self.endtime = mktime(endtimetuple) def __contains__(self, timespan): return (self.starttime <= timespan.starttime) and \ (self.endtime >= timespan.endtime) periodstart = (2004, 6, 01, 8, 0, 0, 0, 0, 0) periodend = (2004, 7, 01, 8, 0, 0, 0, 0, 0) shiftperiod = TimeSpan(periodend,periodstart) shift1start = (2004, 6, 15, 8, 0, 0, 0, 0, 0) shift1end = (2004, 6, 15, 20, 0, 0, 0, 0, 0) shift1 = TimeSpan(shift1start,shift1end) shift2start = (2004, 7, 15, 8, 0, 0, 0, 0, 0) shift2end = (2004, 7, 15, 20, 0, 0, 0, 0, 0) shift2 = TimeSpan(shift2start,shift2end) shift1 in shiftperiod True shift2 in shiftperiod False which ought to come in pretty handy for my purposes. Actually all I'm interested in are years, months, days, hours and minutes so the tuples with 9 elements are a bit of a nuisance. Would it be a good idea to make TimeSpan inherit from time and change the mktime method for instance ? -- Michele From tim.one at comcast.net Fri Jun 4 19:30:10 2004 From: tim.one at comcast.net (Tim Peters) Date: Fri Jun 4 19:30:36 2004 Subject: [Tutor] working with time spans ? In-Reply-To: <1086389457.16484.12.camel@localhost> Message-ID: [Michele Alzetta] > Thanks to Danny Yoo's suggestion I got to this, might be interesting: > > from time import mktime class TimeSpan(object): > def __init__(self, startimetuple, endtimetuple): > self.starttime = mktime(startimetuple) > self.endtime = mktime(endtimetuple) > def __contains__(self, timespan): > return (self.starttime <= timespan.starttime) and \ > (self.endtime >= timespan.endtime) > > periodstart = (2004, 6, 01, 8, 0, 0, 0, 0, 0) > periodend = (2004, 7, 01, 8, 0, 0, 0, 0, 0) > shiftperiod = TimeSpan(periodend,periodstart) The order of the arguments is backwards there, isn't it? That is, didn't you want to pass periodstart first? As written, nothing can actually be in shiftperiod, and both tests below are False. > shift1start = (2004, 6, 15, 8, 0, 0, 0, 0, 0) > shift1end = (2004, 6, 15, 20, 0, 0, 0, 0, 0) > shift1 = TimeSpan(shift1start,shift1end) > > shift2start = (2004, 7, 15, 8, 0, 0, 0, 0, 0) > shift2end = (2004, 7, 15, 20, 0, 0, 0, 0, 0) > shift2 = TimeSpan(shift2start,shift2end) > > shift1 in shiftperiod > True > > shift2 in shiftperiod > False > > which ought to come in pretty handy for my purposes. > > Actually all I'm interested in are years, months, days, hours and minutes > so the tuples with 9 elements are a bit of a nuisance. > > Would it be a good idea to make TimeSpan inherit from time and change the > mktime method for instance ? You can't, because time is a module, and you can only inherit from classes (a module isn't a class). The better news is that there's really no need for the time module at all: Python can compare tuples directly. So this does the same thing (but where I swapped the order of arguments as noted above): class TimeSpan(object): def __init__(self, startimetuple, endtimetuple): self.starttime = startimetuple self.endtime = endtimetuple def __contains__(self, timespan): return (self.starttime <= timespan.starttime and self.endtime >= timespan.endtime) periodstart = (2004, 6, 1, 8) periodend = (2004, 7, 1, 8) shiftperiod = TimeSpan(periodstart, periodend) shift1start = (2004, 6, 15, 8) shift1end = (2004, 6, 15, 20) shift1 = TimeSpan(shift1start, shift1end) shift2start = (2004, 7, 15, 8) shift2end = (2004, 7, 15, 20) shift2 = TimeSpan(shift2start, shift2end) print shift1 in shiftperiod print shift2 in shiftperiod That prints True, then False. You'll eventually want to think about using the datetime module. Doing so will check that the dates passed in are sane, and provide a strong base to build fancier stuff on. For example, just replace the first 4 lines above with: from datetime import datetime class TimeSpan(object): def __init__(self, startimetuple, endtimetuple): self.starttime = datetime(*startimetuple) self.endtime = datetime(*endtimetuple) Everything else works the same then, and not even the __contains__ method needs to change. You can easily add other interesting methods to your TimeSpan class then; e.g., add def length(self): return self.endtime - self.starttime and then print shiftperiod.length() print shift1.length() print shift2.length() prints 30 days, 0:00:00 12:00:00 12:00:00 It's best to get a new job before you have to worry about daylight saving time, though . From michele.alzetta at aliceposta.it Fri Jun 4 19:47:22 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Fri Jun 4 19:45:03 2004 Subject: [Tutor] working with time spans ? In-Reply-To: <407E8B400029A8E4@vsmtp7alice.tin.it> (added by postmaster@aliceposta.it) References: <407E8B400029A8E4@vsmtp7alice.tin.it> (added by postmaster@aliceposta.it) Message-ID: <1086392842.16619.9.camel@localhost> Il sab, 2004-06-05 alle 01:30, Tim Peters ha scritto: > > shiftperiod = TimeSpan(periodend,periodstart) > > The order of the arguments is backwards there, isn't it? copied wrongly, of course > This does the same thing (but where I swapped the order of arguments as > noted above): > > class TimeSpan(object): > def __init__(self, startimetuple, endtimetuple): > self.starttime = startimetuple > self.endtime = endtimetuple > > def __contains__(self, timespan): > return (self.starttime <= timespan.starttime and > self.endtime >= timespan.endtime) Yes, but this can contain any tuple, which means I can't extract self.startime and feed it in to one of the time functions if I ever wanted to. > You'll eventually want to think about using the datetime module. Doing so > will check that the dates passed in are sane, and provide a strong base to > build fancier stuff on. For example, just replace the first 4 lines above > with: > > from datetime import datetime > > class TimeSpan(object): > def __init__(self, startimetuple, endtimetuple): > self.starttime = datetime(*startimetuple) > self.endtime = datetime(*endtimetuple) > > Everything else works the same then, and not even the __contains__ method > needs to change. You can easily add other interesting methods to your > TimeSpan class then; e.g., add > > def length(self): > return self.endtime - self.starttime > > and then > > print shiftperiod.length() > print shift1.length() > print shift2.length() > > prints > > 30 days, 0:00:00 > 12:00:00 > 12:00:00 That's really great. Er ... what on earth does the "*" in *startimetuple mean ? -- Michele From gew75 at hotmail.com Fri Jun 4 20:46:48 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Fri Jun 4 20:46:55 2004 Subject: [Tutor] working with time spans ? References: <407E8B400029A8E4@vsmtp7alice.tin.it>(added by postmaster@aliceposta.it) <1086392842.16619.9.camel@localhost> Message-ID: > [..] > > That's really great. > Er ... what on earth does the "*" in *startimetuple mean ? > Well, it's for unpacking arguments. For example: >>> t = (1,20,3) >>> for i in range(*t): .. print i .. 1 4 7 10 13 16 19 HTH, Glen From game at gameweave.com Fri Jun 4 21:48:41 2004 From: game at gameweave.com (K J) Date: Fri Jun 4 21:45:31 2004 Subject: [Tutor] Defines question? Message-ID: <001201c44a9f$3ad1cce0$30e57218@basp.phub.net.cable.rogers.com> I know in C when you want to define something it would be #define MAX_LETTERS 25 I was wondering what the eqivalent would be in python? Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040604/61e4508a/attachment.html From orbitz at ezabel.com Fri Jun 4 22:11:06 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Fri Jun 4 22:12:21 2004 Subject: [Tutor] Defines question? In-Reply-To: <001201c44a9f$3ad1cce0$30e57218@basp.phub.net.cable.rogers.com> References: <001201c44a9f$3ad1cce0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <20040604221106.2f3d86eb.orbitz@ezabel.com> No, but generally a symbol in all capital letters suggests that it's value is constant. In python people use strings a lot for constants too. On Fri, 4 Jun 2004 21:48:41 -0400 "K J" wrote: > I know in C when you want to define something it would be #define MAX_LETTERS > 25 > > I was wondering what the eqivalent would be in python? > > Kevin From lsloan-000002 at umich.edu Fri Jun 4 07:37:17 2004 From: lsloan-000002 at umich.edu (Lance E Sloan) Date: Fri Jun 4 22:15:21 2004 Subject: [Tutor] New to list & first steps in Python In-Reply-To: References: Message-ID: <2147483647.1086334636@blue-four.us.itd.umich.edu> --On Thursday, June 3, 2004 11:57 AM -0700 Danny Yoo wrote: > This looks fine. You may want to avoid using the 'from foo import *' > statement. I agree that explicitely pulling out the 'choice' function is > better: > > ### > from random import choice > ### What I've been doing lately in cases like this is: import random x = random.choice( y ) What do you other experienced Pythonistas think of that style? I admit that I don't like the length it adds to my lines of code, but I do like that it's clear and easy to see which module each function came from. -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From tim.one at comcast.net Sat Jun 5 00:06:30 2004 From: tim.one at comcast.net (Tim Peters) Date: Sat Jun 5 00:06:38 2004 Subject: [Tutor] working with time spans ? In-Reply-To: <1086392842.16619.9.camel@localhost> Message-ID: [Tim, switches Michele's class to use plain tuples] >> ... [Michele Alzetta] > Yes, but this can contain any tuple, which means I can't extract > self.startime and feed it in to one of the time functions if I ever > wanted to. Good -- you're thinking ahead. Your objection goes away with the next step (moving to datetime objects), and simplifying the code to get back to tuples was a step toward that end. Making code hairier instead is often a step in a wrong direction! [and then to switch from tuples to datetime objects ...] >> For example, just replace the first 4 lines above with: >> >> from datetime import datetime >> >> class TimeSpan(object): >> def __init__(self, startimetuple, endtimetuple): >> self.starttime = datetime(*startimetuple) >> self.endtime = datetime(*endtimetuple) > Er ... what on earth does the "*" in *startimetuple mean ? f(*args) is a shortcut for apply(f, args) and you can read about apply() in the Library Reference Manual (in the section on builtin functions). If you want to pass a variable number of arguments to a function, you define the function with this syntax: def f(*args): print args Then all the arguments in a call to f() are gathered into a tuple (the "*" in front of "args" *tells* Python to gather them into a tuple): >>> f() () >>> f(1) (1,) >>> f("two", "args") ('two', 'args') >>> f("and", 3, "args") ('and', 3, 'args') >>> etc. On the *calling* side, "*something" in an argument list is a bit like the reverse of that: it takes the elements of the sequence "something", and breaks them into out into individual arguments. def g(a=1, b=2, c=3): print a, b, c Then: >>> g(*()) 1 2 3 >>> g(*(10,)) 10 2 3 >>> g(*(10, 11)) 10 11 3 >>> g(*(10, 11, 12)) 10 11 12 >>> g(*(10, 11, 12, 13)) Traceback (most recent call last): File "", line 1, in ? TypeError: g() takes at most 3 arguments (4 given) >>> The datetime.datetime() constructor requires at least 3 arguments, but accepts as many as 8 (see the docs). If you already have a tuple in the right form, it's much easier to use * than to break the tuple apart by hand: >>> ymd = 2004, 12, 31 >>> print datetime(ymd[0], ymd[1], ymd[2]) # yuck! 2004-12-31 00:00:00 >>> print datetime(*ymd) # easier and exactly the same thing 2004-12-31 00:00:00 >>> print datetime(ymd) # not at all the same thing Traceback (most recent call last): File "", line 1, in ? TypeError: function takes at least 3 arguments (1 given) >>> Using the * trick on the call side also lets you not care whether the tuple contains just (year, month, day), or also contains hours and possibly also minutes and possibly also seconds, etc. *something breaks them all out, no matter what len(something) is. From magnus at thinkware.se Sat Jun 5 07:35:07 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Jun 5 07:33:21 2004 Subject: [Tutor] working with time spans ? In-Reply-To: <1086389457.16484.12.camel@localhost> References: <1086385426.16441.2.camel@localhost> <1086385426.16441.2.camel@localhost> Message-ID: <5.2.1.1.0.20040605100323.026a5808@www.thinkware.se> At 00:50 2004-06-05 +0200, Michele Alzetta wrote: >Would it be a good idea to make TimeSpan inherit from time and >change the mktime method for instance ? No. Even if it was technically possible, you should think of inheritance as "is-a". I.e. an employee is a person, a manager is an employee. A time span is not a time, any more than a department is a person. A time span is an interval between two times, so the concept to use is composition, not inheritance. That is "has a" (or "has two" in this case) rather than "is a". That means that you use two times (start and stop) as attributes in the TimeSpan class, just as you've shown. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From missive at hotmail.com Sat Jun 5 08:36:10 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Jun 5 08:36:20 2004 Subject: [Tutor] Re: Defines question? Message-ID: >I know in C when you want to define something it would be #define = >MAX_LETTERS 25 > >I was wondering what the eqivalent would be in python? > MAX_LETTERS = 25 _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From michele.alzetta at aliceposta.it Sat Jun 5 16:31:07 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Sat Jun 5 16:28:44 2004 Subject: [Tutor] working with time spans ? Message-ID: <1086467466.14545.47.camel@localhost> [Tim, gives an interesting explanation of *] Thanks Tim, I must say this escaped me in all my tutorial browsing ! Here is the latest product I came up with: from datetime import datetime, date, timedelta class TimeSpan(object): ''' I thought it might be useful to check if a timespan is contained in another but also if a single moment is contained in another, so I added the isTimeSpan attribute and the exception ''' def __init__(self, startimetuple, endtimetuple): self.starttime = datetime(*startimetuple) self.endtime = datetime(*endtimetuple) self.isTimeSpan = True def __contains__(self, timespan): try: if timespan.isTimeSpan: return (self.starttime <= timespan.starttime) and \ (self.endtime >= timespan.endtime) except AttributeError: moment = datetime(*timespan) return (self.starttime <= moment <= self.endtime) def length(self): return self.endtime - self.starttime class Shift(TimeSpan): '''This derived class knows if the shift is a weekend or night shift, and won't accept shifts longer than 12 hours; doc, hol and label attributes will come in handy later on for the moment they're just here as placeholders''' def __init__(self, startimetuple, endtimetuple, doc = None, \ night = True, hol = False, weekend = False, \ label = None): self.starttime = datetime(*startimetuple) self.endtime = datetime(*endtimetuple) self.isTimeSpan = True self.doc = doc self.night = night self.weekend = weekend self.hol = hol self.label = label if date.weekday(datetime.date(datetime(*startimetuple))) >= 5: self.weekend = True self.startday = self.starttime.day self.endday = self.endtime.day if self.startday == self.endday: self.night = False max = timedelta(hours = 12) assert self.length() <= max Although not complete by any means, this actually seems to work, so I was wandering if the end product of my program (not the pretty output, I mean the 'content' i.e. the program's representation of a monthly shift schedule) might not be a shelve list (containing an instance of my Shift class for every single shift as elements) ... or maybe even a shelve dictionary. However - wouldn't this be __very__ laborious in terms of memory and cpu usage ?? Probably using a postgres database would be more efficient, but I would like to keep things as independent from other programs as possible (if it ever comes to the point where it passes from an excercise in python learning to something actually useful, having to bundle python + postgresql with the program would be a major nuisance). -- Michele From alan.gauld at blueyonder.co.uk Sat Jun 5 17:59:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jun 5 17:59:39 2004 Subject: [Tutor] Defines question? References: <001201c44a9f$3ad1cce0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <001d01c44b48$6b5d9480$6401a8c0@xp> > I know in C when you want to define something it would be > #define MAX_LETTERS 25 > >I was wondering what the eqivalent would be in python? MAX_LETTERS = 25 There is some discussion of adding a const facility to Python which would allow you to prevent changes, but heh, you can change it in C if you really want to - just not programmaticlly, you have to redefine it... :-) But its one good reason to use the Upper case convention only for read only variables. At least that way you get a visual warning that something strange is happening whe you do MAX_LETTERS = foo later in the code. Alan G. From alan.gauld at blueyonder.co.uk Sat Jun 5 18:03:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jun 5 18:03:48 2004 Subject: [Tutor] New to list & first steps in Python References: <2147483647.1086334636@blue-four.us.itd.umich.edu> Message-ID: <002601c44b49$00405b50$6401a8c0@xp> > > from random import choice > > ### > > What I've been doing lately in cases like this is: > > import random > x = random.choice( y ) > > What do you other experienced Pythonistas think of that style? Its the preferred one at the cost of extra typing. Using this approach is safest, ythere is no possibility of accidentally importing another coice and hiding the "random" one. Only if you will use it a lot and know there will never be conflict would I recommend the first option. Even if the typing is too much you can reduce it with import random as r And type r.choice That still keeps it safe (unless you import another module called r or as r I guess!) > I admit that I don't like the length it adds to my lines of code, but I do > like that it's clear and easy to see which module each function came from. That about sums up the pros and cons. Alan G From carroll at tjc.com Sun Jun 6 01:17:30 2004 From: carroll at tjc.com (Terry Carroll) Date: Sun Jun 6 01:17:34 2004 Subject: [Tutor] Any modules for validating data? Message-ID: Are there any modules to assist in validating input data? I'm doing a small application with a lot of user input, and want to validate the data before proceeding. For example, one piece of data (call it DATA_A) may need to be an integer between 1800 and 2004; another may need to be an integer between DATA_A and 2004, etc. I was wondering if there were any modules that simplify this sort of thing. Perl has Data::FormValidator, which looks like the sort of thing I'm looking for (albeit somewhat overkill for me, but it'd certainly work). From Dragonfirebane at aol.com Sun Jun 6 01:21:33 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Jun 6 01:21:39 2004 Subject: [Tutor] printing multiple values from a list in one command Message-ID: <9a.c570eed.2df403dd@aol.com> Hello all, I am trying to write a number-binary-hexadecimal translator than can also act as a makeshift text-binary converter (a is assigned to 01, b to 10, c to 11, etc). However, when I try to write the code such that when the text to be translated is in the lowercase (the first half of ascii_letters), the program should print the corresponding value in binary. Short of defining each letter as a binary number, does anyone have any suggestions? The code as is (not working) is below: def convertxt(): if char in alphabet[range(0-26)]: print binary[range(0-26)] elif char in alphabet[range(27-52)]: print binary[range(27-52)] elif char not in alphabet: print "Sorry, you didn't enter valid text. Please enter standard letters only." def convertnum(): whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal """) if whichconv in('1','Binary','binary','b'): if char in number: print binary[int(original) - 1] from string import * import time alphabet = [ascii_letters] binary = ['01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000','10001','10010','10011','10100','10101','10 110','10111','11000','11001','11010','11011','11100','11101','11110','11111',' 100000','100001','100010','100011','100100','100101','100110','100111','101000 ','101001','101010','101011','101100','101101','101110','101111','110000','110 001','110010','110011','110100','110101','110110','110111','111000','111001',' 111010','111011','111100','111101','111110','111111','1000000','1000001','1000 010','1000011','1000100','1000101','1000110','1000111','1001000','1001001','10 01010','1001011','1001100','1001101','1001110','1001111','1010000','1010001',' 1010010','1010011','1010100','1010101','1010110','1010111','1011000','1011001' ,'1011010','1011011','1011100','1011101','1011110','1011111','1100000','110000 1','1100010','1100011','1100100','1100101','1100110','1100111','1101000','1101 001','1101010','1101011','1101100','1101101','1101110','1101111','1110000','11 10001','1110010','1110011','1110100','1110101','1110110','1110111','1111000',' 1111001','1111010','1111011','1111100','1111101','1111110','1111111','10000000 ','10000001','10000010','10000011','10000100','10000101','10000110','10000111' ,'10001000','10001001','10001010','10001011','10001100','10001101','10001110', '10001111','10010000','10010001','10010010','10010011','10010100','10010101',' 10010110','10010111','10011000','10011001','10011010','10011011','10011100','1 0011101','10011110','10011111','10100000','10100001','10100010','10100011','10 100100','10100101','10100110','10100111','10101000','10101001','10101010','101 01011','10101100','10101101','10101110','10101111','10110000','10110001','1011 0010','10110011','10110100','10110101','10110110','10110111','10111000','10111 001','10111010','10111011','10111100','10111101','10111110','10111111','110000 00','11000001','11000010','11000011','11000100','11000101','11000110','1100011 1','11001000','11001001','11001010','11001011','11001100','11001101','11001110 ','11001111','11010000','11010001','11010010','11010011','11010100','11010101' ,'11010110','11010111','11011000','11011001','11011010','11011011','11011100', '11011101','11011110','11011111','11100000','11100001','11100010','11100011',' 11100100','11100101','11100110','11100111','11101000','11101001','11101010','1 1101011','11101100','11101101','11101110','11101111','11110000','11110001','11 110010','11110011','11110100','11110101','11110110','11110111','11111000','111 11001','11111010','11111011','11111100','11111101','11111110','11111111'] number = ['0','1','2','3','4','5','6','7','8','9'] again = True while again: original = raw_input("Please enter numbers or text to be converted. ") try: int(original) except ValueError: convertxt() pass else: if char in number: convertnum() again = input("Would you like to convert more text or letters [y/n]? ") if again in 'yY': pass elif again in 'nN': break print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040606/325f4f09/attachment.html From Dragonfirebane at aol.com Sun Jun 6 01:27:03 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Jun 6 01:27:08 2004 Subject: [Tutor] printing multiple values from a list in one command Message-ID: <60.3fc899e7.2df40527@aol.com> To clarify: When I try to write the code such that when the text to be translated is in the lowercase (the first half of ascii_letters), the program should print the corresponding value in binary, it either says 'list index out of range' (if char in alphabet[1-26]:) or 'list indices must be integers' (if char in alphabet[0,1,2,3,4,5,6,etc.]). -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040606/182c6ba0/attachment.html From MBussell at aol.com Sun Jun 6 12:28:56 2004 From: MBussell at aol.com (MBussell@aol.com) Date: Sun Jun 6 12:29:09 2004 Subject: [Tutor] Sys.exit() Message-ID: <147.2b701137.2df4a048@aol.com> I have switched to Version 2.3.3, and am having an issue with the sys.exit() function working. Is there an argument required now? Thanks, MB -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040606/9a2582e4/attachment.html From alan.gauld at blueyonder.co.uk Sun Jun 6 12:56:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 6 12:56:17 2004 Subject: [Tutor] printing multiple values from a list in one command References: <9a.c570eed.2df403dd@aol.com> Message-ID: <001901c44be7$34f3fbb0$6401a8c0@xp> > etc). However, when I try to write the code such that when the text to be > translated is in the lowercase (the first half of ascii_letters), the program > should print the corresponding value in binary. > Short of defining each letter as a binary number, You mean like ASCII? I'm not sure what you are trying to achieve by mapping one binary number (the ASCII code) to another (your arbitrary value)? > if char in alphabet[range(0-26)]: This won't work because range returns a list and a list index must be a single integer. I suspect you just want if char in string.ascii_lowercase: print binary[ord(char)] > elif char in alphabet[range(27-52)]: > print binary[range(27-52)] and if char in string.ascii_uppercase: print binary(ord(char)) Or replacing both if char in string.letters: print binary(ord(char)) > elif char not in alphabet: > print "Sorry, you didn't enter valid text. Please enter standard > letters only." And this should probably be plain 'else' just to catch any other condition. If you really do want to use your handcrafted alphabet you should use slicing: if char in alphabet[0:26]: # or just [:26] elif char in alphabet[16:52]: # or just [26:] BTW, It has been discussed several times in the past on tutor, how to write a function to generate binary strings from numbewrs, you might find a search of the tutor archives onActivestate useful. Also for hex display the standard format string can do that for you (%x or %X) Good luck, Alan G. From Dragonfirebane at aol.com Sun Jun 6 12:57:40 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Jun 6 12:57:56 2004 Subject: [Tutor] Sys.exit() Message-ID: <1a8.2485f914.2df4a704@aol.com> >I have switched to Version 2.3.3, and am having an issue with the sys.exit() function >working. Is there an argument required now? > >Thanks, >MB In order to use the sys.exit() function, you must first import sys: def exit(): print "This program will now exit" import sys sys.exit() exit() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040606/a389f25e/attachment.html From waghk at hotmail.com Sun Jun 6 13:23:58 2004 From: waghk at hotmail.com (arearear reraraer) Date: Sun Jun 6 13:24:05 2004 Subject: [Tutor] Display question Message-ID: Hi, I am relatively new to python and I have a question that I couldn't get answered in the tutorials. Is there any way to display text in defined coords? Ex: displaytext(text,coordx,coordy): _________________________________________________________________ ?Est?s pensando en cambiar de coche? Todas los modelos de serie y extras en MSN Motor. http://motor.msn.es/researchcentre/ From Dragonfirebane at aol.com Sun Jun 6 14:02:23 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Jun 6 14:02:31 2004 Subject: [Tutor] printing values from one list that correspond to that in another list Message-ID: <142.2b5a6b13.2df4b62f@aol.com> Hello all, I'm trying to get the program to take user input and, if it is in the 'alphabet' list (alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H' , 'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']), to print the corresponding entry in the binary list (binary = ['01','10','11',etc.]) so that when 'a' is entered, '01' is printed and so on. The current attempt is below and it doesn't work. Any suggestions? def convertxt(): if original in alphabet[:26]: print binary[:26] if original in alphabet[26:]: print binary[:26] def convertnum(): whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal """) if whichconv in('1','Binary','binary','bin','b'): if char in number: print binary[int(original) - 1] elif whichconv in('2','Hexadecimal','hexadecimal','hexadec','hex','h'): if char in number: print hexadec[int(original) - 1] import time alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] binary = ['01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000', '10001','10010','10011','10100','10101','10110','10111','11000','11001','11010 ','11011','11100', '11101','11110','11111','100000','100001','100010','100011','100100','100101', '100110','100111', '101000','101001','101010','101011','101100','101101','101110','101111','11000 0','110001', '110010','110011','110100','110101','110110','110111','111000','111001','11101 0','111011', '111100','111101','111110','111111','1000000','1000001','1000010','1000011','1 000100','1000101', '1000110','1000111','1001000','1001001','1001010','1001011','1001100','1001101 ','1001110', '1001111','1010000','1010001','1010010','1010011','1010100','1010101','1010110 ','1010111', '1011000','1011001','1011010','1011011','1011100','1011101','1011110','1011111 ','1100000', '1100001','1100010','1100011','1100100','1100101','1100110','1100111','110100 0','1101001', '1101010','1101011','1101100','1101101','1101110','1101111','1110000','1110001 ','1110010', '1110011','1110100','1110101','1110110','1110111','1111000','1111001','1111010 ','1111011', '1111100','1111101','1111110','1111111','10000000','10000001','10000010','1000 0011', '10000100','10000101','10000110','10000111','10001000','10001001','10001010',' 10001011', '10001100','10001101','10001110','10001111','10010000','10010001','10010010',' 10010011', '10010100','10010101','10010110','10010111','10011000','10011001','10011010',' 10011011', '10011100','10011101','10011110','10011111','10100000','10100001','10100010',' 10100011', '10100100','10100101','10100110','10100111','10101000','10101001','10101010',' 10101011', '10101100','10101101','10101110','10101111','10110000','10110001','10110010',' 10110011', '10110100','10110101','10110110','10110111','10111000','10111001','10111010',' 10111011', '10111100','10111101','10111110','10111111','11000000','11000001','11000010',' 11000011', '11000100','11000101','11000110','11000111','11001000','11001001','11001010',' 11001011', '11001100','11001101','11001110','11001111','11010000','11010001','11010010',' 11010011', '11010100','11010101','11010110','11010111','11011000','11011001','11011010',' 11011011', '11011100','11011101','11011110','11011111','11100000','11100001','11100010',' 11100011', '11100100','11100101','11100110','11100111','11101000','11101001','11101010',' 11101011', '11101100','11101101','11101110','11101111','11110000','11110001','11110010',' 11110011', '11110100','11110101','11110110','11110111','11111000','11111001','11111010',' 11111011', '11111100','11111101','11111110','11111111'] number = ['0','1','2','3','4','5','6','7','8','9'] hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10','11','12','13','14','15','16','17','18','19','1A','1B','1C', '1D','1E','1F','20','21','22','23','24','25','26','27','28','29','2A','2B','2C ','2D','2E','2F','30','31','32','33','33', '34','35','36','37','38','39','3A','3B','3C','3D','3E','3F','40','41','42','43 ','44','45','46','47','48','49','4A','4B', '4C','4D','4E','4F','50','51','52','53','54','55','56','57','58','59','5A','5B ','5C','5D','5E','5F','60','61','62', '63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F','70','71','72 ','73','74','75','76','77','78','79','7A', '7B','7C','7D','7E','7F','80','81','82','83','84','85','86','87','88','89','8A ','8B','8C','8D','8E','8F','90','91', '92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F','A1','A2 ','A3','A4','A5','A6','A7','A8','A9', 'AA','AB','AC','AD','AE','AF','B0','B1','B2','B3','B4','B5','B6','B7','B8','B9 ','BA','BB','BC','BD','BE', 'BF','C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE ','CF','D0','D1','D2','D3','D4', 'D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF','E0','E1','E2','E3','E4 ','E5','E6','E7','E8','E9','EA', 'EB','EC','ED','EE','EF','F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA ','FB','FC','FD','FE','FF'] print alphabet[:26] print alphabet[26:] again = True while again: original = raw_input("Please enter numbers or text to be converted. ") try: int(original) pass except ValueError: convertxt() pass else: if char in number: convertnum() pass again = raw_input("Would you like to convert more text or letters [y/n]? ") if again in 'Yy': again = True elif again in 'Nn': again = False print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040606/f89ac7f7/attachment.html From clavezza at hotmail.com Sun Jun 6 17:17:32 2004 From: clavezza at hotmail.com (christopher lavezza) Date: Sun Jun 6 17:17:36 2004 Subject: [Tutor] Help on Python Assignment Message-ID: Hello. This program written has a syntax error in it. Can anyone help me out to fix the problem. Chris import time >>>class Account: def __init__(self, initial): self.balance = initial self.payactions={} def deposit(self,amt): self.balance=self.balance+amt t=time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time() + 0)) self.payactions[amt]=t def withdraw(self,amt): if self.balance-amt<0: print 'Not enough Mojo in your account!' else: self.balance=self.balance-amt t=time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time() + 0)) self.payactions[-amt]=t def printbalance(self): print 'Date Activities' for k, v in self.payactions.iteritems(): print v,' ',k print 'Total:'+str(self.balance) _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar – get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From clavezza at hotmail.com Sun Jun 6 17:18:09 2004 From: clavezza at hotmail.com (christopher lavezza) Date: Sun Jun 6 17:18:12 2004 Subject: [Tutor] Help on Python Assignment Message-ID: Hello. This program written has a syntax error in it. Can anyone help me out to fix the problem. Chris import time >>>class Account: def __init__(self, initial): self.balance = initial self.payactions={} def deposit(self,amt): self.balance=self.balance+amt t=time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time() + 0)) self.payactions[amt]=t def withdraw(self,amt): if self.balance-amt<0: print 'Not enough Mojo in your account!' else: self.balance=self.balance-amt t=time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time() + 0)) self.payactions[-amt]=t def printbalance(self): print 'Date Activities' for k, v in self.payactions.iteritems(): print v,' ',k print 'Total:'+str(self.balance) _________________________________________________________________ Stop worrying about overloading your inbox - get MSN Hotmail Extra Storage! http://join.msn.click-url.com/go/onm00200362ave/direct/01/ From bgailer at alum.rpi.edu Sun Jun 6 18:24:08 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Jun 6 18:24:15 2004 Subject: [Tutor] Help on Python Assignment In-Reply-To: References: Message-ID: <6.1.0.6.0.20040606160901.03b9c518@mail.mric.net> Hey Chris - how goes it. Looks like you are working on the class project again. Is that true? What's your relationship with the school's program at this time? Please, when submitting code with a syntax error, also provide the exception. It tells us which line the problem is on. In this case, when I paste your code into my IDE and check it, it has no errors! Here is my copy of your program with some code to exercise it: import time class Account: def __init__(self, initial): self.balance = initial self.payactions={} def deposit(self,amt): self.balance=self.balance+amt t=time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time() + 0)) self.payactions[amt]=t def withdraw(self,amt): if self.balance-amt<0: print 'Not enough Mojo in your account!' else: self.balance=self.balance-amt t=time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime(time.time() + 0)) self.payactions[-amt]=t def printbalance(self): print 'Date Activities' for k, v in self.payactions.iteritems(): print v,' ',k a=Account(100) a.deposit(10) a.withdraw(20) a.printbalance() And here is the output: Date Activities Sun, 06 Jun 2004 16:16:22 10 Sun, 06 Jun 2004 16:16:22 -20 There is a problem with storing transactions using the amount as the key. If you make 2 or more transactions with the same amount, each will replace the previous in the dictionary, and you will be left with only the last. Why did you choose a dictionary? A list is the preferred way to save something like this, especially if you want to keep it in its timestamp order, and retain all transactions. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From alan.gauld at blueyonder.co.uk Sun Jun 6 18:33:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 6 18:33:32 2004 Subject: [Tutor] Display question References: Message-ID: <001001c44c16$52c88140$6401a8c0@xp> > Hi, I am relatively new to python and I have a question that I couldn't get > answered in the tutorials. > Is there any way to display text in defined coords? > Ex: displaytext(text,coordx,coordy): Unfortunately displaying things is very dependant on what kind of device you are using, since Python runs on anything from a PalmPilot to a Sun workstation with all manner of things in between it is virtually impossible for Python to have a standard way of displaying text at specific locations. That's the bad news. The good news is that various ways around this are available. 1) Use HTML and display results in a web browser 2) Use the curses library if its available, it has a coordinate virtual window system whereby you can position the cursor before writing. The downside is its a lot harder to use than 'print'! 3) Use a GUI Toolkit like Tkinter which has a Text widget within which you can control where text appears. 4) There is a kind of generic console module out there which is written, I think, by Fred Lundh. I can't recall if X,Y control is one of its features but it certainly can clear the scren etc. Welcome to the world of cross platform computing! :-) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sun Jun 6 18:42:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 6 18:42:08 2004 Subject: [Tutor] printing values from one list that correspond to that inanother list References: <142.2b5a6b13.2df4b62f@aol.com> Message-ID: <001801c44c17$87bf3370$6401a8c0@xp> > def convertxt(): > if original in alphabet[:26]: This is fine (although using the string module constants is probably still a good idea!) because you are returning a list then checking to see if original is in that list > print binary[:26] But this isn't because you are again generating a list and printing all of it. You need to find the index of your character within the list and then use that to index binary: if original in alphabet[:26]: print binary[alphabet.index(original)] When stuck it's worth reading the documentation carefully to check what types each action expects and returns. Also to browse the list of available functions and constants. There is a saying that "Python comes with batteries included" which means that usually you can find something in the library that will do the bulk of your job for you. The pyhon >>> prompt is your friend here because it makes it very easy to try ideas before committing them to a module/program. Of course sometimes we just want to experiment and do things for the sake of finding out how. That's OK too. :-) HTH, Alan G. From alan.gauld at blueyonder.co.uk Sun Jun 6 18:47:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 6 18:47:29 2004 Subject: [Tutor] Help on Python Assignment References: Message-ID: <001d01c44c18$477f2ee0$6401a8c0@xp> > This program written has a syntax error in it. Can anyone help me out to > fix the problem. Given that your email has lost all the indentation (it did have indentation I assume?) itshard to tell. Try posting using plain text next time. Guessing at the formatting I can't see any obvious problems. It would also help if you posted the actual error message, Python usually gives you a pretty good clue as to where to look! Alan G. From bvande at po-box.mcgill.ca Mon Jun 7 02:01:01 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Jun 7 02:15:49 2004 Subject: [Tutor] A tip from someone who is clawing his way out of being a Python newbie Message-ID: <40C4049D.6060707@po-box.mcgill.ca> Hi all, I've struggled along and reached the point with Python where I can code some serious fun ;-) projects. I recently discovered something I'd like to share with other relative newcomers: Write docstrings. Write them early and often. I don't know that all/many more experienced Pythoners would agree, and I know that many talented programmers dislike writing documentation. But I have found that the effort I put in to writing a semi-English docstring for my functions seems to have been more than repaid in the time saved tracking down bugs. I've tried both writing the docstring before the function, and just after I think I have a first version. I'm not yet sure which is more effective, but both have saved me from a good deal of pain caused by not coding what I meant. The effort of rendering an explanation for existing or projected code has really saved me from my own sloppy thinking a few times. Likewise, revising a docstring to account for changes made to code has often exposed that the change wasn't what I thought I'd made. I've actually come to think that at least for me, writing docstrings is at least as useful as running tests -- too often I miss the test case that would expose the bug, but in explaining my code I seem more likely to catch it. Of course, docstrings are good practice anyway, and they really do speed up the process of understanding code you wrote weeks before. So, I'd been putting them in everything, but until recently only once I had a finished program. Doing them earlier has improved my programming more than anything else in the last while. Anyway, I thought I'd throw that out there for what it is worth. Best to all, Brian vdB From stella at solarenergenex.com Mon Jun 7 10:09:42 2004 From: stella at solarenergenex.com (Stella Rockford) Date: Mon Jun 7 11:10:28 2004 Subject: [Tutor] IMAP2RSS Message-ID: In constant pursuit of lowering the threshold to web publishing I have been experimenting with IMPA2RSS in python here is the script ---> http://www.holgerarendt.de/journal/text/imap2rss.jsp right about line 58 of Holger Arendt's script I get an error --------------------------------------------------------------- pcp08247552pcs:~ stella$ /Users/stella/Desktop/IMAP2RSS Traceback (most recent call last): File "/Users/stella/Desktop/IMAP2RSS", line 97, in ? makeFeed() File "/Users/stella/Desktop/IMAP2RSS", line 89, in makeFeed mail = parse(data) File "/Users/stella/Desktop/IMAP2RSS", line 58, in parse os.remove(f); TypeError: coercing to Unicode: need string or buffer, file found --------------------------------------------------------------- any guidance or suggestions would be appreciated -Stella -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ From dyoo at hkn.eecs.berkeley.edu Mon Jun 7 14:04:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 7 14:04:50 2004 Subject: [Tutor] IMAP2RSS In-Reply-To: Message-ID: On Mon, 7 Jun 2004, Stella Rockford wrote: > In constant pursuit of lowering the threshold to web publishing I have > been experimenting with IMPA2RSS in python > > here is the script ---> > http://www.holgerarendt.de/journal/text/imap2rss.jsp > > right about line 58 of Holger Arendt's script I get an error > --------------------------------------------------------------- > > pcp08247552pcs:~ stella$ /Users/stella/Desktop/IMAP2RSS > Traceback (most recent call last): > File "/Users/stella/Desktop/IMAP2RSS", line 97, in ? > makeFeed() > File "/Users/stella/Desktop/IMAP2RSS", line 89, in makeFeed > mail = parse(data) > File "/Users/stella/Desktop/IMAP2RSS", line 58, in parse > os.remove(f); > TypeError: coercing to Unicode: need string or buffer, file found > > > --------------------------------------------------------------- > > any guidance or suggestions would be appreciated Hi Stella, The code appears to be buggy. Its parse() method opens up a file as a temporary buffer, and when it tries to remove it, the code passes the file object 'f' to os.remove... but os.remove() takes in a file name, not the file object: http://www.python.org/doc/lib/os-file-dir.html#l2h-1452 This should explain why we're getting the error message: > TypeError: coercing to Unicode: need string or buffer, file found Let's look at the function again: ### def parse(maildata): filename="/tmp/imap2rss_fetch_"+str(os.getpid()) f = open(filename,'w') f.write(maildata[0][1]) f.close() f = open(filename,'r') m = rfc822.Message(f) data= {'From' : m.getaddr('from'), 'To' : m.getaddrlist('to'), 'Subject' : encode(m.getheader('subject')), 'Date' : m.getheader('date')} m.rewindbody() body=encode("
")
    while 1:
        line = f.readline();
        if not line:
            body=body+encode("
") break body = body+encode(line) data['Body']=body f.close() os.remove(f); return data ### Ok, I see, so the code uses a temporary file just to feed into rfc822.Message, since rfc822.Message expects a file object, not a string. But rather than reinvent the wheel, the code may want to take advantage of either the 'tempfile' module: http://www.python.org/doc/lib/module-tempfile.html or 'StringIO': http://www.python.org/doc/lib/module-StringIO.html In this case, StringIO looks like a promising module. The code can be simplified by using StringIO to put a file-like wrapper around the mail string. Here is a revised version of the code, replacing the temporary-file stuff with StringIO stuff: ### def parse(maildata): f = StringIO.StringIO(maildata[0][1]) m = rfc822.Message(f) data= {'From' : m.getaddr('from'), 'To' : m.getaddrlist('to'), 'Subject' : encode(m.getheader('subject')), 'Date' : m.getheader('date')} m.rewindbody() body=encode("
")
    while 1:
        line = f.readline();
        if not line:
            body=body+encode("
") break body = body+encode(line) data['Body']=body return data ### Let's try it. ### >>> text = """From: dyoo@hkn.eecs.berkeley.edu ... To: john@doe.com ... Subject: where have all the cowboys gone? ... ... Hi John, ... ... Do you know where all the cowboys have gone? I'm looking ... for them. Thanks. ... """ >>> def encode(x): return x ... >>> parse([['', text]]) {'Date': None, 'To': [('', 'john@doe.com')], 'Body': "
Hi John,\n\nDo
you know where all the cowboys have gone?  I'm looking\nfor them.
Thanks.\n
", 'From': ('', 'dyoo@hkn.eecs.berkeley.edu'), 'Subject': 'where have all the cowboys gone?'} ### I just wrote some mock data (and a mock version of encode()) just to see if parse() is doing something reasonable. Looks functional! But I can't seem to find the email address of the original author of the code. It would be great if we could send these corrections back to Holger Arendt. Good luck to you! From Dragonfirebane at aol.com Mon Jun 7 19:25:45 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 7 19:26:00 2004 Subject: [Tutor] trouble with 'char' Message-ID: <50A428B0.51F15011.34E997B7@aol.com> Hello all, As far as I know, char is a valid variable describing characters in a user response, correct? If that's the case, why does: Traceback (most recent call last): File "C:\Documents and Settings\Orri Ganel\Desktop\Hexadecimal-Binary-Text.py", line 32, in ? convertxt() File "C:\Documents and Settings\Orri Ganel\Desktop\Hexadecimal-Binary-Text.py", line 2, in convertxt if char in alphabet[:26]: NameError: global name 'char' is not defined come up when i run the following program?: def convertxt(): if char in alphabet[:26]: print binary[alphabet.index(original)] elif char in alphabet[26:]: print binary[alphabet.index(original)] def convertnum(): whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal """) if whichconv in('1','Binary','binary','bin','b'): if char in number: print binary[int(original) - 1] elif whichconv in('2','Hexadecimal','hexadecimal','hexadec','hex','h'): if char in number: print hexadec[int(original) - 1] import time alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] binary = ['01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000','10001','10010','10011','10100','10101','10110','10111','11000','11001','11010','11011','11100','11101','11110','11111','100000','100001','100010','100011','100100','100101','100110','100111','101000','101001','101010','101011','101100','101101','101110','101111','110000','110001','110010','110011','110100','110101','110110','110111','111000','111001','111010','111011','111100','111101','111110','111111','1000000','1000001','1000010','1000011','1000100','1000101','1000110','1000111','1001000','1001001','1001010','1001011','1001100','1001101','1001110','1001111','1010000','1010001','1010010','1010011','1010100','1010101','1010110','1010111','1011000','1011001','1011010','1011011','1011100','1011101','1011110','1011111','1100000','1100001','1100010','1100011','1100100','1100101','1100110','1100111','1101000','1101001','1101010','1101011','1101100','1101101','1101110','1101111','1110000','1110001','1110010','1110011','1110100','1110101','1110110','1110111','1111000','1111001','1111010','1111011','1111100','1111101','1111110','1111111','10000000','10000001','10000010','10000011','10000100','10000101','10000110','10000111','10001000','10001001','10001010','10001011','10001100','10001101','10001110','10001111','10010000','10010001','10010010','10010011','10010100','10010101','10010110','10010111','10011000','10011001','10011010','10011011','10011100','10011101','10011110','10011111','10100000','10100001','10100010','10100011','10100100','10100101','10100110','10100111','10101000','10101001','10101010','10101011','10101100','10101101','10101110','10101111','10110000','10110001','10110010','10110011','10110100','10110101','10110110','10110111','10111000','10111001','10111010','10111011','10111100','10111101','10111110','10111111','11000000','11000001','11000010','11000011','11000100','11000101','11000110','11000111','11001000','11001001','11001010','11001011','11001100','11001101','11001110','11001111','11010000','11010001','11010010','11010011','11010100','11010101','11010110','11010111','11011000','11011001','11011010','11011011','11011100','11011101','11011110','11011111','11100000','11100001','11100010','11100011','11100100','11100101','11100110','11100111','11101000','11101001','11101010','11101011','11101100','11101101','11101110','11101111','11110000','11110001','11110010','11110011','11110100','11110101','11110110','11110111','11111000','11111001','11111010','11111011','11111100','11111101','11111110','11111111'] number = ['0','1','2','3','4','5','6','7','8','9'] hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F','20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F','30','31','32','33','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F','40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F','50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F','60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F','70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F','80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F','90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF','B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF','C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF','D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF','E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF','F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'] again = True while again: original = raw_input("Please enter numbers or text to be converted. ") try: int(original) pass except ValueError: convertxt() pass else: if char in number: convertnum() pass again = raw_input("Would you like to convert more text or letters [y/n]? ") if again in 'Yy': again = True elif again in 'Nn': again = False print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() any and all help is welcome and appreciated. "n thats the way the cookie crumbles" America's Favorite Cookie From adeleinandjeremy at yahoo.com Mon Jun 7 20:47:13 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Mon Jun 7 20:47:18 2004 Subject: [Tutor] trouble with 'char' In-Reply-To: <50A428B0.51F15011.34E997B7@aol.com> Message-ID: <20040608004713.25606.qmail@web50308.mail.yahoo.com> *** I had replied to this previously but not to the list, I am sending to the list now. --- Dragonfirebane@aol.com wrote: > Hello all, > > As far as I know, char is a valid variable describing characters in > a user response, correct? It is a valid variable, period. But, variables need to be assigned values before being referenced.... > > Traceback (most recent call last): > File "C:\Documents and Settings\Orri > Ganel\Desktop\Hexadecimal-Binary-Text.py", line 32, in ? > convertxt() > File "C:\Documents and Settings\Orri > Ganel\Desktop\Hexadecimal-Binary-Text.py", line 2, in convertxt > if char in alphabet[:26]: > NameError: global name 'char' is not defined > > come up when i run the following program?: > > def convertxt(): > if char in alphabet[:26]: > print binary[alphabet.index(original)] > elif char in alphabet[26:]: > print binary[alphabet.index(original)] Maybe I am missing something here, but if this is your actual code, how would the interpreter know if 'char' is in the list, when you haven't told it what 'char' is? Maybe you are confusing the if-in construct with the for-in? ``for char in alphabet[:26]:'' is valid, but not what you want. Perhaps you meant to pass 'char' as an argument? And where is 'original' coming from? Also, you have an if-elif, but no else. Maybe if-else would be more appropriate? And the actions to be taken are the same in both cases, so why use a selection structure at all? If I am reading the intent of your code correctly, I would prefer the following: def convertxt(char): return binary[alphabet.index(char)] Note that I have changed the print statement to a return statement so as to avoid side-effects. Print the returned value elsewhere, if that's what's required - in this case it would be more normal to do something like ``new_text += convertxt(next_char)'' - of course, having first properly assigned the variables 'new_text' and 'next_char'. HTH - Jeremy __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From Dragonfirebane at aol.com Mon Jun 7 23:36:20 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 7 23:36:49 2004 Subject: [Tutor] (no subject) Message-ID: <1244AA80.1433026A.34E997B7@aol.com> 'original comes from farther down in the code: again = True while again: original = raw_input("Please enter numbers or text to be converted. ") try: int(original) pass except ValueError: convertxt() pass else: if char in number: convertnum() pass again = raw_input("Would you like to convert more text or letters [y/n]? ") if again in 'Yy': again = True elif again in 'Nn': again = False print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() also, since the program is a work in progress, the if-elif-else statement hasn't been completed and won't be pending functionality of the if-elif part. You're probably right about the "for-in" being what i thought would work, depsite not being what i intended. Thanks for the help, Orri In a message dated 6/7/2004 8:46:01 PM Eastern Daylight Time, adeleinandjeremy@yahoo.com writes: > > Hello all, > > > > As far as I know, char is a valid variable describing characters in > > a user response, correct? > > It is a valid variable, period. But, variables need to be assigned > values before being referenced.... > > > > > Traceback (most recent call last): > > File "C:\Documents and Settings\Orri > > Ganel\Desktop\Hexadecimal-Binary-Text.py", line 32, in ? > > convertxt() > > File "C:\Documents and Settings\Orri > > Ganel\Desktop\Hexadecimal-Binary-Text.py", line 2, in convertxt > > if char in alphabet[:26]: > > NameError: global name 'char' is not defined > > > > come up when i run the following program?: > > > > def convertxt(): > > if char in alphabet[:26]: > > print binary[alphabet.index(original)] > > elif char in alphabet[26:]: > > print binary[alphabet.index(original)] > > Maybe I am missing something here, but if this is your actual code, > how would the interpreter know if 'char' is in the list, when you > haven't told it what 'char' is? Maybe you are confusing the if-in > construct with the for-in? ``for char in alphabet[:26]:'' is valid, > but not what you want. Perhaps you meant to pass 'char' as an > argument? And where is 'original' coming from? > > Also, you have an if-elif, but no else. Maybe if-else would be more > appropriate? And the actions to be taken are the same in both cases, > so why use a selection structure at all? > > If I am reading the intent of your code correctly, I would prefer the > following: > > def convertxt(char): > return binary[alphabet.index(char)] > > Note that I have changed the print statement to a return statement so > as to avoid side-effects. Print the returned value elsewhere, if > that's what's required - in this case it would be more normal to do > something like ``new_text += convertxt(next_char)'' - of > course, > having first properly assigned the variables 'new_text' and > 'next_char'. > > HTH > - Jeremy "n thats the way the cookie crumbles" America's Favorite Cookie From visional_freeman at hotmail.com Tue Jun 8 05:17:28 2004 From: visional_freeman at hotmail.com (Ivan Low) Date: Tue Jun 8 05:17:39 2004 Subject: [Tutor] Python On RedHat? Message-ID: Hi, I had recently install linux and had been trying if make it work for me and the first problem I encounter was using the python program in linux. I can access the program using the comman window but that was like a interactive window for me to test some programming code. Here's my question, are there python software preinstall in Redhat that work like those I use in Mac OS? Since I had chose the full installation. I had access some of those programming tool that had very nice word editing function that can import or export or create a new project. Are there such thing for python since I had found out that those are more for C++? Ivan _________________________________________________________________ Get 10mb of inbox space with MSN Hotmail Extra Storage http://join.msn.com/?pgmarket=en-sg From game at gameweave.com Tue Jun 8 09:34:44 2004 From: game at gameweave.com (K J) Date: Tue Jun 8 09:31:31 2004 Subject: [Tutor] Python On RedHat? References: Message-ID: <000901c44d5d$5cc30b00$30e57218@basp.phub.net.cable.rogers.com> You can setup kwrite to work with the python code. I use it and it works just fine. ----- Original Message ----- From: "Ivan Low" To: Sent: Tuesday, June 08, 2004 5:17 AM Subject: [Tutor] Python On RedHat? > Hi, I had recently install linux and had been trying if make it work for me > and the first problem I encounter was using the python program in linux. I > can access the program using the comman window but that was like a > interactive window for me to test some programming code. > Here's my question, are there python software preinstall in Redhat that work > like those I use in Mac OS? Since I had chose the full installation. > I had access some of those programming tool that had very nice word editing > function that can import or export or create a new project. > Are there such thing for python since I had found out that those are more > for C++? > > Ivan > > _________________________________________________________________ > Get 10mb of inbox space with MSN Hotmail Extra Storage > http://join.msn.com/?pgmarket=en-sg > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From reedobrien at acm.org Tue Jun 8 10:20:19 2004 From: reedobrien at acm.org (Reed L. O'Brien) Date: Tue Jun 8 10:30:59 2004 Subject: [Tutor] SwishE web interface Message-ID: I have an html page whose form calls the function in the following. import SwishE def search(searchWords): # make sure the user provided all the parameters if not (searchWords): return " Nothing to search for. Nothing Found." handle = SwishE.new('/usr/local/swish-e/index.swish-e') search = handle.search('') results = search.execute(searchWords) # return results.hits() for r in results: return r.getproperty('searchdocpath') If I: return results.hits() but for r in results: return r.getproperty('searchdocpath') only returns the first. I would like them all returned. I have been playing around but am in a loop. Any help would be appreciated. I know it is a simple solution like converting to a dict or something. I am humbled by the difficulty of programming. This is my first non shell script. FreeBSD 5.2.1 apache 2.0.49 mod_python 3.1.3 SwishE 0.4 TIA -- reed 4.6692016090 From pythonTutor at venix.com Tue Jun 8 11:05:49 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Jun 8 11:06:02 2004 Subject: [Tutor] SwishE web interface In-Reply-To: References: Message-ID: <1086707148.2098.39.camel@laptop.venix.com> return marks the end of processing in a function. control is returned to the caller. You have multiple results that could be returned as a list. return [r.getproperty('searchdocpath') for r in results] uses "list comprehensions" to return a list of values. This is a very handy addition to the language that makes it extremely easy to write a simple loop and collect the results into a list. On Tue, 2004-06-08 at 10:20, Reed L. O'Brien wrote: > I have an html page whose form calls the function in the following. > > import SwishE > > > > > def search(searchWords): > > > # make sure the user provided all the parameters > if not (searchWords): > return " Nothing to search for. Nothing Found." > > handle = SwishE.new('/usr/local/swish-e/index.swish-e') > search = handle.search('') > results = search.execute(searchWords) > # return results.hits() > for r in results: > return r.getproperty('searchdocpath') > > If I: > return results.hits() > > but > for r in results: > return r.getproperty('searchdocpath') > > only returns the first. I would like them all returned. I have been > playing around but am in a loop. Any help would be appreciated. I know > it is a simple solution like converting to a dict or something. I am > humbled by the difficulty of programming. This is my first non shell > script. > > FreeBSD 5.2.1 > apache 2.0.49 > mod_python 3.1.3 > SwishE 0.4 > > TIA -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From gew75 at hotmail.com Tue Jun 8 11:09:53 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Tue Jun 8 11:10:04 2004 Subject: [Tutor] SwishE web interface References: Message-ID: Hi Reed, Not exactly sure what you're asking, but would this help? def search(searchWords): # make sure the user provided all the parameters if not (searchWords): return " Nothing to search for. Nothing Found." handle = SwishE.new('/usr/local/swish-e/index.swish-e') search = handle.search('') results = search.execute(searchWords) allHits = [] while (hits = results.hits()): allHits.append(hits) return allHits Then you'd have a list with all the _.hits() in it? If there is more than one `hit' to return, then there must be some way of terminating the loop, so I have just assumed that each call to hits() is similar to pop() -- takes the current hit off the top and deletes it from the list. Sorry that I can't be any more use, I've never used SwishE before. Glen ----- Original Message ----- From: "Reed L. O'Brien" To: Sent: Wednesday, June 09, 2004 12:20 AM Subject: [Tutor] SwishE web interface > I have an html page whose form calls the function in the following. > > import SwishE > > > > > def search(searchWords): > > > # make sure the user provided all the parameters > if not (searchWords): > return " Nothing to search for. Nothing Found." > > handle = SwishE.new('/usr/local/swish-e/index.swish-e') > search = handle.search('') > results = search.execute(searchWords) > # return results.hits() > for r in results: > return r.getproperty('searchdocpath') > > If I: > return results.hits() > > but > for r in results: > return r.getproperty('searchdocpath') > > only returns the first. I would like them all returned. I have been > playing around but am in a loop. Any help would be appreciated. I know > it is a simple solution like converting to a dict or something. I am > humbled by the difficulty of programming. This is my first non shell > script. > > FreeBSD 5.2.1 > apache 2.0.49 > mod_python 3.1.3 > SwishE 0.4 > > TIA > -- > > > reed > 4.6692016090 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From reedobrien at acm.org Tue Jun 8 12:16:05 2004 From: reedobrien at acm.org (Reed L. O'Brien) Date: Tue Jun 8 12:15:55 2004 Subject: [Tutor] Re: SwishE web interface In-Reply-To: <1086707148.2098.39.camel@laptop.venix.com> References: <1086707148.2098.39.camel@laptop.venix.com> Message-ID: I replaced for r in results with the line given return [r.getproperty('searchdocpath') for r in results] Now it works. I guess I should get out my python book to find out how to split that to a vertical list as it rolls right of the page s to the right without a scroll. But the return is there. Thanks Lloyd. Lloyd Kvam wrote: > return marks the end of processing in a function. control is returned > to the caller. > > You have multiple results that could be returned as a list. > > > return [r.getproperty('searchdocpath') for r in results] > uses "list comprehensions" to return a list of values. This is a very > handy addition to the language that makes it extremely easy to write a > simple loop and collect the results into a list. > > > > > > On Tue, 2004-06-08 at 10:20, Reed L. O'Brien wrote: > >>FreeBSD 5.2.1 >>apache 2.0.49 >>mod_python 3.1.3 >>SwishE 0.4 >> >>TIA -- reed 4.6692016090 From lsloan-000002 at umich.edu Tue Jun 8 12:21:36 2004 From: lsloan-000002 at umich.edu (Lance E Sloan) Date: Tue Jun 8 12:21:43 2004 Subject: [Tutor] (no subject) In-Reply-To: <1244AA80.1433026A.34E997B7@aol.com> References: <1244AA80.1433026A.34E997B7@aol.com> Message-ID: <2147483647.1086697296@blue-four.us.itd.umich.edu> --On Monday, June 7, 2004 11:36 PM -0400 Dragonfirebane@aol.com wrote: > else: > if char in number: > convertnum() > pass I think you don't want "if". You want "for": for char in number: And you should pass that value into your function: convertnum( char ) And change your function definition to accept the value, as Jeremy sugegsted: def convertxt( char ): Also, I think you're going to run into other problems. For example, where do you define "alphabet"? >> > def convertxt(): >> > if char in alphabet[:26]: >> > print binary[alphabet.index(original)] >> > elif char in alphabet[26:]: >> > print binary[alphabet.index(original)] -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From pythonTutor at venix.com Tue Jun 8 13:19:35 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Jun 8 13:19:44 2004 Subject: [Tutor] Re: SwishE web interface In-Reply-To: References: <1086707148.2098.39.camel@laptop.venix.com> Message-ID: <1086715174.3056.15.camel@laptop.venix.com> If the printing is simply to help with debugging and planning the next step, the pprint module (Pretty Print) should help do the trick nicely. If you need to provide the formating, then you should be learning the % format operator. Also, the method for combining a list of strings into one new string is surprising when you first encounter it. If you called the list that was returned result_list, print '\n'.join(result_list) would: combine each of the items from result_list into one new string while inserting a newline ('\n') character between each item output the new string to stdout print would provide a final newline character Warning: The str.join method requires that each item in result_list is a string (or unicode) object. On Tue, 2004-06-08 at 12:16, Reed L. O'Brien wrote: > I replaced for r in results with the line given > > return [r.getproperty('searchdocpath') for r in results] > > Now it works. I guess I should get out my python book to find out how > to split that to a vertical list as it rolls right of the page s to the > right without a scroll. But the return is there. > > Thanks Lloyd. > > Lloyd Kvam wrote: > > return marks the end of processing in a function. control is returned > > to the caller. > > > > You have multiple results that could be returned as a list. > > > > > > return [r.getproperty('searchdocpath') for r in results] > > uses "list comprehensions" to return a list of values. This is a very > > handy addition to the language that makes it extremely easy to write a > > simple loop and collect the results into a list. > > > > > > > > > > > > On Tue, 2004-06-08 at 10:20, Reed L. O'Brien wrote: > > > > >>FreeBSD 5.2.1 > >>apache 2.0.49 > >>mod_python 3.1.3 > >>SwishE 0.4 > >> > >>TIA -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From bobhe at telkomsa.net Tue Jun 8 13:59:26 2004 From: bobhe at telkomsa.net (Bob Heasman) Date: Tue Jun 8 13:58:41 2004 Subject: [Tutor] Re: Python on Red Hat Message-ID: <40C5FE7E.2010602@telkomsa.net> Hi Ivan, I think you may need a little more than you have been given. I don't have KDE installed, I have Gnome, so I don't know Kedit. I suggest you try "joe". It is a very simple editor to use and with Python it is a breeze. So you know how to bring up the interactive window, that is fine. This is how I have brought up a window in which to write your program. In an xterm, type in "joe (filename).py". You can use any name as filename. Next, in the top left hand corner type in "#!/usr/bin/python" if that is the directory you loaded Python into. Python should be in the path. Now you can start entering your code. To save it type "ctrl K and X". If you need help with joe type in "ctrl K and H" while in the joe window. When you have saved it you will need to get permission to execute it. Make yourself Super User (su and password) then type "chmod +x (filename)". Now to recall that file use "joe filename.py" . To run the file type in "./(filename.py)" , as Ivan, not root. You can use root, but it is safer not to. Root is too damned powerful. Now remember, you can use the up arrow to recall your previous commands, so it is a couple of key taps and to bring up your script. When you have written a script and run it, and it has an error, Linux will show you the error, but it can sometimes lead you astray. You have been warned :-) Ok, this part I have sorted out, but how to write a Python script is another story as far as I am concerned. I am battling like h*ll. GOOD LUCK :-) Regards....Bob ******************************************** Ivans message:- Message: 5 Date: Tue, 08 Jun 2004 17:17:28 +0800 From: "Ivan Low" Subject: [Tutor] Python On RedHat? To: tutor@python.org Message-ID: Content-Type: text/plain; format=flowed Hi, I had recently install linux and had been trying if make it work for me and the first problem I encounter was using the python program in linux. I can access the program using the comman window but that was like a interactive window for me to test some programming code. Here's my question, are there python software preinstall in Redhat that work like those I use in Mac OS? Since I had chose the full installation. I had access some of those programming tool that had very nice word editing function that can import or export or create a new project. Are there such thing for python since I had found out that those are more for C++? Ivan ************************************************ From dyoo at hkn.eecs.berkeley.edu Tue Jun 8 14:29:15 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jun 8 14:29:19 2004 Subject: [Tutor] Python On RedHat? In-Reply-To: Message-ID: On Tue, 8 Jun 2004, Ivan Low wrote: > Hi, I had recently install linux and had been trying if make it work for > me and the first problem I encounter was using the python program in > linux. I can access the program using the comman window but that was > like a interactive window for me to test some programming code. Here's > my question, are there python software preinstall in Redhat that work > like those I use in Mac OS? Since I had chose the full installation. Hi Ivan, I suspect that the IDLE GUI might already be installed on your system, but unfortunately, I can't test my assumption. If you can tell us what Linux distribution you've installed, one of us can probably figure out if IDLE is installed by default. IDLE usually comes bundled with Python, and I've written a brief introduction to it: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ > I had access some of those programming tool that had very nice word > editing function that can import or export or create a new project. Are > there such thing for python since I had found out that those are more > for C++? Hmmm... Yes, there are a few nice IDE's that you may want to try. Here's a list of them: http://www.python.org/cgi-bin/moinmoin/IntegratedDevelopmentEnvironments If you have more questions, please feel free to ask. Good luck! From Dragonfirebane at aol.com Tue Jun 8 16:45:48 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 8 16:46:07 2004 Subject: [Tutor] (no subject) Message-ID: <6E0B6054.269AE5AE.34E997B7@aol.com> the full code as is is below (not working). as of right now, i'm oncentrating only on the text function since the number converter works fine. the reason i'm using if and not for is that using for creates a loop where the program prints the converted number based on the number of characters in the original number (1100 1100) or something of the sort for 12, whereas 'if' prints the same number (1100) once, due to the [print binary[int(original) - 1]] command. def convertxt(char): return binary[alphabet.index(char)] def convertnum(): whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal """) if whichconv in('1','Binary','binary','bin','b'): if char in number: print binary[int(original) - 1] elif whichconv in('2','Hexadecimal','hexadecimal','hexadec','hex','h'): if char in number: print hexadec[int(original) - 1] import time alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] binary = ['01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000','10001','10010','10011','10100','10101','10110','10111','11000','11001','11010','11011','11100','11101','11110','11111','100000','100001','100010','100011','100100','100101','100110','100111','101000','101001','101010','101011','101100','101101','101110','101111','110000','110001','110010','110011','110100','110101','110110','110111','111000','111001','111010','111011','111100','111101','111110','111111','1000000','1000001','1000010','1000011','1000100','1000101','1000110','1000111','1001000','1001001','1001010','1001011','1001100','1001101','1001110','1001111','1010000','1010001','1010010','1010011','1010100','1010101','1010110','1010111','1011000','1011001','1011010','1011011','1011100','1011101','1011110','1011111','1100000','1100001','1100010','1100011','1100100','1100101','1100110','1100111','1101000','1101001','1101010','1101011','1101100','1101101','1101110','1101111','1110000','1110001','1110010','1110011','1110100','1110101','1110110','1110111','1111000','1111001','1111010','1111011','1111100','1111101','1111110','1111111','10000000','10000001','10000010','10000011','10000100','10000101','10000110','10000111','10001000','10001001','10001010','10001011','10001100','10001101','10001110','10001111','10010000','10010001','10010010','10010011','10010100','10010101','10010110','10010111','10011000','10011001','10011010','10011011','10011100','10011101','10011110','10011111','10100000','10100001','10100010','10100011','10100100','10100101','10100110','10100111','10101000','10101001','10101010','10101011','10101100','10101101','10101110','10101111','10110000','10110001','10110010','10110011','10110100','10110101','10110110','10110111','10111000','10111001','10111010','10111011','10111100','10111101','10111110','10111111','11000000','11000001','11000010','11000011','11000100','11000101','11000110','11000111','11001000','11001001','11001010','11001011','11001100','11001101','11001110','11001111','11010000','11010001','11010010','11010011','11010100','11010101','11010110','11010111','11011000','11011001','11011010','11011011','11011100','11011101','11011110','11011111','11100000','11100001','11100010','11100011','11100100','11100101','11100110','11100111','11101000','11101001','11101010','11101011','11101100','11101101','11101110','11101111','11110000','11110001','11110010','11110011','11110100','11110101','11110110','11110111','11111000','11111001','11111010','11111011','11111100','11111101','11111110','11111111'] number = ['0','1','2','3','4','5','6','7','8','9'] hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F','20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F','30','31','32','33','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F','40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F','50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F','60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F','70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F','80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F','90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF','B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF','C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF','D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF','E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF','F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'] again = True while again: original = raw_input("Please enter numbers or text to be converted. ") try: int(original) pass except ValueError: convertxt(char) print convertxt(original) pass else: if char in number: convertnum() pass again = raw_input("Would you like to convert more text or letters [y/n]? ") if again in 'Yy': again = True elif again in 'Nn': again = False print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() In a message dated 6/8/2004 12:21:36 PM Eastern Daylight Time, lsloan-000002@umich.edu writes: > --On Monday, June 7, 2004 11:36 PM -0400 Dragonfirebane@aol.com wrote: > > else: > > if char in number: > > convertnum() > > pass > > I think you don't want "if". You want "for": > > for char in number: > > And you should pass that value into your function: > > convertnum( char ) > > And change your function definition to accept the value, as Jeremy > sugegsted: > > def convertxt( char ): > > Also, I think you're going to run into other problems. For example, where > do you define "alphabet"? > > >> > def convertxt(): > >> > if char in alphabet[:26]: > >> > print binary[alphabet.index(original)] > >> > elif char in alphabet[26:]: > >> > print binary[alphabet.index(original)] > > -- > Lance E Sloan, Systems Research Programmer III > U-M WATS: Web Applications, Technologies, and Solutions > Full-service web and database design, development, and > hosting. > http://www.itcs.umich.edu/wats/ - "Putting U on the Web" "n thats the way the cookie crumbles" America's Favorite Cookie From lsloan-000002 at umich.edu Tue Jun 8 17:17:15 2004 From: lsloan-000002 at umich.edu (Lance E Sloan) Date: Tue Jun 8 17:17:34 2004 Subject: [Tutor] number conversion problem (was: Re: [no subject]) In-Reply-To: <6E0B6054.269AE5AE.34E997B7@aol.com> References: <6E0B6054.269AE5AE.34E997B7@aol.com> Message-ID: <2147483647.1086715035@blue-four.us.itd.umich.edu> --On Tuesday, June 8, 2004 4:45 PM -0400 Dragonfirebane@aol.com wrote: > the full code as is is below (not working). as of right now, i'm > oncentrating only on the text function since the number converter works > fine. the reason i'm using if and not for is that using for creates a > loop where the program prints the converted number based on the number of > characters in the original number (1100 1100) or > something of the sort for 12, whereas 'if' prints the same number (1100) > once, due to the [print binary[int(original) - 1]] command. OK. Then I think we're back to the problem being that you are referencing "char" before you ever assign any value to it. The error I get is: Please enter numbers or text to be converted. 1234 Traceback (most recent call last): File "multivert.py", line 33, in ? if char in number: NameError: name 'char' is not defined What do you expect the variable "char" to contain? A single character of the user's input string, one character at a time until you reach the end of the string? If so, you're going to need a line like this somewhere just before you reference "char": for char in original: I've not checked this, but it would probably go just before your "if char in number" statement. Also, I don't know the details of the problem you're trying to solve, but there are more mathematical ways of converting numbers from one base to another that would not require you to include long lists of all the possible conversions in your program. -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From Dragonfirebane at aol.com Tue Jun 8 17:37:41 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 8 17:38:04 2004 Subject: [Tutor] Re: number conversion problem (was: Re: [no subject]) Message-ID: <556A620E.588A3117.34E997B7@aol.com> In a message dated 6/8/2004 5:17:15 PM Eastern Daylight Time, lsloan-000002@umich.edu writes: > --On Tuesday, June 8, 2004 4:45 PM -0400 Dragonfirebane@aol.com wrote: > > the full code as is is below (not working). as of right now, i'm > > oncentrating only on the text function since the number converter works > > fine. the reason i'm using if and not for is that using for creates a > > loop where the program prints the converted number based on the number of > > characters in the original number (1100 1100) or > > something of the sort for 12, whereas 'if' prints the same number (1100) > > once, due to the [print binary[int(original) - 1]] command. > > OK. Then I think we're back to the problem being that you are referencing > "char" before you ever assign any value to it. The error I get is: > > Please enter numbers or text to be converted. 1234 > Traceback (most recent call last): > File "multivert.py", line 33, in ? > if char in number: > NameError: name 'char' is not defined > > What do you expect the variable "char" to contain? A single character of > the user's input string, one character at a time until you reach the end of > the string? > > If so, you're going to need a line like this somewhere just before you > reference "char": > > for char in original: > > I've not checked this, but it would probably go just before your "if char > in number" statement. thanks, that looks like it might work. > Also, I don't know the details of the problem you're trying to solve, but > there are more mathematical ways of converting numbers from one base to > another that would not require you to include long lists of > all the > possible conversions in your program. basically, i'm writing a program to convert text into binary into hexadecimal in all the possible combinations of those (text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text). while more mathematical possibilities no doubt exist, i'm not up to delving into 'math' right at this moment. also, i wanted to make it work without importing too many things. "n thats the way the cookie crumbles" America's Favorite Cookie From Dragonfirebane at aol.com Tue Jun 8 18:01:20 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 8 18:01:38 2004 Subject: [Tutor] Re: number conversion problem (was: Re: [no subject]) Message-ID: <2AFB0126.40B70B18.34E997B7@aol.com> In a message dated 6/8/2004 5:17:15 PM Eastern Daylight Time, lsloan-000002@umich.edu writes: > What do you expect the variable "char" to contain? A single character of > the user's input string, one character at a time until you reach the end of > the string? > > If so, you're going to need a line like this somewhere just > before you > reference "char": > > for char in original: I tried this, and it wouldn't let me run the program and highlighted the closing quote as the culprit, claiming invalid syntax . . . "n thats the way the cookie crumbles" America's Favorite Cookie From dyoo at hkn.eecs.berkeley.edu Tue Jun 8 19:54:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jun 8 19:54:28 2004 Subject: [Tutor] Re: number conversion problem (was: Re: [no subject]) In-Reply-To: <2AFB0126.40B70B18.34E997B7@aol.com> Message-ID: On Tue, 8 Jun 2004 Dragonfirebane@aol.com wrote: > In a message dated 6/8/2004 5:17:15 PM Eastern Daylight Time, > lsloan-000002@umich.edu writes: > > > What do you expect the variable "char" to contain? A single character > > of the user's input string, one character at a time until you reach > > the end of the string? > > > > If so, you're going to need a line like this somewhere just before you > > reference "char": > > > > for char in original: > > I tried this, and it wouldn't let me run the program and highlighted the > closing quote as the culprit, claiming invalid syntax . . . Hi Dargonefirebane, Can you show us the exact error message? The most common occurrence of this error is due to mismatched quotes. Here is one example of such an error: ### >>> ['a','b','c','d','e','f','g', h'] File "", line 1 ['a','b','c','d','e','f','g', h'] ^ SyntaxError: EOL while scanning single-quoted string ### A missing quote character will do this. And since the program has tables full of string constants, I wouldn't be surprised if one of the entries were mistyped. Computers are much much better about seeing syntax problems than us humans. If the Python system claims that there's a SyntaxError, then it's not just a claim: there IS a syntax error lurking somewhere in that program. *grin* Going back to the comment: > > for char in original: > > I tried this, and it wouldn't let me run the program and highlighted the > closing quote as the culprit, claiming invalid syntax . . . When the 'for' loop was first introduced into the program, it's all too easy to inadvertantly drop or introduce an extra quote. One extra character or one accidental backspace can do it. Computer programs are pretty finicky about details like this. It may be a stupid syntax error (like a missing quote), but that's something that's very easy to do, so I wouldn't take it personally. Try it again, and see if you get the same error message. If you ever see an error message that makes no sense, don't ignore it, but feel free to show it to the folks on Tutor. From Dragonfirebane at aol.com Tue Jun 8 20:04:40 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 8 20:05:15 2004 Subject: [Tutor] Re: number conversion problem (was: Re: [no subject]) Message-ID: <22ED608A.3CCD80AC.34E997B7@aol.com> In a message dated 6/8/2004 7:54:21 PM Eastern Daylight Time, dyoo@hkn.eecs.berkeley.edu writes: > On Tue, 8 Jun 2004 Dragonfirebane@aol.com wrote: > > > In a message dated 6/8/2004 5:17:15 PM Eastern Daylight Time, > > lsloan-000002@umich.edu writes: > > > > > What do you expect the variable "char" to contain? A single character > > > of the user's input string, one character at a time until you reach > > > the end of the string? > > > > > > If so, you're going to need a line like this somewhere just before you > > > reference "char": > > > > > > for char in original: > > > > I tried this, and it wouldn't let me run the program and highlighted the > > closing quote as the culprit, claiming invalid syntax . . . > > > Hi Dargonefirebane, > > > Can you show us the exact error message? The most common occurrence of > this error is due to mismatched quotes. > > > Here is one example of such an error: > ### > >>> ['a','b','c','d','e','f','g', h'] > File "", line 1 > ['a','b','c','d','e','f','g', h'] > ^ > SyntaxError: EOL while scanning single-quoted string > ### > > > A missing quote character will do this. And since the program has tables > full of string constants, I wouldn't be surprised if one of the entries > were mistyped. > > Computers are much much better about seeing syntax problems than us > humans. If the Python system claims that there's a SyntaxError, then it's > not just a claim: there IS a syntax error lurking somewhere in that > program. *grin* > > > Going back to the comment: > > > > for char in original: > > > > I tried this, and it wouldn't let me run the program and highlighted the > > closing quote as the culprit, claiming invalid syntax . . . > > When the 'for' loop was first introduced into the program, it's all too > easy to inadvertantly drop or introduce an extra quote. One extra > character or one accidental backspace can do it. Computer programs are > pretty finicky about details like this. It may be a stupid syntax error > (like a missing quote), but that's something that's very easy to do, so I > wouldn't take it personally. > > > Try it again, and see if you get the same error message. If you ever see > an error message that makes no sense, don't ignore it, but > feel free to > show it to the folks on Tutor. I think you might have misunderstood. It highlighted the end quote on [reference 'char':]. And since the number converted works fine, the only other possible mis-typed quote would have to be in alphabet[] but there are none there. "n thats the way the cookie crumbles" America's Favorite Cookie From glingl at aon.at Tue Jun 8 20:43:23 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Jun 8 20:42:42 2004 Subject: [Tutor] Re: number conversion problem (was: Re: [no subject]) In-Reply-To: <556A620E.588A3117.34E997B7@aol.com> References: <556A620E.588A3117.34E997B7@aol.com> Message-ID: <40C65D2B.5040402@aon.at> Dragonfirebane@aol.com schrieb: >basically, i'm writing a program to convert text into binary into hexadecimal in all the possible combinations of those (text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text). while more mathematical possibilities no doubt exist, i'm not up to delving into 'math' right at this moment. also, i wanted to make it work without importing too many things. > > > Hi Dragonfirebane! I see a problem in your problem statement: You want to make the following conversions: text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text Incidentally, if you output a number you always oputput a string-representation of a number, and you want to get representations of the same number with different bases (2, 16, *and* 10 --- what you called 'text'). In fact all those are texts. But there is a number (behind the scenes), which is - I suppose - stored as a binary number in the computer-memory. The default way to output this number Python uses is in decimal format. If you want to make conversions of the sort bin - hex you have to convert a binary representation of some number into the number (the value) and then this value again into a string representation with some other base. In fact Python has a built in function, which converts the string-representation of a number with an arbitrary base < 36 into a number: >>> int("ff",16) 255 >>> int("1111",2) 15 >>> int("1001",10) 1001 ;-) The interactive Python interpreter doesn't use quotes '...' when printing (the decimal representations of) numbers in order to show that these are stored internally as number objects, and knowing that we cannot think of numbers without using a representation ... (confusing?). And moreover knowing, that the decimal representation is the only one we are accustomed to ... Unfortunately Python - as far as I know - does not have the reverse function, e.g. numstr, which would work like: >>> num2str(255,16) 'ff' >>> num2str(15,2) '1111' etc. With such a function we easily could get something like def convert(number_representation, from_base, to_base): number = int(number_representation, from_base) return num2str(number, to_base) I fear, that this 'explanation' raises more questions than it solves- so I'll stop here. Feel free to ask more questions on this, if you like. Certainly there are people listening and writing to this list, who will help to clarify those things much better than I can .... Gregor From Dragonfirebane at aol.com Tue Jun 8 21:22:48 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 8 21:23:01 2004 Subject: [Tutor] Re: number conversion problem (was: Re: [no subject]) Message-ID: <4C0B3692.4C2CD214.34E997B7@aol.com> In a message dated 6/8/2004 8:43:23 PM Eastern Daylight Time, glingl@aon.at writes: > Dragonfirebane@aol.com schrieb: > > >basically, i'm writing a program to convert text into binary into hexadecimal in all the possible combinations of those (text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text). while more mathematical possibilities no doubt exist, i'm not up to delving into 'math' right at this moment. also, i wanted to make it work without importing too many things. > > > > > > > Hi Dragonfirebane! > I see a problem in your problem statement: > You want to make the following conversions: > > text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text > > Incidentally, if you output a number you always oputput > a string-representation of a number, and you want to get > representations of the same number with different bases (2, 16, > *and* 10 --- what you called 'text'). In fact all those are texts. But > there is a number (behind the scenes), which is - I suppose - > stored as a binary number in the computer-memory. > > The default way to output this number Python uses is in decimal format. > If you want to make conversions of the sort bin - hex you have > to convert a binary representation of some number into the number > (the value) and then this value again into a string representation > with some other base. > > In fact Python has a built in function, which converts the > string-representation of a number with an arbitrary base < 36 > into a number: > > >>> int("ff",16) > 255 > >>> int("1111",2) > 15 > >>> int("1001",10) > 1001 ;-) > > The interactive Python interpreter doesn't use quotes '...' when > printing (the decimal representations of) numbers in order > to show that these are stored internally as number objects, > and knowing that we cannot think of numbers without using a > representation ... (confusing?). And moreover knowing, that > the decimal representation is the only one we are > accustomed to ... > > Unfortunately Python - as far as I know - does not have > the reverse function, e.g. numstr, which would work like: > > >>> num2str(255,16) > 'ff' > >>> num2str(15,2) > '1111' > > etc. > > With such a function we easily could get something like > > def convert(number_representation, from_base, to_base): > number = int(number_representation, from_base) > return num2str(number, to_base) > > > I fear, that this 'explanation' raises more questions than > it solves- so I'll stop here. Feel free to ask more > questions on this, if you like. Certainly there are > people listening and writing to this list, who will > help to clarify those things much better than I can .... > > Gregor I appreciate the explanation and subsequent Python examples, and I may very well end up using them, but i prefer to code using as little pre-existing modules as possible, at least while i'm still learning the language. "n thats the way the cookie crumbles" America's Favorite Cookie From Dragonfirebane at aol.com Tue Jun 8 21:33:33 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 8 21:33:41 2004 Subject: [Tutor] Re: number conversion problem (was: Re: [no subject]) Message-ID: <217B7EE2.0729EF5B.34E997B7@aol.com> In a message dated 6/8/2004 8:43:23 PM Eastern Daylight Time, glingl@aon.at writes: > Dragonfirebane@aol.com schrieb: > > >basically, i'm writing a program to convert text into binary into hexadecimal in all the possible combinations of those (text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text). while more mathematical possibilities no doubt exist, i'm not up to delving into 'math' right at this moment. also, i wanted to make it work without importing too many things. > > > > > > > Hi Dragonfirebane! > I see a problem in your problem statement: > You want to make the following conversions: > > text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text > > Incidentally, if you output a number you always oputput > a string-representation of a number, and you want to get > representations of the same number with different bases (2, 16, > *and* 10 --- what you called 'text'). In fact all those are texts. But > there is a number (behind the scenes), which is - I suppose - > stored as a binary number in the computer-memory. > > The default way to output this number Python uses is in decimal format. > If you want to make conversions of the sort bin - hex you have > to convert a binary representation of some number into the number > (the value) and then this value again into a string representation > with some other base. > > In fact Python has a built in function, which converts the > string-representation of a number with an arbitrary base < 36 > into a number: > > >>> int("ff",16) > 255 > >>> int("1111",2) > 15 > >>> int("1001",10) > 1001 ;-) > > The interactive Python interpreter doesn't use quotes '...' when > printing (the decimal representations of) numbers in order > to show that these are stored internally as number objects, > and knowing that we cannot think of numbers without using a > representation ... (confusing?). And moreover knowing, that > the decimal representation is the only one we are > accustomed to ... > > Unfortunately Python - as far as I know - does not have > the reverse function, e.g. numstr, which would work like: > > >>> num2str(255,16) > 'ff' > >>> num2str(15,2) > '1111' > > etc. > > With such a function we easily could get something like > > def convert(number_representation, from_base, to_base): > number = int(number_representation, from_base) > return num2str(number, to_base) > > > I fear, that this 'explanation' raises more questions than > it solves- so I'll stop here. Feel free to ask more > questions on this, if you like. Certainly there are > people listening and writing to this list, who will > help to clarify those things much better than I can .... > > Gregor also, to clarify: by text i meant alphabet . . . i failed to include decimal numbers in my explanation. What i am truly attempting to do is text-num,text-bin,text-hex,num-text,num-bin,num-hex,bin-text,bin-hex,bin-num,hex-text,hex-bin,hex-num. "n thats the way the cookie crumbles" America's Favorite Cookie From game at gameweave.com Wed Jun 9 01:07:49 2004 From: game at gameweave.com (K J) Date: Wed Jun 9 01:04:30 2004 Subject: [Tutor] While loop problem Message-ID: <000e01c44ddf$b63b4580$30e57218@basp.phub.net.cable.rogers.com> I can't seem to figure out how to make a while loop check for more then one thing. I want the while loop to check for both y and Y and return them true while ever thing else is false. Thanks Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040609/c8278683/attachment.html From gew75 at hotmail.com Wed Jun 9 01:44:22 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Wed Jun 9 01:44:35 2004 Subject: [Tutor] While loop problem References: <000e01c44ddf$b63b4580$30e57218@basp.phub.net.cable.rogers.com> Message-ID: Hi Kevin, Something like while response in 'yY': # do stuff ? Glen ----- Original Message ----- From: K J To: tutor@python.org Sent: Wednesday, June 09, 2004 3:07 PM Subject: [Tutor] While loop problem I can't seem to figure out how to make a while loop check for more then one thing. I want the while loop to check for both y and Y and return them true while ever thing else is false. Thanks Kevin _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From game at gameweave.com Wed Jun 9 01:59:25 2004 From: game at gameweave.com (K J) Date: Wed Jun 9 01:56:06 2004 Subject: [Tutor] While loop problem References: <000e01c44ddf$b63b4580$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <000501c44de6$eb838b60$30e57218@basp.phub.net.cable.rogers.com> Well sorta I want it to be able to to look for anthing like Kevin or kevin while name != 'Kevin': #That only checks for Kevin and not kevin ----- Original Message ----- From: "Glen Wheeler" To: "K J" ; Sent: Wednesday, June 09, 2004 1:44 AM Subject: Re: [Tutor] While loop problem > > Hi Kevin, > > Something like > > while response in 'yY': > # do stuff > > ? > > Glen > > ----- Original Message ----- > From: K J > To: tutor@python.org > Sent: Wednesday, June 09, 2004 3:07 PM > Subject: [Tutor] While loop problem > > > I can't seem to figure out how to make a while loop check for more then one > thing. > > I want the while loop to check for both y and Y and return them true while > ever thing else is false. > > Thanks > > Kevin > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From gew75 at hotmail.com Wed Jun 9 02:00:22 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Wed Jun 9 02:00:29 2004 Subject: [Tutor] While loop problem References: <000e01c44ddf$b63b4580$30e57218@basp.phub.net.cable.rogers.com> <000501c44de6$eb838b60$30e57218@basp.phub.net.cable.rogers.com> Message-ID: This really depends on the given situation. In this case, I'd say use string.lower(): while name.lower == 'kevin': # ... You could use a list to hold all the possible responses, all in lowercase and use a similar construct: valid = ['jim','bob'] while name.lower() in valid: # ... Is that better? Glen ----- Original Message ----- From: "K J" To: Sent: Wednesday, June 09, 2004 3:59 PM Subject: Re: [Tutor] While loop problem > Well sorta I want it to be able to to look for anthing like > Kevin or kevin > > while name != 'Kevin': #That only checks for Kevin and not kevin > > ----- Original Message ----- > From: "Glen Wheeler" > To: "K J" ; > Sent: Wednesday, June 09, 2004 1:44 AM > Subject: Re: [Tutor] While loop problem > > > > > > Hi Kevin, > > > > Something like > > > > while response in 'yY': > > # do stuff > > > > ? > > > > Glen > > > > ----- Original Message ----- > > From: K J > > To: tutor@python.org > > Sent: Wednesday, June 09, 2004 3:07 PM > > Subject: [Tutor] While loop problem > > > > > > I can't seem to figure out how to make a while loop check for more then > one > > thing. > > > > I want the while loop to check for both y and Y and return them true while > > ever thing else is false. > > > > Thanks > > > > Kevin > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From game at gameweave.com Wed Jun 9 02:12:35 2004 From: game at gameweave.com (K J) Date: Wed Jun 9 02:09:15 2004 Subject: [Tutor] While loop problem References: <000e01c44ddf$b63b4580$30e57218@basp.phub.net.cable.rogers.com><000501c44de6$eb838b60$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <000501c44de8$c26b9b80$30e57218@basp.phub.net.cable.rogers.com> Ya that help alot thanks. ----- Original Message ----- From: "Glen Wheeler" To: Sent: Wednesday, June 09, 2004 2:00 AM Subject: Re: [Tutor] While loop problem > > This really depends on the given situation. > > In this case, I'd say use string.lower(): > > while name.lower == 'kevin': > # ... > > You could use a list to hold all the possible responses, all in lowercase > and use a similar construct: > > valid = ['jim','bob'] > > while name.lower() in valid: > # ... > > Is that better? > > Glen > > ----- Original Message ----- > From: "K J" > To: > Sent: Wednesday, June 09, 2004 3:59 PM > Subject: Re: [Tutor] While loop problem > > > > Well sorta I want it to be able to to look for anthing like > > Kevin or kevin > > > > while name != 'Kevin': #That only checks for Kevin and not kevin > > > > ----- Original Message ----- > > From: "Glen Wheeler" > > To: "K J" ; > > Sent: Wednesday, June 09, 2004 1:44 AM > > Subject: Re: [Tutor] While loop problem > > > > > > > > > > Hi Kevin, > > > > > > Something like > > > > > > while response in 'yY': > > > # do stuff > > > > > > ? > > > > > > Glen > > > > > > ----- Original Message ----- > > > From: K J > > > To: tutor@python.org > > > Sent: Wednesday, June 09, 2004 3:07 PM > > > Subject: [Tutor] While loop problem > > > > > > > > > I can't seem to figure out how to make a while loop check for more then > > one > > > thing. > > > > > > I want the while loop to check for both y and Y and return them true > while > > > ever thing else is false. > > > > > > Thanks > > > > > > Kevin > > > > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From visional_freeman at yahoo.com Wed Jun 9 04:01:39 2004 From: visional_freeman at yahoo.com (Ivan low) Date: Wed Jun 9 04:01:46 2004 Subject: [Tutor] Value asign to random.randrange In-Reply-To: <000501c44de8$c26b9b80$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <20040609080139.47239.qmail@web41501.mail.yahoo.com> Hi, I was thinking to asign some value to the program, when random number was generated, that number will be a question that ask the user. I found it hard to asign number to my qustion. Does anybody know how to go about this? Ivan From gew75 at hotmail.com Wed Jun 9 04:36:41 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Wed Jun 9 04:36:56 2004 Subject: [Tutor] Value asign to random.randrange References: <20040609080139.47239.qmail@web41501.mail.yahoo.com> Message-ID: How about; number = random.randint(1,10) # number between 1 and 10 number = str(number) # for comparing the number and the user's guess answer = '' while answer != number: answer = raw_input("What is your guess? ") print "Correct!" It has some flaws, but you can work those out ;). Glen ----- Original Message ----- From: "Ivan low" To: Sent: Wednesday, June 09, 2004 6:01 PM Subject: [Tutor] Value asign to random.randrange > Hi, I was thinking to asign some value to the program, > when random number was generated, that number will be > a question that ask the user. I found it hard to asign > number to my qustion. Does anybody know how to go > about this? > > Ivan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From orbitz at ezabel.com Wed Jun 9 11:50:23 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Wed Jun 9 11:52:06 2004 Subject: [Tutor] While loop problem In-Reply-To: <000e01c44ddf$b63b4580$30e57218@basp.phub.net.cable.rogers.com> References: <000e01c44ddf$b63b4580$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <20040609115023.022f3bb8.orbitz@ezabel.com> while x != y and z == a or not b: On Wed, 9 Jun 2004 01:07:49 -0400 "K J" wrote: > I can't seem to figure out how to make a while loop check for more then one > thing. > > I want the while loop to check for both y and Y and return them true while > ever thing else is false. > > Thanks > > Kevin From michele.alzetta at aliceposta.it Wed Jun 9 17:25:19 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Wed Jun 9 17:22:31 2004 Subject: [Tutor] python $i equivalent ? Message-ID: <1086816319.25455.16.camel@localhost> Suppose I wanted to create numerous instances of a class and name each istance according to an element in a list ? for element in list: element = Class() doesn't work of course; I need something like the bash '$' stuff here for element in list: $element = Class() (of course this is neither bash nor python, I know !) How would this be done ? -- Michele Alzetta From tpc at csua.berkeley.edu Wed Jun 9 18:54:51 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Jun 9 18:55:06 2004 Subject: [Tutor] Python threads Message-ID: <20040609154936.Y45468-100000@localhost.name> hi everybody, I have created a function called determinePlaytimeInSeconds that, given a tuple of, say, 20 tuples consisting of filename and URI: (('filename01', 'http://hostname/audio/filename01.mp3'), ('filename02', 'http://hostname/audio/filename02.mp3'), ('filename03', 'http://hostname/video/filename03.wmv'), etc...) passes each tuple to a threaded class called FileReader. However, for some unknown reason, when I run the script I sometimes (though not always) get a strange error message: AttributeError: 'FileReader' object has no attribute 'playtimeInSeconds' or AttributeError: 'FileReader' object has no attribute 'fileType' I somehow think this error has something to do with the thread not sleeping; however, when I don't comment out the activeCount and sleep code, the script just hangs. I used the example code at: http://starship.python.net/crew/aahz/OSCON2000/SCRIPT3.HTM What am I doing wrong ? import urllib from threading import Thread from threading import activeCount from time import sleep def determinePlayTimeInSeconds(results): threadList = [] for result in results: fileReader = FileReader(result) fileReader.start() threadList.append(fileReader) #while activeCount() > 1: #sleep(1) for fileReader in threadList: (fileType, playtimeInSeconds) = fileReader.getPlaytimeInSeconds() print fileType, playtimeInSeconds class FileReader(Thread): def __init__(self, result): self.fileName = result[0] self.fileURI = result[1] Thread.__init__(self) def run(self): if self.fileURI.endswith("mp3"): self.fileType = "Audio" self.playtimeInSeconds = (len(urllib.urlopen(urllib.quote(self.fileURI, ':/')).read()) * 8) / 24000 elif self.fileURI.endswith("wmv"): self.fileType = "Video" self.playtimeInSeconds = get_asf_time(urllib.urlopen(urllib.quote(self.fileURI, ':/'))) def getPlaytimeInSeconds(self): return (self.fileType, self.playtimeInSeconds) Traceback (most recent call last): File "", line 1, in -toplevel- determinePlayTimeInSeconds(resultsTuple) File "", line 10, in determinePlayTimeInSeconds (fileType, playtimeInSeconds) = fileReader.getPlaytimeInSeconds() File "", line 14, in getPlaytimeInSeconds return (self.fileType, self.playtimeInSeconds) AttributeError: 'FileReader' object has no attribute 'fileType' From darnold02 at sprynet.com Wed Jun 9 19:09:08 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Wed Jun 9 19:09:11 2004 Subject: [Tutor] python $i equivalent ? In-Reply-To: <1086816319.25455.16.camel@localhost> Message-ID: The standard way of doing this is to store the instances in a dictionary, then access them by key. IDLE 1.0.2 >>> items = ['apple','boy','cantaloupe'] >>> myvars = {} >>> for item in items: myvars[item] = len(item) You now effectively have three variables named from the items in your list: >>> print myvars['apple'] 5 >>> print myvars['cantaloupe'] 10 >>> print myvars['boy'] 3 And you can use any legal dictionary key as a variable name, without its having to be a valid Python identifier: >>> myvars['not~a~legal~name'] = 42 >>> print myvars['not~a~legal~name'] 42 >>> HTH, Don -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Michele Alzetta Sent: Wednesday, June 09, 2004 4:25 PM To: Python Tutor Subject: [Tutor] python $i equivalent ? Suppose I wanted to create numerous instances of a class and name each istance according to an element in a list ? for element in list: element = Class() doesn't work of course; I need something like the bash '$' stuff here for element in list: $element = Class() (of course this is neither bash nor python, I know !) How would this be done ? -- Michele Alzetta _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jfabiani at yolo.com Thu Jun 10 03:30:30 2004 From: jfabiani at yolo.com (John Fabiani) Date: Thu Jun 10 03:27:24 2004 Subject: [Tutor] using ftplib Message-ID: <40C80E16.20105@yolo.com> Hi, I'm trying to follow the python 2.1 bible "transferring files via FTP". I'm using a XP, SUSE9.1, and a 4.1 FreeBSD OS's to learn on. import ftplib import sys #test FTP LOGIN remote=ftplib.FTP(host='63.204.66.140',user='username',passwd='password') remote.getwelcome() filename=open("C:\\brssoserv.prg",'rb') remote.sendcmd('PASV') remote.storbinary("STOR brssoserv.prg",filename) #myans=remote.size('booktown.sql') remote.close() the above code creates the file name "brssoserv.prg" with zero bytes on the FTP host. The first issue is the "remote.sendcmd('PASV')" is command unknown on the FreeBSD computer. What is the right command for the freeBSD computer running python 2.1 and how did you discover what the correct command is? Next I get the following error remote.storbinary("STOR johntest.log",filename) Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\ftplib.py", line 415, in storbinary conn = self.transfercmd(cmd) File "C:\Python23\lib\ftplib.py", line 345, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "C:\Python23\lib\ftplib.py", line 327, in ntransfercmd resp = self.sendcmd(cmd) File "C:\Python23\lib\ftplib.py", line 241, in sendcmd return self.getresp() File "C:\Python23\lib\ftplib.py", line 212, in getresp raise error_temp, resp error_temp: 425 192.168.1.195 The above error is from the windows computer on the same network as the FTP server. But I get similar errors from the other computers too. I believe the 425 is a clue and thats the local IP address. But the freeBSD does not give that the same error. I can use FTP from all the computers and using standard commands: FTP>passive FTP>binary FTP>put johntest.log all works without error. So I'm doing something wrong. I believe I am following the book but there has to be something I'm missing. BTW I have tried changing the 'STOR" to 'PUT' - again without success. Thanks in advance John From flaxeater at yahoo.com Thu Jun 10 10:49:59 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Jun 10 10:50:13 2004 Subject: [Tutor] python $i equivalent ? In-Reply-To: <1086816319.25455.16.camel@localhost> Message-ID: <20040610144959.41023.qmail@web52601.mail.yahoo.com> --- Michele Alzetta wrote: > Suppose I wanted to create numerous instances of a > class > and name each istance according to an element in a > list ? > > for element in list: > element = Class() > > doesn't work of course; I need something like the > bash '$' > stuff here > > for element in list: > $element = Class() > > (of course this is neither bash nor python, I know > !) > > How would this be done ? > Well you are right because the list manipulations inside the for loop is another namespace or scope, so any modifications are droped. This is just alittle irritating but atleast it's consistent. Here are two ways to do the list Assumption you have a list you need to iterate over to instantiate the lists properly alist=range(1,11) targetlist=[] for x in alist: targetlist.append(ClassInstanc(x)) This will take the targelist outside of the for loop namespace and append to it so you will have these changes outside of the for loop. This is a method I use often. (Standard Warning) This is a destructive way to iterate over a list it uses the iterator method enumerate() look it up in the docs for a full description. alist=range(1,101) #this the original list for number, value in enumrate(alist): alist[number]=Class(value) when this is done the original list will be gone and in the place of each member will be your class. Python is cool in the manner in wich it unpacks these variables enumerates returns the value and the index number of each list slice. This way you can use it to do usefull stuff. The old way of doing this was this for x in range(0,len(alist)): alist[x]=Class(alist[x]) As as usuall feel free to ask further questions. Good Luck __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From flaxeater at yahoo.com Thu Jun 10 11:00:25 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Jun 10 11:01:32 2004 Subject: [Tutor] using ftplib In-Reply-To: <40C80E16.20105@yolo.com> Message-ID: <20040610150025.92413.qmail@web52609.mail.yahoo.com> --- John Fabiani wrote: > Hi, > I'm trying to follow the python 2.1 bible > "transferring files via FTP". > I'm using a XP, SUSE9.1, and a 4.1 FreeBSD OS's to > learn on. > > import ftplib > import sys > #test FTP LOGIN > remote=ftplib.FTP(host='63.204.66.140',user='username',passwd='password') > remote.getwelcome() > filename=open("C:\\brssoserv.prg",'rb') > remote.sendcmd('PASV') > remote.storbinary("STOR brssoserv.prg",filename) > #myans=remote.size('booktown.sql') > remote.close() > > the above code creates the file name "brssoserv.prg" > with zero bytes on > the FTP host. The first issue is the > "remote.sendcmd('PASV')" is command > unknown on the FreeBSD computer. What is the right > command for the > freeBSD computer running python 2.1 and how did you > discover what the > correct command is? > > Next I get the following error > remote.storbinary("STOR johntest.log",filename) > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\ftplib.py", line 415, in > storbinary > conn = self.transfercmd(cmd) > File "C:\Python23\lib\ftplib.py", line 345, in > transfercmd > return self.ntransfercmd(cmd, rest)[0] > File "C:\Python23\lib\ftplib.py", line 327, in > ntransfercmd > resp = self.sendcmd(cmd) > File "C:\Python23\lib\ftplib.py", line 241, in > sendcmd > return self.getresp() > File "C:\Python23\lib\ftplib.py", line 212, in > getresp > raise error_temp, resp > error_temp: 425 192.168.1.195 > > The above error is from the windows computer on the > same network as the > FTP server. But I get similar errors from the other > computers too. I > believe the 425 is a clue and thats the local IP > address. But the > freeBSD does not give that the same error. > > I can use FTP from all the computers and using > standard commands: > FTP>passive > FTP>binary > FTP>put johntest.log > > all works without error. So I'm doing something > wrong. I believe I am > following the book but there has to be something I'm > missing. > BTW I have tried changing the 'STOR" to 'PUT' - > again without success. > Thanks in advance > John Ok I don't see anything wrong with you code. HOwever it turns out 425 is an ftp error sent by the server. Look at this http://www.netsys.com/fwtk/2000/02/msg00042.html Has a thread on it which may be relevant also this http://www.jsiinc.com/SUBF/TIP2900/rh2936.htm Perhaps you should try the PUT command instead. Good luck. __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From John.Ertl at fnmoc.navy.mil Thu Jun 10 14:00:59 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Jun 10 13:56:26 2004 Subject: [Tutor] UCS4 Message-ID: All, I have not run into this before but I am working on a new system. I have Python 2.3.4 installed and running basic stuff. I also have mod_python up and running but now am trying to use ZSI and mod_python and I am getting the following error. ImportError: /usr/lib/python2.3/site-packages/_xmlplus/parsers/pyexpat.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8 >From what I can gather when I googled this it sounds like is should only be a problem if the modules are pre compiled like an RPM? I have reinstalled PyXML-0.8.3 (usual setup.py build and install). Are C libraries or something causing a problem? Is there away to get around this or do not even have the foggiest idea of what is going on? My system is UCS4. Thanks, John Ertl From paul at basilisk.ukfsn.org Thu Jun 10 14:56:34 2004 From: paul at basilisk.ukfsn.org (Paul Worrall) Date: Thu Jun 10 14:59:18 2004 Subject: [Tutor] python $i equivalent ? In-Reply-To: <1086816319.25455.16.camel@localhost> References: <1086816319.25455.16.camel@localhost> Message-ID: <200406101956.34159.paul@basilisk.ukfsn.org> On Wednesday 09 Jun 2004 22:25, Michele Alzetta wrote: > Suppose I wanted to create numerous instances of a class > and name each istance according to an element in a list ? > > for element in list: > element = Class() > > doesn't work of course; I need something like the bash '$' > stuff here > > for element in list: > $element = Class() > > (of course this is neither bash nor python, I know !) > > How would this be done ? Does this do what you want? for element in list: exec element + " = Class()" this compiles a Python statement as a string and passes it to the exec built-in function for execution. list should contain only strings. -- Paul From flaxeater at yahoo.com Thu Jun 10 16:18:28 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Jun 10 16:18:35 2004 Subject: [Tutor] using ftplib In-Reply-To: <40C8B52C.1070202@yolo.com> Message-ID: <20040610201828.18842.qmail@web52604.mail.yahoo.com> > The link explain something regarding a return port. > So how does one > setup the return port??? > John the impression I got from the board thread is that there's possibly a bug in the ftpserver. __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From dyoo at hkn.eecs.berkeley.edu Thu Jun 10 16:56:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 10 16:57:06 2004 Subject: [Tutor] python $i equivalent ? In-Reply-To: <200406101956.34159.paul@basilisk.ukfsn.org> Message-ID: On Thu, 10 Jun 2004, Paul Worrall wrote: > On Wednesday 09 Jun 2004 22:25, Michele Alzetta wrote: > > Suppose I wanted to create numerous instances of a class > > and name each istance according to an element in a list ? > > > > for element in list: > > element = Class() > > > > doesn't work of course; I need something like the bash '$' > > stuff here > > > > for element in list: > > $element = Class() > > > > (of course this is neither bash nor python, I know !) > > > > How would this be done ? > > Does this do what you want? > > for element in list: > exec element + " = Class()" > > this compiles a Python statement as a string and passes it to the exec > built-in function for execution. list should contain only strings. Hi Paul, Exec/eval, in this case, has a few points against it. One is that, from a readability standpoint, it's not so nice for people. Let's look at the code again: ### for element in list: exec element + " = Class()" ### It's not immediately clear what new variable names are being introduced without looking at the content of 'list'. If the content of 'list' is from a file, then there's no way to know up front what variables are coming in. It's also unsafe --- as Don Arnold mentioned earlier in the thread: > And you can use any legal dictionary key as a variable name, without its > having to be a valid Python identifier: > > >>> myvars['not~a~legal~name'] = 42 > >>> print myvars['not~a~legal~name'] > 42 In particular, there are a few reserved "keywords" that aren't allowed as Python variable names. Things like 'pass', for example, can't be used as variable names, but they could be perfectly legitimate elements in Michele's list. So the code: ### for element in list: exec element + " = Class()" ### might work or might not work, depending on the content of the 'list'. We could easily get SyntaxError from the code above. (There's also the huge security risk of exec/eval which we can talk about later... *grin*) The dictionary approach: ### myvars = {} for element in list: myvars[element] = Class() ### dodges these problems, which is why it's the approach that we'll push hard. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Jun 10 18:14:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 10 18:14:28 2004 Subject: [Tutor] Python threads In-Reply-To: <20040609154936.Y45468-100000@localhost.name> Message-ID: On Wed, 9 Jun 2004 tpc@csua.berkeley.edu wrote: > I have created a function called determinePlaytimeInSeconds that, given a > tuple of, say, 20 tuples consisting of filename and URI: > > (('filename01', 'http://hostname/audio/filename01.mp3'), ('filename02', > 'http://hostname/audio/filename02.mp3'), ('filename03', > 'http://hostname/video/filename03.wmv'), etc...) > > passes each tuple to a threaded class called FileReader. Hi Tpc, I have to ask a silly question: why is the class threaded? I don't see the need for the threading here. Since threaded programming can be complicated, it might be a better idea to avoid it for this particular problem. Jon Ousterhout (creator of Tcl) has said that threads are the wrong tool for many coding problems: http://home.pacbell.net/ouster/threads.pdf And if he says threads are hard, that's a bad sign. *grin* Anyway, let's look at the code. > def determinePlayTimeInSeconds(results): > threadList = [] > for result in results: > fileReader = FileReader(result) > fileReader.start() Ok, so a new 'thread' called fileReader starts up. > threadList.append(fileReader) > #while activeCount() > 1: > #sleep(1) > for fileReader in threadList: > (fileType, playtimeInSeconds) = fileReader.getPlaytimeInSeconds() The problem here is that there is no guarantee that fileReader has started processing files by the time we get to the expression: fileReader.getPlaytimeInSeconds() If we want to maintain the threading paradigm, we need to use "synchronization". That is, we need to set up some kind of traffic cop that will cause our program to wait until the fileReader has finished processing the file. In pseudocode, we'd write something like: while fileReader hasn't finished processing yet: wait until it has notified us that it's done fileReader.getPlaytimeInSeconds() These 'synchronization' primitives live in the 'threading' module, and are named things like 'Condition' or 'Lock' or 'Semaphore': http://www.python.org/doc/current/lib/module-threading.html and we'd use these synchronization objects to implement the idea of "wait until the fileReader is done"... but, again, this seems like overkill to attack this problem with threads. Can you do it without them? If you really really want to use threads, we can continue talking about it, but I just get the feeling that the complexity just isn't worth it here. Good luck! From tpc at csua.berkeley.edu Thu Jun 10 19:10:11 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Jun 10 19:10:20 2004 Subject: [Tutor] Python threads In-Reply-To: Message-ID: <20040610154930.U57016-100000@localhost.name> On Thu, 10 Jun 2004, Danny Yoo wrote: > I have to ask a silly question: why is the class threaded? I don't see > the need for the threading here. Since threaded programming can be > complicated, it might be a better idea to avoid it for this particular > problem. > hi Danny, I created an application that indexes .mp3 and .wmv files and, depending on user input, returns the files that have the corresponding words in the filename, along with the file category (i.e., Audio or Video) and the time-duration of the file. I noticed a marked increase in the time it took from the moment the user pressed 'Submit' to the results appearing in the browser when I ported my application from Redhat Linux 9/Fedora Core 1/Fedora Core 2 to Debian Linux. I used hotshot profiler to arrive at an average of 2.302 seconds for the former to 42.315 seconds for the latter. The reason I had to go the multithreaded route was because I went to: http://www.python.org/doc/current/lib/module-urllib.html and at the bottom of the page you will notice: "The urlopen() and urlretrieve() functions can cause arbitrarily long delays while waiting for a network connection to be set up. This means that it is difficult to build an interactive Web client using these functions without using threads." From orbitz at ezabel.com Thu Jun 10 19:36:36 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Thu Jun 10 19:38:32 2004 Subject: [Tutor] Python threads In-Reply-To: <20040610154930.U57016-100000@localhost.name> References: <20040610154930.U57016-100000@localhost.name> Message-ID: <20040610193636.24c4c180.orbitz@ezabel.com> Doing things asynchronously is easy with twisted. http://www.twistedmatrix.com/ On Thu, 10 Jun 2004 16:10:11 -0700 (PDT) wrote: > > > On Thu, 10 Jun 2004, Danny Yoo wrote: > > > I have to ask a silly question: why is the class threaded? I don't see > > the need for the threading here. Since threaded programming can be > > complicated, it might be a better idea to avoid it for this particular > > problem. > > > > hi Danny, I created an application that indexes .mp3 and .wmv files > and, depending on user input, returns the files that have the > corresponding words in the filename, along with the file category > (i.e., Audio or Video) and the time-duration of the file. I noticed a > marked increase in the time it took from the moment the user pressed > 'Submit' to the results appearing in the browser when I ported > my application from Redhat Linux 9/Fedora Core 1/Fedora Core 2 to > Debian Linux. I used hotshot profiler to arrive at an average of 2.302 > seconds for the former to 42.315 seconds for the latter. The reason I > had to go the multithreaded route was because I went to: > > http://www.python.org/doc/current/lib/module-urllib.html > > and at the bottom of the page you will notice: > > "The urlopen() and urlretrieve() functions can cause arbitrarily long > delays while waiting for a network connection to be set up. This means > that it is difficult to build an interactive Web client using these > functions without using threads." > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From michael at mphpress.com Thu Jun 10 21:03:20 2004 From: michael at mphpress.com (Michael P. Hopcroft) Date: Thu Jun 10 20:58:29 2004 Subject: [Tutor] Very, very new Message-ID: <40C904D8.8080202@mphpress.com> Gentles, Let me state that my only experience with Python has been as an end-user with programs that are programmed in Python. It had never ocured to me that i wanted to program in the langauge until now. Well, armed with the latest version of Python and a program idea that may be too difficult for me to accomplish myself, I was wondering if there was a good source that would teach me how to learn the language. One local group in the Portland area, free Geek, is already teaching me how to build computers. I'd like to be able to build programs too. Anyone have suggestions on a good textbook for that purpose, especially that would teach me how to work with graphical interfaces and with databases (the sort of thing you would find in a roleplaying game character generator). Michael Hopcroft P.S. Isn't the popular "PCGen" program written in Python as well? It doesn;t seem like what i want to do si unprecedented. From jfabiani at yolo.com Thu Jun 10 21:48:00 2004 From: jfabiani at yolo.com (John Fabiani) Date: Thu Jun 10 21:47:47 2004 Subject: [Tutor] using ftplib In-Reply-To: <20040610201818.18758.qmail@web52604.mail.yahoo.com> References: <20040610201818.18758.qmail@web52604.mail.yahoo.com> Message-ID: <40C90F50.4050105@yolo.com> Chad Crabtree wrote: >>The link explain something regarding a return port. >>So how does one >>setup the return port??? >>John >> >> > >the impression I got from the board thread is that >there's possibly a bug in the ftpserver. > > > > > >__________________________________ >Do you Yahoo!? >Friends. Fun. Try the all-new Yahoo! Messenger. >http://messenger.yahoo.com/ > > > > I have discovered more. I'm now able to send data to a windows FTP server. I found a great infomation site on FTP at "slacksite.com". They have a white paper on the differences between Active vs Passive FTP. And another site is www.dreamhaven.org/ftp-raw.html. To get the transfer to work I added the following remote.sendcmd('PASV') remote.set_pasv(0) The first sets the mode to passive at the server. And then I think the second sets the passive off. I know they are the appear to be opposites but it works and does not without the statments. Now I'm sure all of my issues have thing to do with active vs passive FTP. Now I need to understand how the 'PORT ' command work from within python ftplib. John From glingl at aon.at Fri Jun 11 00:42:13 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Jun 11 00:41:28 2004 Subject: [Tutor] 42 Message-ID: <40C93825.2010801@aon.at> What is the most convincing way to mimick this in Python? #include #define SIX 1 + 5 #define NINE 8 + 1 int main(void) { printf("What do you get if you multiply six by nine: %d\n", SIX * NINE); return 0; } Gregor From adeleinandjeremy at yahoo.com Fri Jun 11 01:32:01 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Fri Jun 11 01:32:08 2004 Subject: [Tutor] 42 In-Reply-To: <40C93825.2010801@aon.at> Message-ID: <20040611053201.79531.qmail@web50306.mail.yahoo.com> --- Gregor Lingl wrote: > What is the most convincing way to mimick this in Python? > > #include > > #define SIX 1 + 5 > #define NINE 8 + 1 > > int main(void) { > printf("What do you get if you multiply six by nine: %d\n", SIX * > NINE); > return 0; > } > print "What do you get if you multiply six by nine: %d" % 6 * 7 Or, if you absolutely must be silly and define names for digits (and sillier by using arithmetic to create the digits), the following: # oops - pretend you don't see that nine is set to 8 - 1 digits = {'six': 5 + 1, 'nine': 8 - 1} print "What do you get if you multiply six by nine: %d" % (digits['six'] * digits['nine']) # that was magic I don't think Python can duplicate this specific bug (yes, of course it's a bug) from C, at least not without using a C extension. I think that's probably a good thing. - Jeremy __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From roeland.rengelink at chello.nl Fri Jun 11 03:10:59 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Fri Jun 11 03:10:51 2004 Subject: [Tutor] 42 In-Reply-To: <40C93825.2010801@aon.at> References: <40C93825.2010801@aon.at> Message-ID: <40C95B03.8040804@chello.nl> Gregor Lingl wrote: > What is the most convincing way to mimick this in Python? > > #include > > #define SIX 1 + 5 > #define NINE 8 + 1 > > int main(void) { > printf("What do you get if you multiply six by nine: %d\n", SIX * > NINE); > return 0; > } Since macro's are substituted before compilation in C. You'd have to substitute before iterpretation in Python. This works: >>> SIX = '1+5' >>> NINE = '8+1' >>> eval('%s*%s' % (SIX, NINE)) 42 Have fun, Roeland From asc at vineyard.net Fri Jun 11 08:49:20 2004 From: asc at vineyard.net (Aaron Straup Cope) Date: Fri Jun 11 08:49:03 2004 Subject: [Tutor] creating bitmasks (for bloom filters) Message-ID: <1086958159.529.249.camel@localhost> Hi, A quick introduction : I am mostly a Perl hacker, but I am teaching myself Python because it seems like the right tool for the job in question. [1] I am not, by any stretch, much of a math weenie. I am trying to port the Bloom::Filter Perl module [2] for use with my tool. I know that there is a "pybloom" sourceforge project [3] but licensing issues aside it's reliance on Unix math libs makes it problematic for use with a cross-platform GUI tool. At this point, my not very deep grasp of Python and my poor understanding of some basic compsci/math principles have combined to frustrate my efforts. I was hoping that the the Perl/Python operator and function set would be similar enough that, with only a few modifications, I could clone the B:F.pm package pretty much "as is". All other bugs aside, I am stuck trying to create a bitmask of a key : "Given a key, hashes it using the list of salts and returns a bitmask the same length as the Bloom filter. Note that Perl will pad the bitmask out with zeroes so it's a muliple of 8." # from the docs for the _make_bitmask method Specifically, it's not clear to me : * how to map the various Perl pack/unpack formats to their Python equivalents (things like Perl's "b*" which is "a bit string, in ascending bit order inside each byte" where "*" means to use all the bytes from the input field") * how to account for the fact that unpack returns a list in Perl and Python returns a string * how to pass a salt to the Python sha module * how to XOR the pieces of an unpacked sha digest (which may simply be a function of a bad format unpacking stuff) * A 'vec' [4] function in Python; does one exist? In short, I don't really have any idea what I'm doing :-( As much as I relish the challenge purely on the grounds of learning new stuff I am starting to reach the point of irrational frustration and wanting to just get this done so I can move on to other things. The tool should be written in Python because it's the best choice for the job. The tool needs to be able to read/write Bloom Filters. Python needs a Bloom Filter library, so I will step up and write it. Except it appears to be beyond my skill level right now... Any thoughts, suggestions or clue-bats would be very much welcomed. Pointers to an already existing implementation that I've missed would be even better but I'll take what I can get. :-) Thanks, --- [1] http://aaronland.info/weblog/categories/s/socalled_w5_application_the/ [2] http://search.cpan.org/src/MCEGLOWS/Bloom-Filter-0.02/Filter.pm [3] http://cvs.sourceforge.net/viewcvs.py/pybloom/ [4] http://www.perldoc.com/perl5.8.4/pod/func/vec.html From gew75 at hotmail.com Fri Jun 11 09:12:52 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Fri Jun 11 09:12:59 2004 Subject: [Tutor] creating bitmasks (for bloom filters) References: <1086958159.529.249.camel@localhost> Message-ID: "Aaron Straup Cope" > Hi, > > A quick introduction : I am mostly a Perl hacker, but I am teaching > myself Python because it seems like the right tool for the job in > question. [1] I am not, by any stretch, much of a math weenie. > Not sure of your terminology here; does this mean you are mathematically inclined? Or not as such? > [..] Perhaps the source of pybloom would help? If it's only difference is reliance on the unix math libraries, then this could be changed easily enough...? Sorry I can't be of any more help. -- Glen From bvande at po-box.mcgill.ca Fri Jun 11 09:45:57 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Jun 11 09:49:03 2004 Subject: [Tutor] Very, very new In-Reply-To: <40C904D8.8080202@mphpress.com> References: <40C904D8.8080202@mphpress.com> Message-ID: <40C9B795.60606@po-box.mcgill.ca> Michael P. Hopcroft said unto the world upon 10/06/2004 21:03: > Gentles, > > Let me state that my only experience with Python has been as an > end-user with programs that are programmed in Python. It had never > ocured to me that i wanted to program in the langauge until now. > Well, armed with the latest version of Python and a program idea that > may be too difficult for me to accomplish myself, I was wondering if > there was a good source that would teach me how to learn the language. > One local group in the Portland area, free Geek, is already teaching me > how to build computers. I'd like to be able to build programs too. > Anyone have suggestions on a good textbook for that purpose, > especially that would teach me how to work with graphical interfaces and > with databases (the sort of thing you would find in a roleplaying game > character generator). > > Michael Hopcroft > > P.S. Isn't the popular "PCGen" program written in Python as well? It > doesn;t seem like what i want to do si unprecedented. Hi Michael, I'm still a relative newcomer myself and have never used a GUI in anger, but perhaps the following might help. 1) You've already found one of the best resources there is -- the tutor list. 2) There are quite a few on-line tutorials, ranging from quick guides to book length presentations. (I certainly haven't looked at them all.) You can find a collection of links for ones target at beginners here . Preferences vary, but for a gentle starting from the complete beginning, I thought Think Like a Computer Scientist was very good. Its aimed at high school students so it goes down very easily, but happily it does not condescend. It is also available as a printed book. But, for printed books, I think you can do better. To wit: 3) For physical books, I'd say start with Learning Python by Ascher and Lutz and once you have some skills get a copy of Martelli's Python in a Nutshell. Both are from O'Reilly. Both have some coverage of GUI, but neither are too focused on them, either. So, maybe someone else can recommend something for this. 4) You might also try surfing to , find bits of code that interest you and then work out how and why they do what they do. Hope that helps, Brian vdB From wilfred_y2003 at yahoo.com.sg Fri Jun 11 10:57:07 2004 From: wilfred_y2003 at yahoo.com.sg (=?iso-8859-1?q?Wilfred=20Y?=) Date: Fri Jun 11 10:57:16 2004 Subject: [Tutor] Question about the use of None Message-ID: <20040611145707.97582.qmail@web53903.mail.yahoo.com> Hi,I came across this keyword None. The document I read says "None is python's way of representing nothing. It evaluates to False when treated as a condition"So I assume, if I do start=None, then it's as good as saying start="" or start=0Now, the code to represent it's use is pretty confusing. It goes like this:start=Nonewhile start != "" start=raw_input("Press enter to exit, or key in a string: ")The confusing part is here, since start = "", then it should never be able to go into the while loop. (Well, at least that's if None is really == "")So to check, I tried this in the interactive window:start=Noneprint startand presto !! It prinst the string None, even though i haven't placed it in double quotes. So it seems None does have a value, which explains why it managed to enter the while loop. Is this correct ? Hope someone can help with an explanation. Thanks in advance folks !!-Wil Yahoo! Mobile - Download the latest ringtones, games, and more! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040611/9186ba41/attachment.html From Christian.Wyglendowski at greenville.edu Fri Jun 11 11:51:46 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Fri Jun 11 11:51:55 2004 Subject: [Tutor] 42 Message-ID: > -----Original Message----- > What is the most convincing way to mimick this in Python? > > #include > > #define SIX 1 + 5 > #define NINE 8 + 1 > > int main(void) { > printf("What do you get if you multiply six by nine: %d\n", SIX * > NINE); > return 0; > } > Don't know how convincing it is, but here is my idea: class define: ... def __init__(self, strnumexpr): ... self.val = strnumexpr ... def __mul__(self, x): ... answer = self.val + '*' + x.val ... return eval(answer) ... def __repr__(self): ... return str(eval(self.val)) ... >>> SIX = define('1 + 5') >>> NINE = define('8 + 1') >>> SIX 6 >>> NINE 9 >>> SIX * NINE 42 You could hide the define class in a module which might make it more convincing... >>> from hhgtg import define >>> SIX = define('1 + 5') >>> NINE = define('8 + 1') >>> SIX 6 >>> NINE 9 >>> SIX * NINE 42 Christian http://www.dowski.com From roeland.rengelink at chello.nl Fri Jun 11 12:02:41 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Fri Jun 11 12:02:07 2004 Subject: [Tutor] Question about the use of None In-Reply-To: <20040611145707.97582.qmail@web53903.mail.yahoo.com> References: <20040611145707.97582.qmail@web53903.mail.yahoo.com> Message-ID: <40C9D7A1.5040809@chello.nl> Wilfred Y wrote: > Hi, I came across this keyword None. The document I read says "None is > python's way of representing nothing. It evaluates to False when > treated as a condition" So I assume, if I do start=None, then it's as > good as saying start="" or start=0 Now, the code to represent it's use > is pretty confusing. It goes like this: start=None while start != "" > start=raw_input("Press enter to exit, or key in a string: ") The > confusing part is here, since start = "", then it should never be able > to go into the while loop. (Well, at least that's if None is really == > "") So to check, I tried this in the interactive window: start=None > print start and presto !! It prinst the string None, even though i > haven't placed it in double quotes. So it seems None does have a > value, which explains why it managed to enter the while loop. Is this > correct ? Hi Wilfred, I think you answered your own question correctly. >>> None != '' True None is a value, and that values is different from 0 or '', but it behaves just like 0 or '' in a condition. The sentence 'evaluates to False, when treated as a condition' is somewhat misleading, because None 'evaluates to' None Consider: >>> if expression: ... print 'Condition is True' where expression can be any Python expression (for example: string!='') The if-statement evaluates the expression, and prints 'Condition is True' if the result of the expression is not one of (False, None, 0, 0.0, '', [], (), or {}). I.e.: None, 0, etc are all equivalent to False, as far as the if-statement is concerned, while everything else is equivalent to True (Since v 2.3 of Python, True and False are also build-in values, just like None) Hope this helps, Roeland From relative at unimx.de Fri Jun 11 12:38:58 2004 From: relative at unimx.de (Christoph Karner) Date: Fri Jun 11 12:36:45 2004 Subject: [Tutor] 42 In-Reply-To: <20040611053201.79531.qmail@web50306.mail.yahoo.com> References: <20040611053201.79531.qmail@web50306.mail.yahoo.com> Message-ID: <1086971938.2564.12.camel@christoph.karner> > print "What do you get if you multiply six by nine: %d" % 6 * 7 Okay, that's quite clear :-) Multiplying 6 with 9 to get 42 is rather a joke than programming...seehttp://en.wikipedia.org/wiki/The_Answer_to_Life%2C_the_Universe%2C_and_Everything for details. > I don't think Python can duplicate this specific bug (yes, of course > it's a bug) from C, at least not without using a C extension. I think > that's probably a good thing. I don't think that this is a bug, it's rather an advised error in reason. #define SIX (1 + 5) #define NINE (8 + 1) This works as Adam Riese would appreciate. If you leave the brackets, your computer calculates 1 + 5 * 8 + 1, and this is 42. Christoph From michele.alzetta at aliceposta.it Fri Jun 11 14:19:01 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Fri Jun 11 14:16:02 2004 Subject: [Tutor] python $i equivalent ? Message-ID: <1086977940.8682.17.camel@localhost> Thanks to all for the hints; I have yet to try out the solution because I'm just ending a binge of overwork (over 50 hours in 4 days, including one night on duty) ... it probably won't be until next thursday that I'll have some leisure to try this out. Anyway, my impression is that the problem as someone correctly stated is a question of scopes and that: myvars = {} for element in list: myvars[element] = Class() 'ought' to work as I want. ( "exec element" seems interesting anyway. This real-life example is bringing up no end of interesting pythonic things !) Of course, what I'm aiming at is: schedule = {} list = [(label1, startdatetuple1, enddatetuple1),(label2, \ startdatetuple2, enddatetuple2),(label3, etc. etc. for label, starttimetuple, endtimetuple in list: schedule[label] = Shift(starttimetuple,endtimetuple) (Shift and TimeSpan classes are described in earlier posts). Thanks again to all ! -- Michele Alzetta From alan.gauld at blueyonder.co.uk Fri Jun 11 17:07:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jun 11 17:07:51 2004 Subject: [Tutor] Question about the use of None References: <20040611145707.97582.qmail@web53903.mail.yahoo.com> Message-ID: <004601c44ff8$25509be0$6401a8c0@xp> > Hi,I came across this keyword None. The document I read says > "None is python's way of representing nothing. That is to say nothingat all, not even an empty string or zero. > It evaluates to False when treated as a condition So its boolean value is False, just as "" is False and 0 is false. BUt None is not the same as "" any more than 0 is the same as "", they are three things that evaluate to False in boolean terms. > "So I assume, if I do start=None, then it's as good as saying > start="" or start=0 Thats right because they all evaluate to False. > Now, the code to represent it's use is pretty confusing. No, its totally consistent! ;-) > It goes like this: start=None while start != "": start=raw_input("Press enter to exit, or key in a string: ") The confusing part is here, since start = "", No start is None wjich is NOT the same thing as "". If the test was while not start: Then you would be right, because both None and "" would cause the loop test to fail. But while start != "" will be true for anything except an empty string which will only occur when the user hits return with no content. > at least that's if None is really == "" But None is not the same as "" any more than 0 is the same as "". They just evaluate as Booleans to False. (As does an empty list BTW) > So to check, I tried this in the interactive window: >>> start=None >>> print start Will print the string representation of None which is, not surprisingly 'None'. Remember that the prompt uses the result of the __repr__() function and print uses the result of the __str__() function. > and presto !! It prinst the string None, even though i haven't > placed it in double quotes. If you had placed it in double quootes ythey would not ave appeared: >>> print "None" None >>> print None 'None' >>> > So it seems None does have a value, No it has a string representation, just like almost every other Python object. (Even though None is actually a non-object!!) > which explains why it managed to enter the while loop. Is this correct? No, it entered the loop because None is something different from "" So >>> print None == "" False >>> print None False >>> print 0 == "" False >>> if not 0: print '0 is false' 0 is false >>> if not "": print "'' is false" '' is false >>> if not None: print "None is false" None is false >>> if not None and not "": print 'None and "" are both false' None and "" are both false > Hope someone can help with an explanation. Well, I've tried! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Fri Jun 11 19:47:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jun 11 19:47:49 2004 Subject: [Tutor] Question about the use of None In-Reply-To: <20040611145707.97582.qmail@web53903.mail.yahoo.com> Message-ID: On Fri, 11 Jun 2004, [iso-8859-1] Wilfred Y wrote: > Hi,I came across this keyword None. The document I read says "None is > python's way of representing nothing. It evaluates to False when treated > as a condition" Hi Wilfred, Which document are you referring to? We can also take a look and see if the wording is weird. What you're describing right now actually sounds subtly off. *grin* The 'None' value is a single value that's used to represent the idea of nothing. It can be used in comparisons: ### >>> None == 1 False >>> None == 0 False >>> None == "" False >>> None == None True ### and the only 'value' that None compares favorably to is itself the None value. > So I assume, if I do start=None, then it's as good as saying start="" or > start=0Now, the code to represent it's use is pretty confusing. It goes > like this:start=Nonewhile start != "" start=raw_input("Press enter to > exit, or key in a string: ")The confusing part is here, since start = > "", then it should never be able to go into the while loop. [Small note: use indentation to set off your code from your explanation; it'll make it easier for us to test and see how your code works.] Let's look at the code again: ### start = None while start != "": start = raw_input("Press enter to exit, or key in a string: " ) ### > So it seems None does have a value, which explains why it managed to > enter the while loop. Yes. None is a perfectly legitimate value. What the author of the material you were reading was trying to say, though, is that None is one of the values that Python considers as a 'false' value. If we are working with an 'if' statement, like: ### if foo: ... ### then the '...' part gets executed only if 'foo' is a true-ish value. Every value in Python is considered true, except for a few special cases. You may find the following useful: ### >>> def testTruth(value): ... """Prints true or false, depending if the value that we get is ... a true or false value.""" ... if value: ... print "True!" ... else: ... print "False!" ... >>> testTruth('hello') True! >>> testTruth(42) True! >>> testTruth(False) False! ### The function above will say "True!" or "False!", depending if the value we pass is considered True or False to the 'if' statement. Try testTruth() on these values: 1 42 - 2 * 21 0 == 0 0 None "hello" "hello"[0:0] If you can predict when it says True! or False! with good accuracy, then you probably understand the author's point. *grin* Python is actually quite loose when it comes to truth and falsehood. In fact, there are other computer languages that are really strict about this issue. From roeland.rengelink at chello.nl Sat Jun 12 05:10:33 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Sat Jun 12 05:10:12 2004 Subject: [Tutor] 42 In-Reply-To: <20040611173257.13014.qmail@web50306.mail.yahoo.com> References: <20040611173257.13014.qmail@web50306.mail.yahoo.com> Message-ID: <40CAC889.5000206@chello.nl> Adelein and Jeremy wrote: >--- Roeland Rengelink wrote: > > >>Gregor Lingl wrote: >> >> >> >>>What is the most convincing way to mimick this in Python? >>> >>>#include >>> >>>#define SIX 1 + 5 >>>#define NINE 8 + 1 >>> >>>int main(void) { >>> printf("What do you get if you multiply six by nine: %d\n", SIX >>> >>> >>* >> >> >>> NINE); >>> return 0; >>>} >>> >>> >>Since macro's are substituted before compilation in C. You'd have >>to >>substitute before iterpretation in Python. This works: >> >> >>> SIX = '1+5' >> >>> NINE = '8+1' >> >>> eval('%s*%s' % (SIX, NINE)) >>42 >> >> >> > >Then again, does this actually mimick macros? Or was the point simply >to mimick the "amazing result"? > Well, it does not mimick macros in any meaningful sense of the word. My point was basically to illustrate how macros work in C. Macro's are handled by a preprocessor, and the compiler never 'sees' them. In this example, the string formatting mimicks a preprocessor, and eval() mimicks a compiler. Note that eval doesn't 'see' the string substitution either. Python of course, does not have a preprocessor. Hence, no macros. Fortunately, you don't need macros. String substitution is better handled by code. For example: SIX = 1+5 NINE = 8+1 print SIX*NINE Conditional 'compilation' works too. For example: if sys.platform()=='nt': def a_func(): """Use this on windows"""" ... else: def a_func(): """Use this one elsewhere"""" ... > This is very interesting, using eval >to do this - I figured it might be possible with eval but I wasn't >comfortable enough with the behavior of it nor with the behavior of >the string formatting, apparently. Learned something new. > > > As long as you didn't learn how to do macros in Python, I'm happy :) Cheers, Roeland From alan.gauld at blueyonder.co.uk Sat Jun 12 13:48:28 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jun 12 13:48:18 2004 Subject: [Tutor] Question about the use of None References: <20040611145707.97582.qmail@web53903.mail.yahoo.com> <004601c44ff8$25509be0$6401a8c0@xp> Message-ID: <006101c450a5$7803d700$6401a8c0@xp> Oops, A cut n paste error here, this should be: > >>> print None > False >>> print None == 0 False Alan G. From Dragonfirebane at aol.com Sat Jun 12 16:20:44 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jun 12 16:20:52 2004 Subject: [Tutor] strange behavior in program Message-ID: <39B7E724.07EF2C3E.34E997B7@aol.com> Hello all, I've finally managed to make the text converter in the code below do what its supposed to, but when i run it with more than one character ('hello', for example), it'll do the following (convert the first letter then ask if more letters are to be converted and regardless of the answer continue until the word is done, at which point 'y' begins the program again and 'n' ends it like it's supposed to): >>> Please enter numbers or text to be converted. hello 1000 Would you like to convert more text or numbers [y/n]? n 101 Would you like to convert more text or numbers [y/n]? y 1100 Would you like to convert more text or numbers [y/n]? 1100 Would you like to convert more text or numbers [y/n]? 1 1111 Would you like to convert more text or numbers [y/n]? y Please enter numbers or text to be converted. a 01 Would you like to convert more text or numbers [y/n]? n Thank you for using Multivert. Multivert will now close here's the code: def convertxt(): x = 0 while x <= 25: while char in alphabet[x]: print binary[x] break x += 1 def convertnum(): whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal """) if whichconv in('1','Binary','binary','bin','b'): if char in number: print binary[int(original) - 1] elif whichconv in('2','Hexadecimal','hexadecimal','hexadec','hex','h'): if char in number: print hexadec[int(original) - 1] import time alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] binary = ['01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000','10001','10010','10011','10100','10101','10110','10111','11000','11001','11010','11011','11100','11101','11110','11111','100000','100001','100010','100011','100100','100101','100110','100111','101000','101001','101010','101011','101100','101101','101110','101111','110000','110001','110010','110011','110100','110101','110110','110111','111000','111001','111010','111011','111100','111101','111110','111111','1000000','1000001','1000010','1000011','1000100','1000101','1000110','1000111','1001000','1001001','1001010','1001011','1001100','1001101','1001110','1001111','1010000','1010001','1010010','1010011','1010100','1010101','1010110','1010111','1011000','1011001','1011010','1011011','1011100','1011101','1011110','1011111','1100000','1100001','1100010','1100011','1100100','1100101','1100110','1100111','1101000','1101001','1101010','1101011','1101100','1101101','1101110','1101111','1110000','1110001','1110010','1110011','1110100','1110101','1110110','1110111','1111000','1111001','1111010','1111011','1111100','1111101','1111110','1111111','10000000','10000001','10000010','10000011','10000100','10000101','10000110','10000111','10001000','10001001','10001010','10001011','10001100','10001101','10001110','10001111','10010000','10010001','10010010','10010011','10010100','10010101','10010110','10010111','10011000','10011001','10011010','10011011','10011100','10011101','10011110','10011111','10100000','10100001','10100010','10100011','10100100','10100101','10100110','10100111','10101000','10101001','10101010','10101011','10101100','10101101','10101110','10101111','10110000','10110001','10110010','10110011','10110100','10110101','10110110','10110111','10111000','10111001','10111010','10111011','10111100','10111101','10111110','10111111','11000000','11000001','11000010','11000011','11000100','11000101','11000110','11000111','11001000','11001001','11001010','11001011','11001100','11001101','11001110','11001111','11010000','11010001','11010010','11010011','11010100','11010101','11010110','11010111','11011000','11011001','11011010','11011011','11011100','11011101','11011110','11011111','11100000','11100001','11100010','11100011','11100100','11100101','11100110','11100111','11101000','11101001','11101010','11101011','11101100','11101101','11101110','11101111','11110000','11110001','11110010','11110011','11110100','11110101','11110110','11110111','11111000','11111001','11111010','11111011','11111100','11111101','11111110','11111111'] number = ['0','1','2','3','4','5','6','7','8','9'] hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F','20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F','30','31','32','33','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F','40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F','50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F','60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F','70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F','80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F','90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF','B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF','C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF','D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF','E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF','F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'] again = True while again: original = raw_input("Please enter numbers or text to be converted. ") for char in original: try: int(original) except TypeError: convertxt() except ValueError: convertxt() else: if char in number: convertnum() again = raw_input("Would you like to convert more text or numbers [y/n]? ") if again in 'Yy': again = True elif again in 'Nn': again = False print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() if any one has any idea why this happens and how I can fix it, I'd be grateful. "n thats the way the cookie crumbles" America's Favorite Cookie From pythonTutor at venix.com Sat Jun 12 17:02:21 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Jun 12 17:02:29 2004 Subject: [Tutor] strange behavior in program In-Reply-To: <39B7E724.07EF2C3E.34E997B7@aol.com> References: <39B7E724.07EF2C3E.34E997B7@aol.com> Message-ID: <1087074140.6190.105.camel@laptop.venix.com> I believe that the lines where you prompt for again should be shifted to the left so that they line up with for char in original This way the program will finish processing original before it asks about looping again. These are the lines to shift left. again = raw_input("Would you like to convert more .... if again in 'Yy': again = True elif again in 'Nn': again = False By shifting them left one level you take them out of the for char in original loop, but keep them in the while again loop. I think that fits what you are really trying to do. A minor suggestion. Your if/elif to set again could be replaced by: again = again not in 'Nn' again will be False when the raw_input is N or n or '', otherwise again will be True. I think this matches what you actually coded and is much shorter. Make sure that you follow what is happening. (The expression looks a little funny since again is used to refer to the raw_input and also to the loop control.) On Sat, 2004-06-12 at 16:20, Dragonfirebane@aol.com wrote: > Hello all, > > I've finally managed to make the text converter in the code below do what its supposed to, but when i run it with more than one character ('hello', for example), it'll do the following (convert the first letter then ask if more letters are to be converted and regardless of the answer continue until the word is done, at which point 'y' begins the program again and 'n' ends it like it's supposed to): > > >>> > Please enter numbers or text to be converted. hello > 1000 > Would you like to convert more text or numbers [y/n]? n > 101 > Would you like to convert more text or numbers [y/n]? y > 1100 > Would you like to convert more text or numbers [y/n]? > 1100 > Would you like to convert more text or numbers [y/n]? 1 > 1111 > Would you like to convert more text or numbers [y/n]? y > Please enter numbers or text to be converted. a > 01 > Would you like to convert more text or numbers [y/n]? n > Thank you for using Multivert. Multivert will now close > > here's the code: > > def convertxt(): > x = 0 > while x <= 25: > while char in alphabet[x]: > print binary[x] > break > x += 1 > def convertnum(): > whichconv = raw_input("""Convert to: > 1: Binary > 2: Hexadecimal > """) > if whichconv in('1','Binary','binary','bin','b'): > if char in number: > print binary[int(original) - 1] > elif whichconv in('2','Hexadecimal','hexadecimal','hexadec','hex','h'): > if char in number: > print hexadec[int(original) - 1] > > > import time > > alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] > binary = ['01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000','10001','10010','10011','10100','10101','10110','10111','11000','11001','11010','11011','11100','11101','11110','11111','100000','100001','100010','100011','100100','100101','100110','100111','101000','101001','101010','101011','101100','101101','101110','101111','110000','110001','110010','110011','110100','110101','110110','110111','111000','111001','111010','111011','111100','111101','111110','111111','1000000','1000001','1000010','1000011','1000100','1000101','1000110','1000111','1001000','1001001','1001010','1001011','1001100','1001101','1001110','1001111','1010000','1010001','1010010','1010011','1010100','1010101','1010110','1010111','1011000','1011001','1011010','1011011','1011100','1011101','1011110','1011111','1100000','1100001','1100010','1100011','1100100','1100101','1100110','1100111','1101000','1101001','1101010','1101011','1101100','1101101','1101110','1101111','1110000','1110001','1110010','1110011','1110100','1110101','1110110','1110111','1111000','1111001','1111010','1111011','1111100','1111101','1111110','1111111','10000000','10000001','10000010','10000011','10000100','10000101','10000110','10000111','10001000','10001001','10001010','10001011','10001100','10001101','10001110','10001111','10010000','10010001','10010010','10010011','10010100','10010101','10010110','10010111','10011000','10011001','10011010','10011011','10011100','10011101','10011110','10011111','10100000','10100001','10100010','10100011','10100100','10100101','10100110','10100111','10101000','10101001','10101010','10101011','10101100','10101101','10101110','10101111','10110000','10110001','10110010','10110011','10110100','10110101','10110110','10110111','10111000','10111001','10111010','10111011','10111100','10111101','10111110','10111111','11000000','11000001','11000010','11000011','11000100','11000101','11000110','11000111','11001000','11001001','11001010','11001011','11001100','11001101','11001110','11001111','11010000','11010001','11010010','11010011','11010100','11010101','11010110','11010111','11011000','11011001','11011010','11011011','11011100','11011101','11011110','11011111','11100000','11100001','11100010','11100011','11100100','11100101','11100110','11100111','11101000','11101001','11101010','11101011','11101100','11101101','11101110','11101111','11110000','11110001','11110010','11110011','11110100','11110101','11110110','11110111','11111000','11111001','11111010','11111011','11111100','11111101','11111110','11111111'] > number = ['0','1','2','3','4','5','6','7','8','9'] > hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F','20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F','30','31','32','33','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F','40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F','50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F','60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F','70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F','80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F','90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF','B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF','C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF','D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF','E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF','F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'] > again = True > while again: > original = raw_input("Please enter numbers or text to be converted. ") > for char in original: > try: > int(original) > except TypeError: > convertxt() > except ValueError: > convertxt() > else: > if char in number: > convertnum() > again = raw_input("Would you like to convert more text or numbers [y/n]? ") > if again in 'Yy': > again = True > elif again in 'Nn': > again = False > print "Thank you for using Multivert. Multivert will now close" > time.sleep(1.1) > import sys > sys.exit() > > if any one has any idea why this happens and how I can fix it, I'd be grateful. > > "n thats the way the cookie crumbles" > > America's Favorite Cookie > > ______________________________________________________________________ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From glingl at aon.at Sat Jun 12 17:16:24 2004 From: glingl at aon.at (Gregor Lingl) Date: Sat Jun 12 17:15:39 2004 Subject: [Tutor] strange behavior in program In-Reply-To: <39B7E724.07EF2C3E.34E997B7@aol.com> References: <39B7E724.07EF2C3E.34E997B7@aol.com> Message-ID: <40CB72A8.3080807@aon.at> Dragonfirebane@aol.com schrieb: >Hello all, > >I've finally managed to make the text converter in the code below do what its supposed to, but when i run it with more than one character ('hello', for example), it'll do the following (convert the first letter then ask if more letters are to be converted and regardless of the answer continue until the word is done, at which point 'y' begins the program again and 'n' ends it like it's supposed to): > > > >Please enter numbers or text to be converted. hello >1000 >Would you like to convert more text or numbers [y/n]? n >101 >Would you like to convert more text or numbers [y/n]? y >1100 >Would you like to convert more text or numbers [y/n]? >1100 >Would you like to convert more text or numbers [y/n]? 1 >1111 >Would you like to convert more text or numbers [y/n]? y >Please enter numbers or text to be converted. a >01 >Would you like to convert more text or numbers [y/n]? n >Thank you for using Multivert. Multivert will now close > > Hi Dragonfirebane! This (to you) unexpected behaviour comes from the fact, that in for char in original: try: int(original) except TypeError: convertxt() except ValueError: convertxt() else: if char in number: convertnum() again = raw_input("Would you like to convert more text or numbers [y/n]? ") if again in 'Yy': again = True elif again in 'Nn': again = False the raw_input() call is made once for every char in original, that is - in your example - in "hello": 5 times! And only if you answer with n in the last of these five inputs the enclosing while loop will terminate. So, I think, you shouldn't put the last five lines into the for-loop. Apart from this there are several flaws in your program, which make it hard for me to understand, what it should do. And because the program seems to be relatively complex it's also hard to tear them apart and isolate them. Two tiny examples: (1)I'd much prefer if you wrote something like: more = raw_input("Would you like to convert more text or numbers [y/n]? ") if more in 'Yy': again = True # albeit this doesn't change anything, because # if again weren't true you wouldn't get here elif more in "Nn": again = False (I mean: why use the same name for different things?) (2) The inner "while loop" in convertxt is a strange construction because it contains an unconditional break, which (unconditionally) terminates the loop after the first run through it. while char in alphabet[x]: print binary[x] break I think this should equivavlently better be written as: if char in alphabet[x]: print binary[x] (Moreover note, on the other side, that without the break this "while loop" would run indefinitely as there is nothing in the loop's body, which changes the condition: once True - - forever True Additionally: alphabet[x] is invariably a one-character-string, so char in alphabet[x] should be equivalent to char == alphabet[x] --- did you think of this or did you intend something completely different?) I must confess, that i don't fully understand what your program is intended to do. I would very much appreciate, if you could assemble (for instance at first with paper and pencil) a sample-run of the program with some chracteristic inputs and corresponding outputs and post it here. Perhaps then I ( and other people on this list ) could support you with more fruitful hints or propositions to make it more clear an concise. Regards, Gregor >here's the code: > >def convertxt(): > x = 0 > while x <= 25: > while char in alphabet[x]: > print binary[x] > break > x += 1 >def convertnum(): > whichconv = raw_input("""Convert to: >1: Binary >2: Hexadecimal >""") > if whichconv in('1','Binary','binary','bin','b'): > if char in number: > print binary[int(original) - 1] > elif whichconv in('2','Hexadecimal','hexadecimal','hexadec','hex','h'): > if char in number: > print hexadec[int(original) - 1] > > >import time > >alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] >binary = ['01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000','10001','10010','10011','10100','10101','10110','10111','11000','11001','11010','11011','11100','11101','11110','11111','100000','100001','100010','100011','100100','100101','100110','100111','101000','101001','101010','101011','101100','101101','101110','101111','110000','110001','110010','110011','110100','110101','110110','110111','111000','111001','111010','111011','111100','111101','111110','111111','1000000','1000001','1000010','1000011','1000100','1000101','1000110','1000111','1001000','1001001','1001010','1001011','1001100','1001101','1001110','1001111','1010000','1010001','1010010','1010011','1010100','1010101','1010110','1010111','1011000','1011001','1011010','1011011','1011100','1011101','1011110','1011111','1100000','1100001','1100010','1100011','1100100','1100101','1100110','1100111','1101000','1101001','1101010','1101011','1101100','1101101','1101110','1101111','1110000','1110001','1110010','1110011','1110100','1110101','1110110','1110111','1111000','1111001','1111010','1111011','1111100','1111101','1111110','1111111','10000000','10000001','10000010','10000011','10000100','10000101','10000110','10000111','10001000','10001001','10001010','10001011','10001100','10001101','10001110','10001111','10010000','10010001','10010010','10010011','10010100','10010101','10010110','10010111','10011000','10011001','10011010','10011011','10011100','10011101','10011110','10011111','10100000','10100001','10100010','10100011','10100100','10100101','10100110','10100111','10101000','10101001','10101010','10101011','10101100','10101101','10101110','10101111','10110000','10110001','10110010','10110011','10110100','10110101','10110110','10110111','10111000','10111001','10111010','10111011','10111100','10111101','10111110','10111111','11000000','11000001','11000010','11000011','11000100','11000101','11000110','11000111','11001000','11001001','11001010','11001011','11001100','11001101','11001110','11001111','11010000','11010001','11010010','11010011','11010100','11010101','11010110','11010111','11011000','11011001','11011010','11011011','11011100','11011101','11011110','11011111','11100000','11100001','11100010','11100011','11100100','11100101','11100110','11100111','11101000','11101001','11101010','11101011','11101100','11101101','11101110','11101111','11110000','11110001','11110010','11110011','11110100','11110101','11110110','11110111','11111000','11111001','11111010','11111011','11111100','11111101','11111110','11111111'] >number = ['0','1','2','3','4','5','6','7','8','9'] >hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F','20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F','30','31','32','33','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F','40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F','50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F','60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F','70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F','80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F','90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF','B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF','C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF','D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF','E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF','F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'] >again = True >while again: > original = raw_input("Please enter numbers or text to be converted. ") > for char in original: > try: > int(original) > except TypeError: > convertxt() > except ValueError: > convertxt() > else: > if char in number: > convertnum() > again = raw_input("Would you like to convert more text or numbers [y/n]? ") > if again in 'Yy': > again = True > elif again in 'Nn': > again = False >print "Thank you for using Multivert. Multivert will now close" >time.sleep(1.1) >import sys >sys.exit() > >if any one has any idea why this happens and how I can fix it, I'd be grateful. > >"n thats the way the cookie crumbles" > >America's Favorite Cookie > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at blueyonder.co.uk Sat Jun 12 17:47:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jun 12 17:47:10 2004 Subject: [Tutor] strange behavior in program References: <39B7E724.07EF2C3E.34E997B7@aol.com> Message-ID: <007801c450c6$d710b6c0$6401a8c0@xp> > while again: > original = raw_input("Please enter numbers or text to be converted. ") The following for loop is not controlled by again, it will process every letter regardless, as you've seen. If you want the loop to stop at an arbitrary point rather than process every letter you need another while loop: > for char in original: index = 0 while index < len(original) and again: char = original[index] > try: > int(original) > except TypeError: > convertxt() > except ValueError: > convertxt() > else: > if char in number: > convertnum() > again = raw_input("Would you like to convert more text or numbers [y/n]? ") > if again in 'Yy': > again = True > elif again in 'Nn': > again = False An alternative approach uses break like so: for char in original: if not again: break # otherwise continue as before I'm not a big fan of break because it goes against the principles of structured programming and can lead to obscure bugs. But in this case it seems to me to be the cleanest solution so I'd go with break. Alan G. From Dragonfirebane at aol.com Sat Jun 12 18:06:58 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jun 12 18:07:06 2004 Subject: [Tutor] strange behavior in program Message-ID: <78F0861B.0F90C569.34E997B7@aol.com> >Hi Dragonfirebane! This (to you) unexpected behaviour comes from the fact, that in for char in original: try: int(original) except TypeError: convertxt() except ValueError: convertxt() else: if char in number: convertnum() again = raw_input("Would you like to convert more text or numbers [y/n]? ") if again in 'Yy': again = True elif again in 'Nn': again = False the raw_input() call is made once for every char in original, that is - in your example - in "hello": 5 times! And only if you answer with n in the last of these five inputs the enclosing while loop will terminate. So, I think, you shouldn't put the last five lines into the for-loop. Apart from this there are several flaws in your program, which make it hard for me to understand, what it should do. And because the program seems to be relatively complex it's also hard to tear them apart and isolate them. Two tiny examples: (1)I'd much prefer if you wrote something like: more = raw_input("Would you like to convert more text or numbers [y/n]? ") if more in 'Yy': again = True # albeit this doesn't change anything, because # if again weren't true you wouldn't get here elif more in "Nn": again = False (I mean: why use the same name for different things?) (2) The inner "while loop" in convertxt is a strange construction because it contains an unconditional break, which (unconditionally) terminates the loop after the first run through it. while char in alphabet[x]: print binary[x] break I think this should equivavlently better be written as: if char in alphabet[x]: print binary[x] (Moreover note, on the other side, that without the break this "while loop" would run indefinitely as there is nothing in the loop's body, which changes the condition: once True - - forever True Additionally: alphabet[x] is invariably a one-character-string, so char in alphabet[x] should be equivalent to char == alphabet[x] --- did you think of this or did you intend something completely different?) I must confess, that i don't fully understand what your program is intended to do. I would very much appreciate, if you could assemble (for instance at first with paper and pencil) a sample-run of the program with some chracteristic inputs and corresponding outputs and post it here. Perhaps then I ( and other people on this list ) could support you with more fruitful hints or propositions to make it more clear an concise. >Regards, Gregor I see the problem. Thanks for pointing it out to me. Also, I'll change the 'again' input to more and do something like: more = raw_input("Would you like to convert more text or numbers [y/n]? ") if more in 'Yy': pass ##because this continues the loop. after all, as you ##said, 'again' is already true or this would not be ##arrived at elif more in 'Nn': again = False As for the second flaw, you are correct. Originally, i was attempting to have the program process the entire word inputed, not merely the first character, not realizing that happens without a loop there. That section will be changed to: if char in alphabet[x]: print alphabet[x] I tried to use that structure (if char == 'alphabet[x]':) but i encountered some problems probably unrelated. However, the structure i am currently using suits my tastes better in any case. I believe you are correct regarding the interchangeability of the two. This program, called 'Multivert', is eventually intended to be able to convert text (abc) into binary (01,10,11,etc.) into hexadecimal (1,2,3,4,5,6,7,8,9,A,B,C,etc.) into numbers (1,2,3,etc.) with any and all combinations. Essentially, it would be a 4-way dictionary. If a person wanted to convert text into binary, they would type in text and select binary (currently the default choice until i fix bugs) or numbers or hexadecimal for those conversions. Then, the program would print the converted text. For example, "banana" in text would yield "10 01 1110 01 1110 01" in binary, "2 1 E 1 E 1" in hexadecimal, or "2 1 14 1 14 1" in numbers. Obviously, this is not all possible with the current code, which is why I'm still workin on it. Similarly, any of the other entries ("10 01 1110 01 1110 01", "2 1 E 1 E 1", or "2 1 14 1 14 1") would yield "banana" in text and each other otherwise (each 'means' the same thing). I hope to be able to modify the program to distinguish between the four styles of input so that the user can begin with any style and convert it to any style. This would probably be accomplished in a very similar manner to what i have alread set up (try int(original), except Name/TypeError: convertxt(), else convertnum). However, I will need to come up with a method for the program to distinguish hexadecimal from text, since both would yield an Error at int(original), and binary from numbers, since neither would yield an error. For the latter i will probably do something along the lines of: ... for char in original: try: int(original) except TypeError: convertxt() except ValueError: convertxt() else: if char in number[1:]: convertnum() else: convertbin() ##not yet in code again = raw_input("Would you like to convert more text or numbers [y/n]? ") if again in 'Yy': pass elif again in 'Nn': again = False print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() I realize this would not work exactly as is, but it is a start. "n thats the way the cookie crumbles" America's Favorite Cookie From Dragonfirebane at aol.com Sat Jun 12 18:40:32 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jun 12 18:40:40 2004 Subject: [Tutor] printing without a new line Message-ID: <5ECEECDE.1559B870.34E997B7@aol.com> Hello all, Thanks to all those who helped me with the last problem i had with this program, and that section now works beautifully, aside from the fact that a new line is printed at the end of each character conversion. Thus, "hello o my" yields: 1000 101 1100 1100 1111 1111 1101 11001 using the following code: def convertxt(): x = 0 while x <= 26: if char in alphabet[x]: print binary[x] + ' ' x += 1 def convertnum(): whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal """) if whichconv in('1','Binary','binary','bin','b'): if char in number: print binary[int(original) - 1] elif whichconv in('2','Hexadecimal','hexadecimal','hexadec','hex','h'): if char in number: print hexadec[int(original) - 1] import time alphabet = [' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] binary = [' ','01','10','11','100','101','110','111','1000','1001','1010','1011','1100','1101','1110','1111','10000','10001','10010','10011','10100','10101','10110','10111','11000','11001','11010','11011','11100','11101','11110','11111','100000','100001','100010','100011','100100','100101','100110','100111','101000','101001','101010','101011','101100','101101','101110','101111','110000','110001','110010','110011','110100','110101','110110','110111','111000','111001','111010','111011','111100','111101','111110','111111','1000000','1000001','1000010','1000011','1000100','1000101','1000110','1000111','1001000','1001001','1001010','1001011','1001100','1001101','1001110','1001111','1010000','1010001','1010010','1010011','1010100','1010101','1010110','1010111','1011000','1011001','1011010','1011011','1011100','1011101','1011110','1011111','1100000','1100001','1100010','1100011','1100100','1100101','1100110','1100111','1101000','1101001','1101010','1101011','1101100','1101101','1101110','1101111','1110000','1110001','1110010','1110011','1110100','1110101','1110110','1110111','1111000','1111001','1111010','1111011','1111100','1111101','1111110','1111111','10000000','10000001','10000010','10000011','10000100','10000101','10000110','10000111','10001000','10001001','10001010','10001011','10001100','10001101','10001110','10001111','10010000','10010001','10010010','10010011','10010100','10010101','10010110','10010111','10011000','10011001','10011010','10011011','10011100','10011101','10011110','10011111','10100000','10100001','10100010','10100011','10100100','10100101','10100110','10100111','10101000','10101001','10101010','10101011','10101100','10101101','10101110','10101111','10110000','10110001','10110010','10110011','10110100','10110101','10110110','10110111','10111000','10111001','10111010','10111011','10111100','10111101','10111110','10111111','11000000','11000001','11000010','11000011','11000100','11000101','11000110','11000111','11001000','11001001','11001010','11001011','11001100','11001101','11001110','11001111','11010000','11010001','11010010','11010011','11010100','11010101','11010110','11010111','11011000','11011001','11011010','11011011','11011100','11011101','11011110','11011111','11100000','11100001','11100010','11100011','11100100','11100101','11100110','11100111','11101000','11101001','11101010','11101011','11101100','11101101','11101110','11101111','11110000','11110001','11110010','11110011','11110100','11110101','11110110','11110111','11111000','11111001','11111010','11111011','11111100','11111101','11111110','11111111'] number = ['0','1','2','3','4','5','6','7','8','9'] hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','10','11','12','13','14','15','16','17','18','19','1A','1B','1C','1D','1E','1F','20','21','22','23','24','25','26','27','28','29','2A','2B','2C','2D','2E','2F','30','31','32','33','33','34','35','36','37','38','39','3A','3B','3C','3D','3E','3F','40','41','42','43','44','45','46','47','48','49','4A','4B','4C','4D','4E','4F','50','51','52','53','54','55','56','57','58','59','5A','5B','5C','5D','5E','5F','60','61','62','63','64','65','66','67','68','69','6A','6B','6C','6D','6E','6F','70','71','72','73','74','75','76','77','78','79','7A','7B','7C','7D','7E','7F','80','81','82','83','84','85','86','87','88','89','8A','8B','8C','8D','8E','8F','90','91','92','93','94','95','96','97','98','99','9A','9B','9C','9D','9E','9F','A1','A2','A3','A4','A5','A6','A7','A8','A9','AA','AB','AC','AD','AE','AF','B0','B1','B2','B3','B4','B5','B6','B7','B8','B9','BA','BB','BC','BD','BE','BF','C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','CA','CB','CC','CD','CE','CF','D0','D1','D2','D3','D4','D5','D6','D7','D8','D9','DA','DB','DC','DD','DE','DF','E0','E1','E2','E3','E4','E5','E6','E7','E8','E9','EA','EB','EC','ED','EE','EF','F0','F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE','FF'] again = True while again: original = raw_input("Please enter numbers or text to be converted. ") for char in original: try: int(original) except TypeError: convertxt() except ValueError: convertxt() else: if char in number: convertnum() more = raw_input("Would you like to convert more text or numbers [y/n]? ") if more in 'Yy': pass elif more in 'Nn': again = False print "Thank you for using Multivert. Multivert will now close" time.sleep(1.1) import sys sys.exit() Any ideas about how to prevent the program from beginning a new line with each character would be appreciated. Also, to address the issue of a triple-space appearing between binary 'words' (a single space appears between letters of a word) once the new line issue has been resolved (due to: if char in alphabet[x]: print binary[x] + ' ' and alphabet = [' ', . . .] binary = [' ', . . .] ##a space in text converts to a space in ##binary, so that 'a bc' converts to ##'01 10 11' ), i will change binary so that a space in text is converted to an underscore in binary, meaning that 'a bc' is converted to '01 _ 10 11'. "n thats the way the cookie crumbles" America's Favorite Cookie From fusco_john at yahoo.com Sat Jun 12 22:24:20 2004 From: fusco_john at yahoo.com (John Fusco) Date: Sat Jun 12 22:24:25 2004 Subject: [Tutor] Getting started with COM Message-ID: <20040613022421.44284.qmail@web52210.mail.yahoo.com> I am not a windows programmer, but I am interested in using Python to script some tasks on my Windows workstation. Reading the Python win32com documentation is not encouraging. In one section where it discusses the specific attributes of COM objects it states "you are just expected to know". One thing I'd like to do is use OpenOffice to convert a document to PDF. I know how to do this with the mouse, but how do I script it with COM. I used the COM browser to look for OpenOffice or Soffice objects and I found some, but that's all I know about them. I checked the OpenOffice.org website and searched for COM and found nothing. Is this really so difficult? How do I get started? Thanks in advance. John __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From darnold02 at sprynet.com Sun Jun 13 00:56:09 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun Jun 13 00:55:52 2004 Subject: [Tutor] Getting started with COM In-Reply-To: <20040613022421.44284.qmail@web52210.mail.yahoo.com> Message-ID: Reportlab (www.reportlab.com) offers an excellent suite of Python modules for generating PDFs. If your original document is straight text, I can almost guarantee that using them will be less daunting than having to dabble in COM. HTH, Don -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of John Fusco Sent: Saturday, June 12, 2004 9:24 PM To: tutor@python.org Subject: [Tutor] Getting started with COM I am not a windows programmer, but I am interested in using Python to script some tasks on my Windows workstation. Reading the Python win32com documentation is not encouraging. In one section where it discusses the specific attributes of COM objects it states "you are just expected to know". One thing I'd like to do is use OpenOffice to convert a document to PDF. I know how to do this with the mouse, but how do I script it with COM. I used the COM browser to look for OpenOffice or Soffice objects and I found some, but that's all I know about them. I checked the OpenOffice.org website and searched for COM and found nothing. Is this really so difficult? How do I get started? Thanks in advance. John __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From christian at treesforlife.org Sun Jun 13 03:45:01 2004 From: christian at treesforlife.org (Christian Junker) Date: Sun Jun 13 03:50:35 2004 Subject: [Tutor] Re: Getting started with COM References: <20040613022421.44284.qmail@web52210.mail.yahoo.com> Message-ID: Hello John, you probably didn't find anything about COM on openoffice.org, because OpenOffice has it's own component models concept, called UNO. The UNO has an Automation Bridge that provides the use of WSH, VBScript etc. OpenOffice also comes along with its own small Python core, small because it doesn't support a lot of modules and you cannot just install extension modules, because every module must be known to UNO. Though you can easily write add-ons with the OOo Python core which would then be available to others, even if they wouldn't have Python (they would at least have Python in their OpenOffice). So you have two options what you could do now: 1. get to know another component model (the one of OOo called UNO, which is pretty new, so don't expect it to be as good as COM) and write python code to make use of it: http://udk.openoffice.org/python/python-bridge.html 2. or delve into COM by using Python code for doing something in MS Word or Excel. "John Fusco" wrote in message news:20040613022421.44284.qmail@web52210.mail.yahoo.com... > I am not a windows programmer, but I am interested in > using Python to script some tasks on my Windows > workstation. > > Reading the Python win32com documentation is not > encouraging. In one section where it discusses the > specific attributes of COM objects it states "you are > just expected to know". > > One thing I'd like to do is use OpenOffice to convert > a document to PDF. I know how to do this with the > mouse, but how do I script it with COM. > > I used the COM browser to look for OpenOffice or > Soffice objects and I found some, but that's all I > know about them. I checked the OpenOffice.org website > and searched for COM and found nothing. > > Is this really so difficult? How do I get started? > > Thanks in advance. > > John > > > > > __________________________________ > Do you Yahoo!? > Friends. Fun. Try the all-new Yahoo! Messenger. > http://messenger.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythontut at pusspaws.net Sun Jun 13 04:12:47 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Jun 13 04:13:05 2004 Subject: [Tutor] Printing a progress bar Message-ID: <40CC0C7F.5000102@pusspaws.net> Some of the code I have written handels a lot of data, I would like to add a progress bar. Initualy I tried ... print 'Progress ', .. loop ... print '#', ... But it appears python does not send a line to the console until it can send a CR. This has stumped me. How do I generate a progress bar without it looking like Progress # # # # Dave PS can anyone tell me the ASCII code to move the cursor left one position so I can write a string of .............................................. becoming #########............................ as progress is made ? Dave From christian at treesforlife.org Sun Jun 13 04:20:31 2004 From: christian at treesforlife.org (Christian Junker) Date: Sun Jun 13 04:20:47 2004 Subject: [Tutor] Re: Getting started with COM References: <20040613022421.44284.qmail@web52210.mail.yahoo.com> Message-ID: Doh, you made me curious about whether it is possible to connect via COM to UNO with Python, and yes it is! I claim to know that there is no information about how to do that with Python (especially), but it might be useful that you read documentation about the Automation Bridge: http://udk.openoffice.org/common/man/tutorial/office_automation.html What I did is easily use the lines you write in VB for Python and it absolutely worked: The following example will open a new writer document of OOo: >>> from win32com.client.dynamic import Dispatch >>> server = Dispatch('com.sun.star.ServiceManager') >>> odesktop = server.CreateInstance('com.sun.star.frame.Desktop') >>> odesktop.loadComponentfromURL('private:factory/swriter', '_blank', 0, []) list is the equivalent to an array type of UNO. Now it should be easy for you to figure out how to export something to pdf, I would just read how you do it with Starbasic (OOo's own scripting language) and then translate it into Python (as you saw in my example it's actually a very simple translation of how you would do it with Starbasic, VB). Christian "John Fusco" wrote in message news:20040613022421.44284.qmail@web52210.mail.yahoo.com... > I am not a windows programmer, but I am interested in > using Python to script some tasks on my Windows > workstation. > > Reading the Python win32com documentation is not > encouraging. In one section where it discusses the > specific attributes of COM objects it states "you are > just expected to know". > > One thing I'd like to do is use OpenOffice to convert > a document to PDF. I know how to do this with the > mouse, but how do I script it with COM. > > I used the COM browser to look for OpenOffice or > Soffice objects and I found some, but that's all I > know about them. I checked the OpenOffice.org website > and searched for COM and found nothing. > > Is this really so difficult? How do I get started? > > Thanks in advance. > > John > > > > > __________________________________ > Do you Yahoo!? > Friends. Fun. Try the all-new Yahoo! Messenger. > http://messenger.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at blueyonder.co.uk Sun Jun 13 05:55:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 13 05:54:54 2004 Subject: [Tutor] Getting started with COM References: <20040613022421.44284.qmail@web52210.mail.yahoo.com> Message-ID: <009601c4512c$8177a7d0$6401a8c0@xp> > I used the COM browser to look for OpenOffice or > Soffice objects and I found some, but that's all I > know about them. I checked the OpenOffice.org website > and searched for COM and found nothing. > > Is this really so difficult? How do I get started? The short answer is yes. COM programming relies on each application documenting its objects and how to use them but very few have adequate documentation - including Microsofts own! The best you can hope for is an object by object description. Usually you have to use the object browser and lots of trial and error. COM programming is, in my experience, an exercise in frustration :-( Sorry, I know you didn't want to hear that! Alan G. From roypython at hotmail.com Sun Jun 13 06:44:35 2004 From: roypython at hotmail.com (roy ollis) Date: Sun Jun 13 06:44:47 2004 Subject: [Tutor] mepis llinux with pyton Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040613/ef927dd6/attachment.html From sacarasc at osmodiar.mine.nu Sun Jun 13 07:10:30 2004 From: sacarasc at osmodiar.mine.nu (sacarasc) Date: Sun Jun 13 07:12:25 2004 Subject: [Tutor] mepis llinux with pyton In-Reply-To: References: Message-ID: <1087125029.5492.6.camel@osmodiar.mine.nu> for all your GNU/Linux documentation needs, try here: http://www.tldp.org/ Linux isnt all that hard, once you give it a proper try ;D have fun From fusco_john at yahoo.com Sun Jun 13 10:15:16 2004 From: fusco_john at yahoo.com (John Fusco) Date: Sun Jun 13 10:15:21 2004 Subject: [Tutor] Python / Windows Question Message-ID: <20040613141516.32484.qmail@web52208.mail.yahoo.com> Thanks for all the replies on my COM question. My takeaway is to avoid COM if possible, and in the example I gave it's possible. So I have a more general question about Python scripts for Windows. I would like to write Python scripts that can manage some point-and-click tasks in Windows. Is it reasonable to expect that anything I can point and click can be scripted by a Python script? Is there a common framework for this type of scripting or is this unique in every case? I that COM would be the answer, but maybe I'm missing something. Here's another example that maybe someone can walk me through or get me started on. Suppose I want to write a Python script to change my display mode. Is this possible? Thanks again. John __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From amonroe at columbus.rr.com Sun Jun 13 10:28:52 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Jun 13 10:19:34 2004 Subject: [Tutor] Python / Windows Question In-Reply-To: <20040613141516.32484.qmail@web52208.mail.yahoo.com> References: <20040613141516.32484.qmail@web52208.mail.yahoo.com> Message-ID: <1441132693006.20040613102852@columbus.rr.com> > So I have a more general question about Python scripts > for Windows. I would like to write Python scripts > that can manage some point-and-click tasks in Windows. > Is it reasonable to expect that anything I can point > and click can be scripted by a Python script? Google for "Autoitx". That might do what you want. Alan From Dragonfirebane at aol.com Sun Jun 13 11:17:03 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sun Jun 13 11:17:19 2004 Subject: Fwd: [Tutor] printing without a new line Message-ID: <70D5E2CF.2AE96944.34E997B7@aol.com> I sent this out a couple of days ago; just wondering if anyone's working on it. Thanks. "n thats the way the cookie crumbles" America's Favorite Cookie -------------- next part -------------- An embedded message was scrubbed... From: Dragonfirebane@aol.com Subject: [Tutor] printing without a new line Date: Sat, 12 Jun 2004 18:40:32 -0400 Size: 11114 Url: http://mail.python.org/pipermail/tutor/attachments/20040613/d7e62b09/attachment-0001.mht From alan.gauld at blueyonder.co.uk Sun Jun 13 12:15:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 13 12:15:53 2004 Subject: [Tutor] Python / Windows Question References: <20040613141516.32484.qmail@web52208.mail.yahoo.com> Message-ID: <00b201c45161$b6860310$6401a8c0@xp> > Thanks for all the replies on my COM question. My > takeaway is to avoid COM if possible, and in the > example I gave it's possible. Yes, but note that this is a problem with COM not with Python. If oits possible in COM you can do it using Python, the difficulty is figuring out exactly what COM objects exist and what they expect you to do! > So I have a more general question about Python scripts > for Windows. I would like to write Python scripts > that can manage some point-and-click tasks in Windows. > Is it reasonable to expect that anything I can point > and click can be scripted by a Python script? Not really, there is usually a better way. Even COM won't let you do that. It is possible to do anything in Windows from Python using the win32 package and a few other bits n pieces but its at a very technical and difficult level - you need dozens of lines of code just to emulate a simple mouse operation. > Is there a common framework for this type of scripting > or is this unique in every case? I that COM would be > the answer, but maybe I'm missing something. COM is the framework but sadly its different for each application. Even the Microsoft applications aren't completely consistent (Outlook is totally different in structure from the other office apps for example) If you can find how to do it in COM then Python is as good a language to use as any other COM enabled language, and better than some. > Here's another example that maybe someone can walk me > through or get me started on. Suppose I want to write > a Python script to change my display mode. Is this > possible? I'm sure it is although I'm not sure how! It might be easiest to do that via the Registry, and the WSH library provides COM objects for accessing the registry. One thing I think you should do is run, don't walk, to your nearest bookshop(Amazoin?) and buy Mark Hammond's book "Python Programming on Win32". It is the best source of info on using Python and Windows. (Although it could do with a second edition to cover XP and some of the recent Python features etc) Alan G. From tim at johnsons-web.com Sun Jun 13 12:59:10 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Sun Jun 13 12:53:23 2004 Subject: [Tutor] Null Object Design Pattern Question Message-ID: <20040613165910.GD10326@johnsons-web.com> I have been looking at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 which has an example of using a Null() object. Unfortunately, I'm having a problem wrapping my brain around the usefulness of this object compared to just using None. Does anyone have some further examples of the 'superiority' of this approach over *None*. Or pointers to further documentations. Thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From darnold02 at sprynet.com Sun Jun 13 13:38:30 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun Jun 13 13:38:38 2004 Subject: [Tutor] printing without a new line In-Reply-To: <70D5E2CF.2AE96944.34E997B7@aol.com> Message-ID: I'd suggest storing the individual convertxt() results in a list instead of printing them as you go. Then, use the join() string method when you're done to create a string from the list. Something like this: >>> res = [] >>> for char in 'this is a test': res.append(char.upper()) res.append(' ') >>> print res ['T', ' ', 'H', ' ', 'I', ' ', 'S', ' ', ' ', ' ', 'I', ' ', 'S', ' ', ' ', ' ', 'A', ' ', ' ', ' ', 'T', ' ', 'E', ' ', 'S', ' ', 'T', ' '] >>> print ''.join(res[:-1]) ##sliced to lose trailing space T H I S I S A T E S T >>> HTH, Don -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Dragonfirebane@aol.com Sent: Sunday, June 13, 2004 10:17 AM To: tutor@python.org Subject: Fwd: [Tutor] printing without a new line I sent this out a couple of days ago; just wondering if anyone's working on it. Thanks. "n thats the way the cookie crumbles" America's Favorite Cookie From alan.gauld at blueyonder.co.uk Sun Jun 13 14:12:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 13 14:12:31 2004 Subject: [Tutor] printing without a new line References: <5ECEECDE.1559B870.34E997B7@aol.com> Message-ID: <00ca01c45172$0bcfb5e0$6401a8c0@xp> > aside from the fact that a new line is printed at the end of each > character conversion. > def convertxt(): > x = 0 > while x <= 26: > if char in alphabet[x]: > print binary[x] + ' ' > x += 1 Part of the problem is that you have fallen into the trap of mixing processing and display. This is always a bad idea. Thus if you were to return a string from the function instead of printing it things would be easier. Also the while loop and 'in' test is pretty inefficient, it would be easier to use a single in test: def convertxt(): if char in alphabet: return binary[alphabet.index(char)] + ' ' > def convertnum(): > whichconv = raw_input("""Convert to: > 1: Binary > 2: Hexadecimal > """) Similarly it would be better to capture the users requirements outside the function and pass the value in as a parameter. binaryChoice = ['1','B','b','Binary','binary','bin'] whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal """) if whichconv in binaryChoice: whichconv = 2 else: whichconv = 16 def convertNum(number, base = 2): if base == 2: if char in number: return binary[int(original) - 1] elif base = 16 if char in number: return hexadec[int(original) - 1] Of course it's better still to use the built in convertion functions but we've already had that debate... > import time, string > alphabet = string.letters > binary = ['','01','10','11','100','101','110','111', ........ double eek! ...... '11111100','11111101','11111110','11111111'] And it really would be easier to use a function to do the binary conversion! number = string.numbers > hexadec = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F', ...eeek!... 'F1','F2','F3','F4','F5','F6','F7','F8','F9','FA','FB','FC','FD','FE', 'FF'] And itoa() for the hex convertions... > again = True > while again: > original = raw_input("Please enter numbers or text to be converted. ") > for char in original: > try: > int(original) > except TypeError: print convertxt(char), > except ValueError: print convertxt(char), > else: > if char in number: print convertnum(char), > more = raw_input("Would you like to convert more text or numbers [y/n]? ") > if more in 'Yy': > pass > elif more in 'Nn': > again = False > print "Thank you for using Multivert. Multivert will now close" > time.sleep(1.1) > import sys > sys.exit() Since this is the end of the program you don't need to import sys sys.exit() the program will do that by itself. I'm not sure why you have the sleep(1.1) there either? This does seem to be an extraordinarily complex way of doing a fairly simple task, is there any reason other than the fun of experimenting why you don't just use the builtin features of Python such as format strings and dictionaries? Alan G. From op73418 at mail.telepac.pt Sun Jun 13 16:55:07 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Jun 13 16:52:08 2004 Subject: [Tutor] Null Object Design Pattern Question In-Reply-To: <20040613165910.GD10326@johnsons-web.com> References: <20040613165910.GD10326@johnsons-web.com> Message-ID: Em Sun, 13 Jun 2004 08:59:10 -0800, Tim Johnson atirou este peixe aos pinguins: >I have been looking at > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 > >which has an example of using a Null() object. > >Unfortunately, I'm having a problem wrapping my brain around >the usefulness of this object compared to just using None. > >Does anyone have some further examples of the 'superiority' >of this approach over *None*. Imagine a null object as a kind of sink: it responds to all messages without barfing. Compare the following: >>> obj = None >>> obj.method() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'method' >>> class Null(object): ... def __call__(self, *args, **kwargs): ... return self ... def __getattr__(self, attrib): ... return self ... >>> obj = Null() >>> obj.method() <__main__.Null object at 0x00EFECF0> >>> The Null() doesn't barf when method is called. This allows for simpler coding in some situations. With my best regards, G. Rodrigues P.S: Googling for "null object pattern" (or some such) is bound to turn up something. From isrgish at fastem.com Sun Jun 13 17:35:24 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Jun 13 17:36:31 2004 Subject: [Tutor] OT problem reading message Message-ID: I seem to have a problem reading mail from Dragonfirebane. It comes out to be all in one long line. I'm using pocket Outlook on a Pocket PC. And as far as I know its the first time I have this problem. Even from Dragonfirebane it only started recently. Any ideas what I could do would be appreciated. All the best, Isr From dyoo at hkn.eecs.berkeley.edu Sun Jun 13 23:51:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jun 13 23:51:33 2004 Subject: [Tutor] Printing a progress bar In-Reply-To: <40CC0C7F.5000102@pusspaws.net> Message-ID: On Sun, 13 Jun 2004, Dave S wrote: > Initualy I tried ... > > print 'Progress ', > .. > loop > ... > print '#', > ... > > But it appears python does not send a line to the console until it can > send a CR. Hi Dave, Right; what's happening is called "buffering". Internally, the system keeps track of the character to be written out, and saves them in a line buffer. As soon as we send the system a CR, it'll flush that buffer out to disk. (By the way, the same thing happens when we write() to file objects.) We can manually force a flush by calling the flush() methods on the standard output file object: ### def printUnbufferedHash(): print '#', sys.stdout.flush() ### > PS can anyone tell me the ASCII code to move the cursor left one > position so I can write a string of > .............................................. > becoming > #########............................ > as progress is made ? Ah, you're looking for the backspace character '\b'. No need to remember the exact ASCII code: use the escape sequence. But if you're really interested, it's: ### >>> ord('\b') 8 ### Eight. *grin* Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Jun 14 04:01:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 14 04:01:35 2004 Subject: [Tutor] Null Object Design Pattern Question [sentinels and Minesweeper] In-Reply-To: Message-ID: On Sun, 13 Jun 2004, [ISO-8859-1] Gon=E7alo Rodrigues wrote: > >I have been looking at > > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 > > > >which has an example of using a Null() object. > > > >Unfortunately, I'm having a problem wrapping my brain around the > >usefulness of this object compared to just using None. > > > >Does anyone have some further examples of the 'superiority' of this > >approach over *None*. > > Imagine a null object as a kind of sink: it responds to all messages > without barfing. Hi Tim, If you're familiar with the use of a "sentinel" to simplify a program's logic, then you can think of a "Null Object" as an OOP analogy to a sentinel. I like using concrete examples, and one of the nice examples where sentinels come in really handy is something like a Minesweeper-like game program. Here's a quick link to one: http://www.programming-challenges.com/pg.php?page=3Ddownloadproblem&probid= =3D110102&format=3Dhtml In the game of Minesweeper, we might want to report the number of mines adjacent to a space. For example, if we have: *... =2E... =2E*.. =2E... we'd like to get back something like: *100 2210 1*10 1110 If we represent a minefield as a list of rows, like this: minefield =3D ['*...', '....', '.*..', '....'] and if we wanted to get the number of mines at an arbitrary row and col, we might write something like: ### def countMines(row, col): """Returns the number of mines around position(row, col).""" count =3D 0 for i in [-1, 0, 1]: for j in [-1, 0, 1]: if minefield[row + i][col +j] =3D=3D '*': count +=3D 1 return count ### The only problem is that this code doesn't work. *grin* ### >>> countMines(3, 3) Traceback (most recent call last): File "", line 1, in ? File "", line 6, in countMines IndexError: string index out of range ### The problem is that there's this special logic around the edges of the board, so our beautiful countMines() function malfunctions around the board edges. One way to fix countMines() is to add special-case logic into countMines() for counting mines around the edges of the board, maybe something like: ### if not (0 <=3D row + i < 4): continue ### But there's another way of fixing the problem, and it involves using sentinels. In effect, we take something like: *... =2E... =2E*.. =2E... and wrap a sentinel border of '=3D' characters around the whole game board: =3D=3D=3D=3D=3D=3D =3D*...=3D =3D....=3D =3D.*..=3D =3D....=3D =3D=3D=3D=3D=3D=3D With this sentinel border, the code doesn't have to worry about the edge of the board so much. If I ask for the number of mines on the bottom-right corner --- countMines(4, 4) --- then we're perfectly ok, since we don't go off the board. Does this make sense? Null Objects perform a similar function: they are "sentinels" that allow us to simplify our main code, so that we don't have to worry so much about the special case of handling a reference to None. Hope this helps! From Francis.Moore at shaws.co.uk Mon Jun 14 05:20:36 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Mon Jun 14 05:25:52 2004 Subject: [Tutor] Null Object Design Pattern Question Message-ID: <6081EBC21D52F744B484088BBBE665C3199F05@sbserver.shaws.local> > From: Tim Johnson [mailto:tim@johnsons-web.com] > which has an example of using a Null() object. > Unfortunately, I'm having a problem wrapping my brain > around the usefulness of this object compared to just using None. Tim, I've never used a Null Object pattern (NOP) in Python but I've used it quite a few times in C++. The NOP is primarily handy for removing lots of conditional code. For instance, imagine a program where we have an option to log user output. We should then allow the user to switch logging on or off (to speed up the program). So, in our program we would normally need to use lots of conditional code to see whether logging is turned off or not i.e. if logging_on: Logger.Log(message) elif: pass etc... An easier way is to code a base class called Logger and two concrete classes derived from Logger called RealLogger and NullLogger (an instance of the NOP). At the beginning of the program we create an instance of the correct class (RealLogger or NullLogger) depending on whether the user has logging switched on or not and bind it to an instance of the Logger class. We can then use the objects polymorphically, by just calling Logger.Log(message) and the correct class will be called. There is now no need to write conditional code and check against None. The correct object does the right thing. The RealLogger logs all messages, the NullLogger lets the message pass through. Using the same line of code. If logging is widespread throughout your application this can provide a huge reduction in the number of lines and make the application logic clearer. Hope this helps, Francis. CONFIDENTIALITY NOTICE This communication contains information which is confidential and may also be privileged. It is for the exclusive use of the intended recipient(s). If you are not the intended recipient(s) please note that any distribution, copying or use of this communication or the information in it is strictly prohibited. If you have received this communication in error please notify us by e-mail or by telephone (+44(0) 1322 621100) and then delete the e-mail and any copies of it. This communication is from Shaw & Sons Limited whose registered office is at Shaway House, 21 Bourne Park, Bourne Road, Crayford, Kent DA1 4BZ. The views expressed in this communication may not be the views held by Shaw & Sons Limited. This message has been checked for all known viruses by McAfee VirusScan. From pythontut at pusspaws.net Mon Jun 14 13:45:24 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon Jun 14 13:45:46 2004 Subject: [Tutor] Printing a progress bar In-Reply-To: <40CC0C7F.5000102@pusspaws.net> References: <40CC0C7F.5000102@pusspaws.net> Message-ID: <40CDE434.3060105@pusspaws.net> Thanks for your input, I will go and give it a try :-) Cheers Dave From asc at vineyard.net Mon Jun 14 14:53:48 2004 From: asc at vineyard.net (Aaron Straup Cope) Date: Mon Jun 14 14:53:46 2004 Subject: [Tutor] creating bitmasks (for bloom filters) In-Reply-To: References: <1086958159.529.249.camel@localhost> Message-ID: <1087239227.536.96.camel@localhost> On Fri, 2004-06-11 at 09:12, Glen Wheeler wrote: > Not sure of your terminology here; does this mean you are mathematically > inclined? Or not as such? I am not especially mathematically inclined. Given enough time I can usually start to "get" it but it is not my strong suit. > Perhaps the source of pybloom would help? If it's only difference is > reliance on the unix math libraries, then this could be changed easily > enough...? Pybloom is calling mpz.mpz which is supposed to : "Create a new mpz-number. value can be an integer, a long, another mpz-number, or even a string. If it is a string, it is interpreted as an array of radix-256 digits, least significant digit first, resulting in a positive number" http://cvs.sourceforge.net/viewcvs.py/pybloom/pybloom/bloom.py?rev=1.1.1.1&view=auto http://www.python.org/doc/current/lib/module-mpz.html The docs for mpz indicate that it is deprecated, as of Python 2.3, in favour of two possible alternatives. I'm not sure that I haven't jumped from the frying pan in to the fire, though :-) From Dragonfirebane at aol.com Mon Jun 14 16:59:58 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 14 17:00:12 2004 Subject: [Tutor] KeyError Message-ID: <92.d712327.2dff6bce@aol.com> Hello all, Using the command prompt to run my program, the following error occurs. I do not believe it is because I'm using the command prompt because the same error occurs in IDLE. Since I used the same structure to convert text to binary as I did to convert text to hexadecimal (see code below error), I do not understand why the hexadecimal conversion doesn't work but the binary does. Additionally, much of the commenting had not been updated and is no longer correct, so please disregard any apparent misunderstanding through comments. C:\Program Files\Python 2.3.4c1\Programming\Programs (Complete)>python hexadecimal-binary-text.py Please enter numbers or text to be converted. "Hello. My name is Bob," said Fred. Convert to: 1: Binary 2: Hexadecimal 3: Decimal 2 Traceback (most recent call last): File "Hexadecimal-Binary-Text.py", line 128, in ? convertxthex() ##convert text to hexadecimal File "Hexadecimal-Binary-Text.py", line 36, in convertxthex res += hexadec[c] ##same deal KeyError: 'C' def convertxtbin(): ##convert text to binary for char in original: ##loops over the entire entry x = 0 ##allows checking every character against the entire alphabet list if char in punct: res += char elif char in alphabet: while x <= 26: ##if the character is punctuation or a lowercase letter if char in alphabet[x]: ##if its in the dictionary asOctal = "%o" % int(number[x]) global res for c in asOctal: res += binary[c] ##add the corresponding entry in the binary list to the res list if char not in punct: ##if the character isn't punctuation res += ' ' ##add a space at the end to separate numbers x += 1 ##adds 1 to the value of x so the loop doesnt go on forever while 26 < x <= 52: ##if the character is an uppercase letter if char in alphabet[x]: ##if the character is in the alphabet dictionary asOctal = "%o" % int(number[x - 26]) global res for c in asOctal: res += binary[c] ##print the corresponding entry in the binary entry (A = entry 36, so 36 - 26 = entry 10 = '01' = a) if char not in punct: ##if character isn't punctuation res += ' ' ##add a space at the end x += 1 ##adds 1 to x so the loop ends eventually def convertxthex(): ##convert text to hexadecimal for char in original: ##same deal x = 0 ##same deal if char in punct: res += char elif char in alphabet: while x <= 26: ##same deal if char in alphabet[x]: ##same deal asHex = "%X" % int(number[x]) global res for c in asHex: res += hexadec[c] ##same deal Line 36 if char not in punct: ##same deal res += ' ' ##same deal x += 1 ##same deal while 26 < x <= 52: ##same deal if char in alphabet[x]: ##same deal asHex = "%X" % int(number[x - 26]) global res for c in asHex: res += hexadec[c] ##same deal if char not in punct: ##same deal res += ' ' ##same deal x += 1 ##same deal def convertxtnum(): ##convert text to decimal for char in original: ##same deal x = 0 ##same deal while x <= 34: ##same deal if char in alphabet[x]: ##same deal res.append(number[x]) ##same deal if char not in alphabet[:8]: ##same deal res.append(' ') ##same deal x += 1 ##same deal while 34 < x <= 60: ##same deal if char in alphabet[x]: ##same deal res.append(number[x - 26]) ##same deal if char not in alphabet[:8]: ##same deal res.append(' ') ##same deal x += 1 ##same deal def convertnum(): ##converts numbers if whichconv in('1','Binary','binary','Bin','bin','B','b'): ##if user wants to convert to binary if int(original) <= 0: print "Please enter a positive number. " try: int(original) except ValueError: x = 0 if char in punct[x]: print [punct[x] for c in original] ##prints the corresponding binary entry (if '12' is entered, it is treated as a string, so binary[int(original) - 1] converts it to an integer and subtracts one from it so that the corresponding entry can be printed since the first entry in a list is 0 x += 1 else: asOctal = "%o" % int(original) print ''.join([binary[c] for c in asOctal]) elif whichconv in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): ##same deal if original >= 0: print hexadec[int(original) + 8] ##same deal else: print "Please enter a positive number. " elif whichconv in('3','Text','text','T','t'): ##same deal if int(original) <= 26: ##if the number is between 8 and 27 (the lowercase letters of the alphabet list print alphabet[int(original) + 8] ##it prints the corresponding entry in the alphabet list else: ##if its not one of those numbers print "Sorry, you didn't enter a valid number. Please enter only numbers between 0 and 26." ##prints message import time ##for time.sleep(1.1) at end import string alphabet = [' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] ##define the alphabet list punct = ['.',',',';',':','?','!','"',"'"] binary = {'0':'000','1':'001','2':'010', '3':'011','4':'100','5':'101', '6':'110','7':'111'} ##define the binary dictionary number = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30',' 31','32','33','34'] ##defines the number entry. goes up to 34 so convertnum() will work under the text conversion hexadec = {'0':'0','1':'1','2':'2','3':'3','4':'4','5':'5','6':'6','7':'7','8':'8','9':'9','10':'A','11':'B','12':'C','13':'D','14':'E','15':'F'} ##defines the hexadecimal list res = '' ##makes an empty list so all the conversions will work again = True ##beginning condition for loop while again: ##starts loop original = raw_input("Please enter numbers or text to be converted. ") ##enter text to be converted try: int(original) ##distinguishes the numbers from the text, needs to be revised to distinguish binary and hexadecimal ## except TypeError: ## whichconv = raw_input("""Convert to: ##1: Binary ##2: Hexadecimal ##3: Decimal ##""") ## if whichconv in('1','Binary','binary','Bin','bin','B','b'): ## convertxtbin() ## print ''.join(res) ## elif whichconv in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): ## convertxthex() ## elif whichconv in('3','Decimal','decimal','Dec','dec','D','d'): ## convertxtnum() except ValueError: ##if its not numbers whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal 3: Decimal """) ##what conversion? if whichconv in('1','Binary','binary','Bin','bin','B','b'): ##if binary convertxtbin() ##convert text to binary elif whichconv in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): ##if hexadecimal convertxthex() ##convert text to hexadecimal Line 128 elif whichconv in('3','Decimal','decimal','Dec','dec','D','d'): ##if decimal convertxtnum() ##convert text to decimal print res ##print the list entries together on a line else: ##if the text is numbers whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal 3: Text """) ##which conversion? str(original) ##convert numbers back to a string convertnum() ##convert numbers to whatever more = raw_input("Would you like to convert more text or numbers [y/n]? ") ##more? if more in 'Yy': ##if so, continue loop pass elif more in 'Nn': ##if not, again = False ##break loop print "Thank you for using Multivert. Multivert will now close" ##loop broken, prints message time.sleep(1.1) ##waits for 1.1 seconds so message can be read ##end of program; program closes Thanks in advance, Orri -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040614/efd1d0b8/attachment-0001.html From orbitz at ezabel.com Mon Jun 14 17:40:49 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Jun 14 17:43:06 2004 Subject: [Tutor] KeyError In-Reply-To: <92.d712327.2dff6bce@aol.com> References: <92.d712327.2dff6bce@aol.com> Message-ID: <20040614174049.63a55471.orbitz@ezabel.com> This reply may come off as harsh, but I beleive it is in your best interest to follow it. Delete this code and start from scratch. What you are trying to do can be done in atleast half the amount of code you have given, and much cleaner. You should really be passing parameters and using more generic functions. This is really not like anything any python tutorial teachs from what I've seen. Looks like you are taking bad practices from other languages an dusing it here. Please, just rewrite the whole thign from scratch. If you take the time to think it over you should come up with something that works better, in less time, and far easier to debug. On Mon, 14 Jun 2004 16:59:58 EDT Dragonfirebane@aol.com wrote: > Hello all, > > Using the command prompt to run my program, the following error occurs. I do > not believe it is because I'm using the command prompt because the same error > occurs in IDLE. Since I used the same structure to convert text to binary as > I did to convert text to hexadecimal (see code below error), I do not > understand why the hexadecimal conversion doesn't work but the binary does. > Additionally, much of the commenting had not been updated and is no longer > correct, so please disregard any apparent misunderstanding through comments. > > C:\Program Files\Python 2.3.4c1\Programming\Programs (Complete)>python > hexadecimal-binary-text.py > Please enter numbers or text to be converted. "Hello. My name is Bob," said > Fred. > Convert to: > 1: Binary > 2: Hexadecimal > 3: Decimal > 2 > Traceback (most recent call last): > File "Hexadecimal-Binary-Text.py", line 128, in ? > convertxthex() ##convert text to hexadecimal > File "Hexadecimal-Binary-Text.py", line 36, in convertxthex > res += hexadec[c] ##same deal > KeyError: 'C' > > > def convertxtbin(): ##convert text to binary > for char in original: ##loops over the entire entry > x = 0 ##allows checking every character against the entire alphabet > list > if char in punct: > res += char > elif char in alphabet: > while x <= 26: ##if the character is punctuation or a lowercase > letter > if char in alphabet[x]: ##if its in the dictionary > asOctal = "%o" % int(number[x]) > global res > for c in asOctal: > res += binary[c] ##add the corresponding entry in > the binary list to the res list > if char not in punct: ##if the character isn't punctuation > res += ' ' ##add a space at the end to separate > numbers > x += 1 ##adds 1 to the value of x so the loop doesnt go on > forever > while 26 < x <= 52: ##if the character is an uppercase letter > if char in alphabet[x]: ##if the character is in the alphabet > dictionary > asOctal = "%o" % int(number[x - 26]) > global res > for c in asOctal: > res += binary[c] ##print the corresponding entry in > the binary entry (A = entry 36, so 36 - 26 = entry 10 = '01' = a) > if char not in punct: ##if character isn't punctuation > res += ' ' ##add a space at the end > x += 1 ##adds 1 to x so the loop ends eventually > def convertxthex(): ##convert text to hexadecimal > for char in original: ##same deal > x = 0 ##same deal > if char in punct: > res += char > elif char in alphabet: > while x <= 26: ##same deal > if char in alphabet[x]: ##same deal > asHex = "%X" % int(number[x]) > global res > for c in asHex: > res += hexadec[c] ##same deal Line 36 > if char not in punct: ##same deal > res += ' ' ##same deal > x += 1 ##same deal > while 26 < x <= 52: ##same deal > if char in alphabet[x]: ##same deal > asHex = "%X" % int(number[x - 26]) > global res > for c in asHex: > res += hexadec[c] ##same deal > if char not in punct: ##same deal > res += ' ' ##same deal > x += 1 ##same deal > def convertxtnum(): ##convert text to decimal > for char in original: ##same deal > x = 0 ##same deal > while x <= 34: ##same deal > if char in alphabet[x]: ##same deal > res.append(number[x]) ##same deal > if char not in alphabet[:8]: ##same deal > res.append(' ') ##same deal > x += 1 ##same deal > while 34 < x <= 60: ##same deal > if char in alphabet[x]: ##same deal > res.append(number[x - 26]) ##same deal > if char not in alphabet[:8]: ##same deal > res.append(' ') ##same deal > x += 1 ##same deal > def convertnum(): ##converts numbers > if whichconv in('1','Binary','binary','Bin','bin','B','b'): ##if user > wants to convert to binary > if int(original) <= 0: > print "Please enter a positive number. " > try: > int(original) > except ValueError: > x = 0 > if char in punct[x]: > print [punct[x] for c in original] ##prints the corresponding > binary entry (if '12' is entered, it is treated as a string, so > binary[int(original) - 1] converts it to an integer and subtracts one from it > so that the corresponding entry can be printed since the first entry in a list > is 0 > x += 1 > else: > asOctal = "%o" % int(original) > print ''.join([binary[c] for c in asOctal]) > elif whichconv > in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): > ##same deal > if original >= 0: > print hexadec[int(original) + 8] ##same deal > else: > print "Please enter a positive number. " > elif whichconv in('3','Text','text','T','t'): ##same deal > if int(original) <= 26: ##if the number is between 8 and 27 (the > lowercase letters of the alphabet list > print alphabet[int(original) + 8] ##it prints the corresponding > entry in the alphabet list > else: ##if its not one of those numbers > print "Sorry, you didn't enter a valid number. Please enter only > numbers between 0 and 26." ##prints message > > import time ##for time.sleep(1.1) at end > import string > > alphabet = [' > ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s' > ,'t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L', > 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] > ##define the alphabet list > punct = ['.',',',';',':','?','!','"',"'"] > binary = {'0':'000','1':'001','2':'010', > '3':'011','4':'100','5':'101', > '6':'110','7':'111'} ##define the binary dictionary > number = > ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',' > 17','18','19','20','21','22','23','24','25','26','27','28','29','30',' > 31','32','33','34'] ##defines the number entry. goes up to 34 so > convertnum() will work under the text conversion hexadec = > {'0':'0','1':'1','2':'2','3':'3','4':'4','5':'5','6':'6','7':'7','8':'8','9': > '9','10':'A','11':'B','12':'C','13':'D','14':'E','15':'F'} > ##defines the hexadecimal list > > res = '' ##makes an empty list so all the conversions will work > again = True ##beginning condition for loop > while again: ##starts loop > original = raw_input("Please enter numbers or text to be converted. ") > ##enter text to be converted > try: > int(original) ##distinguishes the numbers from the text, needs to > be revised to distinguish binary and hexadecimal > ## except TypeError: > ## whichconv = raw_input("""Convert to: > ##1: Binary > ##2: Hexadecimal > ##3: Decimal > ##""") > ## if whichconv in('1','Binary','binary','Bin','bin','B','b'): > ## convertxtbin() > ## print ''.join(res) > ## elif whichconv > in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): > ## convertxthex() > ## elif whichconv in('3','Decimal','decimal','Dec','dec','D','d'): > ## convertxtnum() > except ValueError: ##if its not numbers > whichconv = raw_input("""Convert to: > 1: Binary > 2: Hexadecimal > 3: Decimal > """) ##what conversion? > if whichconv in('1','Binary','binary','Bin','bin','B','b'): ##if > binary > convertxtbin() ##convert text to binary > elif whichconv > in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): > ##if hexadecimal > convertxthex() ##convert text to hexadecimal Line 128 > elif whichconv in('3','Decimal','decimal','Dec','dec','D','d'): ##if > decimal > convertxtnum() ##convert text to decimal > print res ##print the list entries together on a line > else: ##if the text is numbers > whichconv = raw_input("""Convert to: > 1: Binary > 2: Hexadecimal > 3: Text > """) ##which conversion? > str(original) ##convert numbers back to a string > convertnum() ##convert numbers to whatever > more = raw_input("Would you like to convert more text or numbers [y/n]? > ") ##more? > if more in 'Yy': ##if so, continue loop > pass > elif more in 'Nn': ##if not, > again = False ##break loop > print "Thank you for using Multivert. Multivert will now close" ##loop > broken, prints message > time.sleep(1.1) ##waits for 1.1 seconds so message can be read > ##end of program; program closes > > Thanks in advance, > Orri > From Dragonfirebane at aol.com Mon Jun 14 17:50:59 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 14 17:51:22 2004 Subject: [Tutor] KeyError Message-ID: <12b.43fa5952.2dff77c3@aol.com> In a message dated 6/14/2004 5:43:51 PM Eastern Standard Time, orbitz@ezabel.com writes: This reply may come off as harsh, but I beleive it is in your best interest to follow it. Delete this code and start from scratch. What you are trying to do can be done in atleast half the amount of code you have given, and much cleaner. You should really be passing parameters and using more generic functions. This is really not like anything any python tutorial teachs from what I've seen. Looks like you are taking bad practices from other languages an dusing it here. Please, just rewrite the whole thign from scratch. If you take the time to think it over you should come up with something that works better, in less time, and far easier to debug. Whether or not I take your advice, I would like to have something to build off of for the new attempt, which means that i will need a semi-functional program (the one i'm working on now). So regardless of whether or not i start over, i must first finish this attempt. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040614/aefbec6e/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Jun 14 18:33:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 14 18:33:33 2004 Subject: [Tutor] KeyError In-Reply-To: <92.d712327.2dff6bce@aol.com> Message-ID: On Mon, 14 Jun 2004 Dragonfirebane@aol.com wrote: > Using the command prompt to run my program, the following error occurs. > I do not believe it is because I'm using the command prompt because the > same error occurs in IDLE. Since I used the same structure to convert > text to binary as I did to convert text to hexadecimal (see code below > error), I do not understand why the hexadecimal conversion doesn't work > but the binary does. Hi Dragonfirebane, Ok, let's take a look. > Additionally, much of the commenting had not been updated and is no > longer correct, so please disregard any apparent misunderstanding > through comments. If the comments don't follow the code, drop the comments. Incorrect comments do much more damage than good. And comments that just say "same deal" are, frankly speaking, not useful. We can tell that it's similar to the other conversion functions by just looking at them. Here's converttxthex() with the comments stripped out: ### def convertxthex(): for char in original: x = 0 if char in punct: res += char elif char in alphabet: while x <= 26: if char in alphabet[x]: asHex = "%X" % int(number[x]) global res for c in asHex: res += hexadec[c] if char not in punct: res += ' ' x += 1 while 26 < x <= 52: if char in alphabet[x]: asHex = "%X" % int(number[x - 26]) global res for c in asHex: res += hexadec[c] if char not in punct: res += ' ' x += 1 ### Hmm... I'd strongly suggest reducing and simplifying the code here. The thing about long functions is that they're not fun to debug. The thing about highly nested functions is that they're hard to reason with. Your converttxthex is both long and deeply nested. *grin* Let's try shortening it first. The bodies of both inner while loops look almost exactly the same, so we can reduce the code by limiting the conditional statement to the line that's varying, ### asHex = "%X" % int(number[x - 26]) ### With this change, we can collapse those two while loops into one: ### def convertxthex(): for char in original: if char in punct: res += char elif char in alphabet: x = 0 while x <= 52: if char in alphabet[x]: if x <= 26: asHex = "%X" % int(number[x]) else: asHex = "%X" % int(number[x - 26]) global res for c in asHex: res += hexadec[c] if char not in punct: res += ' ' x += 1 ### At the same time, I did a little bit of reorganizing: the initialization of 'x=0' should be close to its usage as an indexing variable, right next to the loop: it has nothing to do with what happens if the character is punctuation, so that's why 'x=0' belongs in the 'elif char in alphabet' body. I still don't clearly understand the code's structure, since there's some heavy nesting of the code. I will break it out into some helper functions: ### def convertxthex(): global res for char in original: if char in punct: res += char elif char in alphabet: convert_txt_hex_alphabet(char) def convert_txt_hex_alphabet(char): global res x = 0 while x <= 52: if char in alphabet[x]: if x <= 26: asHex = "%X" % int(number[x]) else: asHex = "%X" % int(number[x - 26]) for c in asHex: res += hexadec[c] if char not in punct: res += ' ' x += 1 ### Ok, the structure is a little clearer here. There are several things in convert_txt_hex_alphabet_char() that look very fishy. The 'hexadec' dictionary is defined as: ### hexadec = {'0':'0', '1':'1', '2':'2', '3':'3', '4':'4', '5':'5', '6':'6', '7':'7', '8':'8', '9': '9', '10':'A', '11':'B', '12':'C', '13':'D', '14':'E', '15':'F'} ### So conceptually, it's taking in a digit string, and returning the corresponding hexadecimal value. But 'asHex' here is defined as: ### asHex = "%X" % int(number[x]) ### and this has no guarantee of being a digit string. If we try asking 'hexadex' a key/value that it doesn't have, we'll get KeyError. In fact, take a look at what the '%X' stuff is giving you back: ### >>> for i in range(16): ... print i, "%X" % i ... 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 A 11 B 12 C 13 D 14 E 15 F ### "%X" already does hexadecimal conversion for you, so asHex is not guaranteed to be a digit string. That's the bug in the program. The approach that you're taking now is very bug-prone. I strongly recommend you reconsider the program's approach here. I'd also strongly suggest that you cut down the program's behavior to just converting between a pair of types, and get that working nicely first. Trying to add and extend the functionality of a buggy program is not a good idea. A lot of the program logic can dissolve if you use 'ord()' to convert from a character to a particular number. ord() is a built-in function, and is described here: http://www.python.org/doc/lib/built-in-funcs.html#l2h-52 Good luck to you. From tim at johnsons-web.com Mon Jun 14 18:56:58 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Jun 14 18:51:09 2004 Subject: [Tutor] Null Object Design Pattern Question [sentinels and Minesweeper] In-Reply-To: References: Message-ID: <20040614225658.GC1234@johnsons-web.com> Thanks to all for the pointers and examples on the topic. I believe you've given me a good handle on the NOP. cheers tim * Danny Yoo [040614 00:20]: > > On Sun, 13 Jun 2004, [ISO-8859-1] Gon?alo Rodrigues wrote: > > > >I have been looking at > > > > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 > > > > > >which has an example of using a Null() object. > > > > > >Unfortunately, I'm having a problem wrapping my brain around the > > >usefulness of this object compared to just using None. > > > > > >Does anyone have some further examples of the 'superiority' of this > > >approach over *None*. > > > > Imagine a null object as a kind of sink: it responds to all messages > > without barfing. > > > Hi Tim, > > If you're familiar with the use of a "sentinel" to simplify a program's > logic, then you can think of a "Null Object" as an OOP analogy to a > sentinel. > > > I like using concrete examples, and one of the nice examples where > sentinels come in really handy is something like a Minesweeper-like game > program. Here's a quick link to one: > > http://www.programming-challenges.com/pg.php?page=downloadproblem&probid=110102&format=html > > In the game of Minesweeper, we might want to report the number of mines > adjacent to a space. For example, if we have: > > *... > .... > .*.. > .... > > we'd like to get back something like: > > *100 > 2210 > 1*10 > 1110 > > > If we represent a minefield as a list of rows, like this: > > minefield = ['*...', > '....', > '.*..', > '....'] > > and if we wanted to get the number of mines at an > arbitrary row and col, we might write something like: > > ### > def countMines(row, col): > """Returns the number of mines around position(row, col).""" > count = 0 > for i in [-1, 0, 1]: > for j in [-1, 0, 1]: > if minefield[row + i][col +j] == '*': > count += 1 > return count > ### > > > The only problem is that this code doesn't work. *grin* > > ### > >>> countMines(3, 3) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 6, in countMines > IndexError: string index out of range > ### > > The problem is that there's this special logic around the edges of the > board, so our beautiful countMines() function malfunctions around the > board edges. > > > One way to fix countMines() is to add special-case logic into countMines() > for counting mines around the edges of the board, maybe something like: > > ### > if not (0 <= row + i < 4): continue > ### > > > But there's another way of fixing the problem, and it involves using > sentinels. In effect, we take something like: > > *... > .... > .*.. > .... > > > and wrap a sentinel border of '=' characters around the whole game board: > > ====== > =*...= > =....= > =.*..= > =....= > ====== > > With this sentinel border, the code doesn't have to worry about the edge > of the board so much. If I ask for the number of mines on the > bottom-right corner --- countMines(4, 4) --- then we're perfectly ok, > since we don't go off the board. Does this make sense? > > > Null Objects perform a similar function: they are "sentinels" that allow > us to simplify our main code, so that we don't have to worry so much about > the special case of handling a reference to None. > > > Hope this helps! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From Dragonfirebane at aol.com Mon Jun 14 21:08:54 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 14 21:09:32 2004 Subject: [Tutor] Local/Global Variable Message-ID: <7d.5099e3ea.2dffa626@aol.com> It is my understanding that if python does not find a variable locally, it is coded to look for it globally. However, every time i attempt to run a certain program, it comes up with an UnboundLocalError despite the fact that i defined the variable outside of the loop in the outermost area of code. Short of inserting 'global variablename' in every loop, is there any way to remedy this? Relevant segment(s) of code: def convertnum(): if whichconv in('1','Binary','binary','Bin','bin','B','b'): if int(original) <= 0: print "Please enter a positive number. " try: int(original) except ValueError: x = 0 for char in original: if char in punct: res += char x += 1 else: asOctal = "%o" % int(original) for char in asOctal: res += str(binary[char]) ##heres the problem . . . ... ... res = '' again = True while again: ... original = raw_input("Please enter numbers or text to be converted. ") ... str(original) convertnum() print res Error: Traceback (most recent call last): File "C:\Program Files\Python 2.3.4c1\Programming\Programs (Complete)\Hexadecimal-Binary-Text.py", line 147, in ? convertnum() ##convert numbers to whatever File "C:\Program Files\Python 2.3.4c1\Programming\Programs (Complete)\Hexadecimal-Binary-Text.py", line 83, in convertnum res += str(binary[char]) UnboundLocalError: local variable 'res' referenced before assignment -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040614/281585c7/attachment-0001.html From orbitz at ezabel.com Mon Jun 14 21:51:56 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Jun 14 21:52:03 2004 Subject: [Tutor] Local/Global Variable In-Reply-To: <7d.5099e3ea.2dffa626@aol.com> References: <7d.5099e3ea.2dffa626@aol.com> Message-ID: <20040614215156.3f0579d6.orbitz@ezabel.com> The eror only shows itself when you do semthing like: globalvar = 1 def foo(): globalvar += 1 The interpreter see's yoau re assignign, and decides to think it's a local variable. The remedy is easy: def foo(): global globalvar globalvar += 1 You don't need to do it in every loop ro anything, since loops don't have thier own scope Anything you wish to do this with, you just can do it at the beginning of your method, or before you use the variable atleast. On Mon, 14 Jun 2004 21:08:54 EDT Dragonfirebane@aol.com wrote: > It is my understanding that if python does not find a variable locally, it is > coded to look for it globally. However, every time i attempt to run a certain > program, it comes up with an UnboundLocalError despite the fact that i > defined the variable outside of the loop in the outermost area of code. Short > of inserting 'global variablename' in every loop, is there any way to remedy > this? Relevant segment(s) of code: > > def convertnum(): > if whichconv in('1','Binary','binary','Bin','bin','B','b'): > if int(original) <= 0: > print "Please enter a positive number. " > try: > int(original) > except ValueError: > x = 0 > for char in original: > if char in punct: > res += char > x += 1 > else: > asOctal = "%o" % int(original) > for char in asOctal: > res += str(binary[char]) ##heres the problem . . . > > ... > ... > res = '' > again = True > while again: > ... > original = raw_input("Please enter numbers or text to be converted. ") > ... > str(original) > convertnum() > print res > > > Error: > > Traceback (most recent call last): > File "C:\Program Files\Python 2.3.4c1\Programming\Programs > (Complete)\Hexadecimal-Binary-Text.py", line 147, in ? > convertnum() ##convert numbers to whatever > File "C:\Program Files\Python 2.3.4c1\Programming\Programs > (Complete)\Hexadecimal-Binary-Text.py", line 83, in convertnum > res += str(binary[char]) > UnboundLocalError: local variable 'res' referenced before assignment > From Dragonfirebane at aol.com Mon Jun 14 22:44:19 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 14 22:45:01 2004 Subject: [Tutor] KeyError Message-ID: <149.2bc12256.2dffbc83@aol.com> Skipped content of type multipart/alternative-------------- next part -------------- def convertxtbin(): ##convert text to binary for char in original: ##loops over the entire entry global res x = 0 ##allows checking every character against the entire alphabet list if char in punct: ##if character is punctuation res = split(res) ##prints contents of res into a list and names it res res.append(' ') ##adds a space at the end del res[-1] ##deletes the space res = ' '.join(res) ##returns res to string form res += char ##adds punctuation elif char in alphabet: ##if the character is in the alphabet while x <= 26: ##if the character is a lowercase letter or space if char in alphabet[x]: ##redundant. only there to allow x += 1 to stay inside the while loop but outside the ifs asOctal = "%o" % int(number[x]) ##converts alphabet number (a = 1) to an unsigned octal for char in asOctal: ##for character in resulting octal res += binary[char] ##add the corresponding entry in the binary list to the res list if char not in punct: ##if the character isn't punctuation res += ' ' ##add a space at the end to separate numbers x += 1 ##adds 1 to the value of x so the loop doesnt go on forever while 26 < x <= 52: ##if the character is an uppercase letter if char in alphabet[x]: ##if the character is in the alphabet dictionary asOctal = "%o" % int(number[x - 26]) ##converts alphabet number (A = 1) to an unsigned octal for char in asOctal: res += binary[char] if char not in punct: res += ' ' x += 1 def convertxthex(): ##convert text to hexadecimal for char in original: global res x = 0 if char in punct: res = split(res) res.append(' ') del res[-1] res = ' '.join(res) res += char elif char in alphabet: while x <= 26: if char in alphabet[x]: asHex = "%X" % int(number[x]) ##convert alphabet number to corresponding Hexadecimal number res += asHex ##add hexadecimal number to string if char not in punct: res += ' ' x += 1 while 26 < x <= 52: if char in alphabet[x]: asHex = "%X" % int(number[x - 26]) ##convert alphabet number to corresponding hex number res += asHex if char not in punct: res += ' ' x += 1 def convertxtnum(): ##convert text to decimal for char in original: global res x = 0 if char in punct: res = split(res) res.append(' ') del res[-1] res = ' '.join(res) res += char elif char in alphabet: while x <= 52: if x == 0: if char == alphabet[x]: ##if character is a space res += '%d' % int(ord(char) - 32) ##add a space to the string if char not in punct: res += ' ' x += 1 elif 0 < x <= 26: ##if character is a lowercase letter if char in alphabet[x]: res += '%d' % int(ord(char) - 96) ##add corresponding number to string if char not in punct: res += ' ' x += 1 elif 26 < x <= 52: ##if character is an uppercase letter if char in alphabet[x]: res += '%d' % int(ord(char) - 64) if char not in punct: res += ' ' x += 1 def convertnum(): ##converts numbers if whichconv in('1','Binary','binary','Bin','bin','B','b'): ##if user wants to convert to binary if int(original) <= 0: ##if negative number entered global res global original res += '-' original = -int(original) try: int(original) except ValueError: x = 0 for char in original: if char in punct: res += char x += 1 else: asOctal = "%o" % int(original) for char in asOctal: res += str(binary[char]) elif whichconv in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): if int(original) <= 0: res += '-' original = -int(original) asHex = "%X" % int(original) res += asHex elif whichconv in('3','Text','text','T','t'): if int(original) == 0: res += '%s' % chr(int(original) + 32) elif 0 < int(original) <= 26: ##if the number is between 8 and 27 (the lowercase letters of the alphabet list res += '%s' % chr(int(original) + 96) elif 26 < int(original) <= 52: res += '%s' % chr(int(original) - 64) else: ##if its not one of those numbers print "Sorry, you didn't enter a valid number. Please enter only numbers between 0 and 26." ##prints message import time ##for time.sleep(1.1) at end import string alphabet = [' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] ##define the alphabet list punct = ['-','.',',',';',':','?','!','"',"'"] binary = {'0':'000','1':'001','2':'010', '3':'011','4':'100','5':'101', '6':'110','7':'111'} ##define the binary dictionary number = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34'] ##defines the number entry. goes up to 34 so convertnum() will work under the text conversion hexadec = {'0':'0','1':'1','2':'2','3':'3','4':'4','5':'5','6':'6','7':'7','8':'8','9':'9','10':'A','11':'B','12':'C','13':'D','14':'E','15':'F'} ##defines the hexadecimal list allconv = '' res = '' again = True ##beginning condition for loop while again: ##starts loop res = '' ##makes an empty list so all the conversions will work original = raw_input("Please enter numbers or text to be converted. ") ##enter text to be converted try: int(original) ##distinguishes the numbers from the text, needs to be revised to distinguish binary and hexadecimal ## except TypeError: ## whichconv = raw_input("""Convert to: ##1: Binary ##2: Hexadecimal ##3: Decimal ##""") ## if whichconv in('1','Binary','binary','Bin','bin','B','b'): ## convertxtbin() ## print ''.join(res) ## elif whichconv in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): ## convertxthex() ## elif whichconv in('3','Decimal','decimal','Dec','dec','D','d'): ## convertxtnum() except ValueError: ##if its not numbers whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal 3: Decimal """) ##what conversion? if whichconv in('1','Binary','binary','Bin','bin','B','b'): ##if binary convertxtbin() ##convert text to binary elif whichconv in('2','Hexadecimal','hexadecimal','Hexadec','hexadec','Hex','hex','H','h'): ##if hexadecimal convertxthex() ##convert text to hexadecimal elif whichconv in('3','Decimal','decimal','Dec','dec','D','d'): ##if decimal convertxtnum() ##convert text to decimal print res ##print the list entries together on a line else: ##if the text is numbers whichconv = raw_input("""Convert to: 1: Binary 2: Hexadecimal 3: Text """) ##which conversion? str(original) ##convert numbers back to a string convertnum() ##convert numbers to whatever print res allconv += res + '_____' more = raw_input("Would you like to convert more text or numbers [y/n]? ") ##more? if more in 'Yy': ##if so, continue loop pass elif more in 'Nn': ##if not, again = False ##break loop callconv = raw_input("Would you like to see all the conversions made during this session [y/n]? ") if callconv in('y','Y','1','yes','Yes'): print allconv else: pass print "Thank you for using Multivert. Multivert will now close" ##loop broken, prints message time.sleep(1.1) ##waits for 1.1 seconds so message can be read ##end of program; program closes From alan.gauld at blueyonder.co.uk Tue Jun 15 02:38:04 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jun 15 02:37:38 2004 Subject: [Tutor] Local/Global Variable References: <7d.5099e3ea.2dffa626@aol.com> Message-ID: <003701c452a3$50111460$6401a8c0@xp> > It is my understanding that if python does not find a variable locally, it is > coded to look for it globally. Correct, where globally means in the same file but outside any class or functionn definitions. > defined the variable outside of the loop in the outermost area of code. Short of > inserting 'global variablename' in every loop, is there any way to remedy this? > Relevant segment(s) of code: You only need to put the global declaration in the function not in each loop. Thus in your sample you could put the global statement as the first statement inside the function. > def convertnum(): global res > if whichconv in('1','Binary','binary','Bin','bin','B','b'): > if int(original) <= 0: etc... > for char in original: > if char in punct: > res += char Note that if you had not been assigning a value to res you would not need the global statement, but because you are trying to assign to it PYthon is attempting to create a local variable called res. But because the value of res relies on res (effectively you are saying res = res + 1 which Python cannot compute) > UnboundLocalError: local variable 'res' referenced before assignment Which is why the error is phrased the way it is. Python makes use of global variables slightly awkward for the very good reason that global variables are bad pratice, so you have to have a good reason for using them. In most cases where you might try to use a global it is better to pass a parameter in or return a value. Python ties quite hard to encourage good programming habits while not preventing you from avoiding them if you really need to. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Tue Jun 15 02:42:04 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jun 15 02:41:42 2004 Subject: [Tutor] Local/Global Variable References: <7d.5099e3ea.2dffa626@aol.com> <20040614215156.3f0579d6.orbitz@ezabel.com> Message-ID: <004d01c452a3$df0685b0$6401a8c0@xp> > The eror only shows itself when you do semthing like: > > globalvar = 1 > > def foo(): > globalvar += 1 > > The interpreter see's yoau re assignign, and decides to think it's a local > variable. Normally you'd be right but in this case the actual error he got can be found in this situation too: def foo(): bar += 1 And could be solved with: def foo(): bar = 0 bar += 1 In both cases the += operator needs a predefined variable to compute the result. Whether it is global or not is a variant on the problem but not directly related. Alan G From rumpy at mrbitter.org Tue Jun 15 17:13:38 2004 From: rumpy at mrbitter.org (Josh Eror) Date: Tue Jun 15 17:12:13 2004 Subject: [Tutor] On-line courses. In-Reply-To: <20040614215156.3f0579d6.orbitz@ezabel.com> References: <7d.5099e3ea.2dffa626@aol.com> <20040614215156.3f0579d6.orbitz@ezabel.com> Message-ID: <1087334018.40cf66827f054@mrbitter.org> Hi Folks, I'm very interested if taking a Python Course to accelerate my learning. My preference is for a Web Course if possible, but I'd certainly attend a boot camp type training. The cost of the course isn't so much of an issue. If it's good, and recommended here, I'll buck up for it. BTW, the many Python Books I have are great. I have learned a great deal already. It's simply a matter of wanting to pick up the pace and try a different mechanism for absorbing the subject. Thanks in advance for your suggestions, Josh. From magnus at thinkware.se Tue Jun 15 18:33:46 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Jun 15 18:34:00 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gT24tbGluZSBjb3Vyc2VzLg==?= Message-ID: There aren't so many commercial offerings for Python courses that I know of. Also, I don't know where in the world you are... If you visit OSCON in july, you'll get a chance to attend some Python tutorials, but note that early bird registration ends June 18! http://conferences.oreillynet.com/pub/w/29/tutorial_python.html Otherwise there are some well known Python trainers in the USA, such as Wesley Chun http://roadkill.com/~wesc/cyberweb/services.html and Mark Lutz http://www.rmi.net/~lutz/mytrain.html . You just missed one of Mark's classes in Colorado... There are more trainers out there, but these are the ones I know of in the US who regularly give open classes. Others do on-site training for companies etc. -----Ursprungligt meddelande----- Fr?n: Josh Eror Skickat: 2004-06-15 23:13:38 Till: tutor@python.org ?mne: [Tutor] On-line courses. > Hi Folks, > > > I'm very interested if taking a Python Course to accelerate my learning. My > preference is for a Web Course if possible, but I'd certainly attend a boot > camp type training. The cost of the course isn't so much of an issue. If it's > good, and recommended here, I'll buck up for it. > > BTW, the many Python Books I have are great. I have learned a great deal > already. It's simply a matter of wanting to pick up the pace and try a > different mechanism for absorbing the subject. > > > Thanks in advance for your suggestions, > > Josh. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From gubbs at fudo.org Tue Jun 15 21:23:03 2004 From: gubbs at fudo.org (Conrad Gavin) Date: Tue Jun 15 20:11:08 2004 Subject: [Tutor] pstree cgi-script Message-ID: <1087348983.10755.6.camel@drachenfels> Hi there. I'm trying to write a simple little cgi-script that executes pstree and echos/prints the output to the webpage .. Clearly I am doing it wrong, as it will not work. Here's my code: #!/usr/bin/python import os cmd = "pstree" status = os.system(cmd) print "Status:", status When I run it .. I get the following error from Apache: [Wed Jun 16 01:18:14 2004] [error] [client 81.104.190.151] malformed header from script. Bad header=init-+-5*[agetty]: hello.py When run from the python intepreter its clearly working: [drachenfels][~/Desktop]$ python hello.py init-+-5*[agetty] |-apache2---3*[apache2] |-aterm---bash---azureus---java |-aterm---bash---su---bash |-aterm---bash |-aterm---bash---python---pstree |-bonobo-activati |-devfsd |-dhcpcd |-epiphany-bin |-esd |-events/0-+-aio/0 | |-kblockd/0 | |-2*[pdflush] | `-reiserfs/0 |-evolution-1.4 |-evolution-alarm |-evolution-womba |-gaim |-gconfd-2 |-gnome-panel |-gnome-settings- |-gnome-smproxy |-idle---python |-kseriod |-ksoftirqd/0 |-kswapd0 |-login---bash---startx---xinit-+-X | `-gnome-session |-metacity |-metalog---metalog |-nautilus |-nautilus-text-v |-nautilus-throbb |-notification-ar |-proftpd |-sshd |-wnck-applet |-xchat-2 `-xscreensaver Status: 0 I suspect there's something wrong with the way I am outputting .. as the first line of the program's output is being fed directly to apache by the looks of it, which is righlty getting very confused. How can I make this work out? Conrad. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20040616/156859a4/attachment.bin From flaxeater at yahoo.com Tue Jun 15 23:20:29 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Jun 15 23:20:36 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1087348983.10755.6.camel@drachenfels> Message-ID: <20040616032029.29572.qmail@web52605.mail.yahoo.com> --- Conrad Gavin wrote: > Hi there. > > I'm trying to write a simple little cgi-script that executes pstree > and > echos/prints the output to the webpage .. > > Clearly I am doing it wrong, as it will not work. > > Here's my code: > > #!/usr/bin/python > > import os > cmd = "pstree" > status = os.system(cmd) > print "Status:", status > Ok this is an easy one. I also had this problem at first with cgi. you need to put print "text/plain/n/n" in this case at the begining of the script this tells apache to tell the browser whats going on. Otherwise apache croaks. If you outputing html then type print "text/html/n/n" The two caraiage returns are important. There you go good luck __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From carroll at tjc.com Wed Jun 16 01:14:54 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Jun 16 01:15:00 2004 Subject: [Tutor] Printing a progress bar In-Reply-To: <40CC0C7F.5000102@pusspaws.net> Message-ID: On Sun, 13 Jun 2004, Dave S wrote: > Some of the code I have written handels a lot of data, I would like to > add a progress bar. I use Randy Pargman's progress bar from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 ; I find it does the job nicely. From dyoo at hkn.eecs.berkeley.edu Wed Jun 16 18:53:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jun 16 19:06:49 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1087428070.29204.4.camel@drachenfels> Message-ID: On Wed, 16 Jun 2004, Conrad Gavin wrote: > Btw did you test this script on your own apache before sending it to me? > Did it work? Good question. No. *grin* I have tested the following version of the code: ###### #!/usr/bin/python import sys import os import cgitb; cgitb.enable() sys.stdout.write("Content-type: text/plain\n\n") cmd = "/usr/bin/pstree" status = os.popen(cmd).read() print status ###### I can confirm that this works on my machine. The major fix here is to use os.popen() instead of os.system(). os.system() returns the "errorlevel" of the program, not its standard output. os.popen() is probably what you want to use to capture the output of other programs. Good luck! From magnus at thinkware.se Wed Jun 16 20:07:47 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 17 06:13:58 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gT24tbGluZSBjb3Vyc2VzLg==?= Message-ID: BTW, I stumbled over this: http://www.icanprogram.com/pythonlinux.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Jun 16 19:59:29 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 17 06:14:39 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gT24tbGluZSBjb3Vyc2VzLg==?= Message-ID: > Thank you Magnus. I have to say that I'm a little surprised this niche has yet > to filled. On-line education still seems to be struggling to develop > curriculum that can teach more advanced subjects. Oh well, thanks again. I think there are two "problems" here: One is that Python isn't so widely used in the commercial sector that companies frequently decide to send employees on Python training. While a lot of people (like me) use Python in a commercial environment, this is often a grass roots effort, rather than a corporate strategy--simply because there is no big sales force that market Python to management. Secondly, Python is easy to learn, so people typically don't feel a big need for formal training. But I agree that formal training might give you a kick-start which is helpful. There are plenty of on-line Python tutorials though, and I think the people on the Tutor mailing list are very helpful in assisting people who are trying to learn Python. But I think you are right. I'm wondering what it would take to get an on-line Python-course to work... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Wed Jun 16 14:33:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 17 06:16:27 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <20040616032029.29572.qmail@web52605.mail.yahoo.com> Message-ID: On Tue, 15 Jun 2004, Chad Crabtree wrote: > --- Conrad Gavin wrote: > > Hi there. > > > > I'm trying to write a simple little cgi-script that executes pstree > > and > > echos/prints the output to the webpage .. > > > > Clearly I am doing it wrong, as it will not work. > > > > Here's my code: > > > > #!/usr/bin/python > > > > import os > > cmd = "pstree" > > status = os.system(cmd) > > print "Status:", status > > > Ok this is an easy one. I also had this problem at first with cgi. > you need to put > print "text/plain/n/n" > > The two caraiage returns are important. There you go good luck Hi Chad, Small correction: this should really be: ### print "Content-type: text/plain\n\n" ### according to the CGI spec: http://hoohoo.ncsa.uiuc.edu/cgi/out.html The reason why the Content-type header is important, and why it has to be explicitely defined, is because CGI programs can generate more than dynamic text content: CGI's can just as easily do things like dynamic images. Page counters are one example of such a dynamic image CGI. Hope this helps! From clavezza at hotmail.com Wed Jun 16 16:22:54 2004 From: clavezza at hotmail.com (christopher lavezza) Date: Thu Jun 17 07:26:09 2004 Subject: [Tutor] FW: Module 1 question Message-ID: Can anyone help us out with this problem in our script? >From: Chad Varner >To: clavezza@hotmail.com >Subject: Module 1 question >Date: Tue, 15 Jun 2004 20:47:29 -0500 > >Chris, > > Did you get an answer from your professor on what he is looking for on >these modules? > >Also, I've tried running our code and it keeps giving me the following >error: > >Traceback (most recent call last): > File "Script5_1.py", line 23, in ? > a.deposit(550.23) > File "Script5_1.py", line 8, in deposit > t=time.strtime('%a, %d %b %Y %H:%M:%S' , time.localtime(time.time() >+ 0)) >AttributeError: 'module' object has no attribute 'strtime' > >Could you pass the error on to that guy you know in Colorado,and see if >he can explain what the @#$# is wrong exactly? > >Thanks, >-- >Chad Varner > _________________________________________________________________ Get fast, reliable Internet access with MSN 9 Dial-up – now 3 months FREE! http://join.msn.click-url.com/go/onm00200361ave/direct/01/ From gubbs at fudo.org Wed Jun 16 17:14:55 2004 From: gubbs at fudo.org (Conrad Gavin) Date: Thu Jun 17 08:15:41 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: References: Message-ID: <1087420495.7415.7.camel@drachenfels> On Wed, 2004-06-16 at 18:33, Danny Yoo wrote: > On Tue, 15 Jun 2004, Chad Crabtree wrote: > > > --- Conrad Gavin wrote: > > > Hi there. > > > > > > I'm trying to write a simple little cgi-script that executes pstree > > > and > > > echos/prints the output to the webpage .. > > > > > > Clearly I am doing it wrong, as it will not work. > > > > > > Here's my code: > > > > > > #!/usr/bin/python > > > > > > import os > > > cmd = "pstree" > > > status = os.system(cmd) > > > print "Status:", status > > > > > Ok this is an easy one. I also had this problem at first with cgi. > > you need to put > > print "text/plain/n/n" > > > > The two caraiage returns are important. There you go good luck > > > Hi Chad, > > Small correction: this should really be: > > ### > print "Content-type: text/plain\n\n" > ### > > according to the CGI spec: > > http://hoohoo.ncsa.uiuc.edu/cgi/out.html > > > The reason why the Content-type header is important, and why it has to be > explicitely defined, is because CGI programs can generate more than > dynamic text content: CGI's can just as easily do things like dynamic > images. Page counters are one example of such a dynamic image CGI. > > > Hope this helps! > My script still doesnt work. I sent an email to the list earlier in reply to Chad's original message but it was not posted for some reason? Anyway, here it is again .. That doesnt seem to work either .. My code now: #!/usr/bin/python ^ import os print "text/plain/n/n" cmd = "pstree" ^ status = os.system(cmd) ^ print status I have tried placing print "text/plain/n/n" and the 'html' varianteverywhere in the program it can feasably go (marked by the ^ symbol above), checked the permissions of the file etc. It still doesnt work, the same error appears in the log: [Wed Jun 16 13:15:14 2004] [error] [client 81.104.190.151] malformed header from script. Bad header=init-+-5*[agetty]: hello.py I am usingapache-2.0.49-r3, IDLE to write and save my script with and python-2.3.4. I am then moving it as root to /var/www/localhost/cgi-bin and chmod 755'ing it and then chmod +x _just_ to be absolutely certain. It seems to be running tho, as the error is pretty indicative of the line you suggested not being parsed or being ignored. This is why I asked really, I found a website that suggested using the solution you offered but it didnt work .. I'm pretty much stumped. :( Could you possibly place a working version on your server I could surf too? At least then I would be absolutely certain it was a problem with my end not the method .. I have confirmed my cgi works: http://cpc3-nfds2-6-0-cust151.nott.cable.ntl.com/cgi-bin/test-cgi Sorry to be a bother! Since Danny's message, I tried his suggestion also: #!/usr/bin/python ### print "Content-type: text/plain\n\n" ### import os cmd = "pstree" status = os.system(cmd) print status Oddly. It still does not work. I should add .. other scripts (which do not use the os module work just fine). Any further advise? :( -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20040616/a2327bf8/attachment.bin From gubbs at fudo.org Wed Jun 16 09:36:12 2004 From: gubbs at fudo.org (Conrad Gavin) Date: Thu Jun 17 08:37:39 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <20040616032029.29572.qmail@web52605.mail.yahoo.com> References: <20040616032029.29572.qmail@web52605.mail.yahoo.com> Message-ID: <1087392972.5678.20.camel@drachenfels> > --- Conrad Gavin wrote: > > Hi there. > > > > I'm trying to write a simple little cgi-script that executes pstree > > and > > echos/prints the output to the webpage .. > > > > Clearly I am doing it wrong, as it will not work. > > > > Here's my code: > > > > #!/usr/bin/python > > > > import os > > cmd = "pstree" > > status = os.system(cmd) > > print "Status:", status > > > Ok this is an easy one. I also had this problem at first with cgi. > you need to put > print "text/plain/n/n" > in this case at the begining of the script this tells apache to tell > the browser whats going on. Otherwise apache croaks. If you > outputing html then type > print "text/html/n/n" > > The two caraiage returns are important. There you go good luck That doesnt seem to work either .. My code now: #!/usr/bin/python ^ import os print "text/plain/n/n" cmd = "pstree" ^ status = os.system(cmd) ^ print status I have tried placing print "text/plain/n/n" and the 'html' varianteverywhere in the program it can feasably go (marked by the ^ symbol above), checked the permissions of the file etc. It still doesnt work, the same error appears in the log: [Wed Jun 16 13:15:14 2004] [error] [client 81.104.190.151] malformed header from script. Bad header=init-+-5*[agetty]: hello.py I am usingapache-2.0.49-r3, IDLE to write and save my script with and python-2.3.4. I am then moving it as root to /var/www/localhost/cgi-bin and chmod 755'ing it and then chmod +x _just_ to be absolutely certain. It seems to be running tho, as the error is pretty indicative of the line you suggested not being parsed or being ignored. This is why I asked really, I found a website that suggested using the solution you offered but it didnt work .. I'm pretty much stumped. :( Could you possibly place a working version on your server I could surf too? At least then I would be absolutely certain it was a problem with my end not the method .. I have confirmed my cgi works: http://cpc3-nfds2-6-0-cust151.nott.cable.ntl.com/cgi-bin/test-cgi Sorry to be a bother! Conrad. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20040616/01800a22/attachment.bin From pythonTutor at venix.com Thu Jun 17 11:55:45 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Jun 17 11:56:57 2004 Subject: [Tutor] FW: Module 1 question In-Reply-To: References: Message-ID: <1087487745.2609.21.camel@laptop.venix.com> The error message says that strtime is NOT FOUND in the time module. If you run pyton, import time and type dir(time), you will notice that time contains strftime. You can print out its docstring and get a brief description. I've pasted the commands and results below. $ python Python 2.3.3 (#1, Jan 29 2004, 12:42:14) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import time >>> dir(time) ['__doc__', '__file__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset'] >>> print time.strftime.__doc__ strftime(format[, tuple]) -> string Convert a time tuple to a string according to a format specification. See the library reference manual for formatting codes. When the time tuple is not present, current time as returned by localtime() is used. >>> In other words, you mistyped the name of the function. On Wed, 2004-06-16 at 16:22, christopher lavezza wrote: > Can anyone help us out with this problem in our script? > > > >From: Chad Varner > >To: clavezza@hotmail.com > >Subject: Module 1 question > >Date: Tue, 15 Jun 2004 20:47:29 -0500 > > > >Chris, > > > > Did you get an answer from your professor on what he is looking for on > >these modules? > > > >Also, I've tried running our code and it keeps giving me the following > >error: > > > >Traceback (most recent call last): > > File "Script5_1.py", line 23, in ? > > a.deposit(550.23) > > File "Script5_1.py", line 8, in deposit > > t=time.strtime('%a, %d %b %Y %H:%M:%S' , time.localtime(time.time() > >+ 0)) > >AttributeError: 'module' object has no attribute 'strtime' > > > >Could you pass the error on to that guy you know in Colorado,and see if > >he can explain what the @#$# is wrong exactly? > > > >Thanks, > >-- > >Chad Varner > > > > _________________________________________________________________ > Get fast, reliable Internet access with MSN 9 Dial-up now 3 months FREE! > http://join.msn.click-url.com/go/onm00200361ave/direct/01/ > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Wed Jun 16 18:38:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 17 13:19:28 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1087428029.29204.2.camel@drachenfels> Message-ID: [Conrad, please keep tutor@python.org in CC. That way, even if I'm gone for the day, you'll still give the others there a chance to answer your question.] On Wed, 16 Jun 2004, Conrad Gavin wrote: > That didnt make much difference sadly .. > > ### > #!/usr/bin/python > > import cgitb; cgitb.enable() > > print "Content-type: text/plain\n\n" > import os > cmd = "/usr/bin/pstree" > status = os.system(cmd) > print status > ### > > Produces the same error: > > [Wed Jun 16 23:17:38 2004] [error] [client 127.0.0.1] (8)Exec format > error: exec of '/var/www/localhost/cgi-bin/pstree' failed > [Wed Jun 16 23:17:38 2004] [error] [client 127.0.0.1] Premature end of > script headers: pstree That error is different from the one you were reporting earlier. Remember, Apache originally reported: ### [Wed Jun 16 01:18:14 2004] [error] [client 81.104.190.151] malformed header from script. Bad header=init-+-5*[agetty]: hello.py ### But what Apache is saying now, with, > [Wed Jun 16 23:17:38 2004] [error] [client 127.0.0.1] (8)Exec format > error: exec of '/var/www/localhost/cgi-bin/pstree' failed is that it can't even execute the 'pstree' script anymore. When we're debugging, we have to be aware of what kind of error is being reported, and not just that an error is occuring. What happens if you say: $ /var/www/localhost/cgi-bin/pstree from your command line? Is the magic line: #!/usr/bin/python the very first line of your script? Good luck. From pythontut at pusspaws.net Thu Jun 17 13:33:52 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Jun 17 13:34:10 2004 Subject: [Tutor] floating point range() ? Message-ID: <40D1D600.1010409@pusspaws.net> Is there a floating point range() type builtin ? I need to generate a sequence for a 'for loop' every 0.5 for i in reange(0,1000,5) j=float(i)/10 print j The above works but seems clumbsy. Is there a better way ? Dave From dyoo at hkn.eecs.berkeley.edu Wed Jun 16 17:09:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 17 14:19:20 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1087420495.7415.7.camel@drachenfels> Message-ID: > Since Danny's message, I tried his suggestion also: > > #!/usr/bin/python > print "Content-type: text/plain\n\n" > import os > cmd = "pstree" > status = os.system(cmd) > print status > > Oddly. It still does not work. The environment that CGI's run under is more restricted than your own. In particular, the PATH is probably a lot more restricted when the CGI runs under Apache. Try using an absolute path for your executables. If pstree lives under /usr/bin, then: ### #!/usr/bin/python print "Content-type: text/plain\n\n" import os cmd = "/usr/bin/pstree" status = os.system(cmd) print status ### is better. When writing any CGI application, all external resources should probably be absolute-pathed to avoid these kinds of problems. More importantly, whenever we develop a CGI, we should also use the invaluable 'cgitb' traceback-reporting module: http://www.python.org/doc/lib/module-cgitb.html If something bad happens during the CGI program execution, the traceback monitor should capture the error so that you can get some good debugging output. It's a lot better than seeing "Internal Server Error". So try doing: ### #!/usr/bin/python import cgitb; cgitb.enable() print "Content-type: text/plain\n\n" import os cmd = "/usr/bin/pstree" status = os.system(cmd) print status ### Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Jun 17 13:34:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 17 19:04:40 2004 Subject: [Tutor] FW: Module 1 question In-Reply-To: Message-ID: On Wed, 16 Jun 2004, christopher lavezza wrote: > Can anyone help us out with this problem in our script? Hi Christopher, Let's take a closer look at the error. > >Traceback (most recent call last): > > File "Script5_1.py", line 23, in ? > > a.deposit(550.23) > > File "Script5_1.py", line 8, in deposit > > t=time.strtime('%a, %d %b %Y %H:%M:%S' , time.localtime(time.time() > >+ 0)) > >AttributeError: 'module' object has no attribute 'strtime' Ok, it sounds like you're trying to use a function called 'strtime' in the 'time' module: http://www.python.org/doc/lib/module-time.html Unfortunately, there is no such function named 'strtime'. The author probably mistyped 'strftime', which translates a time value to a nicely formatted string. Hope this helps! From tim at johnsons-web.com Thu Jun 17 22:34:55 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Thu Jun 17 22:29:12 2004 Subject: [Tutor] What Eval() Hath Men Wrought Message-ID: <20040618023455.GD5618@johnsons-web.com> Couldn't resist that subject since I hear the eval (the built-in) is 'evil'. I've been looking through the Python Cookbook, and there's an example at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 look for class Eval: # ...... code following This appears to be a handy class, but given the concerns about built-in function eval, I would welcome comments and caveats. Thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From kp8 at mac.com Fri Jun 18 13:36:10 2004 From: kp8 at mac.com (kevin parks) Date: Fri Jun 18 13:59:11 2004 Subject: [Tutor] time calc Message-ID: hi all. I have a bit of a task that i have been doing by hand, but as it turns out there is pages and pages more of this so i would like to make a python script that does this work and have it handy. I have a list that has several columns like so: 1 1 1 00:23 1 2 2 8:23 1 3 3 9:41 1 4 3 10:47 1 5 3 11:21 What this is a list that has tape number, program number, item number and start time for a recording. What i want to do is append the duration to the end of this list by subtracting the start of the item from the start time of the next so that the first line would look like: 1 1 1 00:23 08:00 1 2 2 8:23 01:18 etc. So the task is really two part : reading in a list of numbers and adding one more piece of data and (2) doing time (base 60) math. It is the time math part i simply can't get my head around. Anyone know if there is a module that does time math? or a method for doing this by hand? cheers, kevin parks From michele.alzetta at aliceposta.it Fri Jun 18 08:29:56 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Fri Jun 18 14:01:43 2004 Subject: [Tutor] New keyword ? Message-ID: <1087561796.3288.34.camel@localhost> I'm still fiddling with timespans - only I've just found out that WxPython has something with the same name but fundamentally different ( WxPythons' is an abstract periods of time, mine is a period with a precise beginning and end, from which of course the abstract period can be obtained) .. so I've started calling my class Period. Besides the _contains_ function, I've added an olaps function which returns true not only if a period is entirely contained in another, but also if it overlaps. Here is the code: ----------------------------------------------------------------- from datetime import datetime, date, timedelta class Period(object): def __init__(self, startimetuple, endtimetuple): self.starttime = datetime(*startimetuple) self.endtime = datetime(*endtimetuple) self.isPeriod = True def __contains__(self, period): try: if period.isPeriod: return (self.starttime <= period.starttime) and \ (self.endtime >= period.endtime) except AttributeError: moment = datetime(*period) return (self.starttime <= moment <= self.endtime) def length(self): return self.endtime - self.starttime def olaps(self, period): try: if period.isPeriod: return (( self.starttime < period.starttime \ < self.endtime) \ or ( self.starttime < period.endtime < self.endtime )) except AttributeError: moment = datetime(*period) return (self.starttime <= moment \ <= self.endtime) As I understand it, the 'in' keyword calls my __contains__ function, e.g. > week1 in fortnight1 True Whereas to call my olaps function I have to do this: > periodinstance.olaps(otherinstance) True Is it possible to create a new keyword (say, 'ovlps') to call my function like this: > week1 ovlps fortnight If it is possible, would it be desirable ? -- Michele Alzetta From gubbs at fudo.org Fri Jun 18 15:56:02 2004 From: gubbs at fudo.org (Conrad Gavin) Date: Fri Jun 18 16:06:13 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1791486478933.20040617124518@columbus.rr.com> References: <20040616032029.29572.qmail@web52605.mail.yahoo.com> <1087392972.5678.20.camel@drachenfels> <1791486478933.20040617124518@columbus.rr.com> Message-ID: <1087588562.5793.6.camel@drachenfels> On Thu, 2004-06-17 at 16:45, R. Alan Monroe wrote: > > print "text/plain/n/n" > > This should probably be: > print "Content-Type: text/plain\n\n" > > Yes, my bad. NB: With regard the previous post, I am finding similar things on google about python's seemingly dogey co-exhistence with Apache. http://lists.debian.org/debian-user/2002/05/msg00967.html Seems to be more or less what I am experiencing ... Conrad. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20040618/273175d0/attachment.bin From gubbs at fudo.org Fri Jun 18 15:50:08 2004 From: gubbs at fudo.org (Conrad Gavin) Date: Sun Jun 20 23:24:36 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: References: Message-ID: <1087588208.5793.3.camel@drachenfels> On Wed, 2004-06-16 at 22:53, Danny Yoo wrote: > On Wed, 16 Jun 2004, Conrad Gavin wrote: > > > Btw did you test this script on your own apache before sending it to me? > > Did it work? > > Good question. No. *grin* > > > I have tested the following version of the code: > > ###### > #!/usr/bin/python > import sys > import os > import cgitb; cgitb.enable() > > sys.stdout.write("Content-type: text/plain\n\n") > cmd = "/usr/bin/pstree" > status = os.popen(cmd).read() > print status > ###### > > > I can confirm that this works on my machine. > > The major fix here is to use os.popen() instead of os.system(). > os.system() returns the "errorlevel" of the program, not its standard > output. os.popen() is probably what you want to use to capture the output > of other programs. > > > Good luck! Danny .. this is still not working for me! I have tested it on a remote server running Apache 1.3 in addition to my local machine running Apache 2. I have ensured that the user Apache runs as owns the script and that all paths and permissions are correct and it _still_ returns a 500 'Premature end of script Headers' error ... I am pretty much conceeding defeat at this point since it works perfectly well as a python script but not it seems as a cgi one. There has to be a bug somewhere because this really seems dumb to me .. Conrad. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20040618/02b2e90a/attachment.bin From John.Ertl at fnmoc.navy.mil Fri Jun 18 17:50:17 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Sun Jun 20 23:25:55 2004 Subject: [Tutor] XSV validating XML with a schema Message-ID: I have been putting off the schema portion of a web service long enough so I wrote a schema for the XML that I produce. Now I need to validate it. The idea is this will also let me know if my schema is OK. I loaded XSV and all of the other files. I used the following code. from XSV.driver import runit import sys xmlfile = "tmdXML.xml" schemafile = "tmdschema.xsd" res = runit(xmlfile, [schemafile]) #res[0].printme(sys.stdout) ###### this line always gives me an error ###### Traceback (most recent call last): ###### File "./tmdXSV.py", line 11, in ? ###### res[0].printme(sys.stdout) ###### TypeError: printme() takes at least 4 arguments (2 given) print res The output I get is: (, None, [], ) What does this mean? I could not find documentation anywhere. Is XSV the best way to go? Thanks. John Ertl From amonroe at columbus.rr.com Thu Jun 17 12:45:18 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Jun 20 23:30:02 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1087392972.5678.20.camel@drachenfels> References: <20040616032029.29572.qmail@web52605.mail.yahoo.com> <1087392972.5678.20.camel@drachenfels> Message-ID: <1791486478933.20040617124518@columbus.rr.com> > print "text/plain/n/n" This should probably be: print "Content-Type: text/plain\n\n" From darnold02 at sprynet.com Fri Jun 18 18:59:32 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun Jun 20 23:33:09 2004 Subject: [Tutor] time calc In-Reply-To: Message-ID: Just convert each time to minutes, do the subtraction, then convert back. Off the top of my head, but hopefully close to correct: MINS_PER_DAY = 60 * 24 startTimes = ['00:23','8:23','17:45','00:17'] def convertToMins(timeStr): hh, mm = timeStr.split(':') return int(hh) * 60 + int(mm) def convertFromMins(minutes): hh, mm = divmod(minutes,60) return '%02d:%02d' % (hh, mm) for i in range(len(startTimes) - 1): begin = startTimes[i] end = startTimes[i + 1] beginAsMins = convertToMins(begin) endAsMins = convertToMins(end) if endAsMins < beginAsMins: #rolled over midnight endAsMins += MINS_PER_DAY print 'begin: %-6s end: %-6s duration: %-6s' % \ (begin, end, convertFromMins(endAsMins - beginAsMins)) [---output---] begin: 00:23 end: 8:23 duration: 08:00 begin: 8:23 end: 17:45 duration: 09:22 begin: 17:45 end: 00:17 duration: 06:32 HTH, Don -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of kevin parks Sent: Friday, June 18, 2004 12:36 PM To: tutor@python.org Cc: kevin parks Subject: [Tutor] time calc hi all. I have a bit of a task that i have been doing by hand, but as it turns out there is pages and pages more of this so i would like to make a python script that does this work and have it handy. I have a list that has several columns like so: 1 1 1 00:23 1 2 2 8:23 1 3 3 9:41 1 4 3 10:47 1 5 3 11:21 What this is a list that has tape number, program number, item number and start time for a recording. What i want to do is append the duration to the end of this list by subtracting the start of the item from the start time of the next so that the first line would look like: 1 1 1 00:23 08:00 1 2 2 8:23 01:18 etc. So the task is really two part : reading in a list of numbers and adding one more piece of data and (2) doing time (base 60) math. It is the time math part i simply can't get my head around. Anyone know if there is a module that does time math? or a method for doing this by hand? cheers, kevin parks _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From rumpy at mrbitter.org Wed Jun 16 13:34:55 2004 From: rumpy at mrbitter.org (Josh Eror) Date: Sun Jun 20 23:35:39 2004 Subject: [Tutor] On-line courses. In-Reply-To: References: Message-ID: <1087407295.40d084bf4d12c@mrbitter.org> Thank you Magnus. I have to say that I'm a little surprised this niche has yet to filled. On-line education still seems to be struggling to develop curriculum that can teach more advanced subjects. Oh well, thanks again. Quoting Magnus Lycka : > There aren't so many commercial offerings for Python courses that I > know of. Also, I don't know where in the world you are... > > If you visit OSCON in july, you'll get a chance to attend some Python > tutorials, but note that early bird registration ends June 18! > http://conferences.oreillynet.com/pub/w/29/tutorial_python.html > > Otherwise there are some well known Python trainers in the USA, such > as Wesley Chun http://roadkill.com/~wesc/cyberweb/services.html and > Mark Lutz http://www.rmi.net/~lutz/mytrain.html . You just missed one > of Mark's classes in Colorado... > > There are more trainers out there, but these are the ones I know of > in the US who regularly give open classes. Others do on-site training > for companies etc. > > -----Ursprungligt meddelande----- > Fr?n: Josh Eror > Skickat: 2004-06-15 23:13:38 > Till: tutor@python.org > ?mne: [Tutor] On-line courses. > > > > Hi Folks, > > > > > > I'm very interested if taking a Python Course to accelerate my learning. My > > > preference is for a Web Course if possible, but I'd certainly attend a boot > > > camp type training. The cost of the course isn't so much of an issue. If > it's > > good, and recommended here, I'll buck up for it. > > > > BTW, the many Python Books I have are great. I have learned a great deal > > already. It's simply a matter of wanting to pick up the pace and try a > > different mechanism for absorbing the subject. > > > > > > Thanks in advance for your suggestions, > > > > Josh. > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Magnus Lycka, Thinkware AB > Alvans vag 99, SE-907 50 UMEA, SWEDEN > phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 > http://www.thinkware.se/ mailto:magnus@thinkware.se > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From game at gameweave.com Thu Jun 17 22:14:11 2004 From: game at gameweave.com (K J) Date: Sun Jun 20 23:41:33 2004 Subject: [Tutor] Best place to learn on the web Message-ID: <001201c454d9$f22405e0$30e57218@basp.phub.net.cable.rogers.com> I was wondering where the best tutorial on the net would be to learn def functions. I am having trouble learning them. Thanks Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040617/13a8e873/attachment.html From pythontut at pusspaws.net Thu Jun 17 13:40:25 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Jun 20 23:44:45 2004 Subject: [Tutor] Printing a progress bar In-Reply-To: References: Message-ID: <40D1D789.1040400@pusspaws.net> Terry Carroll wrote: >On Sun, 13 Jun 2004, Dave S wrote: > > > >>Some of the code I have written handels a lot of data, I would like to >>add a progress bar. >> >> > >I use Randy Pargman's progress bar from >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 ; I find it >does the job nicely. > > I will combine this class with backspacing to hopefully produce a static line with a dynamic progress bar ! Cheers Dave From magnus at thinkware.se Fri Jun 18 06:54:38 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jun 20 23:45:52 2004 Subject: [Tutor] What Eval() Hath Men Wrought In-Reply-To: <20040618023455.GD5618@johnsons-web.com> Message-ID: <5.2.1.1.0.20040618121728.02716390@www.thinkware.se> At 18:34 2004-06-17 -0800, Tim Johnson wrote: >Couldn't resist that subject since I hear >the eval (the built-in) is 'evil'. > >I've been looking through the Python Cookbook, and >there's an example at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 >look for > class Eval: > # ...... code following > >This appears to be a handy class, but given the concerns about >built-in function eval, I would welcome comments and caveats. As I see it, there are some problems with eval() - It's slow, e.g. eval('5') is about ten times slower than int('5'). - It might cause unpredicted results unless you are certain about what you run eval on. This isn't really a problem if you only run eval on hardcoded strings in your source code as the Cookbook example does. In some programs eval could cause security problems. For instance, an attacker might be able to display passwords stored in program variables etc. - It makes it more difficult to analyse the code, for instance with some automatic tool such as PyChecker or PyLint. (Or manually for that matter.) - Debugging get's harder. You might hide syntax errors until runtime etc. I imagine tracebacks are less helpful too. Besides, I'm not really sure that print "%(text.capitalize())s %(number/9.0).1f rules!" % Eval() is better than print "% %.1f rules!" % (text.capitalize(), number/9.0) This is some kind of ASP syndrome, and it seems to me that most programmers seem to agree that mixing code in text as in ASP or as in the Eval example typically causes maintenance problems. Whether we're talking about web pages or something else, we'll often want to separate the maintenace of the text from the maintenance of the code. I often do things similar to: params = dict(capText=text.capitalize(), verNumber=number/9.0) print "%(capText)s %(verNumber).1f rules!" % params() or even something like print "%(capText)s %(verNumber).1f rules!" % vars() but it might be even better to use a real templating system such as cheetah etc. See http://www.python.org/cgi-bin/moinmoin/WebProgramming#head-9d0636d6da8e88f8f09de1454c5961b44183b04d Eval might look neat, but I think you will end up missing the syntax coloring of your python statements if you put them in strings, and that it will turn out to be trickier to find bugs. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From gew75 at hotmail.com Fri Jun 18 20:24:49 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sun Jun 20 23:47:23 2004 Subject: [Tutor] time calc References: Message-ID: Howdy Kevin, The time math shouldn't be too hard. What format is your duration in? Hours:Mins? Minutes? Hours.? To get around the time math, I would use a single intermediary calculation; convert all pairs first into minutes. This would be different if you have the duration in a different format, but on the back of the tapes that I have it says minutes, so I'll use that for the time being :). For each time pair, (hh:mm) simply think of the (hh) part as mm*60. Then, to obtain total minutes, we have an easy operation -- totalMinutes = hh*60 + mm. You can perform the conversion, etc yourself. To get the original tuple, use the string.split(':') method. Once that's finished we can add the duration on, then convert back to time form again. The easiest way in my mind for this is to use modulus. As a quick reminder/introduction : x (mod y) = remainder of x upon repeated division of y So that we want total_minutes (mod 60) = new_minutes Also, new_hours = total_minutes / 60, which is regular integer division. Python has an incredibly useful builtin with divmod(..), which performs integer division and modulus on the two arguments. Modulus in python is with the % operator. So, recapping in code: >>> hhmm = (2,45) >>> total_minutes = hhmm[0]*60 + hhmm[1] >>> total_minutes += 120 >>> divmod(total_minutes, 60) (4, 45) HTH, Glen ----- Original Message ----- From: "kevin parks" To: Cc: "kevin parks" Sent: Saturday, June 19, 2004 3:36 AM Subject: [Tutor] time calc > hi all. > > I have a bit of a task that i have been doing by hand, but as it turns > out there is pages and pages more of this so i would like to make a > python script that does this work and have it handy. > > I have a list that has several columns like so: > > 1 1 1 00:23 > 1 2 2 8:23 > 1 3 3 9:41 > 1 4 3 10:47 > 1 5 3 11:21 > > > What this is a list that has tape number, program number, item number > and start time for a recording. > > What i want to do is append the duration to the end of this list by > subtracting the start of the item from the start time of the next so > that the first line would look like: > > 1 1 1 00:23 08:00 > 1 2 2 8:23 01:18 > > etc. > > So the task is really two part : reading in a list of numbers and > adding one more piece of data and (2) doing time (base 60) math. It is > the time math part i simply can't get my head around. Anyone know if > there is a module that does time math? or a method for doing this by > hand? > > cheers, > > kevin parks > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Janssen at rz.uni-frankfurt.de Fri Jun 18 05:30:54 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sun Jun 20 23:53:17 2004 Subject: [Tutor] What Eval() Hath Men Wrought In-Reply-To: <20040618023455.GD5618@johnsons-web.com> References: <20040618023455.GD5618@johnsons-web.com> Message-ID: On Thu, 17 Jun 2004, Tim Johnson wrote: > Couldn't resist that subject since I hear > the eval (the built-in) is 'evil'. AFAIK one reason eval is considered harmful, is because it's dangerous when you eval something that might be dangerous code. So, eval'ing input you get from a website is an enormous bad idea. Imaging you've got the os modul imported, an attacker can do anything with os.system . "eval" will only eval expresions no statements, wich means that the attacker can't do an "import os" but there is a workaround: eval("__import__('os').system('ls')") Given you run this on Linux, the commandline tool "ls" will list the current directory, but it could have been as easily a more destructive command. So, one reason eval is evil is that it will eval anything including evil code. OTOH, there is nothing wrong about eval'ing your own input (so long as you know that your input will get eval'ed). Another reason might be, that it lends to untestable and un-re-usable code. Look at what eval does: it turns a string into functionality. The "normal" way to get functionality is using functions. Functions have defined input-output behaviour: they take arguments and return return-values. Eval don't do this but uses the variables it finds in current namespace and can create new variables. Such side-effects have to be taken into account when you want to write test code or re-use code containing eval. This means you will have to set up the proper variables expected by your to-be-evaled-string and you will have to go on with the variables created within the eval'ed- string. Anyway, eval can be used - but keep care. Don't eval untrusted input and keep the to-be-evaled-code short: Fixing errors within strings is harder than in normal python code, because the traceback output tends to be less infomative. Michael > I've been looking through the Python Cookbook, and > there's an example at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 > look for > class Eval: > # ...... code following > > This appears to be a handy class, but given the concerns about > built-in function eval, I would welcome comments and caveats. From scott_hamma at yahoo.com Wed Jun 16 18:13:55 2004 From: scott_hamma at yahoo.com (Hamma Scott) Date: Sun Jun 20 23:55:11 2004 Subject: [Tutor] Is Python a valid business tool? Message-ID: <20040616221355.15433.qmail@web12824.mail.yahoo.com> I hope this is the area where I could post this. If this is off topic please forgive me. I've tried authors of articles about Python and user groups devoted to Python (Bay Piggies to be exact) and have gotten no response. I'm looking for direction. I'm currently working in a company whose direction is pointed towards Java and Websphere. We used Visual Basic in the past and have some applications still about. We develop software under a windows environment to distributed unders the Windows OS. I have seen some smaller in-roads towards .NET and some in-roads towards Linux, but nothing that will bring Linux company-wide. My question; Is Python a language that is a good fit in this environment or is this something just for me? I'm just starting to learn it, but I've been met with questions that I cannot answer - I have read that Python can be used like Perl CGI pages but I've heard that CGI is a resource pig. Right? Wrong? Is there another way to use Python on the Web? - How can Python integrate in the above environment? Is there a need that it can fill? I would appreciate any response...thanks for your time on this matter. Scott __________________________________ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail From darnold02 at sprynet.com Fri Jun 18 22:25:45 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun Jun 20 23:58:09 2004 Subject: [Tutor] time calc Message-ID: sorry if this is a double post. maybe i'm just not receiving the tutor emails at the moment. just in case it didn't go out the first time: -----Original Message----- From: Don Arnold [mailto:darnold02@sprynet.com] Sent: Friday, June 18, 2004 6:00 PM To: 'kevin parks'; 'tutor@python.org' Subject: RE: [Tutor] time calc Just convert each time to minutes, do the subtraction, then convert back. Off the top of my head, but hopefully close to correct: MINS_PER_DAY = 60 * 24 startTimes = ['00:23','8:23','17:45','00:17'] def convertToMins(timeStr): hh, mm = timeStr.split(':') return int(hh) * 60 + int(mm) def convertFromMins(minutes): hh, mm = divmod(minutes,60) return '%02d:%02d' % (hh, mm) for i in range(len(startTimes) - 1): begin = startTimes[i] end = startTimes[i + 1] beginAsMins = convertToMins(begin) endAsMins = convertToMins(end) if endAsMins < beginAsMins: #rolled over midnight endAsMins += MINS_PER_DAY print 'begin: %-6s end: %-6s duration: %-6s' % \ (begin, end, convertFromMins(endAsMins - beginAsMins)) [---output---] begin: 00:23 end: 8:23 duration: 08:00 begin: 8:23 end: 17:45 duration: 09:22 begin: 17:45 end: 00:17 duration: 06:32 HTH, Don -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of kevin parks Sent: Friday, June 18, 2004 12:36 PM To: tutor@python.org Cc: kevin parks Subject: [Tutor] time calc hi all. I have a bit of a task that i have been doing by hand, but as it turns out there is pages and pages more of this so i would like to make a python script that does this work and have it handy. I have a list that has several columns like so: 1 1 1 00:23 1 2 2 8:23 1 3 3 9:41 1 4 3 10:47 1 5 3 11:21 What this is a list that has tape number, program number, item number and start time for a recording. What i want to do is append the duration to the end of this list by subtracting the start of the item from the start time of the next so that the first line would look like: 1 1 1 00:23 08:00 1 2 2 8:23 01:18 etc. So the task is really two part : reading in a list of numbers and adding one more piece of data and (2) doing time (base 60) math. It is the time math part i simply can't get my head around. Anyone know if there is a module that does time math? or a method for doing this by hand? cheers, kevin parks _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From reed at intersiege.com Wed Jun 16 09:45:16 2004 From: reed at intersiege.com (Reed L. O'Brien) Date: Mon Jun 21 00:00:43 2004 Subject: [Tutor] psp_site mmods Message-ID: I posted this to the mod_python mailing list the other day but there hasn't been a post that has gone up there since lunch on the 14th. I odn't know if grisha is on vacation or what. I really need halp to get this working though... Or does this belong on the questions list? I have been tasked to make a web interface to search (swish-e) and index of pdf's. I have never done any programming (but have done some scripting) so I apologize in advance for any questions that may seen like common sense. I feel like there will be many of them as this is very humbling to me. I chose python to develop (and learn to program with) for numerous reasons. I quickly found mod_python and chose that. I saw the example site and thought it would be a nice simple site to modify (tries to conceal leeching noises). I have it all up and running and somewhat modified but have reached an impass. I have modified the three pages to be search, results and help. I modified search_page.html to have text input and submit calls:
I added it as a value passed (required by) to results (continued after bad code): def results(req, searchWords): return _any_page(req, 'results') #def performSearch(searchWords): # make sure the user provided all the parameters if not (searchWords): return " Nothing to search for. Nothing Found." # do the search handle = SwishE.new('/usr/local/swish-e/index.swish-e') search = handle.search('') results = search.execute(searchWords) return [r.getproperty('swishdocpath') for r in results] also I have the following in results_page.html: <% print results %> I have tried with it as a call to performSearch and directly to search. I have tried with different indentations. I have also tried including it in the page return, but either the page returns: name error results not defined ## wiith the <%psp%> tag in html or: as a blank formatted results page with a broken menu and images. I could keep playing around but I figured it was time to put down my pride and ask the experts. Any help is appreciated. TIA cheers, reed (very newb programmer) PS If (when) I get this working I will gladly roll it up with a demo index and put it up as an example site with the original. PSS: FreeBSD 5.2.1 mod_python 3.1.3 python 2.3.4 SwishE 0.4 From nick at javacat.f2s.com Thu Jun 17 18:42:02 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Jun 21 00:03:29 2004 Subject: [Tutor] class variables Message-ID: <40D21E3A.7000608@javacat.f2s.com> Hi folks, Im making my way through the book 'Learning Python 2nd Edition'. I understand classes but I have a question. Take the following for example - class beer: def __init__(self): self.make = 'murphys' cans = 4 There's several examples I've seen where 'self.var' isn't used, just 'var' is, as in 'cans' above. I know that each instance of 'beer' will have its own value for 'make' but what is the use of 'cans' without using self ? Any pointers in the right direction happily received :) Regards Nick. From dyoo at hkn.eecs.berkeley.edu Thu Jun 17 16:29:31 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 21 00:04:28 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gT24tbGluZSBjb3Vyc2VzLg==?= In-Reply-To: Message-ID: On Thu, 17 Jun 2004, Magnus Lycka wrote: > > Thank you Magnus. I have to say that I'm a little surprised this niche > > has yet to filled. On-line education still seems to be struggling to > > develop curriculum that can teach more advanced subjects. Oh well, > > thanks again. [some text cut] > There are plenty of on-line Python tutorials though, and I think the > people on the Tutor mailing list are very helpful in assisting people > who are trying to learn Python. But I think you are right. I'm wondering > what it would take to get an on-line Python-course to work... The ACCU recently tried to do a kind of online course with Python: http://www.cix.co.uk/~jimh/python/ As far as I can tell, it's inactive now, but it might be a good idea to see if it can be revived. From dyoo at hkn.eecs.berkeley.edu Thu Jun 17 16:23:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 21 00:08:14 2004 Subject: [Tutor] floating point range() ? In-Reply-To: <40D1D600.1010409@pusspaws.net> Message-ID: On Thu, 17 Jun 2004, Dave S wrote: > Is there a floating point range() type builtin ? > > I need to generate a sequence for a 'for loop' every 0.5 > > for i in reange(0,1000,5) > j=float(i)/10 > print j > > The above works but seems clumbsy. > > Is there a better way ? Hi Dave, I don't think there is a built-in equivalent for range() with floats. However, it isn't too bad to write something ourselves: ### def frange(start, stop, skip=1.0): """A range-like generator that returns numbers in the interval [start, stop). """ i = start while i < stop: yield i i += skip ### Here's an example of how to use frange(): ### >>> for x in frange(0, 10, 0.5): ... print x ... 0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0 9.5 ### Does this seem reasonable? Hope this helps! From gaedol at softhome.net Thu Jun 17 15:11:38 2004 From: gaedol at softhome.net (Marco) Date: Mon Jun 21 00:11:56 2004 Subject: [Tutor] FW: Module 1 question In-Reply-To: References: Message-ID: <20040617211138.71dc17d9.gaedol@softhome.net> On Wed, 16 Jun 2004 15:22:54 -0500 "christopher lavezza" wrote: > >Traceback (most recent call last): > > File "Script5_1.py", line 23, in ? > > a.deposit(550.23) > > File "Script5_1.py", line 8, in deposit > > t=time.strtime('%a, %d %b %Y %H:%M:%S' , time.localtime(time.time() > >+ 0)) > >AttributeError: 'module' object has no attribute 'strtime' I have not seen your code, so i can't say, but: in the time module there are 2 function similar, in name, to strtime: there's one called strftime() [-- convert time tuple to string according to format specification] and one called strptime() [-- parse string to time tuple according to format specification]. I suppose, so, that's a typo. But, again, not seeing your code i can't really say. pydoc, anyway is a friend of yours ;) marco -- "Anche io sono un maschio. Solo che non esercito." -- Dario Vergassola From game at gameweave.com Thu Jun 17 19:19:04 2004 From: game at gameweave.com (K J) Date: Mon Jun 21 00:16:55 2004 Subject: [Tutor] Where to learn def's References: Message-ID: <000b01c454c1$7c0f1100$30e57218@basp.phub.net.cable.rogers.com> I was wondering where the best tutorial on the net would be to learn def functions. I am having trouble learning them. Thanks Kevin From bvande at po-box.mcgill.ca Sat Jun 19 02:40:25 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Jun 21 00:21:19 2004 Subject: [Tutor] time calc In-Reply-To: References: Message-ID: <40D3DFD9.9030407@po-box.mcgill.ca> kevin parks said unto the world upon 18/06/2004 13:36: > hi all. > > I have a bit of a task that i have been doing by hand, but as it turns > out there is pages and pages more of this so i would like to make a > python script that does this work and have it handy. > > I have a list that has several columns like so: > > 1 1 1 00:23 > 1 2 2 8:23 > 1 3 3 9:41 > 1 4 3 10:47 > 1 5 3 11:21 > > > What this is a list that has tape number, program number, item number > and start time for a recording. > > What i want to do is append the duration to the end of this list by > subtracting the start of the item from the start time of the next so > that the first line would look like: > > 1 1 1 00:23 08:00 > 1 2 2 8:23 01:18 > > etc. > > So the task is really two part : reading in a list of numbers and adding > one more piece of data and (2) doing time (base 60) math. It is the time > math part i simply can't get my head around. Anyone know if there is a > module that does time math? or a method for doing this by hand? > > cheers, > > kevin parks > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Kevin, I have a question for you. If you know how to do the math on paper, why not just use the same math in your program? (If you are doing it right with pencil you *are* doing it is base 60 ;-) Is the problem to see how to express the math in python code? Best, Brian vdB From magnus at thinkware.se Thu Jun 17 12:30:09 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Jun 21 00:24:30 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRlc6IE1vZHVsZSAxIHF1ZXN0aW9u?= Message-ID: christopher lavezza wrote: > Can anyone help us out with this problem in our script? Just as the error message says, the module (time) has no attribute called strtime. I suspect you misspelled strftime. Note the 'f' in the name. The names comes from the C language library module "time". The Python time module is just a thin wrapper for the standard C library. >>> import time >>> time.strtime Traceback (most recent call last): File "", line 1, in -toplevel- time.strtime AttributeError: 'module' object has no attribute 'strtime' >>> time.strftime >>> t=time.strftime('%a, %d %b %Y %H:%M:%S' , time.localtime(time.time())) >>> print t Thu, 17 Jun 2004 18:06:22 For a more "modern" and high level approach to date and time handling, Python has a nice module called datetime since version 2.3. Using datetime, it's more easy to do time calculations etc. You don't need to bother about tuples and numeric representations. You simply use a datetime object. The datetime module is also safe from year 1 to 9999, while the time module is limited to 1970 to 2038 on 32 bit systems, just as the underlying C library. >>> import datetime >>> print datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S') Thu, 17 Jun 2004 18:13:44 Read the Python Library Reference for more info: http://docs.python.org/lib/module-time.html and http://docs.python.org/lib/module-datetime.html > >Traceback (most recent call last): > > File "Script5_1.py", line 23, in ? > > a.deposit(550.23) > > File "Script5_1.py", line 8, in deposit > > t=time.strtime('%a, %d %b %Y %H:%M:%S' , time.localtime(time.time() > >+ 0)) > >AttributeError: 'module' object has no attribute 'strtime' -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From rick at niof.net Thu Jun 17 09:46:33 2004 From: rick at niof.net (Rick Pasotto) Date: Mon Jun 21 00:27:55 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1087392972.5678.20.camel@drachenfels> References: <20040616032029.29572.qmail@web52605.mail.yahoo.com> <1087392972.5678.20.camel@drachenfels> Message-ID: <20040617134633.GF9978@niof.net> On Wed, Jun 16, 2004 at 01:36:12PM +0000, Conrad Gavin wrote: > > That doesnt seem to work either .. > My code now: > > #!/usr/bin/python > > ^ > > import os > > print "text/plain/n/n" That should be print "text/plain\n" That's a newline at the end of the string and you only need one since the print statement supplies the second. -- "If you think education is expensive, try ignorance." -- Derek Bok, President, Harvard University Rick Pasotto rick@niof.net http://www.niof.net From Francis.Moore at shaws.co.uk Thu Jun 17 11:43:37 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Mon Jun 21 00:28:35 2004 Subject: [Tutor] FW: Module 1 question Message-ID: <6081EBC21D52F744B484088BBBE665C32EEB1B@sbserver.shaws.local> From: christopher lavezza [mailto:clavezza@hotmail.com] Christopher, > Can anyone help us out with this problem in our script? You seem to have a typo in the following line: > t=time.strtime('%a, %d %b %Y %H:%M:%S' , The time module has two methods, 'strftime' and 'strptime'. Try one of these instead. Francis. CONFIDENTIALITY NOTICE This communication contains information which is confidential and may also be privileged. It is for the exclusive use of the intended recipient(s). If you are not the intended recipient(s) please note that any distribution, copying or use of this communication or the information in it is strictly prohibited. If you have received this communication in error please notify us by e-mail or by telephone (+44(0) 1322 621100) and then delete the e-mail and any copies of it. This communication is from Shaw & Sons Limited whose registered office is at Shaway House, 21 Bourne Park, Bourne Road, Crayford, Kent DA1 4BZ. The views expressed in this communication may not be the views held by Shaw & Sons Limited. This message has been checked for all known viruses by McAfee VirusScan. From rumpy at mrbitter.org Thu Jun 17 15:20:59 2004 From: rumpy at mrbitter.org (Josh Eror) Date: Mon Jun 21 00:30:15 2004 Subject: [Tutor] On-line courses. In-Reply-To: References: Message-ID: <1087500059.40d1ef1bac24e@mrbitter.org> Cool, thanks. I'll check it out. Quoting Magnus Lycka : > BTW, I stumbled over this: > http://www.icanprogram.com/pythonlinux.html > > > -- > Magnus Lycka, Thinkware AB > Alvans vag 99, SE-907 50 UMEA, SWEDEN > phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 > http://www.thinkware.se/ mailto:magnus@thinkware.se > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From Dragonfirebane at aol.com Thu Jun 17 22:04:46 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 21 00:31:20 2004 Subject: [Tutor] IDLE vs. Python Command Line Message-ID: <42.50c836ac.2e03a7be@aol.com> when i type: ## >>>import string >>>string.letters ## in IDLE, i get: ## 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\x9a\x9c\ x9e\x9f\xaa\xb5\xba\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xc e\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\ xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf 6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' ## but when i do it on the Python Command Line, i get: ## 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ## is this a flaw in IDLE or the Command Line? Which is more accurate? Since one of my programs uses string.letters, it is important for me to know. Thanks in advance, Orri P.S.: IDLE: >>> print string.letters ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz???????? ????????????????????????????????????????????????????????????????? Command Line: >>>print string.letters abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040617/4bec5d48/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Jun 18 14:25:12 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 21 00:31:54 2004 Subject: [Tutor] time calc In-Reply-To: Message-ID: On Fri, 18 Jun 2004, kevin parks wrote: > Anyone know if there is a module that does time math? or a method for > doing this by hand? Hi Kevin, Check the 'datetime' module: http://www.python.org/doc/lib/module-datetime.html 'datetime' defines a bunch of types, including ones for doing date and time arithmetic. For example: ### >>> from datetime import timedelta >>> t1 = timedelta(hours=1) >>> t2 = timedelta(minutes=30) >>> t1 + t2 datetime.timedelta(0, 5400) ### Hope this helps! From pythontut at pusspaws.net Sat Jun 19 07:16:15 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon Jun 21 00:34:10 2004 Subject: [Tutor] floating point range() ? In-Reply-To: References: Message-ID: <40D4207F.6050404@pusspaws.net> > > > >Hi Dave, > > >I don't think there is a built-in equivalent for range() with floats. >However, it isn't too bad to write something ourselves: > >### >def frange(start, stop, skip=1.0): > """A range-like generator that returns numbers in the interval > [start, stop). > """ > i = start > while i < stop: > yield i > i += skip >### > > > >Here's an example of how to use frange(): > >### > > >>>>for x in frange(0, 10, 0.5): >>>> >>>> >... print x >... >0 >0.5 >1.0 >1.5 >2.0 >2.5 >3.0 >3.5 >4.0 >4.5 >5.0 >5.5 >6.0 >6.5 >7.0 >7.5 >8.0 >8.5 >9.0 >9.5 >### > >Does this seem reasonable? > > > >Hope this helps! > > Sure does, It also reminds me of the yield builtin. Things are getting clearer - though I still catch myself thinking in terms of BASIC & forgetting to open up to the flexability of Python - Guess it will just take time & practice. Dave From orbitz at ezabel.com Sat Jun 19 12:19:53 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon Jun 21 00:39:35 2004 Subject: [Tutor] New keyword ? In-Reply-To: <1087561796.3288.34.camel@localhost> References: <1087561796.3288.34.camel@localhost> Message-ID: <20040619121953.51f420ea.orbitz@ezabel.com> No, No On Fri, 18 Jun 2004 14:29:56 +0200 Michele Alzetta wrote: > I'm still fiddling with timespans - only I've just found out that > WxPython has something with the same name but fundamentally different > ( WxPythons' is an abstract periods of time, mine is a period with a > precise beginning and end, from which of course the abstract period can > be obtained) .. so I've started calling my class Period. > > Besides the _contains_ function, I've added an olaps function which > returns true not only if a period is entirely contained in another, but > also if it overlaps. Here is the code: > > ----------------------------------------------------------------- > from datetime import datetime, date, timedelta > > class Period(object): > > def __init__(self, startimetuple, endtimetuple): > self.starttime = datetime(*startimetuple) > self.endtime = datetime(*endtimetuple) > self.isPeriod = True > > def __contains__(self, period): > try: > if period.isPeriod: > return (self.starttime <= period.starttime) and \ > (self.endtime >= period.endtime) > except AttributeError: > moment = datetime(*period) > return (self.starttime <= moment <= self.endtime) > > def length(self): > return self.endtime - self.starttime > > def olaps(self, period): > try: > if period.isPeriod: > return (( self.starttime < period.starttime \ > < self.endtime) \ > or ( self.starttime < period.endtime < self.endtime )) > except AttributeError: > moment = datetime(*period) > return (self.starttime <= moment \ > <= self.endtime) > > > As I understand it, the 'in' keyword calls my __contains__ function, > e.g. > > > week1 in fortnight1 > True > > Whereas to call my olaps function I have to do this: > > > periodinstance.olaps(otherinstance) > True > > Is it possible to create a new keyword (say, 'ovlps') to call my > function like this: > > > week1 ovlps fortnight > > If it is possible, would it be desirable ? > > -- > Michele Alzetta > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From pythontut at pusspaws.net Sat Jun 19 15:00:10 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon Jun 21 00:43:43 2004 Subject: [Tutor] classes & required method not working Message-ID: <40D48D3A.4030708@pusspaws.net> I have a class problem. I have a script, ggScanStock.py which defines a class ScanData : #!/usr/bin/env python """ AnalizeClass """ import os,ggdatacore3 class ScanData: def __init__(self,stockdir='/home/dave/gg/stockdata/'): self.datadir=stockdir self.cyclecount=0 self.reset() def scan(self): datadirs=os.listdir(self.stockdir) # Loop for stockdir days datadirs.sort() # ############################# debug temp ######################### datadirs=datadirs[:3] # ############################################################### for datadir in datadirs: print 'Processing Directory : ',datadir ggdatacore3.adddata(stockdir+datadir) keys=ggdatacore3.readkeys() for key in keys: ftselist,yftselist,ftsestats=ggdatacore3.readdata(key) # A probing loop to checkout all possible combinations of buying and selling slots for offset in range(1,101): for buy in range(0,101-offset): # from ... start to start+offset = profit / loss sell=buy+offset bought=float(ftselist[buy][1]) sold=float(ftselist[sell][1]) pcinc=((sold-bought)/bought)*100 # buy = slot I bought from # sell = slot I sold in # bought = pence I bought shares at # sold = pence I sold shares at # pcinc = % increase of share value for pcprofit_min in xrange(5,31): # scans each pcinc for varing profit levels self.process(pcprofit_min,buy,sell,bought,sold,pcinc,ftselist,yftselist,ftsestats) It has two dummy 'stub' class methods, namely self.reset() & self.process(). Because different instances will have different 'stub' class methods I have defined these methods in a seperate script, ggpcprofit.py #!/usr/bin/env python import os,ggScanStock class pcprofit(ScanData): def reset(self): self.totalcycles=self.profitcycles=float(0) def process(self,pcprofit_min,buy,sell,bought,sold,pcinc,ftselist,yftselist,ftsestats): self.totalcycles=+1 if pcinc>0: self.profitcycles=+1 def output(self): print '\n*** ggpcprofit module ***' print '\nTotal %% profitable transactions over full range : %0.2f' % self.profitcycles/self.totalcycles inst=pcprofit inst.scan() inst.output() It seemed like a good idea & a way to learn about classes filling in required methods. However when I try & execute ggpcprofit.py I get : bash-2.05b$ ./ggpcprofit.py Traceback (most recent call last): File "./ggpcprofit.py", line 5, in ? class pcprofit(ScanData): NameError: name 'ScanData' is not defined bash-2.05b$ Can anyone explain where I am going wrong - I imported ggScanStock so why cant my class pcprofit find class ScanData ? Dave From pythonTutor at venix.com Sat Jun 19 20:34:24 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Jun 21 00:49:43 2004 Subject: [Tutor] floating point range() ? In-Reply-To: <40D1D600.1010409@pusspaws.net> References: <40D1D600.1010409@pusspaws.net> Message-ID: <1087691663.5286.25.camel@laptop.venix.com> There is no builtin range for floats. There is a Python Cookbook frange recipe which could be useful. An alternative for getting the list is: [i*.5 for i in range(200)] On Thu, 2004-06-17 at 13:33, Dave S wrote: > Is there a floating point range() type builtin ? > > I need to generate a sequence for a 'for loop' every 0.5 > > for i in reange(0,1000,5) > j=float(i)/10 > print j > > The above works but seems clumbsy. > > Is there a better way ? > > Dave > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From carroll at tjc.com Sun Jun 20 03:26:13 2004 From: carroll at tjc.com (Terry Carroll) Date: Mon Jun 21 00:56:56 2004 Subject: [Tutor] time calc In-Reply-To: Message-ID: On Fri, 18 Jun 2004, kevin parks wrote: > So the task is really two part : reading in a list of numbers and > adding one more piece of data and (2) doing time (base 60) math. It is > the time math part i simply can't get my head around. Anyone know if > there is a module that does time math? or a method for doing this by > hand? This is really an ugly-looking hack, but maybe someone can improve on it: import time import datetime time1 = "00:57" dur1 = "08:05" # get the time; give a year, etc. just to keep strptime happy ttup1 = time.strptime(time1,"%M:%S") t1=datetime.datetime(1970,1,1,minute=ttup1[4],second=ttup1[5]) print t1 # get the duration dtup1 = time.strptime(dur1,"%M:%S") d1=datetime.timedelta(minutes=dtup1[4],seconds=dtup1[5]) print d1 # you can add the time and duration t2=t1+d1 print t2 time2printable = str(t2)[-5:] print time2printable From mjekl at iol.pt Sun Jun 20 14:55:00 2004 From: mjekl at iol.pt (Miguel Lopes) Date: Mon Jun 21 01:11:03 2004 Subject: [Tutor] Record Locking & Access - newbye Message-ID: <003001c456f8$17ba9b00$6601a8c0@clixdialupadapt> Hi, Here's my problem. Using python dbapi I get groups of records back from a database into a list for example to feed a "List Form" which is just a grid on a form (the db is about 9000 thousand records - so I suppose there's not a big problem to fetch all records in a go!). Now when a user selects a record from a grid on screen I can send him to another form "Record Form" where he can edit the record. This way I can have only one query to the database and have the users working locally on there record sets. But when a user edits an existing record I puzzled to think that another user might be changing that record at the same time (because they are not locking any records and are using lists with the record contents locally)! This could cause for example that user A changes record 1 from "bar" to "foo" and updates the db, just after user A user B updates the db with a change in the same record from "bar" to "foobar" (never seeing user As changes)!!! I guess this is a very common problem with a standard solution. How can I avoid this? Best regards, Mekl From magnus at thinkware.se Sun Jun 20 19:31:43 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Jun 21 01:14:36 2004 Subject: [Tutor] Material from my EPC presentations on DB programming and testing available. Message-ID: <5.2.1.1.0.20040621012721.0272fc28@www.thinkware.se> My presentations from the Europython Conference and some example code is now on-line. It can be reached from http://www.python.org/cgi-bin/moinmoin/EuroPython2004Slides /Magnus -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From python at kc.rr.com Sun Jun 20 19:29:28 2004 From: python at kc.rr.com (python@kc.rr.com) Date: Mon Jun 21 01:15:11 2004 Subject: [Tutor] changing string to integer in a script Message-ID: Hi, all. Having a problem with a script that I can't seem to lick. I *think* I know what the issue is, but I am powerless to fix it. In short, it will attempt to see if myvar is located in list mylist. If it does, then something interesting happens. Otherwise, it will sleep for a bit and try again. (The script will ultimately be for logging someone out automagically during certain hours of the day). Ok, script... ----- import sys, os, time, EasyDialogs mylist = [ 9, 10, 16, 17, 18, 19, 20, 21] # If i assign myvar to the below, it works peachy. #myvar = 9 # If I assign myvar to the system time, it fails. always. myvar = time.strftime('%H') # All below this works fine. you can cheerfully ignore it. try: mylist.index(myvar) except ValueError: EasyDialogs.Message('No problems. Sleeping. blah blah...') else: EasyDialogs.Message('something interesting happens here...') ----- Ok. if I set the myvar to time.strftime('%H') it will always fail, even when I try to set the clock back, et. al. I run a 'type' against it and get: >>> import time >>> time.strftime('%H') '18' >>> type (time.strftime('%H')) So it looks like I am getting a string back instead of an integer. If I just assign it a number and run type on it again it looks OK... >>> myvar = 9 >>> type(myvar) I'm sure I have not looked hard enough, but I can't see any way to change a string to an int. I *imagine* it would be something kinda like: time.strftime('%H').something.something() But I'm stuck and need an extra bit of cleverness to fix this. At the moment I am *assuming* the string .vs int. thing is the issue, would love to know if it's really something else I have not run into yet. Sorry for the length, but would rather soak you with all I have than be inscrutable. Thanks in advance for any bits that may help out. P.S. First newbie post! :D Cheers! tom Weinberg's Law: "If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization" From game at gameweave.com Sun Jun 20 23:00:45 2004 From: game at gameweave.com (K J) Date: Mon Jun 21 01:17:43 2004 Subject: [Tutor] This thing still working? Message-ID: <001001c4573b$f3008100$30e57218@basp.phub.net.cable.rogers.com> Just wondering if the mailing list is still working? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040620/4b998a18/attachment.html From game at gameweave.com Sun Jun 20 23:04:29 2004 From: game at gameweave.com (K J) Date: Mon Jun 21 01:21:37 2004 Subject: [Tutor] Is this working? Message-ID: <002101c4573c$788123c0$30e57218@basp.phub.net.cable.rogers.com> Is the mailing list working right? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040620/fbdc0a0a/attachment.html From adam at monkeez.org Mon Jun 21 04:06:35 2004 From: adam at monkeez.org (Adam) Date: Mon Jun 21 06:15:27 2004 Subject: [Tutor] Creating subclasses (newbie) Message-ID: <20040621090635.0edff64b@debian> I have a subclass I want to create - my intuition told me that it would be done like this: class MainClass: class SubClass: code... subclassinstance = SubClass() mainclassinstance = MainClass() But it seems that this isn't going to work. I'm reading a couple of Python books, but they don't seem to cover this topic very well (I don't see any coding examples). What is the best way of creating (coding) subclasses? Thanks in advance. Adam From rschroev_nospam_ml at fastmail.fm Mon Jun 21 08:16:25 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon Jun 21 10:57:40 2004 Subject: [Tutor] time calc In-Reply-To: References: Message-ID: <40D6D199.1020504@fastmail.fm> kevin parks wrote: > What i want to do is append the duration to the end of this list by > subtracting the start of the item from the start time of the next so > that the first line would look like: > > 1 1 1 00:23 08:00 > 1 2 2 8:23 01:18 > > etc. > > So the task is really two part : reading in a list of numbers and adding > one more piece of data and (2) doing time (base 60) math. It is the time > math part i simply can't get my head around. Anyone know if there is a > module that does time math? or a method for doing this by hand? I don't know if there is a module that makes this easier, but here is how I would do it by hand. You basically have times consisting of an hour part and a minute part. I would convert this to minutes by multiplying the hours with 60 and adding it to the minutes: m = 60*h + m Then do your math on the minutes alone, and convert back to hours and minutes when done: h = m % 60 m = m / 60 -- "Codito ergo sum" Roel Schroeven From pythontut at pusspaws.net Mon Jun 21 13:32:01 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon Jun 21 13:33:02 2004 Subject: [Tutor] floating point range() ? In-Reply-To: <1087691663.5286.25.camel@laptop.venix.com> References: <40D1D600.1010409@pusspaws.net> <1087691663.5286.25.camel@laptop.venix.com> Message-ID: <40D71B91.2050501@pusspaws.net> Lloyd Kvam wrote: >There is no builtin range for floats. There is a Python Cookbook frange >recipe which could be useful. > >An alternative for getting the list is: > [i*.5 for i in range(200)] > > > Thanks for your input, [i*.5 for i in range(200)] 'list comprehension' (think I got it right) is something I had forgotten about but I can see a use for it now :-) Cheers Dave From project5 at redrival.net Mon Jun 21 14:36:25 2004 From: project5 at redrival.net (Andrei) Date: Mon Jun 21 14:40:16 2004 Subject: [Tutor] Re: time calc References: Message-ID: <1exhy0rsmj4oy.1n6r4ac5crxch$.dlg@40tude.net> kevin parks wrote on Fri, 18 Jun 2004 13:36:10 -0400: Hi, > What i want to do is append the duration to the end of this list by > subtracting the start of the item from the start time of the next so > that the first line would look like: > > 1 1 1 00:23 08:00 > 1 2 2 8:23 01:18 > So the task is really two part : reading in a list of numbers and > adding one more piece of data and (2) doing time (base 60) math. It is > the time math part i simply can't get my head around. Anyone know if > there is a module that does time math? or a method for doing this by > hand? Here's a simple solution: convert the time to the base unit (I assume that's minutes:seconds). This means that you take the part before the colon, multiply with 60 and add it to the part at the right of the colon (a split() combined with int() will do the trick). Then you calculate in seconds whatever you like and convert it back to minutes. Converting back is done using integer division, for example 92 seconds: minutes = 92 // 60 # integer division seconds = 92 % 60 # remainder print "%s:%s" % (minutes, seconds) gives: 1:32 -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Mon Jun 21 14:49:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 21 15:23:42 2004 Subject: [Tutor] pstree cgi-script In-Reply-To: <1087588562.5793.6.camel@drachenfels> Message-ID: On Fri, 18 Jun 2004, Conrad Gavin wrote: > NB: With regard the previous post, I am finding similar things on google > about python's seemingly dogey co-exhistence with Apache. > > http://lists.debian.org/debian-user/2002/05/msg00967.html > > Seems to be more or less what I am experiencing ... Hi Conrad, What they're running into is a tricky interaction between the buffering that Apache and Python is doing, combined with the behavior of os.system(). Let's go back to the script that isn't working: ### #!/usr/bin/python import sys import os import cgitb; cgitb.enable() sys.stdout.write("Content-type: text/plain\n\n") cmd = "/usr/bin/pstree" os.system(cmd) ### The reason it doesn't work is subtle, and I have to admit that I don't quite understand it fully yet. But I'll try saying something reasonable. *grin* It appears that Python keeps its own buffered standard output stream, and because it's buffered, Python won't write it out until it triggered to do so. I assumed that any writes of '\n' newlines will do it, but it appears that later versions of Apache do something funny to the STDOUT file handle so that even '\n' doesn't flush it automatically. Usually, this shouldn't matter much... except that the script also calls os.system(), which accesses the underlying STDOUT file handle as a side effect. What Apache ends up seeing, ultimately, is the output of 'pstree' first, followed by the Content-type header. The following is one way to address the problem: ### #!/usr/bin/python import sys import os import cgitb; cgitb.enable() sys.stdout.write("Content-type: text/plain\n\n\n") sys.stdout.flush() ## line change here cmd = "/usr/bin/pstree" os.system(cmd) ### The explicit call to flush() guarantees that Apache will first see the Content-type header. And after that, Apache should be happy. But a better way to fix this is to avoid depending on the 'side effect' of os.system(), and to actually capture its output with os.popen() instead: ### #!/usr/bin/python import sys import os import cgitb; cgitb.enable() sys.stdout.write("Content-type: text/plain\n\n\n") cmd = "/usr/bin/pstree" print os.popen(cmd).read() ### That way, we avoid all the weird buffer issues that your script is running into. In summary: os.system() isn't meant to be used for output purposes, and it gives no guarantee when you'll see its output on screen. os.popen() is more appropriate for the task of capturing the output. There are some other weird things with Apache's CGI sytem that have very little to do with Python. It appears that in some versions of Apache, printing to STDERR was not a good idea: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=22030 And this just sounded insane to me. *grin* But I'm glad the Apache folks are getting this fixed, finally. Anyway, hope this helps! From project5 at redrival.net Mon Jun 21 14:54:20 2004 From: project5 at redrival.net (Andrei) Date: Mon Jun 21 15:31:19 2004 Subject: [Tutor] Re: floating point range() ? References: <40D1D600.1010409@pusspaws.net> Message-ID: Dave S wrote on Thu, 17 Jun 2004 18:33:52 +0100: > Is there a floating point range() type builtin ? > > I need to generate a sequence for a 'for loop' every 0.5 > > for i in reange(0,1000,5) > j=float(i)/10 > print j > > The above works but seems clumbsy. > > Is there a better way ? Write your own range function, say frange(). The implementation below is simple and not as versatile as the built-in since it only allows positive steps: def frange(start, stop=0, step=1): result = [] if step <= 0: # prevent endless loop raise "step must be > 0" start, stop = min(start, stop), max(start, stop) i = start while i < stop: result.append(i) i = i + step return result This function might surprise you though, due to the inaccuracies of floating point: >>> frange(1, 2, .2) [1, 1.2, 1.3999999999999999, 1.5999999999999999, 1.7999999999999998, 1.9999999999999998] Particularly the inclusion of 1.99999999 (in fact, 2) is the one you might not have expected here. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From python at kc.rr.com Mon Jun 21 21:25:28 2004 From: python at kc.rr.com (python@kc.rr.com) Date: Mon Jun 21 21:27:35 2004 Subject: [Tutor] Test - ignore Message-ID: <0B33743F-C3EB-11D8-B5AB-0003934BF52E@kc.rr.com> The world does not have enough test messages so I thought I would help out :D Weinberg's Law: "If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization" From david at graniteweb.com Tue Jun 22 00:34:01 2004 From: david at graniteweb.com (David Rock) Date: Tue Jun 22 00:34:10 2004 Subject: [Tutor] time calc In-Reply-To: References: Message-ID: <20040622043401.GA28232@wdfs.graniteweb.com> * kevin parks [2004-06-18 13:36]: > hi all. > > I have a bit of a task that i have been doing by hand, but as it turns > out there is pages and pages more of this so i would like to make a > python script that does this work and have it handy. > > I have a list that has several columns like so: > > 1 1 1 00:23 > 1 2 2 8:23 > 1 3 3 9:41 > 1 4 3 10:47 > 1 5 3 11:21 > > > What this is a list that has tape number, program number, item number > and start time for a recording. > > What i want to do is append the duration to the end of this list by > subtracting the start of the item from the start time of the next so > that the first line would look like: > > 1 1 1 00:23 08:00 > 1 2 2 8:23 01:18 > > etc. > > So the task is really two part : reading in a list of numbers and > adding one more piece of data and (2) doing time (base 60) math. It is > the time math part i simply can't get my head around. Anyone know if > there is a module that does time math? or a method for doing this by > hand? Look at the datetime module in python 2.3 I use it a lot to do date calculations (subtract one time from another, etc). http://www.python.org/doc/current/lib/module-datetime.html Especially look at the timedelta and datetime objects http://www.python.org/doc/current/lib/datetime-timedelta.html http://www.python.org/doc/current/lib/module-datetime.html These are probably overkill, but they are VERY powerful date calc tools Here is an example of how I have used these to figure out the date from 7 days ago. Where this really starts to get cool is when you are overlapping month and year ranges, or in your case, rolling over hours. import time import datetime def get_last_week(): dtup_now = time.localtime() # Gets current time tuple y,m,d = dtup_now[:3] # Gets year,month,day from tuple d_today = datetime.datetime(y,m,d) # Creates datetime object from current date d_delta = datetime.timedelta(7) # Creates timedelta object of 7 days d_last_week = d_today - d_delta # subtracts 7 days from current day return d_last_week last_week = get_last_week() print last_week.month, last_week.day, last_week.year -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040621/18ea35a0/attachment.bin From glingl at aon.at Tue Jun 22 01:34:34 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Jun 22 01:35:14 2004 Subject: [Tutor] Best place to learn on the web In-Reply-To: <001201c454d9$f22405e0$30e57218@basp.phub.net.cable.rogers.com> References: <001201c454d9$f22405e0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <40D7C4EA.1020800@aon.at> Hi Kevin! Try http://www.freenetpages.co.uk/hp/alan.gauld/ -- Chapter Modules & Functions http://www.ibiblio.org/obp/thinkCSpy/chap03.htm and generally http://www.python.org/topics/learn/non-prog.html HTH, Gregor K J schrieb: > I was wondering where the best tutorial on the net would be to learn def > functions. I am having trouble learning them. > > Thanks > > Kevin > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From python at kc.rr.com Tue Jun 22 03:08:46 2004 From: python at kc.rr.com (python@kc.rr.com) Date: Tue Jun 22 03:09:22 2004 Subject: [Tutor] testing - please ignore. Message-ID: <00F99D7E-C41B-11D8-B5AB-0003934BF52E@kc.rr.com> emails keep getting eaten. odd. tom Weinberg's Law: "If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization" From robinst at MIT.EDU Tue Jun 22 12:22:47 2004 From: robinst at MIT.EDU (Theresa Robinson) Date: Tue Jun 22 12:23:32 2004 Subject: [Tutor] What Eval() Hath Men Wrought In-Reply-To: <5.2.1.1.0.20040618121728.02716390@www.thinkware.se> References: <5.2.1.1.0.20040618121728.02716390@www.thinkware.se> Message-ID: I'm really glad to see discussion about eval(), since I was wondering what the alternatives are to it. I'm brand new to python, and my best skills are probably in C++ & Matlab. Some of us want to write an optimization toolbox for python, similar to the one in Matlab. Many of the toolbox functions will require functions as arguments. For example, we'll want to write a function to minimize the return value of another function by varying the latter function's vector argument. The C way to do it is to pass in a pointer to a function. This is good because C nicely checks that the function 1) is actually a function 2) takes the right arguments 3) returns the right type. The Matlab way to do it is to pass a string that contains the function name, and to use the Matlab feval function, which is similar to the Python eval but nicer since you don't have to construct the whole string yourself, but instead can use the form feval('function_name',argument). This works but is bad because you get weird errors if the function name is wrong, or if the function takes an unexpected kind of argument or returns an unexpected type. What is the right way to do this in Python? Where can I learn how to do it? Thanks, Theresa On Fri, 18 Jun 2004, Magnus [iso-8859-1] Lyck=E5 wrote: > At 18:34 2004-06-17 -0800, Tim Johnson wrote: > >Couldn't resist that subject since I hear > >the eval (the built-in) is 'evil'. > > > >I've been looking through the Python Cookbook, and > >there's an example at > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 > >look for > > class Eval: > > # ...... code following > > > >This appears to be a handy class, but given the concerns about > >built-in function eval, I would welcome comments and caveats. > > As I see it, there are some problems with eval() > - It's slow, e.g. eval('5') is about ten times slower than int('5'). > - It might cause unpredicted results unless you are certain about > what you run eval on. This isn't really a problem if you only run > eval on hardcoded strings in your source code as the Cookbook > example does. In some programs eval could cause security problems. > For instance, an attacker might be able to display passwords stored > in program variables etc. > - It makes it more difficult to analyse the code, for instance with > some automatic tool such as PyChecker or PyLint. (Or manually for > that matter.) > - Debugging get's harder. You might hide syntax errors until runtime > etc. I imagine tracebacks are less helpful too. > > Besides, I'm not really sure that > print "%(text.capitalize())s %(number/9.0).1f rules!" % Eval() > is better than > print "% %.1f rules!" % (text.capitalize(), number/9.0) > > This is some kind of ASP syndrome, and it seems to me that most > programmers seem to agree that mixing code in text as in ASP or > as in the Eval example typically causes maintenance problems. > Whether we're talking about web pages or something else, we'll > often want to separate the maintenace of the text from the > maintenance of the code. I often do things similar to: > > params =3D dict(capText=3Dtext.capitalize(), verNumber=3Dnumber/9.0) > print "%(capText)s %(verNumber).1f rules!" % params() > or even something like > print "%(capText)s %(verNumber).1f rules!" % vars() > but it might be even better to use a real templating system > such as cheetah etc. See > http://www.python.org/cgi-bin/moinmoin/WebProgramming#head-9d0636d6da8e88= f8f09de1454c5961b44183b04d > > Eval might look neat, but I think you will end up missing > the syntax coloring of your python statements if you put > them in strings, and that it will turn out to be trickier > to find bugs. > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From visional_freeman at yahoo.com Sat Jun 12 13:30:34 2004 From: visional_freeman at yahoo.com (ivan low) Date: Tue Jun 22 13:29:23 2004 Subject: [Tutor] Loop Variables Message-ID: <40CB3DBA.4020408@yahoo.com> Hi, I had come to read a book about loop variable that have i, j, k. I don't understand why are there 3 type? What's the different? Ivan From tim at johnsons-web.com Tue Jun 22 13:41:46 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Jun 22 13:35:12 2004 Subject: [Tutor] Testing list Message-ID: <20040622174146.GC10975@johnsons-web.com> Testing: Have received nothing from this list in 3 days. That's strange. tim -- Tim Johnson http://www.alaska-internet-solutions.com From scott_hamma at yahoo.com Tue Jun 22 15:56:09 2004 From: scott_hamma at yahoo.com (Hamma Scott) Date: Tue Jun 22 15:57:47 2004 Subject: [Tutor] Question about Python's marketablilty Message-ID: <20040622195609.62425.qmail@web12821.mail.yahoo.com> I hope this is the area where I could post this. If this is off topic please forgive me. I've tried authors of articles about Python and user groups devoted to Python (Bay Piggies to be exact) and have gotten no response. I'm looking for direction. I'm currently working in a company whose direction is pointed towards Java and Websphere. We used Visual Basic in the past and have some applications still about. We develop software under a windows environment to distributed unders the Windows OS. I have seen some smaller in-roads towards .NET and some in-roads towards Linux, but nothing that will bring Linux company-wide. My question; Is Python a language that is a good fit in this environment or is this something just for me? I'm just starting to learn it, but I've been met with questions that I cannot answer - I have read that Python can be used like Perl CGI pages but I've heard that CGI is a resource pig. Right? Wrong? Is there another way to use Python on the Web? - How can Python integrate in the above environment? Is there a need that it can fill? I would appreciate any response...thanks for your time on this matter. Scott __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From mjekl at clix.pt Sat Jun 19 08:08:15 2004 From: mjekl at clix.pt (mjekl) Date: Tue Jun 22 17:11:34 2004 Subject: [Tutor] Record Locking and Access - newbye Message-ID: Hi, Here's my problem. Using python dbapi I get groups of records back from a database into a list for example to feed a "List Form" which is just a grid on a form (the db is about 9000 thousand records - so I suppose there's not a big problem to fetch all records in a go!). Now when a user selects a record from a grid on screen I can send him to another form "Record Form" where he can edit the record. This way I can have only one query to the database and have the users working locally on there record sets. But when a user edits an existing record I puzzled to think that another user might be changing that record at the same time (because they are not locking any records and are using lists with the record contents locally)! This could cause for example that user A changes record 1 from "bar" to "foo" and updates the db, just after user A user B updates the db with a change in the same record from "bar" to "foobar" (never seeing user As changes)!!! I guess this is a very common problem with a standard solution. How can I avoid this? Best regards, Mekl From magnus at thinkware.se Tue Jun 22 19:05:08 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Jun 22 20:15:31 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQmVzdCBwbGFjZSB0byBsZWFybiBvbiB0aGUgd2Vi?= Message-ID: Kevin wrote: > I was wondering where the best tutorial on the net would be to learn def > functions. I am having trouble learning them. The best problem is obviously the tutor mailing list! :) (Apart from the fact that all the Python mailing lists has worked poorly the last days.) What's your problem? We define functions in Python and in other programming languages for two reasons. We want to reuse code that we use over and over again, and we want to be able to split up our problem in separate pieces, so that we don't have to think about all aspects of a problem at once. We might call this separation of concerns. An aspect of this separation of concerns is that we want to be able to view the interior of a function as a little world of it's own. We want to be able solve the little problem a function is involved with in an unrestricted way, without having to worry about the rest of the program when we do this. Likewise, we want to be able to use a function without concern for that functions interior. When we call a function, we just want to care about what we put in and what we get pack. It should be like an automat. If we enter coins, we get jelly-beans in return. To use the jelly- bean automat we shouldn't have to care about how jelly-beans are made. And to make the jelly-bean machine, we shouln't have to be concerned with how the user got his money, or what he does with the jelly-beans or if he calls them gottisar instead of jelly- beans. A way to avoid this unwanted coupling between the outside of a function and it's interior, is something we call name-spaces, or scopes. When we define variables, names, inside a function, these names only exist inside the function. The code inside the function can actually see the variables defined outside the function, and it can manipulate them as well, it's not entirely sealed off, but it's usually best for the function to leave exterior things untouched. When we define a function, we define parameters that the function requires, and when we want to use the function, we pass these into the function by placing them after the function name within parenthesis. We return data to the caller of the function with the return statement. E.g. >>> def add(a, b): return a + b >>> c = add(2,3) >>> print c 5 Note that the variables a and b only exist inside the function. >>> print a Traceback (most recent call last): File "", line 1, in -toplevel- print a NameError: name 'a' is not defined >>> print b Traceback (most recent call last): File "", line 1, in -toplevel- print b NameError: name 'b' is not defined This is a fairly pointless example though. Let's do something more useful. Let's imagine that we are calculating upper and lower quartiles and medians. Perhaps 10% and 90% percentiles as well. Without functions that might look something like this. There are many more features in function definitions. See for instance http://docs.python.org/tut/node6.html Feel free to ask what you like. Tutorials aren't very interactive... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Jun 22 19:04:03 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Jun 22 21:49:15 2004 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIHRpbWUgY2FsYw==?= Message-ID: Don Arnold wrote: > Anyone know if there is a module that does time math Certainly. Just read the standard library reference! The module is called datetime. *Don't* reinvent this wheel, regardless of what people might suggest! ;) >>> import datetime >>> TD = datetime.timedelta >>> td1 = TD(hours=5,minutes=23) >>> td2 = TD(hours=3,minutes=2) >>> sum = td1+td2 >>> print sum 8:25:00 >>> td3 = TD(hours=23,minutes=2,seconds=13) >>> sum += td3 >>> print sum 1 day, 7:27:13 >>> sum.days 1 >>> sum.seconds 26833 >>> now = datetime.datetime.now() >>> then = now + sum >>> print then 2004-06-24 06:47:42.732000 >>> then.date() datetime.date(2004, 6, 24) >>> then.time() datetime.time(6, 47, 42, 732000) >>> then.year 2004 >>> then.second 42 >>> then.strftime('%Y.%m.%d') '2004.06.24' Note that the time module has a strptime function: >>> import time >>> time.strptime('23:12','%M:%S') (1900, 1, 1, 0, 23, 12, 0, 1, -1) but in general, datetime is much more useful. I guess it would be nice with a datetime.timedelta.strptime function, but I'm afraid we don't have that in the standard library yet. You can use the components you have to turn your "MM:SS" strings into timedeltas though. >>> def minsec(s): return (datetime.datetime(*time.strptime(s,'%M:%S')[:7]) - datetime.datetime(1900,1,1,0)) >>> sum = TD(0) >>> for s in "23:12 5:56 6:34 7:34".split(): sum += minsec(s) >>> print sum 0:43:16 >>> print sum.seconds 2596 (Or was that hours:minutes? Just change '%M:%S' to '%H:%M' and (of course) rename the function as appropriate.) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From j.ezequiel at spitech.com Tue Jun 22 23:14:30 2004 From: j.ezequiel at spitech.com (Ezequiel, Justin) Date: Tue Jun 22 23:43:19 2004 Subject: [Tutor] Mailing list Message-ID: <048A40781D05D143842A596D7C78F40F01025ED4@SPI-MAIL2003.SPITECH.COM> Is it just me or are there no new messages in the mailing list? The last message I got was on Mon 6/21/2004 3:50 PM (GMT+8:00). From amonroe at columbus.rr.com Wed Jun 23 06:32:05 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Jun 23 06:22:55 2004 Subject: [Tutor] Is Python a valid business tool? In-Reply-To: <20040616221355.15433.qmail@web12824.mail.yahoo.com> References: <20040616221355.15433.qmail@web12824.mail.yahoo.com> Message-ID: <100201154725.20040623063205@columbus.rr.com> > - I have read that Python can be used like Perl CGI > pages but I've heard that CGI is a resource pig. > Right? Wrong? Is there another way to use Python on > the Web? Depends on the web server and how many hits it will get. If it has to spawn a new instance of python.exe every time someone hits a page, yeah, it can be slow. But there are things like mod_python for apache that fix this problem. Dunno if they make an equivalent for websphere. Alan From darnold02 at sprynet.com Wed Jun 23 06:32:59 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Wed Jun 23 08:37:58 2004 Subject: [Tutor] time calc In-Reply-To: Message-ID: I was going to suggest using the the datetime module, but wasn't sure how datetime.datetime() objects could be used without having the date specified. I hadn't thought of using datetime.timedelta() objects all by themselves. Very nice. Thanks, Magnus. Don -----Original Message----- From: Magnus Lycka [mailto:magnus@thinkware.se] Sent: Tuesday, June 22, 2004 6:04 PM To: Don Arnold; 'kevin parks'; tutor@python.org Subject: Re: RE: [Tutor] time calc Don Arnold wrote: > Anyone know if there is a module that does time math Certainly. Just read the standard library reference! The module is called datetime. *Don't* reinvent this wheel, regardless of what people might suggest! ;) >>> import datetime >>> TD = datetime.timedelta >>> td1 = TD(hours=5,minutes=23) >>> td2 = TD(hours=3,minutes=2) >>> sum = td1+td2 >>> print sum 8:25:00 >>> td3 = TD(hours=23,minutes=2,seconds=13) >>> sum += td3 >>> print sum 1 day, 7:27:13 >>> sum.days 1 >>> sum.seconds 26833 >>> now = datetime.datetime.now() >>> then = now + sum >>> print then 2004-06-24 06:47:42.732000 >>> then.date() datetime.date(2004, 6, 24) >>> then.time() datetime.time(6, 47, 42, 732000) >>> then.year 2004 >>> then.second 42 >>> then.strftime('%Y.%m.%d') '2004.06.24' Note that the time module has a strptime function: >>> import time >>> time.strptime('23:12','%M:%S') (1900, 1, 1, 0, 23, 12, 0, 1, -1) but in general, datetime is much more useful. I guess it would be nice with a datetime.timedelta.strptime function, but I'm afraid we don't have that in the standard library yet. You can use the components you have to turn your "MM:SS" strings into timedeltas though. >>> def minsec(s): return (datetime.datetime(*time.strptime(s,'%M:%S')[:7]) - datetime.datetime(1900,1,1,0)) >>> sum = TD(0) >>> for s in "23:12 5:56 6:34 7:34".split(): sum += minsec(s) >>> print sum 0:43:16 >>> print sum.seconds 2596 (Or was that hours:minutes? Just change '%M:%S' to '%H:%M' and (of course) rename the function as appropriate.) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From pythonTutor at venix.com Wed Jun 23 09:18:24 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Wed Jun 23 09:19:16 2004 Subject: [Tutor] Is Python a valid business tool? In-Reply-To: <20040616221355.15433.qmail@web12824.mail.yahoo.com> References: <20040616221355.15433.qmail@web12824.mail.yahoo.com> Message-ID: <1087996704.2104.38.camel@laptop.venix.com> On Wed, 2004-06-16 at 18:13, Hamma Scott wrote: > I hope this is the area where I could post this. If > this is off topic please forgive me. I've tried > authors of articles about Python and user groups > devoted to Python (Bay Piggies to be exact) and have > gotten no response. I'm looking for direction. > > I'm currently working in a company whose direction is > pointed towards Java and Websphere. We used Visual > Basic in the past and have some applications still > about. We develop software under a windows environment > to distributed unders the Windows OS. I have seen some > smaller in-roads towards .NET and some in-roads > towards Linux, but nothing that will bring Linux > company-wide. > > My question; Is Python a language that is a good fit > in this environment or is this something just for me? I think it is a good fit, but you may have trouble convincing others. I think the key argument for Python is productivity everywhere. Java covers a language, a runtime environment (JVM), and a platform. Jython would allow you to use Java the platform and Java the runtime environment with a more productive language. The C implementation of Python lets you use the Python language outside the Java platform. It has terrific COM support if you are using Windows. Dot-Net is a future, but based on Jim Hugunin's talk at PyCon, IronPython proves that Python can work in a .Net environment. I do not know of any other language that offers the same kind of cross platform productivity. > I'm just starting to learn it, but I've been met with > questions that I cannot answer > > - I have read that Python can be used like Perl CGI > pages but I've heard that CGI is a resource pig. > Right? Wrong? Sort of right. The problem with CGI is that it creates a new process for each web request. If the process is simple and the number of requests is not too high, then CGI works well. I have a number of python cgi scripts that work quite well for their situation. > Is there another way to use Python on > the Web? Yes. You have choices depending upon your web server. You can run a webserver written in Python and integrate your scripts with the server. Zope is one of many possibilities. You can use mod_python to integrate python scripts with Apache. You can use fastCGI to avoid the new process overhead of regular CGI. > > - How can Python integrate in the above environment? > Is there a need that it can fill? As you can tell from the above, I'm a bit of a Python nut. I believe that Python should be the default choice for most situations. Then fall back to C or Java or whatever would make sense to fit a specific need. > > I would appreciate any response...thanks for your time > on this matter. > > Scott > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail Address AutoComplete - You start. We finish. > http://promotions.yahoo.com/new_mail > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From flaxeater at yahoo.com Wed Jun 23 10:39:26 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Wed Jun 23 10:40:29 2004 Subject: [Tutor] Is Python a valid business tool? In-Reply-To: <20040616221355.15433.qmail@web12824.mail.yahoo.com> Message-ID: <20040623143926.5549.qmail@web52606.mail.yahoo.com> --- Hamma Scott wrote: > I hope this is the area where I could post this. If > this is off topic please forgive me. I've tried > authors of articles about Python and user groups > devoted to Python (Bay Piggies to be exact) and have > gotten no response. I'm looking for direction. > > I'm currently working in a company whose direction is > pointed towards Java and Websphere. We used Visual > Basic in the past and have some applications still > about. We develop software under a windows environment > to distributed unders the Windows OS. I have seen some > smaller in-roads towards .NET and some in-roads > towards Linux, but nothing that will bring Linux > company-wide. http://www.hps1.demon.co.uk/users/andy/pyvb/ This talks about python vb integration pehaps you could use this as a bridge. There is also Jython which is a python implementation in java which can be compiled into java classes and any java class can be used in jython. Applets SWING and all the other stuff can by made/used with jython. Look up www.jython.org. Perhaps you could use websphere with jython. In addition there is Zope which is a very useful content management system written with python. I believe that is what websphere is. > > My question; Is Python a language that is a good fit > in this environment or is this something just for me? > I'm just starting to learn it, but I've been met with > questions that I cannot answer Python may be what you need. If you could use VB before python could be used. It's not speedy but often fast enough. It runs very nicely accross platforms with little or not modifiction. The proof of this is all the production code that is toted as cross platform and they are just source distributiuons. > - I have read that Python can be used like Perl CGI > pages but I've heard that CGI is a resource pig. > Right? Wrong? Is there another way to use Python on > the Web? Python can be used for CGI. The reason it's a resource hog is because an instantiation is made everytime the script is called. However this can be mitigated with mod_python which imbeds an interpreter inside apache. If you are not using apache then perhaps this is not a good idea. > - How can Python integrate in the above environment? > Is there a need that it can fill? > > I would appreciate any response...thanks for your time > on this matter. > > Scott This post is definatly off topic. This list is for teaching python. However I feel that you needed to learn perhaps this helps. In short I feel python is a good platform for producing software. It has a plethora of mature development tools and other stuff. Look more closely Check out www.python.org/pypi which is a package index and the vaults of parasues or something google for python vault. You will see alot of stuff. __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From nick at javacat.f2s.com Wed Jun 23 15:40:09 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Jun 23 15:39:56 2004 Subject: [Tutor] class variables In-Reply-To: <40D21E3A.7000608@javacat.f2s.com> Message-ID: Just replying to my own email :) I sent this about 3 days ago, and it's only just been received on the list, after being forwarded by the tutor bouncer, what gives there ? Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Nick Lunt Sent: 17 June 2004 23:42 To: Tutor Subject: [Tutor] class variables Hi folks, Im making my way through the book 'Learning Python 2nd Edition'. I understand classes but I have a question. Take the following for example - class beer: def __init__(self): self.make = 'murphys' cans = 4 There's several examples I've seen where 'self.var' isn't used, just 'var' is, as in 'cans' above. I know that each instance of 'beer' will have its own value for 'make' but what is the use of 'cans' without using self ? Any pointers in the right direction happily received :) Regards Nick. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Wed Jun 23 15:31:16 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Jun 23 15:43:26 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcHNwX3NpdGUgbW1vZHM=?= Message-ID: Might this excerpt from the mod_python docs be useful? ---- Here is an example of how PSP can be used as a templating mechanism: The template file:

Hello, <%=what%>!

The handler code: from mod_python import apache, psp def handler(req): template = psp.PSP(req, filename='template.html') template.run({'what':'world'}) return apache.OK --- By the way, as a general programming advice, I'd suggest that you keep your swishE logic and your mod_python logic in different modules. This will have two benefits: * It gets easier to replace mod_python with something else without touching your swishE code or vice versa. * It makes it easier to write/test/debug the swishE code without having to think about mod_python problems and vice versa. This means that your code might be something like this (entirely untested and just guessing wildly): from mod_python import apache, psp import search def results(req, searchWords): template = psp.PSP(req, filename='template.html') if not (searchWords): query = 'Nothing to search for.' answer = 'Nothing Found' else: query = 'Looking for: %s' % searchWords answer = search.wordSearch(searchWords) template.run({'query':query, 'answer':answer}) return apache.OK template.html:

<%=query%>

<%=answer%> and then in "search.py": .. def wordSearch(searchWords): handle = SwishE.new('/usr/local/swish-e/index.swish-e') search = handle.search('') results = search.execute(searchWords) files = [r.getproperty('swishdocpath') for r in results] if files: return "The files found are: %s" % files else: return "No files found." -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Jun 23 15:54:53 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Jun 23 15:55:04 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gY2xhc3MgdmFyaWFibGVz?= Message-ID: Nick Lunt wrote: > Hi folks, > > Im making my way through the book 'Learning Python 2nd Edition'. I > understand classes but I have a question. > Take the following for example - > > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, just > 'var' is, as in 'cans' above. > I know that each instance of 'beer' will have its own value for 'make' > but what is the use of 'cans' without using self ? It's simply a local variable in the function. In this case it's completely pointless, since you just assign to it and then the function ends! Compare it with def init(): global make make = 'murphys' cans = 4 Note that class variables, i.e. variables defined in the scope of the class, is something completely different. Like this: class Beer: cans = 4 def __init__(self): self.make = 'murphys' a_local = 5 The class varaible Beer.cans is shared between all instances of the class. There is a separate instance variable self.make for each instance of the Beer class. The local varable only exists during the duration of the execution of the __init__ method. Note that instance varables hide class varaibles. >>> class Beer: cans = 4 def __init__(self): self.make = 'murphys' >>> a = Beer() >>> b = Beer() >>> a.make, a.cans ('murphys', 4) >>> b.make, b.cans ('murphys', 4) >>> a.make = 'Utenos' >>> a.make, a.cans ('Utenos', 4) >>> b.make, b.cans ('murphys', 4) >>> Beer.cans = 6 >>> a.make, a.cans ('Utenos', 6) >>> b.make, b.cans ('murphys', 6) >>> b.cans = 3 >>> b.make, b.cans ('murphys', 3) >>> del b.cans >>> b.make, b.cans ('murphys', 6) >>> -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Jun 23 14:47:19 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Jun 23 15:56:55 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcHNwX3NpdGUgbW1vZHM=?= Message-ID: Reed L. O'Brien wrote: > def results(req, searchWords): > return _any_page(req, 'results') > > > > #def performSearch(searchWords): > > # make sure the user provided all the parameters > if not (searchWords): > return " Nothing to search for. Nothing Found." > > > # do the search > handle = SwishE.new('/usr/local/swish-e/index.swish-e') > search = handle.search('') > results = search.execute(searchWords) > return [r.getproperty('swishdocpath') for r in results] I'm not sure what this is meant to do, but you should be aware that everything after the line "return _any_page(req, 'results')" will be ignored by Python. Since you have an uncondional return on that line, any call to the function "results" will end there, and because of it's indentation, the code below is considered to be a part of the "results" function. If you are uncertain about indentation, make sure that you consistently use spaces *or* tabs for indentation, never mix them. Most Pythonistas use four spaces for indentaion. > I could keep playing around but I figured it was time to put down my > pride and ask the experts. Any help is appreciated. > > TIA > cheers, > reed (very newb programmer) Did you get an unmodified version if the demo to work? Make sure that you do. Start with that and try to change it in *really* small steps. Don't add any more features if you've broken your code. Always make it work before you go to the next step. I don't know if anyone here has used mod_python and psp (I haven't), but if you have a working example, and then can show that it broke when you made a tiny change, we can probably help you sort that out. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Jun 23 16:18:20 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Jun 23 16:18:40 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gcHNwX3NpdGUgbW1vZHM=?= Message-ID: Reed L. O'Brien wrote: > Yes the demo site was working. I am trying to add functionality. > If you'd like to browse the current code you can at: > http://snake.rokomworldwide.com/cgi-bin/trac.cgi/browser/trunk/ Ok, now I understand a bit more: def results(req, searchWords): global answer if not (searchWords): #req.write answer = "Nothing to search for. Nothing Found" handle = SwishE.new('/usr/local/swish-e/index.swish-e') search = handle.search('') results = search.execute(searchWords) files = [r.getproperty('swishdocpath') for r in results] # req.write("The files found are: %s" % files) answer = "The files found are: %s" % files return _any_page(req, 'results') There seems to be two bugs here. First of all, even if you go into the if-block, you will continue to do the search after that, replacing the first "answer" every time. You need to use else. (I'd also get rid of the not, and make the "if" more "positive". Secondly, "answer" should be included in the vars parameter of the psp.PSP instance if I understand this correctly. You should pass it to "_any_page". Avoid globals. I've added a named parameter to _any_page for that. Note that existing callers of _any_page can go on like before, no change needed there. def results(req, searchWords): if (searchWords): handle = SwishE.new('/usr/local/swish-e/index.swish-e') search = handle.search('') results = search.execute(searchWords) files = [r.getproperty('swishdocpath') for r in results] answer = "The files found are: %s" % files else: answer = "Nothing to search for. Nothing Found" return _any_page(req, 'results', my_vars={'answer':answer}) def _any_page(req, name, vars={}): body_tmpl = _tmpl_path('%s_body.html' % name) vars.update({"menu": _menu(req, hlight=name), "body": psp.PSP(req, body_tmpl)}) main_tmpl = _tmpl_path(MAIN_TMPL) return psp.PSP(req, main_tmpl, vars=vars) I still think it's clever to factor out the swishE stuff in a separate module. No big deal for this small program, but code tends to grow and get more complex, and then it's a good thing to keep different things, such as dependencies on different 3rd party modules separate if it's easy to achieve. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From python at kc.rr.com Wed Jun 23 17:19:18 2004 From: python at kc.rr.com (python@kc.rr.com) Date: Wed Jun 23 17:20:33 2004 Subject: [Tutor] errr... Message-ID: My messages never seem to make it to the list. final test before I sadly have to unsubscribe. From adeleinandjeremy at yahoo.com Wed Jun 23 17:31:24 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Wed Jun 23 17:31:30 2004 Subject: [Tutor] Where to learn def's In-Reply-To: <000b01c454c1$7c0f1100$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <20040623213124.54529.qmail@web50309.mail.yahoo.com> --- K J wrote: > I was wondering where the best tutorial on the net would be to > learn def > functions. I am having trouble learning them. > I think I saw this before somewhere.... Have you tried http://www.defjam.com? What sort of trouble are you having? How old are you? Are you taking a class that requires Python? Are you learning on your own? Have you programmed before (in other languages)? How can anyone help you if you don't explain what your real problem is? One trouble it seems you are having is teminological confusion. def is not a type of function - it is a python keyword which denotes a function definition. Perhaps you mean to distinguish between built in or library functions and user-defined functions? No one could possibly answer this without knowing your circumstances, but I'll lay money that you will find the answer among the links scattered around http://www.python.org. - Jeremy __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From nick at javacat.f2s.com Wed Jun 23 17:33:30 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Jun 23 17:33:19 2004 Subject: [Tutor] class variables In-Reply-To: Message-ID: Magnus and Danny, thankyou very much for your explanations. >From what you've both told me, it would seem that putting a local variable in the __init__ method of a class is quite pointless, ie example 1 >>>class beer: >>> def __init__(self): >>> cans = 4 >>> self.make = 'murphys' The variable 'cans' will not be useable in any invocation of the class beer. When I try to use the class in example 1, I get this - >>> b1 = beer() >>> b1.cans Traceback (most recent call last): File "", line 1, in ? AttributeError: beer instance has no attribute 'cans' When I put the cans variable outside of the init method, ie example 2 >>>class beer: >>> cans = 4 >>> def __init_(self): >>> self.make = 'murphys' then instances of the class 'beer' will be able to set and get instance.cans, just as if it was coded as 'self.cans'. Here's what I get with the version of the 'beer' class in example 2 - >>> b2 = beer() >>> b2.cans 4 >>> b3 = beer() >>> b3.cans 4 >>> b2.cans = 10 >>> b2.cans 10 >>> b3.cans 4 >>> Which is how Magnus showed me. As it stands now I cant see any use for a local variable inside the __init__ method, ie a variable without the self prefix. But also, I can see no reason to use a class variable outside of a class method with no self prefix. I admit Im quite confused by this still. Many python programs Ive studied mix up class variable with and without the 'instance/self' prefix. Im also confused about whether I should put my class variable inside a method and use the self prefix, leave them outside of a method with no prefix, or leave them outside of a method but give them a prefix. With the simple programs I write at the moment, it wouldnt really make much difference how I did it in most cases, but I would like to know when I should or shouldn't be using self. And when I should be putting class variables outside a class method (if ever). I apologise for not grasping it very quickly. My previous experiences with classes comes from java, and that was a while ago, and java classes seem a lot stricter than python classes. Many thanks, Nick. -----Original Message----- From: Magnus Lycka [mailto:magnus@thinkware.se] Sent: 23 June 2004 20:55 To: Nick Lunt Cc: tutor@python.org Subject: Re: [Tutor] class variables Nick Lunt wrote: > Hi folks, > > Im making my way through the book 'Learning Python 2nd Edition'. I > understand classes but I have a question. > Take the following for example - > > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, just > 'var' is, as in 'cans' above. > I know that each instance of 'beer' will have its own value for 'make' > but what is the use of 'cans' without using self ? It's simply a local variable in the function. In this case it's completely pointless, since you just assign to it and then the function ends! Compare it with def init(): global make make = 'murphys' cans = 4 Note that class variables, i.e. variables defined in the scope of the class, is something completely different. Like this: class Beer: cans = 4 def __init__(self): self.make = 'murphys' a_local = 5 The class varaible Beer.cans is shared between all instances of the class. There is a separate instance variable self.make for each instance of the Beer class. The local varable only exists during the duration of the execution of the __init__ method. Note that instance varables hide class varaibles. >>> class Beer: cans = 4 def __init__(self): self.make = 'murphys' >>> a = Beer() >>> b = Beer() >>> a.make, a.cans ('murphys', 4) >>> b.make, b.cans ('murphys', 4) >>> a.make = 'Utenos' >>> a.make, a.cans ('Utenos', 4) >>> b.make, b.cans ('murphys', 4) >>> Beer.cans = 6 >>> a.make, a.cans ('Utenos', 6) >>> b.make, b.cans ('murphys', 6) >>> b.cans = 3 >>> b.make, b.cans ('murphys', 3) >>> del b.cans >>> b.make, b.cans ('murphys', 6) >>> -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From adeleinandjeremy at yahoo.com Wed Jun 23 17:46:26 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Wed Jun 23 17:46:43 2004 Subject: [Tutor] class variables In-Reply-To: <40D21E3A.7000608@javacat.f2s.com> Message-ID: <20040623214626.59594.qmail@web50309.mail.yahoo.com> --- Nick Lunt wrote: > Hi folks, > > Im making my way through the book 'Learning Python 2nd Edition'. I > understand classes but I have a question. > Take the following for example - > > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, > just > 'var' is, as in 'cans' above. > I know that each instance of 'beer' will have its own value for > 'make' > but what is the use of 'cans' without using self ? In this example, there is no use. Once __init__ has been called and executed, the variable cans will be taking up memory space with no way for you to access it (well, normally, anyway). Given that x = Beer(), neither x.cans nor Beer.cans is going to turn up anything but an AttributeError exception. On what page are you? Perhaps you are referring to something such as the following: class Beer: beers = 0 def __init__(self, make=''): self.make = make Beer.beers += 1 x = Beer('michelob') y = Beer('murphys') z = Beer('busch') After this, the variable beers is 3, and x.beers, y.beers, z.beers, and Beer.beers will all be 3. This, of course, is very useful. HTH - Jeremy __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From alan.gauld at blueyonder.co.uk Wed Jun 23 18:46:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 23 18:46:37 2004 Subject: [Tutor] time calc References: Message-ID: <002201c45973$fbbdaf40$6401a8c0@xp> > So the task is really two part : reading in a list of numbers and > adding one more piece of data and (2) doing time (base 60) math. It is > the time math part i simply can't get my head around. Anyone know if > there is a module that does time math? or a method for doing this by > hand? Look at the datetime module - new in 2.3. Alternatively you can convert time to seconds using the older time module, do the math in seconds and convert back to readable format again... Alan g From gew75 at hotmail.com Wed Jun 23 18:55:34 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Wed Jun 23 18:55:44 2004 Subject: [Tutor] IDLE vs. Python Command Line References: <42.50c836ac.2e03a7be@aol.com> Message-ID: Hi Dragonfirebane, I don't use IDLE to code with, so I can't explain the output you see there. The command line is correct. HTH, Glen ----- Original Message ----- From: Dragonfirebane@aol.com To: tutor@python.org Sent: Friday, June 18, 2004 12:04 PM Subject: [Tutor] IDLE vs. Python Command Line when i type: ## >>>import string >>>string.letters ## in IDLE, i get: ## 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\x9a\x9 c\x9e\x9f\xaa\xb5\xba\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xc d\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe 1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf 4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' ## but when i do it on the Python Command Line, i get: ## 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ## is this a flaw in IDLE or the Command Line? Which is more accurate? Since one of my programs uses string.letters, it is important for me to know. Thanks in advance, Orri P.S.: IDLE: >>> print string.letters ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz???????????????????????? ????????????????????????????????????????????????? Command Line: >>>print string.letters abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Wed Jun 23 19:23:42 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Jun 23 19:22:40 2004 Subject: {Spam?} [Tutor] IDLE vs. Python Command Line In-Reply-To: <42.50c836ac.2e03a7be@aol.com> References: <42.50c836ac.2e03a7be@aol.com> Message-ID: <6.1.0.6.0.20040623172302.03e27008@mail.mric.net> At 08:04 PM 6/17/2004, Dragonfirebane@aol.com wrote: >when i type: > >## > >>>import string > >>>string.letters >## > >in IDLE, i get: > >## >'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\x9a\x9c\x9e\x9f\xaa\xb5\xba\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' >## > >but when i do it on the Python Command Line, i get: > >## >'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >## I can confirm that behavior, but not explain it. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bgailer at alum.rpi.edu Wed Jun 23 19:29:53 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Jun 23 19:28:45 2004 Subject: {Spam?} [Tutor] class variables In-Reply-To: <40D21E3A.7000608@javacat.f2s.com> References: <40D21E3A.7000608@javacat.f2s.com> Message-ID: <6.1.0.6.0.20040623172621.03ebb008@mail.mric.net> At 04:42 PM 6/17/2004, Nick Lunt wrote: >Hi folks, > >Im making my way through the book 'Learning Python 2nd Edition'. I >understand classes but I have a question. >Take the following for example - > >class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > >There's several examples I've seen where 'self.var' isn't used, just 'var' >is, as in 'cans' above. >I know that each instance of 'beer' will have its own value for 'make' but >what is the use of 'cans' without using self ? cans is a local variable, not a class variable. It disappears when the __init__ method terminates. If you move the assignment to the class level, cans becomes a class variable; every instance of beer will have the class property with value 4 unless overridden. class beer: cans = 4 def __init__(self): self.make = 'murphys' Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From roeland.rengelink at chello.nl Wed Jun 23 19:40:51 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Wed Jun 23 19:38:10 2004 Subject: [Tutor] classes & required method not working In-Reply-To: <40D48D3A.4030708@pusspaws.net> References: <40D48D3A.4030708@pusspaws.net> Message-ID: <40DA1503.40001@chello.nl> Dave S wrote: > I have a class problem. I have a script, ggScanStock.py which defines a > class ScanData : > > #!/usr/bin/env python > > """ > AnalizeClass > """ > > import os,ggdatacore3 > > class ScanData: > ggpcprofit.py > > #!/usr/bin/env python > > import os,ggScanStock > > class pcprofit(ScanData): > However when I try & execute ggpcprofit.py I get : > > bash-2.05b$ ./ggpcprofit.py > Traceback (most recent call last): > File "./ggpcprofit.py", line 5, in ? > class pcprofit(ScanData): > NameError: name 'ScanData' is not defined > bash-2.05b$ > > Can anyone explain where I am going wrong - I imported ggScanStock so > why cant my class pcprofit > find class ScanData ? > You should use: class pcprofit(ggScanStock.ScanData): ... i.e.: the object ScanData from the module ggScanStock import amodule, does not import the objects defined in 'amodule' in your module. It creates them in 'amodule' and you can access them using the dot-notation Hope this help, Roeland -- Author of PyORQ (http://pyorq.sourceforge.net), an Object-Relational binding that lets you write queries as Python expression 'half of what I say is nonsense, unfortunately I don't know which half' From dyoo at hkn.eecs.berkeley.edu Wed Jun 23 15:57:10 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jun 23 21:28:29 2004 Subject: [Tutor] class variables In-Reply-To: <40D21E3A.7000608@javacat.f2s.com> Message-ID: On Thu, 17 Jun 2004, Nick Lunt wrote: > Im making my way through the book 'Learning Python 2nd Edition'. I > understand classes but I have a question. Take the following for example > - > > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, just > 'var' is, as in 'cans' above. Hi Nick, In this particular example, 'cans' is a local variable, so it lasts for just the method call. Hope this helps! From Dragonfirebane at aol.com Wed Jun 23 22:18:37 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Wed Jun 23 22:18:53 2004 Subject: [Tutor] changing string to integer in a script Message-ID: <84.2cad98c4.2e0b93fd@aol.com> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 2177 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040623/63bf606d/attachment.jpe -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 1715 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040623/63bf606d/attachment-0001.jpe From reed at intersiege.com Wed Jun 23 23:05:08 2004 From: reed at intersiege.com (Reed L. O'Brien) Date: Wed Jun 23 23:05:21 2004 Subject: [Tutor] Re: Is this working? In-Reply-To: <002101c4573c$788123c0$30e57218@basp.phub.net.cable.rogers.com> References: <002101c4573c$788123c0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: K J wrote: > Is the mailing list working right? > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor I am under the impression that a number of lists are having spam issues. Perhaps mailman based lists. mod_python is down. I just got my subscription link from python-list 4 days later. They time out after three days. r From david at graniteweb.com Thu Jun 24 00:20:28 2004 From: david at graniteweb.com (David Rock) Date: Thu Jun 24 00:20:40 2004 Subject: [Tutor] Is Python a valid business tool? In-Reply-To: <20040616221355.15433.qmail@web12824.mail.yahoo.com> References: <20040616221355.15433.qmail@web12824.mail.yahoo.com> Message-ID: <20040624042028.GF1222@wdfs.graniteweb.com> * Hamma Scott [2004-06-16 15:13]: > I hope this is the area where I could post this. If > this is off topic please forgive me. I've tried > authors of articles about Python and user groups > devoted to Python (Bay Piggies to be exact) and have > gotten no response. I'm looking for direction. > > I'm currently working in a company whose direction is > pointed towards Java and Websphere. We used Visual > Basic in the past and have some applications still > about. We develop software under a windows environment > to distributed unders the Windows OS. I have seen some > smaller in-roads towards .NET and some in-roads > towards Linux, but nothing that will bring Linux > company-wide. > > My question; Is Python a language that is a good fit > in this environment or is this something just for me? > I'm just starting to learn it, but I've been met with > questions that I cannot answer > > - I have read that Python can be used like Perl CGI > pages but I've heard that CGI is a resource pig. > Right? Wrong? Is there another way to use Python on > the Web? Yes, it can. I guess "resource pig" is a bit subjective. Apache has a mod_python that can deal with a lot of the overhead of calling the interpreter. > - How can Python integrate in the above environment? > Is there a need that it can fill? Are you using it for an end-application? Is it something that you would be concerend about letting other end-users have access to the source of the app? Python works primarily as a script file that is run by an interpreter, although there are ways to create executable binary versions (py2exe, for one). About the best place I can think of to get information about Python as a web tool is to look at Zope. http://www.zope.org Zope's existience is a pretty good argument for Python on the web. Actually, so is Google, NASA, and ILM http://www.python.org/Quotes.html -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040623/0fbce901/attachment.bin From flaxeater at yahoo.com Thu Jun 24 01:03:52 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Jun 24 01:03:58 2004 Subject: [Tutor] changing string to integer in a script In-Reply-To: Message-ID: <20040624050352.86064.qmail@web52604.mail.yahoo.com> ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a='this is a string' >>> type(a) >>> a='11' >>> type(a) >>> a=int(a) >>> type(a) >>> __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at yahoo.com Thu Jun 24 01:08:32 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Jun 24 01:08:40 2004 Subject: [Tutor] Record Locking & Access - newbye In-Reply-To: <003001c456f8$17ba9b00$6601a8c0@clixdialupadapt> Message-ID: <20040624050832.71258.qmail@web52607.mail.yahoo.com> > Now when a user selects a record from a grid on screen I can send > him to > another form "Record Form" where he can edit the record. This way I > can have > only one query to the database and have the users working locally > on there > record sets. But when a user edits an existing record I puzzled to > think > that another user might be changing that record at the same time > (because > they are not locking any records and are using lists with the > record > contents locally)! > I guess this is a very common problem with a standard solution. How > can I > avoid this? I have not done this personaly but *I* would just make some file on the system that indicates wether or not the db should be "LOCKED" or not. Another way that I have tought about doing it. Maybe not in scope. But to create a client server system where the server is the only one that can make db writes. And the server acts as a que for writing. As I was writing I realized the trouble. You will need to check wether the field has changed since the user has viewed the field. perhaps you should have a last_changed field in each row and if it's newere than last viewed by the user then notify the user that he has new information he should consider before submiting the change. This could get tedious for the user depending on the situation. __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From flaxeater at yahoo.com Thu Jun 24 01:12:40 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Jun 24 01:12:51 2004 Subject: [Tutor] class variables In-Reply-To: <40D21E3A.7000608@javacat.f2s.com> Message-ID: <20040624051240.49831.qmail@web52602.mail.yahoo.com> > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, > just > 'var' is, as in 'cans' above. > I know that each instance of 'beer' will have its own value for > 'make' > but what is the use of 'cans' without using self ? > this troubled me at first and I'm not sure but I may have asked this very question here. self.var in this case means that it's a class variable available to the instance. In this case 'cans' is a function variable only available to things inside that function. just like this x=10 def dosomething(): x=20 print x print x >>dosomething() 20 >>print x 10 I hope this helps. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From carroll at tjc.com Thu Jun 24 02:12:33 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Jun 24 02:12:46 2004 Subject: [Tutor] Printing a progress bar In-Reply-To: <40D1D789.1040400@pusspaws.net> Message-ID: On Thu, 17 Jun 2004, Dave S wrote: > Terry Carroll wrote: > > >I use Randy Pargman's progress bar from > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 ; I find it > >does the job nicely. > > > > > I will combine this class with backspacing to hopefully produce a static > line with a dynamic progress bar ! Don't sweat the backspacing. Look at the examples on that web page. The line printing the progress bar string looks like this: print prog, "\r", This prints the string named prog, which is your progress-bar, followed by a return ("\r"), which sets up the curser back to column 1, no backspacing needed. Then the newline that's normallt added to a printed statement is supressed, due to the trailing comma. That's one thing I like about this progress bar; you just print it, and that's it, no counting, no backspacing, none of that. Just remember when you're done to do that final bare "print" statement, because otherwise you'll still be poised at the beginning of the line for your next print statement, and your line will look messy, with a progress bar partially overwritten by your next print. From alan.gauld at blueyonder.co.uk Thu Jun 24 02:55:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 02:54:42 2004 Subject: [Tutor] Best place to learn on the web References: <001201c454d9$f22405e0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <003701c459b8$2ca1c3f0$6401a8c0@xp> > I was wondering where the best tutorial on the net would be > to learn def functions. I am having trouble learning them. Being biased I'd suggest my web tutor :-) But you could also try the official tutor that comes with Python. And if you have specific questions post them here thats what the list is for. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From project5 at redrival.net Thu Jun 24 03:02:31 2004 From: project5 at redrival.net (Andrei) Date: Thu Jun 24 03:02:46 2004 Subject: [Tutor] Re: Creating subclasses (newbie) References: <20040621090635.0edff64b@debian> Message-ID: Adam monkeez.org> writes: > I have a subclass I want to create - my intuition told me > that it would be done like this: > > class MainClass: > class SubClass: > code... > subclassinstance = SubClass() > mainclassinstance = MainClass() Your intuition is wrong :). A subclass is not a class defined in a different class, but a class that inherits and builds upon an ancestor class (a little bit like a child inherits from her parents, but is not identical to them). For example we know that all spheres have a diameter. We also know that all balls are spheres and are intended for a certain game. However, not all spheres are for playing games with (e.g. the sun or one of those glass "lightning" spheres). So let's express that in classes: class Sphere(object): # means Spere inherits from object def __init__(self, diameter): self.diameter = diameter def getRadius(self): # all spheres have a radius too return self.diameter/2 class Ball(Sphere): # Ball inherits from (or is a subclass of) Sphere def __init__(self, diameter, game): Sphere.__init__(self, diameter) # initializes the Sphere properties # (which Ball obviously also has) self.game = game # a Ball is meant to play a certain game football = Ball(14.0, 'football') # instance of Ball sun = Sphere(1.4e11) # instance of Sphere print football.getRadius() # method inherited by Ball from Sphere # Subclassing Sphere got us all its functionality # for free! If you need more sphere-like objects, # like a Planet class, they too will inherit all # functionality shared by all Spheres. print football.game # will print game property of Ball instance. print sun.game # will give an error message, since Sphere does # not inherit anything from Ball (parents don't # inherit anything from their children!) > But it seems that this isn't going to work. I'm reading a > couple of Python books, but they don't seem to cover this > topic very well (I don't see any coding examples). You should look a bit better :). People on the main Python mailing list have already pointed you to some tutorials, so read those and all will be clear(er). Yours, Andrei From alan.gauld at blueyonder.co.uk Thu Jun 24 03:10:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 03:09:52 2004 Subject: [Tutor] Is Python a valid business tool? References: <20040616221355.15433.qmail@web12824.mail.yahoo.com> Message-ID: <005101c459ba$4a0335d0$6401a8c0@xp> > I hope this is the area where I could post this. If > this is off topic please forgive me. Somewhat off topic but we'll forgive you! > authors of articles about Python and user groups > devoted to Python (Bay Piggies to be exact) and have > gotten no response. I'm looking for direction. Have you tried the web site? There is a section about Python usage in "the real world" http://www.python.org/community/users.html > We develop software under a windows environment > to distributed unders the Windows OS. That can be done. If you want to distribute .exes you need to use third party tools (such as py2exe) to create the .exe bundle, but its possible. > smaller in-roads towards .NET There is a project underway to create a Python.NET, dunno how far its gotten. Search sourceforge I guess. > - I have read that Python can be used like Perl CGI > pages but I've heard that CGI is a resource pig. CGI is a resource hog compared to some other technologies but for low volume use it is extremely portable and "good enough" in many cases. But there are several other options in Python too. Zope is the serious commercial level web development using Python, there are several books on Zope and extensive material on their web site, but it is a complete web development environment complete with object database, ORB etc - rather like WebSphere itself. Lower cost(in effort terms - zope is free in cash terms) options include mod-cgi which reduces the resource hogging aspect of CGI considerably, and improves the speed. > - How can Python integrate in the above environment? > Is there a need that it can fill? Python works well in Windows, you can access MFC, COM or WSH and even the raw Win32 API. .NET support is coming but probably not ready for srious use just yet. Python is a valid alternative to VBScript and VB. There are a few areas where the raw power of C# or C++ might be needed but Python can probably do 80% of what you need. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Jun 24 03:14:28 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 03:14:08 2004 Subject: [Tutor] class variables References: <40D21E3A.7000608@javacat.f2s.com> Message-ID: <005601c459ba$e36dceb0$6401a8c0@xp> > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, just > 'var' is, as in 'cans' above. > I know that each instance of 'beer' will have its own value for 'make' > but what is the use of 'cans' without using self ? Its just a local variable inside the init function. Just like any other local variable it will go out of scope and be garbage collected when init terminates. However if the variable is declared outside of a method it is a class variable (see a previous thread - last month mebbe?) and is shared across all instances: class C: shared = 42 def __init__(s,v): self.inst = v a = C(24) b = C(12) print a.shared, a.inst # -> 42,24 print b.shared,b.inst # -> 42,12 HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Jun 24 03:24:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 03:24:35 2004 Subject: [Tutor] classes & required method not working References: <40D48D3A.4030708@pusspaws.net> Message-ID: <007501c459bc$5aec8430$6401a8c0@xp> > I have a class problem. I have a script, ggScanStock.py which defines a > class ScanData : > > 'stub' class methods I have defined these methods in a seperate script, > ggpcprofit.py > > #!/usr/bin/env python > > import os,ggScanStock > > class pcprofit(ScanData): You need to specify where ScanData lives: class pcprofit(ggScanStock.ScanData): > However when I try & execute ggpcprofit.py I get : > > bash-2.05b$ ./ggpcprofit.py > Traceback (most recent call last): > File "./ggpcprofit.py", line 5, in ? > class pcprofit(ScanData): > NameError: name 'ScanData' is not defined Its looking for the name ScanData in your module but it can't find it because its in the ggScanStock module. You only imported the name ggScanStock not all of its contents. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Jun 24 03:30:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 03:30:25 2004 Subject: [Tutor] Creating subclasses (newbie) References: <20040621090635.0edff64b@debian> Message-ID: <008501c459bd$258e24a0$6401a8c0@xp> > I have a subclass I want to create - my intuition told me > that it would be done like this: > > class MainClass: > class SubClass: While Python is an intuitive language learning by guesswork is probably not an effective method! :-) Even if you stumble across something that seems to work its unlikely to be the best way. (Unless you are genetically related to Guido vannROssum maybe...) You really should try following one of the many tutorials, the official one if you have already programmed another language or one of the others if you are a complete newbie. The short answer to your question is: class Main: # main definition code here class Sub(Main): # sub extensions here > subclassinstance = Sub() > mainclassinstance = Main() > But it seems that this isn't going to work. I'm reading a > couple of Python books, but they don't seem to cover this > topic very well (I don't see any coding examples). Dunno which books you are reading but most Python tutorials should cover this topic, look under "inheritance" in the index. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Jun 24 03:36:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 03:36:15 2004 Subject: [Tutor] changing string to integer in a script References: Message-ID: <008c01c459bd$fae6b090$6401a8c0@xp> > >>> import time > >>> time.strftime('%H') > '18' > >>> type (time.strftime('%H')) > > > So it looks like I am getting a string back instead of an integer. If I > just assign it a number and run type on it again it looks OK... the clue is in the name. strftime returns a *str*ing. You might want to try using localtime() instead, that returns a tuple of values, the 4th of which is the hour: >>> hour = time.localtime()[3] > I'm sure I have not looked hard enough, but I can't see any way to > change a string to an int. int() works pretty well: >>> int('18') 18 > I *imagine* it would be something kinda like: > > time.strftime('%H').something.something() Nope, just int() :-) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Thu Jun 24 07:45:15 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 07:44:56 2004 Subject: [Tutor] Creating subclasses (newbie) References: <20040621090635.0edff64b@debian><008501c459bd$258e24a0$6401a8c0@xp> <20040624113407.3df3f3a8@debian> Message-ID: <00a001c459e0$b71639d0$6401a8c0@xp> > On to my next related question. Is the best way to build up > a relation of objects through the use of lists (or > dictionaries or tuples). Yes, usually dictionaries for the sort of thing you describe... > I'm writing an application to manage a catalogue of magazines > objects Title, Issues, Articles - there will be many titles, > which in turn will hold many issues - so is the best way of > managing this giving each Title a list, which holds each > Issue object instance? In turn, each Issue will hold a list > (mutable) which can then hold the article instances. How > does that sound as a design? I'd go with dictionaries, and why would the list of articles be mutable? Surely the articles in an Issue is fixed? But I'd be careful of creating too many classes. Think about each classes responsibilities and behaviours. In this case it may be that you only need data for some of the items. Also consider data volumes, it may be that you have enough magazines to warrant a database solution. At least think about how you will store the data to/from files. Using dictionaries leads nicely to the shelve module (Which creates a file that acts a lot like a dictionary). Just some thoughts. > ps. forgive me for posting directly to you, but the list > seems to be undergoing some problems at the moment. No probs I've CCd the reply anyway. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From gew75 at hotmail.com Thu Jun 24 08:56:36 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Thu Jun 24 08:56:46 2004 Subject: [Tutor] testing - please ignore. References: <00F99D7E-C41B-11D8-B5AB-0003934BF52E@kc.rr.com> Message-ID: Not to me they don't. I keep getting them... Please make a conclusion. ----- Original Message ----- From: To: Sent: Tuesday, June 22, 2004 5:08 PM Subject: [Tutor] testing - please ignore. > emails keep getting eaten. odd. > > tom > > Weinberg's Law: > > "If builders built buildings the way programmers wrote programs, then > the first woodpecker that came along would destroy civilization" > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From wilson at visi.com Thu Jun 24 09:49:52 2004 From: wilson at visi.com (Tim Wilson) Date: Thu Jun 24 09:50:53 2004 Subject: [Tutor] Loop Variables In-Reply-To: <40CB3DBA.4020408@yahoo.com> Message-ID: On 6/12/04 12:30 PM, "ivan low" wrote: > Hi, I had come to read a book about loop variable that have i, j, k. > I don't understand why are there 3 type? > What's the different? Looping variables are often used to keep track of how many times the loop has been executed and not for any other purpose. Using i, j, and k is a common convention. They're quick to type and remind the programmer that they're just for counting loops. -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From magnus at thinkware.se Thu Jun 24 10:07:05 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 10:07:53 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ3JlYXRpbmcgc3ViY2xhc3NlcyAobmV3YmllKQ==?= Message-ID: Adam wrote: > I have a subclass I want to create - my intuition told me > that it would be done like this: > > class MainClass: > class SubClass: > code... > subclassinstance = SubClass() > mainclassinstance = MainClass() I'm afraid your intuition misled you completely. ;) To be completely honest, it doesn't seem that you quite understand what subclasses are for and how they are used if you think they would be made inside the base class. I guess the word subclass is really misleading. Maybe it's not really what you actually need. Feel free do discuss your design with us. A subclass is a specialization of a base class. For instance an employee is a kind of person, and a manager is a kind of employee. The more abstract and generic code, i.e. the base class code, should only deal with the abstract and generic issues, and should know nothing about the more concrete and specialized uses of itself. In other words, the base class shouldn't know which subclasses it has. It's common that base classes are part of standard libraries and third party libraries, and that applications programmers subclass these classes in their own modules. This is an example of subclassing, where Employee is a sbclass of Person, and Manager is a subclass of Employee. Note that Person inherits from the standard base class 'object'. class Person(object): def __init__(self, name): self.name = name def __str__(self): return "A Person called %s" % self.name class Employee(Person): dept = 'Unknown' def set_dept(self, dept): self.dept = dept def __str__(self): return "An Employee called %s working at %s department" % ( self.name, self.dept) class Manager(Employee): def __init__(self, *args): self.subjects = [] super(Employee, self).__init__(*args) def add_emp(self, emp): self.subjects.append(emp) def remove_emp(self, emp): self.subjects.remove(emp) def __str__(self): emps = [str(emp) for emp in self.subjects] return "%s at %s department is manager for %s" % ( self.name, self.dept, ",".join(emps)) >>> p = Person('Peter') >>> print p A Person called Peter >>> e1 = Employee('Eric') >>> e1.set_dept('Sales') >>> e2 = Employee('Ed') >>> print e1 An Employee called Eric working at Sales department >>> print e2 An Employee called Ed working at Unknown department >>> e2.set_dept('Construction') >>> print e2 An Employee called Ed working at Construction department >>> m = Manager('Mike') >>> m.set_dept('Sales') >>> e3 = Employee('Emma') >>> e3.set_dept('Sales') >>> for e in (e1,e2,e3): if e.dept == m.dept: m.add_emp(e) >>> print m Mike at Sales department is manager for An Employee called Eric working at Sales department,An Employee called Emma working at Sales department -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From pythonTutor at venix.com Thu Jun 24 10:51:10 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Jun 24 10:51:23 2004 Subject: [Tutor] Record Locking & Access - newbye In-Reply-To: <003001c456f8$17ba9b00$6601a8c0@clixdialupadapt> References: <003001c456f8$17ba9b00$6601a8c0@clixdialupadapt> Message-ID: <1088088669.3929.23.camel@laptop.venix.com> You can often handle this with a timestamp on the record. The database should support a timestamp type that will NOT BE DUPLICATED on single record updates within a table. The basic update algorithm is: lock record (or table or block depending on DBMS) read record if record timestamp == user timestamp do update refresh user copy unlock else unlock notify user that record was modified by someone else if the timestamp changed, be careful about automatically refreshing the user's copy of the record and discarding the user's changes to the original record. We've been successful using this approach with MySQL. On Sun, 2004-06-20 at 14:55, Miguel Lopes wrote: > Hi, > > Here's my problem. > Using python dbapi I get groups of records back from a database into a list > for example to feed a "List Form" which is just a grid on a form (the db is > about 9000 thousand records - so I suppose there's not a big problem to > fetch all records in a go!). > > Now when a user selects a record from a grid on screen I can send him to > another form "Record Form" where he can edit the record. This way I can have > only one query to the database and have the users working locally on there > record sets. But when a user edits an existing record I puzzled to think > that another user might be changing that record at the same time (because > they are not locking any records and are using lists with the record > contents locally)! This could cause for example that user A changes record 1 > from "bar" to "foo" and updates the db, just after user A user B updates the > db with a change in the same record from "bar" to "foobar" (never seeing > user As changes)!!! > > I guess this is a very common problem with a standard solution. How can I > avoid this? > > Best regards, > Mekl > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From magnus at thinkware.se Thu Jun 24 11:15:16 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 11:15:27 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gTG9vcCBWYXJpYWJsZXM=?= Message-ID: > Hi, I had come to read a book about loop variable that have i, j, k. > I don't understand why are there 3 type? In general, variable names should use descriptive names, so calling any variable i, j or k is probably a poor decision. It doesn't tell us anything about the purpose of the code. One might say that i, j, etc are well established as loop variable names, but typically, the loop variables in loops represent something meaningful which we have a name for. Depending on context, better loop varable names might be 'row', 'player', 'transaction' or whatever we are dealing with in the program. There is a conflict for those who write educational code examples. On one hand, you don't want to distract the reader with a lot of irrelevant context (such as long variable names with a meaning which is irrelevant for the detail you want to explain). On the other hand, by constantly using really bad variable names like i,j,k and a,b,c, you teach your readers a bad programming habit. The typical reasons for using several loop variables such as i, j, k is that you nest loops. You have several loops inside each other, and you need to keep track of your position in these loops independently of each other. For instance, imagine that you want to display a multiplication table: def mult(max_x, max_y): print ' *', for x in range(1, max_x + 1): print "%5i" % x, print for y in range(1, max_y + 1): print "%5i" % y, for x in range(1, max_x + 1): print "%5i" % (x * y), print >>> mult(8,10) * 1 2 3 4 5 6 7 8 1 1 2 3 4 5 6 7 8 2 2 4 6 8 10 12 14 16 3 3 6 9 12 15 18 21 24 4 4 8 12 16 20 24 28 32 5 5 10 15 20 25 30 35 40 6 6 12 18 24 30 36 42 48 7 7 14 21 28 35 42 49 56 8 8 16 24 32 40 48 56 64 9 9 18 27 36 45 54 63 72 10 10 20 30 40 50 60 70 80 I guess you understand that you need to use two different variables for x and y here. I do use x two times in different loop as you see. For me, x is the x-axis (i.e. horizontal) values, and y is the y-axis (vertical) values. I guess I could have called y 'row', and x 'col' instead, but x and y are well established terms in this context. You should also note that code blocks don't imply scopes in Python as they do in i.e. C++. So, even if you don't need to access a loop varible in any inner loop, using the same loop variable in nested loops will mess things up. See below: >>> for i in range(2): for j in range(2): for k in range(2): print ' Inner', k print ' Middle', j print 'Outer', i Inner 0 Inner 1 Middle 0 Inner 0 Inner 1 Middle 1 Outer 0 Inner 0 Inner 1 Middle 0 Inner 0 Inner 1 Middle 1 Outer 1 >>> for i in range(2): for i in range(2): for i in range(2): print ' Inner', i print ' Middle', i print 'Outer', i Inner 0 Inner 1 Middle 1 <= BUG! Inner 0 Inner 1 Middle 1 Outer 1 <= BUG! Inner 0 Inner 1 Middle 1 <= BUG! Inner 0 Inner 1 Middle 1 Outer 1 You will still get the right number of iterations, since the range functions will produce the right number of elements anyway. A C style for loop such as "for (i=0; i<2; i++)" would end prematurely if the same loop variable was used. Python is more robust, but things can still go wrong... :) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From derekp at sentechsa.co.za Fri Jun 25 11:19:47 2004 From: derekp at sentechsa.co.za (Derek Pienaar) Date: Thu Jun 24 11:19:20 2004 Subject: [Tutor] a byte of python... error with while statement? Message-ID: <200406251719.47498.derekp@sentechsa.co.za> Halo Guys. Is there an error in the documentation or code example for the "while" statement? Look at the code for the example, and then read the second paragraph under the "How it works" section... It mentions that the variable stop is set to true BEFORE the while loop... From what I can see its not. Ive mailed the author without but he's not responding. The page for the abovementioned can be found here: http://www.python.g2swaroop.net/byte/ch06s03.html If this is not wrong, then I dont understand the "while not stop:" statement right. Please explain this if so. Thanks. Derek From missive at hotmail.com Thu Jun 24 12:10:32 2004 From: missive at hotmail.com (Lee Harr) Date: Thu Jun 24 12:42:59 2004 Subject: [Tutor] Re: Record Locking and Access - newbye Message-ID: >Using python dbapi I get groups of records back from a database into a list >for example to feed a "List Form" which is just a grid on a form (the db is >about 9000 thousand records - so I suppose there's not a big problem to >fetch all records in a go!). > >Now when a user selects a record from a grid on screen I can send him to >another form "Record Form" where he can edit the record. This way I can >have >only one query to the database and have the users working locally on there >record sets. But when a user edits an existing record I puzzled to think >that another user might be changing that record at the same time (because >they are not locking any records and are using lists with the record >contents locally)! This could cause for example that user A changes record >1 >from "bar" to "foo" and updates the db, just after user A user B updates >the >db with a change in the same record from "bar" to "foobar" (never seeing >user As changes)!!! > >I guess this is a very common problem with a standard solution. How can I >avoid this? You say "...and Access" but it is not clear to me. Are you using a MicroSoft Access database (ie Jet)? In PostgreSQL, I think the standard solution to this would be to SELECT ... FOR UPDATE which would lock the record against other UPDATE, DELETE, or SELECT ... FOR UPDATE transactions. http://developer.postgresql.org/docs/postgres/sql-select.html#SQL-FOR-UPDATE Googling around, it is not clear to me whether MS Access has that capability. If not, you might have to do the locking in your application. Actually, either way, your app will probably need to know something about the fact that records might need to be locked so that it can let the user know what is happening. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From missive at hotmail.com Thu Jun 24 12:27:35 2004 From: missive at hotmail.com (Lee Harr) Date: Thu Jun 24 12:46:19 2004 Subject: [Tutor] Re: Loop Variables Message-ID: >Hi, I had come to read a book about loop variable that have i, j, k. >I don't understand why are there 3 type? >What's the different? > It would help to see some of the code that uses the variable, so that we can see exactly why they have chosen to use those names. As far as I can tell from what you have written, there are not really 3 different types, just 3 different variables. They are just 3 different storage areas for data that you want to keep track of. Let's say you want to count up to 10 twice. >>>for count_twice in range(2): ... for up_to_10 in range(1, 11): ... print 'this is count', count_twice, 'at number', up_to_10 ... this is count 0 at number 1 this is count 0 at number 2 this is count 0 at number 3 this is count 0 at number 4 this is count 0 at number 5 this is count 0 at number 6 this is count 0 at number 7 this is count 0 at number 8 this is count 0 at number 9 this is count 0 at number 10 this is count 1 at number 1 this is count 1 at number 2 this is count 1 at number 3 this is count 1 at number 4 this is count 1 at number 5 this is count 1 at number 6 this is count 1 at number 7 this is count 1 at number 8 this is count 1 at number 9 this is count 1 at number 10 But we could have written it like this ... >>>for i in range(2): ... for j in range(1, 11): ... print 'this is count', i, 'at number', j ... this is count 0 at number 1 this is count 0 at number 2 this is count 0 at number 3 this is count 0 at number 4 this is count 0 at number 5 this is count 0 at number 6 this is count 0 at number 7 this is count 0 at number 8 this is count 0 at number 9 this is count 0 at number 10 this is count 1 at number 1 this is count 1 at number 2 this is count 1 at number 3 this is count 1 at number 4 this is count 1 at number 5 this is count 1 at number 6 this is count 1 at number 7 this is count 1 at number 8 this is count 1 at number 9 this is count 1 at number 10 Same result. But we definitely need 2 different variables. If we tried to use the same variable twice, it would not work ... >>>for i in range(2): ... for i in range(1, 11): ... # not really sure what to put here ... ... print 'this is count', i, 'at number', i ... this is count 1 at number 1 this is count 2 at number 2 this is count 3 at number 3 this is count 4 at number 4 this is count 5 at number 5 this is count 6 at number 6 this is count 7 at number 7 this is count 8 at number 8 this is count 9 at number 9 this is count 10 at number 10 this is count 1 at number 1 this is count 2 at number 2 this is count 3 at number 3 this is count 4 at number 4 this is count 5 at number 5 this is count 6 at number 6 this is count 7 at number 7 this is count 8 at number 8 this is count 9 at number 9 this is count 10 at number 10 Which (surprisingly enough to me) works better than expected. Of course the output is nonsense. I guess what happens is that the second "for loop" is creating a new "namespace". So the second use of x is actually a different variable than the first use of x. If that seems confusing, I guess I would just say "don't do that" :o) It is almost always better to try to come up with some meaningful name for your variables (rather than just use i, j, k) Of course for every rule ... If it is just a counter, and the value will only be used in one small section of code, then i, j or k might be perfectly reasonable variable names. _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From robinst at MIT.EDU Thu Jun 24 12:30:11 2004 From: robinst at MIT.EDU (Theresa Robinson) Date: Thu Jun 24 12:50:14 2004 Subject: [Tutor] What Eval() Hath Men Wrought In-Reply-To: <00e001c45a06$b4bc7610$6401a8c0@xp> References: <5.2.1.1.0.20040618121728.02716390@www.thinkware.se> <00e001c45a06$b4bc7610$6401a8c0@xp> Message-ID: > There is no right way, mostly I would pass a function reference > as my preferred route and apply() as a close second if, for > example the functions took different numbers of arguments. Thank you very much for your help. I did a little more research and it looks like somebody has already started on an optimization package, although it doesn't have everything we'll need. (http://pylab.sourceforge.net/packages/optimize.py) I think it would be a good idea for me to use the same techniques, and hopefully even the same argument list etc. for any algorithms I add to it. And it has: def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None, fulloutput=0, printmessg=1) fxr = apply(func,(xr,)+args) so I think I'll just copy that. Next I should look up apply(). Thanks, Theresa From magnus at thinkware.se Thu Jun 24 12:34:33 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 13:05:51 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gV2hhdCBFdmFsKCkgSGF0aCBNZW4gV3JvdWdodA==?= Message-ID: Theresa Robinson wrote: > The C way to do it is to pass in a pointer to a function. This is good > because C nicely checks that the function 1) is actually a function 2) > takes the right arguments 3) returns the right type. The Matlab way to do > it is to pass a string that contains the function name, and to use the > Matlab feval function, which is similar to the Python eval but nicer since > you don't have to construct the whole string yourself, but instead can use > the form feval('function_name',argument). This works but is bad because It's even simpler than that in Python with the old "apply" function, but you don't need that either... That's obsolete. > you get weird errors if the function name is wrong, or if the function > takes an unexpected kind of argument or returns an unexpected type. Python obviously doesn't have static typing, but in all it's much better than C for things like that. There are things that might not be discovered until runtime, but you can write much, much more generic and simple code for the kind of things you describe. > What is the right way to do this in Python? Where can I learn how to do > it? The C way, but skip the pointer thingie. Just do it. It's trivial. I will even refuce to show any example. Just imagine that it is as simple as it could possibly be. If you don't get it to work, it's probably because you don't believe it can be that simple, and you try to convolute your code. ;) Almost everything is an object in Python, and objects are dealt with in a very uniform way. Look at the chapter about functions in the Python Tutorial, and be amazed about how easy it is to write generic code that will pass any number of positional or named arguments to a function. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Thu Jun 24 12:12:29 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 13:19:09 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUmVjb3JkIExvY2tpbmcgYW5kIEFjY2VzcyAtIG5ld2J5ZQ==?= Message-ID: mjekl wrote: > Here's my problem. > Using python dbapi I get groups of records back from a database into a list > for example to feed a "List Form" which is just a grid on a form (the db is > about 9000 thousand records - so I suppose there's not a big problem to > fetch all records in a go!). If you meant 9 000, it's no problem, if you meant 9 000 000, it might be a bit slow... > Now when a user selects a record from a grid on screen I can send him to > another form "Record Form" where he can edit the record. This way I can have > only one query to the database and have the users working locally on there > record sets. But when a user edits an existing record I puzzled to think > that another user might be changing that record at the same time (because > they are not locking any records and are using lists with the record > contents locally)! This could cause for example that user A changes record 1 > from "bar" to "foo" and updates the db, just after user A user B updates the > db with a change in the same record from "bar" to "foobar" (never seeing > user As changes)!!! > > I guess this is a very common problem with a standard solution. How can I > avoid this? Certainly. It's also a pure SQL/database problem which has little to do with Python... As far as I know, there is nothing particular in the DB API that will help you with this. The solution depends on several things. Which RDBMS are you using? One solution which works regardless of what database you use is to have a timestamp column in your table, and only update the row if the timestamp is the same as when you selected the row. Always set timestamp to CURRENT TIMESTAMP (or whatever it's called in your database) whenever you update the table. Simply include the timestamp column in the WHERE clause of the UPDATE. If someone else touched the row since you fetched it, your update won't change any rows. In other words, cursor.rowcount will be 0, not 1 as expected. For this timestamp solution to work, you need to be sure that the timestamp isn't messed up. If you use adodbapi on Windows NT, Windows will truncate the microseconds from your timestamp, which will cause this to fail unless you do some special trick. One solution to that is to cast the timestamp column to CHAR, e.g. "SELECT FOO, BAR, BAZ, CAST(TSTAMP AS CHAR(26)) FROM MYTABLE". The other solutions involve the use of SQL commands such as SET TRANSACTION ISOLATION LEVEL or LOCK TABLE, but you'd better check the docs for your own database to sort that out. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From lbblair at adaptisinc.com Thu Jun 24 13:11:10 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Thu Jun 24 13:27:08 2004 Subject: [Tutor] regular expressions Message-ID: I am trying to use regular expressions to delete a wildcard set of tables. My pattern is 'TEMP*' The code below is how I am implementing the delete. My problem is that it also deletes a file 'SYSTEM' also. I can see where the TEM parts match. First is why does it ignore the P from the patterns? Second I understand that search scans through the string looking for a match. What I am wanting to do is use the \A switch , I think, that will match only the start of the string. I have tried puting the switch in various places and don't seem to quit understand where it should go. I need an example :) Thanks for any help Larry pattern = re.compile(del_pattern) try: for each in os.listdir(file_location): if pattern.search(each): name = os.path.join(file_location, each) os.remove(name) except: type,value,tb = sys.exc_info() msgs.sendInfo(str(traceback.format_exception(type,value,tb) )) __________________________________ Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s) and may contain information that is confidential privileged and/or exempt from disclosure under applicable law. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. From dyoo at hkn.eecs.berkeley.edu Thu Jun 24 13:20:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 24 13:33:18 2004 Subject: [Tutor] Mailing list [mail system is sick; give it time] In-Reply-To: <048A40781D05D143842A596D7C78F40F01025ED4@SPI-MAIL2003.SPITECH.COM> Message-ID: On Wed, 23 Jun 2004, Ezequiel, Justin wrote: > Is it just me or are there no new messages in the mailing list? > The last message I got was on Mon 6/21/2004 3:50 PM (GMT+8:00). Hi Justin, The mail server that hosts us is being overwhelmed. Someone's trying to fix this now: there's an upgrade in progress that should help to fix the load problem There's a small notice at the top of: http://python.org/ which should tell us when the mail system is back to normal. My apologies; I can't do anything on my end to help speed things up. *grin* From dyoo at hkn.eecs.berkeley.edu Thu Jun 24 13:38:32 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 24 13:39:07 2004 Subject: [Tutor] What Eval() Hath Men Wrought In-Reply-To: Message-ID: On Tue, 22 Jun 2004, Theresa Robinson wrote: > For example, we'll want to write a function to minimize the return value > of another function by varying the latter function's vector argument. > > The C way to do it is to pass in a pointer to a function. This is good > because C nicely checks that the function 1) is actually a function 2) > takes the right arguments 3) returns the right type. Hi Theresa, It's perfectly possible to do something similar here in Python, since functions can take functions as arguments very easily. For example: ### >>> def find_fixed_point(some_function, initial_guess, tolerance): ... """Tries to find the fixed point of a function within a certain ... tolerance.""" ... x = initial_guess ... while True: ... new_x = some_function(x) ... if abs(new_x - x) < tolerance: ... return new_x ... x = new_x ... >>> import math >>> find_fixed_point(math.cos, 1.0, 0.0000001) 0.73908516994455442 ### > The Matlab way to do it is to pass a string that contains the function > name, and to use the Matlab feval function, which is similar to the > Python eval but nicer since you don't have to construct the whole string > yourself, but instead can use the form feval('function_name',argument). > This works but is bad because you get weird errors if the function name > is wrong, or if the function takes an unexpected kind of argument or > returns an unexpected type. Right. Don't use eval() for this purpose in Python. *grin* Just pass the function value around as an argument, and you should be fine. Python's approach, in allowing us to pass around and construct functions, is similar to that of Scheme. You may find the "Structure and Interpretation of Computer Programs": http://mitpress.mit.edu/sicp/full-text/book/book.html very useful in learning this technique of treating functions as passable values. Even though the book uses a different programming language, most of the concepts map very closely to Python. We can take an example from: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_sec_1.3.1 like this one: ;;;;;; Scheme (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) ;;;;;; This Scheme SUM function calculates the sum of a bunch of terms. It takes in two functions: a TERM and a NEXT. A Python adaptation might look something like this: ### def sum(term, a, next, b): result = 0 while a <= b: result += term(a) a = next(a) return result ### Here's how it might work: ### >>> def square(x): return x * x ... >>> def inc(x): return x + 1 ... >>> sum(square, 1, inc, 5) ## [This calculates 1 + 4 + 9 + 16 + 25] 55 ### I hope this gives a taste of what we can do with function passing. If you have more questions, please feel free to ask on the Tutor list. Good luck! From alan.gauld at blueyonder.co.uk Thu Jun 24 12:17:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 13:57:35 2004 Subject: [Tutor] What Eval() Hath Men Wrought References: <5.2.1.1.0.20040618121728.02716390@www.thinkware.se> Message-ID: <00e001c45a06$b4bc7610$6401a8c0@xp> > The C way to do it is to pass in a pointer to a function. And you can pass a function object in Python too but... > This is good because C nicely checks that the function > 1) is actually a function > 2) takes the right arguments > 3) returns the right type. Python does none of these, although you can explicitly check the object is callable in the receiving code. > The Matlab way to do it is to pass a string that contains > the function name, and to use the Matlab feval function, > .... but instead can use the form feval('function_name',argument). You can use the Python apply() function to do a similar thing, it takes a callable object and a tuple of arguments to be passed to the callable. > you get weird errors if the function name is wrong, or if > the function takes an unexpected kind of argument or returns > an unexpected type. Yes, thats always a problem with this type of eval() behaviour. > What is the right way to do this in Python? There is no right way, mostly I would pass a function reference as my preferred route and apply() as a close second if, for example the functions took different numbers of arguments. Note that you can get the callable function object from its name by using the local namespace dictionary. Alan G. From nick at javacat.f2s.com Thu Jun 24 15:40:00 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Jun 24 15:39:55 2004 Subject: [Tutor] class variables In-Reply-To: <20040623214626.59594.qmail@web50309.mail.yahoo.com> Message-ID: Aha, the penny has dropped :) Now I see how it can be useful I can understand it much better. In the example you've given Jeremy I see that here: >>>class beer: >>> beers = 0 >>> def __init__(self): >>> self.make = 'murphys' >>> beer.beers += 1 beer.beers can be used as a static variable. Superb. I get it know :) Thanks very much everyone for your help. Nick. -----Original Message----- From: tutor-bounces+nick=javacat.f2s.com@python.org [mailto:tutor-bounces+nick=javacat.f2s.com@python.org]On Behalf Of Adelein and Jeremy Sent: 23 June 2004 22:46 To: tutor@python.org Subject: Re: [Tutor] class variables --- Nick Lunt wrote: > Hi folks, > > Im making my way through the book 'Learning Python 2nd Edition'. I > understand classes but I have a question. > Take the following for example - > > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, > just > 'var' is, as in 'cans' above. > I know that each instance of 'beer' will have its own value for > 'make' > but what is the use of 'cans' without using self ? In this example, there is no use. Once __init__ has been called and executed, the variable cans will be taking up memory space with no way for you to access it (well, normally, anyway). Given that x = Beer(), neither x.cans nor Beer.cans is going to turn up anything but an AttributeError exception. On what page are you? Perhaps you are referring to something such as the following: class Beer: beers = 0 def __init__(self, make=''): self.make = make Beer.beers += 1 x = Beer('michelob') y = Beer('murphys') z = Beer('busch') After this, the variable beers is 3, and x.beers, y.beers, z.beers, and Beer.beers will all be 3. This, of course, is very useful. HTH - Jeremy __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Thu Jun 24 16:03:51 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 16:04:01 2004 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIGNsYXNzIHZhcmlhYmxlcw==?= Message-ID: Nick Lunt wrote: > As it stands now I cant see any use for a local variable inside the __init__ > method, ie a variable without the self prefix. You use local variables for temporary storage of data that you only need during the run of the function. Whether it's __init__, another method in a class or a plain function doesn't matter. Look here: >>> def avg(values): n = len(values) sum = 0.0 for value in values: sum += value return sum / n >>> print avg([1,2,3,4,5]) 3.0 The function avg contains two local variables, n and sum. These are lost as soon as avg exits. Are they useless? Nope, they serve a purpose, and when they are done doing that, we discard them. > But also, I can see no reason to use a class variable outside of a class > method with no self prefix. The point with a class variable is that it can be used to share information between all the instances of a class. A class attribute exists in the scope of the class. There is just one copy of this variable, regardless of how many instances of the class you create. Let's imagine that you have a class in a GUI system which described some kind of widget, maybe some kind of button. If you have a variable which determines the color of the button, and you have decided that all buttons on the screen must always be the same color, then this variable belongs in the scope of the class. If you want different buttons to be able to have different colors, you want this variable in the scope of the instance object, i.e. under "self". > I admit Im quite confused by this still. Many python programs Ive studied > mix up class variable with and without the 'instance/self' prefix. I hope the examples above help you understand what these different scopes are used for. Where a variable is defined should help you understand what it's used for, and when it contains anything of interest. > Im also confused about whether I should put my class variable inside a > method and use the self prefix, leave them outside of a method with no > prefix, or leave them outside of a method but give them a prefix. I'm wondering if you should use any classes at all... > With the simple programs I write at the moment, it wouldnt really make much > difference how I did it in most cases, but I would like to know when I > should or shouldn't be using self. And when I should be putting class > variables outside a class method (if ever). I hope you already grokked the purpose of local variables from the example above. I'll make a silly example using both instance and class variables here! :) >>> class Animal: def __init__(self, weight): assert hasattr(self.__class__, 'legs'), 'Concrete animals need legs' self.weight = weight def weight_per_leg(self): return self.weight/self.legs >>> class Insect(Animal): legs = 6 >>> class Spider(Animal): legs = 8 >>> i = Insect(0.001) >>> print i.weight_per_leg() 0.000166666666667 >>> s = Spider(0.004) >>> print s.weight_per_leg() 0.0005 You see? All spiders have eight legs (unless you pull some off). Each spider has an individual weight. Number of legs is an attribute of the class spider, and weight is an attribute of the individual spider instance. > I apologise for not grasping it very quickly. My previous experiences with > classes comes from java, and that was a while ago, and java classes seem a > lot stricter than python classes. Ok. Are you sure that you really want to use classes for the code you are writing? Java has this stupid attitude that everything should be shoehorned into a class whether it fits there or not, as if designs would become better if they are in a class. It's a bit like believing that cars run faster if we paint them red, just because Ferraris are red. In Python there is no reason to use a class unless you want to use some of the benefits that classes give. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From jeff at ccvcorp.com Thu Jun 24 16:26:37 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Jun 24 16:27:25 2004 Subject: {Spam?} [Tutor] IDLE vs. Python Command Line In-Reply-To: <6.1.0.6.0.20040623172302.03e27008@mail.mric.net> References: <42.50c836ac.2e03a7be@aol.com> <6.1.0.6.0.20040623172302.03e27008@mail.mric.net> Message-ID: <40DB38FD.3090604@ccvcorp.com> Bob Gailer wrote: > At 08:04 PM 6/17/2004, Dragonfirebane@aol.com wrote: > >> when i type: >> ## >> >>>import string >> >>>string.letters >> ## >> >> in IDLE, i get: >> ## >> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\x9a\x9c\x9e\x9f\xaa\xb5\xba\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' >> ## >> >> but when i do it on the Python Command Line, i get: >> ## >> 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >> ## > > I can confirm that behavior, but not explain it. My hunch is that this is Unicode (or at least Locale) related. The "extra" characters reported under IDLE are all letters that are not part of the standard American English character set, and are thus not in ASCII. I'm presuming that the command line is reporting the ASCII letters, and that IDLE is reporting a non-ASCII superset. Whether this is an alternate codepage or a Unicode character set would presumably depend upon the O.P.'s settings. (I don't have any grasp on why IDLE would behave differently than the command line, though; it's probably due to some sort of setting in IDLE, but I wouldn't know where to look.) Jeff Shannon Technician/Programmer Credit International From orbitz at ezabel.com Thu Jun 24 16:34:31 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Thu Jun 24 16:35:38 2004 Subject: [Tutor] errr... In-Reply-To: References: Message-ID: <20040624163431.084ff27f.orbitz@ezabel.com> What is up with all these test messages, do people have no patience? On Wed, 23 Jun 2004 16:19:18 -0500 python@kc.rr.com wrote: > My messages never seem to make it to the list. final test before I sadly have > to unsubscribe. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Thu Jun 24 16:35:39 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 16:35:50 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSURMRSB2cy4gUHl0aG9uIENvbW1hbmQgTGluZQ==?= Message-ID: Orri wrote: > when i type: > >>>import string > >>>string.letters > in IDLE, i get: > 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\x9a\x9c\ > x9e\x9f\xaa\xb5\xba\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xc > e\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\ > xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf > 6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' > but when i do it on the Python Command Line, i get: > 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' > > is this a flaw in IDLE or the Command Line? Maybe... I agree that it's a bit confusing. I'm not sure why they default to different locales. > Which is more accurate? Both are accurate, but in different contexts. :) > Since one of my programs uses string.letters, it is important for me to know. As I'm sure you know, the set of letters is different in different contexts. If you ask someone in Japan, they are likely to say that both sequences fail to describe the letters. If you run this... >>> import locale >>> locale.getlocale() I assume you will get different results in IDLE and at the command line. At least I do in Windows. I also get strings that are constent with the locale settings. (Well, fairly at least, my GUI locale says 'Swedish_Sweden', '1252' and I get all the letters in codepage 1252 as letters, but that's much more than the Swedish letters of course...but that's how it is...) I'm not sure why IDLE is set up to give a different default that the CLI version, but remember the Python mottos: Explicit is better than implicit. In the face of ambiguity, refuse the temptation to guess. If you depend on string.letters to return only US ASCII letters, run this: import locale locale.setlocale(locale.LC_CTYPE, "C") Another option is to use string.ascii_letters instead, which is always the same. If you want the locale setting defined by the OS, use this: import locale locale.setlocale(locale.LC_CTYPE, "") If you always set locale in your program, you won't depend on any unclear defaults. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Thu Jun 24 16:40:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jun 24 16:40:24 2004 Subject: [Tutor] class variables In-Reply-To: Message-ID: On Wed, 23 Jun 2004, Nick Lunt wrote: > Magnus and Danny, thankyou very much for your explanations. > > >From what you've both told me, it would seem that putting a local variable > in the __init__ method of a class is quite pointless, ie > > example 1 > >>>class beer: > >>> def __init__(self): > >>> cans = 4 > >>> self.make = 'murphys' Hi Nick, It's not exactly pointless to use local variables. In the example above, it's pointless, though. *grin* But here's a more concrete example where having a local variable might help readability: ### class NameMaker: """A class to make poor variable names.""" def __init__(self, prefix): self.prefix = prefix self.counter = 0 def makeName(self): nextName = "%s%s" % (self.prefix, self.counter) self.counter = self.counter + 1 return nextName ### Here's how it works: ### >>> namer = NameMaker("x") >>> namer.makeName() 'x0' >>> namer.makeName() 'x1' >>> namer.makeName() 'x2' ### The use of 'nextName' as a local variable is fine here, just as long as we understand that it's not part of the state of the instance. > I admit Im quite confused by this still. Many python programs Ive > studied mix up class variable with and without the 'instance/self' > prefix. In Java, the scope of a variable is very implicit. The example we cooked up above could be written in several ways: /*** Java ***/ class NameMaker { private String prefix; private int counter; public NameMaker(String prefix) { this.prefix = prefix; } public String makeName() { String nextName = this.prefix + this.counter; this.counter = this.counter + 1; return nextName; } } /******/ In this Java example, all the variables are explicitely scoped. But we could just as easily have written this: /*** Java ***/ class NameMaker { private String prefix; private int counter; public NameMaker(String p) { prefix = p; } public String makeName() { String nextName = prefix + counter; counter = counter + 1; return nextName; } } /******/ Python enforces an explicit coding style that makes it clear what's an instance attribute and what's a local variable. If we see the following Python snippet: self.counter = self.counter + 1 return nextName in isolation, it's pretty clear what things are accessing the object state. But if we try the same experiement in Java: counter = counter + 1; return nextName; then it's not as immediately clear what the scope of each variable is, without looking at the immediate context. In Java, we're often required to look at the context of the snippet to figure out what things are local variables, and what things are instance attributes. In Python, we're forced to encode that knowledge more explicitely. It means that we type a little bit more, but we gain a lot in code clarity. [Digression: And it means that certain stupid scoping bugs just aren't possible in Python. For example, we can easily mess up the Java constructor: public NameMaker(String prefix) { prefix = prefix; } This compiles, but of course it's doing the wrong thing. In contrast, there's less of a danger of making this kind of error in Python, since all object state change has that 'self' attribute. Consistancy in variable name access is a good thing.] > Im also confused about whether I should put my class variable inside a > method and use the self prefix, leave them outside of a method with no > prefix, or leave them outside of a method but give them a prefix. Ah! What you've found is the equivalent of class attributes, or in Java terminology, "static" variables. When we say something like: ### >>> class NameMaker2: ... counter = 0 ... def __init__(self, prefix): ... self.prefix = prefix ... def makeName(self): ... nextName = "%s%s" % (self.prefix, NameMaker2.counter) ... NameMaker2.counter += 1 ... return nextName ... >>> xmaker = NameMaker2('x') >>> ymaker = NameMaker2('y') >>> xmaker.makeName() 'x0' >>> xmaker.makeName() 'x1' >>> xmaker.makeName() 'x2' >>> ymaker.makeName() 'y3' ### then we are defining an attribute that is bound to the class alone, and not to individual instances of the class. We can see in NameMaker2 that the 'counter' is being shared by both the 'xmaker' and 'ymaker' instances. Does this make sense so far? Please feel free to continue asking questions about this. Hope this helps! From magnus at thinkware.se Thu Jun 24 16:47:21 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 16:47:31 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSXMgUHl0aG9uIGEgdmFsaWQgYnVzaW5lc3MgdG9vbD8=?= Message-ID: Chad Crabtree wrote: > Check out .... the vaults of parasues Parnassus, see http://www.vex.net/parnassus/ The Python was a monstrous serpent who guarded the oracle of Delphi on mount Parnassus. It was unfortunately killed by the god Apollo with a single arrow. :( -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From gubbs at fudo.org Thu Jun 24 18:13:23 2004 From: gubbs at fudo.org (Conrad Gavin) Date: Thu Jun 24 17:01:18 2004 Subject: [Tutor] errr... In-Reply-To: References: Message-ID: <1088115203.14854.0.camel@drachenfels> Don't fret everyone has had this problem. On Wed, 2004-06-23 at 21:19, python@kc.rr.com wrote: > My messages never seem to make it to the list. final test before I sadly have to unsubscribe. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20040624/f09077fc/attachment.bin From alan.gauld at blueyonder.co.uk Thu Jun 24 17:04:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jun 24 17:04:10 2004 Subject: [Tutor] class variables References: Message-ID: <011c01c45a2e$db81f860$6401a8c0@xp> > >From what you've both told me, it would seem that putting a local variable > in the __init__ method of a class is quite pointless, No you often need to do that where the init does more than simple initialisation. Here is an example where init reads values from a file: class C: def __init__(self,val) self.val = val temp = file("MySecretSettings.dat") self.setting1 = temp.readline().strip() self.setting2 = int(temp.readline().strip()) temp.close def someMethod(self):.... So temp is used as a local variable within init to hold the file object, but once read the file is never needed again so it is not stored as a class or instance variable. Local variables inside methods are just as useful as local variables in any other function, but they have nothing to do with classes or objects as such. > But also, I can see no reason to use a class variable outside of a class > method with no self prefix. It's for shared information. Instead of every instance of the class having its own copy of the data they simply refer to the Class object which stores it once. It also means that changes in that class value can affect all instances of the class in one go: class C: v = 2 def __init__(self,msg): self.msg = msg def printit(self): for n in range(C.v): # uses class value print self.msg a = C("Hello from A") b = C("Hello from B") for obj in [a,b]: obj.printit() # both objects print 2 messages C.v = 3 # Change behaviour of all instances here for obj in [a,b]: obj.printit() # both objects print 3 now So we can control the behaviour of all our instances at one stroke by changing the Class variable value. This can be a very powerful technique, especially if writing simulation software - eg network traffic predictions - where you can change the network parameters easily and do "What If" type scenarios etc. (Imagine a mesh of network objects and you can change the modelled protocol from IP4 to IP6 or X25 or ATM etc by changing one single value...) Of course you could just use a regular global variable but that's going against the principles of good OO design and also is making the value visible to a wider namespace. It's also less obvious that the value is related to the class and finally means the user has to import the module with the global defined. A Class variable gets inherited so the user only needs to import the module where the definition of the subclass exists and can access the class variable from the superclass via the subclass: class Super: v = 42 pass class Sub(Super): pass x = Super() y = Sub() print Super.v, Sub.v print x.v, y.v And of course the definition of Sub could be in a different module to Super... > I admit Im quite confused by this still. Many python programs Ive studied > mix up class variable with and without the 'instance/self' prefix. There shouldn't be many programs doing that, despite what I just said class variables are relatively uncommon in most programs. I doubt if I use them in more than about 10% of my programs - at most! > Im also confused about whether I should put my class variable inside a > method and use the self prefix, leave them outside of a method with no > prefix, or leave them outside of a method but give them a prefix. Either outside a method with no prefix - a class variable, or Inside a method with a self prefix - an instance variable. The former will be a shared value across all instances (and even when no instances exist!) the latter will have a distinct value for each instance. You should never need to use a variable outside a method with a self prefix. Note you can access the class variables either through the class name (as I did in my example, coz I think the intent is clearer) or using self. Python will look for it locally and if not finding it will look in the class. > With the simple programs I write at the moment, it wouldnt really make much > difference how I did it in most cases, but I would like to know when I > should or shouldn't be using self. And when I should be putting class > variables outside a class method (if ever). Mostly put them inside init with self. Only if you want to share the same value over all instances should you put it outside. > I apologise for not grasping it very quickly. My previous experiences with > classes comes from java, and that was a while ago, and java classes seem a > lot stricter than python classes. Java classes are frankly a bit weird, mainly because Java made a lot of stupid decisions early on in an attempt to simplify things. Then when they needed to do clever stuff they had to find weird ways round the limitations they had built for themselves - inner classes being a prime example. A lot of Java things are very bad OO design but are needed because of the "simplifications" inherent in the language! The Java equivalent of class methods is static variables. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From nick at javacat.f2s.com Thu Jun 24 17:56:16 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Jun 24 17:56:01 2004 Subject: [Tutor] class variables In-Reply-To: Message-ID: Thanks for the explanation Magnus, it was very informative and very funny :) I now understand when one would use a local variable and why, thanks to you and others who have replied to my question. Thanks again Nick. -----Original Message----- From: Magnus Lycka [mailto:magnus@thinkware.se] Sent: 24 June 2004 21:04 To: Nick Lunt; Python Tutor Subject: Re: RE: [Tutor] class variables Nick Lunt wrote: > As it stands now I cant see any use for a local variable inside the __init__ > method, ie a variable without the self prefix. You use local variables for temporary storage of data that you only need during the run of the function. Whether it's __init__, another method in a class or a plain function doesn't matter. Look here: >>> def avg(values): n = len(values) sum = 0.0 for value in values: sum += value return sum / n >>> print avg([1,2,3,4,5]) 3.0 The function avg contains two local variables, n and sum. These are lost as soon as avg exits. Are they useless? Nope, they serve a purpose, and when they are done doing that, we discard them. > But also, I can see no reason to use a class variable outside of a class > method with no self prefix. The point with a class variable is that it can be used to share information between all the instances of a class. A class attribute exists in the scope of the class. There is just one copy of this variable, regardless of how many instances of the class you create. Let's imagine that you have a class in a GUI system which described some kind of widget, maybe some kind of button. If you have a variable which determines the color of the button, and you have decided that all buttons on the screen must always be the same color, then this variable belongs in the scope of the class. If you want different buttons to be able to have different colors, you want this variable in the scope of the instance object, i.e. under "self". > I admit Im quite confused by this still. Many python programs Ive studied > mix up class variable with and without the 'instance/self' prefix. I hope the examples above help you understand what these different scopes are used for. Where a variable is defined should help you understand what it's used for, and when it contains anything of interest. > Im also confused about whether I should put my class variable inside a > method and use the self prefix, leave them outside of a method with no > prefix, or leave them outside of a method but give them a prefix. I'm wondering if you should use any classes at all... > With the simple programs I write at the moment, it wouldnt really make much > difference how I did it in most cases, but I would like to know when I > should or shouldn't be using self. And when I should be putting class > variables outside a class method (if ever). I hope you already grokked the purpose of local variables from the example above. I'll make a silly example using both instance and class variables here! :) >>> class Animal: def __init__(self, weight): assert hasattr(self.__class__, 'legs'), 'Concrete animals need legs' self.weight = weight def weight_per_leg(self): return self.weight/self.legs >>> class Insect(Animal): legs = 6 >>> class Spider(Animal): legs = 8 >>> i = Insect(0.001) >>> print i.weight_per_leg() 0.000166666666667 >>> s = Spider(0.004) >>> print s.weight_per_leg() 0.0005 You see? All spiders have eight legs (unless you pull some off). Each spider has an individual weight. Number of legs is an attribute of the class spider, and weight is an attribute of the individual spider instance. > I apologise for not grasping it very quickly. My previous experiences with > classes comes from java, and that was a while ago, and java classes seem a > lot stricter than python classes. Ok. Are you sure that you really want to use classes for the code you are writing? Java has this stupid attitude that everything should be shoehorned into a class whether it fits there or not, as if designs would become better if they are in a class. It's a bit like believing that cars run faster if we paint them red, just because Ferraris are red. In Python there is no reason to use a class unless you want to use some of the benefits that classes give. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From nick at javacat.f2s.com Thu Jun 24 17:56:17 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Jun 24 17:56:07 2004 Subject: [Tutor] class variables In-Reply-To: <011c01c45a2e$db81f860$6401a8c0@xp> Message-ID: Hi Alan, thanks again for the explanation. Now I can see the relationship between pythons class variables and javas static variables I understand what is going on. Thanks again, Nick. ps I apologise for replying to each response to my original email seperately, I just thought it was the simplest way to do it. If that goes against the etiquette of the list, please let me know. -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: 24 June 2004 22:05 To: Nick Lunt; Python Tutor Subject: Re: [Tutor] class variables > >From what you've both told me, it would seem that putting a local variable > in the __init__ method of a class is quite pointless, No you often need to do that where the init does more than simple initialisation. Here is an example where init reads values from a file: class C: def __init__(self,val) self.val = val temp = file("MySecretSettings.dat") self.setting1 = temp.readline().strip() self.setting2 = int(temp.readline().strip()) temp.close def someMethod(self):.... So temp is used as a local variable within init to hold the file object, but once read the file is never needed again so it is not stored as a class or instance variable. Local variables inside methods are just as useful as local variables in any other function, but they have nothing to do with classes or objects as such. > But also, I can see no reason to use a class variable outside of a class > method with no self prefix. It's for shared information. Instead of every instance of the class having its own copy of the data they simply refer to the Class object which stores it once. It also means that changes in that class value can affect all instances of the class in one go: class C: v = 2 def __init__(self,msg): self.msg = msg def printit(self): for n in range(C.v): # uses class value print self.msg a = C("Hello from A") b = C("Hello from B") for obj in [a,b]: obj.printit() # both objects print 2 messages C.v = 3 # Change behaviour of all instances here for obj in [a,b]: obj.printit() # both objects print 3 now So we can control the behaviour of all our instances at one stroke by changing the Class variable value. This can be a very powerful technique, especially if writing simulation software - eg network traffic predictions - where you can change the network parameters easily and do "What If" type scenarios etc. (Imagine a mesh of network objects and you can change the modelled protocol from IP4 to IP6 or X25 or ATM etc by changing one single value...) Of course you could just use a regular global variable but that's going against the principles of good OO design and also is making the value visible to a wider namespace. It's also less obvious that the value is related to the class and finally means the user has to import the module with the global defined. A Class variable gets inherited so the user only needs to import the module where the definition of the subclass exists and can access the class variable from the superclass via the subclass: class Super: v = 42 pass class Sub(Super): pass x = Super() y = Sub() print Super.v, Sub.v print x.v, y.v And of course the definition of Sub could be in a different module to Super... > I admit Im quite confused by this still. Many python programs Ive studied > mix up class variable with and without the 'instance/self' prefix. There shouldn't be many programs doing that, despite what I just said class variables are relatively uncommon in most programs. I doubt if I use them in more than about 10% of my programs - at most! > Im also confused about whether I should put my class variable inside a > method and use the self prefix, leave them outside of a method with no > prefix, or leave them outside of a method but give them a prefix. Either outside a method with no prefix - a class variable, or Inside a method with a self prefix - an instance variable. The former will be a shared value across all instances (and even when no instances exist!) the latter will have a distinct value for each instance. You should never need to use a variable outside a method with a self prefix. Note you can access the class variables either through the class name (as I did in my example, coz I think the intent is clearer) or using self. Python will look for it locally and if not finding it will look in the class. > With the simple programs I write at the moment, it wouldnt really make much > difference how I did it in most cases, but I would like to know when I > should or shouldn't be using self. And when I should be putting class > variables outside a class method (if ever). Mostly put them inside init with self. Only if you want to share the same value over all instances should you put it outside. > I apologise for not grasping it very quickly. My previous experiences with > classes comes from java, and that was a while ago, and java classes seem a > lot stricter than python classes. Java classes are frankly a bit weird, mainly because Java made a lot of stupid decisions early on in an attempt to simplify things. Then when they needed to do clever stuff they had to find weird ways round the limitations they had built for themselves - inner classes being a prime example. A lot of Java things are very bad OO design but are needed because of the "simplifications" inherent in the language! The Java equivalent of class methods is static variables. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From nick at javacat.f2s.com Thu Jun 24 17:56:16 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Jun 24 17:56:13 2004 Subject: [Tutor] class variables In-Reply-To: Message-ID: Hi Danny, thanks for the explanation, and Im glad you mentioned 'static variables' as I do understand those from a java point of view. >From what you and Magnus have mentioned it seems that a so called static variable can be created in a class scope or in a method scope. Which again makes sense. I think I've got enough info now to make sure my idea of local variables is correct. Many thanks for taking the time to explain it. Nick. -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: 24 June 2004 21:40 To: Nick Lunt Cc: Python Tutor Subject: RE: [Tutor] class variables On Wed, 23 Jun 2004, Nick Lunt wrote: > Magnus and Danny, thankyou very much for your explanations. > > >From what you've both told me, it would seem that putting a local variable > in the __init__ method of a class is quite pointless, ie > > example 1 > >>>class beer: > >>> def __init__(self): > >>> cans = 4 > >>> self.make = 'murphys' Hi Nick, It's not exactly pointless to use local variables. In the example above, it's pointless, though. *grin* But here's a more concrete example where having a local variable might help readability: ### class NameMaker: """A class to make poor variable names.""" def __init__(self, prefix): self.prefix = prefix self.counter = 0 def makeName(self): nextName = "%s%s" % (self.prefix, self.counter) self.counter = self.counter + 1 return nextName ### Here's how it works: ### >>> namer = NameMaker("x") >>> namer.makeName() 'x0' >>> namer.makeName() 'x1' >>> namer.makeName() 'x2' ### The use of 'nextName' as a local variable is fine here, just as long as we understand that it's not part of the state of the instance. > I admit Im quite confused by this still. Many python programs Ive > studied mix up class variable with and without the 'instance/self' > prefix. In Java, the scope of a variable is very implicit. The example we cooked up above could be written in several ways: /*** Java ***/ class NameMaker { private String prefix; private int counter; public NameMaker(String prefix) { this.prefix = prefix; } public String makeName() { String nextName = this.prefix + this.counter; this.counter = this.counter + 1; return nextName; } } /******/ In this Java example, all the variables are explicitely scoped. But we could just as easily have written this: /*** Java ***/ class NameMaker { private String prefix; private int counter; public NameMaker(String p) { prefix = p; } public String makeName() { String nextName = prefix + counter; counter = counter + 1; return nextName; } } /******/ Python enforces an explicit coding style that makes it clear what's an instance attribute and what's a local variable. If we see the following Python snippet: self.counter = self.counter + 1 return nextName in isolation, it's pretty clear what things are accessing the object state. But if we try the same experiement in Java: counter = counter + 1; return nextName; then it's not as immediately clear what the scope of each variable is, without looking at the immediate context. In Java, we're often required to look at the context of the snippet to figure out what things are local variables, and what things are instance attributes. In Python, we're forced to encode that knowledge more explicitely. It means that we type a little bit more, but we gain a lot in code clarity. [Digression: And it means that certain stupid scoping bugs just aren't possible in Python. For example, we can easily mess up the Java constructor: public NameMaker(String prefix) { prefix = prefix; } This compiles, but of course it's doing the wrong thing. In contrast, there's less of a danger of making this kind of error in Python, since all object state change has that 'self' attribute. Consistancy in variable name access is a good thing.] > Im also confused about whether I should put my class variable inside a > method and use the self prefix, leave them outside of a method with no > prefix, or leave them outside of a method but give them a prefix. Ah! What you've found is the equivalent of class attributes, or in Java terminology, "static" variables. When we say something like: ### >>> class NameMaker2: ... counter = 0 ... def __init__(self, prefix): ... self.prefix = prefix ... def makeName(self): ... nextName = "%s%s" % (self.prefix, NameMaker2.counter) ... NameMaker2.counter += 1 ... return nextName ... >>> xmaker = NameMaker2('x') >>> ymaker = NameMaker2('y') >>> xmaker.makeName() 'x0' >>> xmaker.makeName() 'x1' >>> xmaker.makeName() 'x2' >>> ymaker.makeName() 'y3' ### then we are defining an attribute that is bound to the class alone, and not to individual instances of the class. We can see in NameMaker2 that the 'counter' is being shared by both the 'xmaker' and 'ymaker' instances. Does this make sense so far? Please feel free to continue asking questions about this. Hope this helps! From nick at javacat.f2s.com Thu Jun 24 18:37:47 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu Jun 24 18:37:27 2004 Subject: [Tutor] class variables In-Reply-To: <20040624051240.49831.qmail@web52602.mail.yahoo.com> Message-ID: Thankyou chad. I replied to this yesterday but it has yet to appear on the list. Thanks for your help. There is definitely something wrong with the list at the moment. Its now 2330 in the UK, Ill see what time this gets to the list. Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Chad Crabtree Sent: 24 June 2004 06:13 To: tutor@python.org Subject: Re: [Tutor] class variables > class beer: > def __init__(self): > self.make = 'murphys' > cans = 4 > > There's several examples I've seen where 'self.var' isn't used, > just > 'var' is, as in 'cans' above. > I know that each instance of 'beer' will have its own value for > 'make' > but what is the use of 'cans' without using self ? > this troubled me at first and I'm not sure but I may have asked this very question here. self.var in this case means that it's a class variable available to the instance. In this case 'cans' is a function variable only available to things inside that function. just like this x=10 def dosomething(): x=20 print x print x >>dosomething() 20 >>print x 10 I hope this helps. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From magnus at thinkware.se Thu Jun 24 19:12:35 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Jun 24 19:12:46 2004 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIGNsYXNzIHZhcmlhYmxlcw==?= Message-ID: Perhaps you should have a look at http://apache.ece.arizona.edu/~edatools/Python/PythonOOP.doc -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From alan.gauld at blueyonder.co.uk Fri Jun 25 02:43:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jun 25 02:43:25 2004 Subject: [Tutor] regular expressions References: Message-ID: <019d01c45a7f$a89d8b20$6401a8c0@xp> > First is why does it ignore the P from the patterns? P* means *zero* or more repetitions of P For one or more repetitions you need to use P+ > Second I understand that search scans through the string looking for a > match. What I am wanting to do is use the \A switch , I think, that will > match only the start of the string. Or use the re.match() function instead. Ironically the usual mistake is to use match() when search() was neeeded, in your case its the other way round! Still another way would be to change the pattern to use the ^ symbol to indicate the beginning of the string. The fun(?!) thing about regex is that there are usually multiple ways of achieving the same end - all with very subtle gotchas attached... Alan G. From alan.gauld at blueyonder.co.uk Fri Jun 25 02:35:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jun 25 02:51:59 2004 Subject: [Tutor] a byte of python... error with while statement? References: <200406251719.47498.derekp@sentechsa.co.za> Message-ID: <018301c45a7e$9ebf8ff0$6401a8c0@xp> > Is there an error in the documentation or code example for > the "while" statement? Yes. -----------Code------------- number = 23 stop = False while not stop: guess = int(raw_input('Enter an integer : ')) if guess == number: -----------Code------------- The code above is correct. ----------Quote-------------- We move the raw_input and if statements to inside the while loop and set the variable stop to True before the while loop. First, we check the variable stop and if it is True, we proceed to execute the corresponding while-block. ----------Quote-------------- The description is wrong. THe variable stop is set to *False* before the loop, which makes the while *test* (not stop) evaluate to *True", thus we execute the code block. The author has confused himself(herself?) between the value of the variable and the value of the test. THis is a good reason to avoid negative tests where possible. It would have been more readable to write it as: ---------------- number = 23 start = True while start: guess = int(raw_input('Enter an integer : ')) if guess == number: ----------------- And would abvoid the distinction between the test and the variable value. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From project5 at redrival.net Fri Jun 25 02:57:53 2004 From: project5 at redrival.net (Andrei) Date: Fri Jun 25 02:58:09 2004 Subject: [Tutor] Re: Loop Variables References: <40CB3DBA.4020408@yahoo.com> Message-ID: ivan low yahoo.com> writes: > Hi, I had come to read a book about loop variable that have i, j, k. > I don't understand why are there 3 type? > What's the different? They're the same type (integer), but three different integers so you can loop over three different things at once. For example you might have recorded in a sport competition for every player in a team for every game that team played how many points the player made. If you'd want to calculate averages per player, you'd have to loop over all teams, within that loop have a second loop over each player in the team and within that loop have a third loop over the list of points scored by that player. In Python you'll not be using as many integer loop variables as you would in other languages though, because you can just say: for team in competition: for player in team: for match in player.games: ... where in a different language you'd do something similar to this (only even longer!): for i in range(len(competition)): team = competition[i] for j in range(len(team)): player = team[i] for k in range(len(player.games)): match = player.games[k] ... From dyoo at hkn.eecs.berkeley.edu Fri Jun 25 02:59:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jun 25 02:59:16 2004 Subject: [Tutor] class variables [meta: mailing list netiquette] In-Reply-To: Message-ID: On Thu, 24 Jun 2004, Nick Lunt wrote: > thanks again for the explanation. Now I can see the relationship between > pythons class variables and javas static variables I understand what is > going on. > > ps I apologise for replying to each response to my original email > seperately, I just thought it was the simplest way to do it. If that > goes against the etiquette of the list, please let me know. Hi Nick, That's fine. One thing you may want to do, though, is to crop the 'quoted' part of your replies down to the part you want to talk about. A few lines from the last email usually is enough to restore the thread of conversation. A strong reason for doing this kind of cropping is to be helpful to the folks who are reading the list in "Digest mode": they probably don't want to see the same message over and over again. *grin* There's a nice "Mailing List Netiquette" page here: http://www.woodgate.org/FAQs/netiquette.html as well as the more colorful "How To Ask Questions the Smart Way": http://www.catb.org/~esr/faqs/smart-questions.html Both have reasonable suggestions that will serve you well in technical mailing lists. Good luck to you! From nick at javacat.f2s.com Fri Jun 25 03:42:42 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Fri Jun 25 03:42:48 2004 Subject: [Tutor] class variables In-Reply-To: References: Message-ID: <1088149362.40dbd77295c64@webmail.freedom2surf.net> Quoting Magnus Lycka : > Perhaps you should have a look at > http://apache.ece.arizona.edu/~edatools/Python/PythonOOP.doc Flipping brilliant Magnus. Thanks for finding that for me. Im fortunate enough to be able to use python at work, and now I can go about making my future programs more OOP. Thanks again, Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From jtk at yahoo.com Fri Jun 25 11:20:38 2004 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Fri Jun 25 10:20:19 2004 Subject: [Tutor] Need to explicitly del a file object after reading contents? Message-ID: I've been explicitly opening, reading, closing and deleting files when I read their contents into variables. In these cases, I don't need the file object kept around for anything. I do this mainly because I don't know enough about when the garbage collector will delete the file object, and I wouldn't want it left open until the gc happens. Is it necessary to do this: f = open(filepath,'r') filestring = f.read() f.close() del f vs. this? filestring = open(filepath,'r').read() The same filepath *may* be read or written in the next few seconds/minutes by other code, but it usually won't happen. Is there a rule of thumb on when to go with the explicit file management? Thanks. From flaxeater at yahoo.com Fri Jun 25 10:57:45 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Jun 25 10:57:52 2004 Subject: [Tutor] Need to explicitly del a file object after reading contents? In-Reply-To: Message-ID: <20040625145745.47163.qmail@web52610.mail.yahoo.com> --- Jeff Kowalczyk wrote: > I've been explicitly opening, reading, closing and deleting files > when I > read their contents into variables. In these cases, I don't need > the file object kept around for anything. I do this mainly because > I don't > know enough about when the garbage collector will delete the file > object, > and I wouldn't want it left open until the gc happens. > > Is it necessary to do this: > > f = open(filepath,'r') > filestring = f.read() > f.close() > del f > > vs. this? > > filestring = open(filepath,'r').read() > > The same filepath *may* be read or written in the next few > seconds/minutes > by other code, but it usually won't happen. Is there a rule of > thumb on > when to go with the explicit file management? Thanks. > I've been told that infact it's ok to do what you wrote. Python will note that it's not longer needed and get rid of it in due time. __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From project5 at redrival.net Fri Jun 25 12:34:17 2004 From: project5 at redrival.net (Andrei) Date: Fri Jun 25 12:34:52 2004 Subject: [Tutor] Re: Need to explicitly del a file object after reading contents? References: Message-ID: Jeff Kowalczyk wrote on Fri, 25 Jun 2004 10:20:38 -0500: > I've been explicitly opening, reading, closing and deleting files when I del does not delete the file. In fact it's not even guaranteed to remove the file object I think. Even more, if you del a file object which is currently open, the file will remain open and you won't be able to overwrite it for example. > read their contents into variables. In these cases, I don't need > the file object kept around for anything. I do this mainly because I don't > know enough about when the garbage collector will delete the file object, > and I wouldn't want it left open until the gc happens. That a file object exists, does not mean that the file is open. If you close the file (which you do in the sample code you provided), the file on the HD is closed and therefore it's possible to overwrite it, delete it, open it, whatever you like. This has nothing whatsoever to do with the file object. > filestring = open(filepath,'r').read() In my experience the file is closed immediately if you use this kind of code, but I don't know if this behavior is guaranteed. > The same filepath *may* be read or written in the next few seconds/minutes > by other code, but it usually won't happen. Is there a rule of thumb on > when to go with the explicit file management? Thanks. I usually go for the one-liner when reading files. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Fri Jun 25 14:22:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jun 25 14:21:53 2004 Subject: [Tutor] class variables References: Message-ID: <001401c45ae1$51bed9a0$6401a8c0@xp> > >From what you and Magnus have mentioned it seems that a so called static > variable can be created in a class scope or in a method scope. Which again > makes sense. No, sorry not quite. static variables in Java equate to class variables in Python. THese are completely different to the local variables that you can create inside a method. Local variables dissappear after the method finishes executing. class variables are there for as long as the class (not just the instances!) exists. BTW static is a pretty meaningless term in Java, it is really borrowed from C++ which borrowed it from C to indicate a variable created on the memory heap as opposed to the stack. It was statically located in memory. Since this doesn't apply in Java the term static is kind of pointless! Alan G. From alan.gauld at blueyonder.co.uk Fri Jun 25 14:27:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jun 25 14:27:44 2004 Subject: [Tutor] Need to explicitly del a file object after reading contents? References: Message-ID: <002d01c45ae2$224f5630$6401a8c0@xp> > Is it necessary to do this: > > f = open(filepath,'r') > filestring = f.read() > f.close() > del f > > vs. this? > > filestring = open(filepath,'r').read() NO. The second is fine if you only want to suck the file into memory and do nothing else. If you want to read bits at a time, or read it multiple times (rewinding to the begining with seek() in between) then the first method is better. But even then you don't need the del line, after you close the file the file variable will be swept away in the garbage. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From gew75 at hotmail.com Fri Jun 25 20:17:09 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Fri Jun 25 20:17:30 2004 Subject: [Tutor] Speed of accessing list components Message-ID: Hi all, This is mainly for curiosity's sake, but when accessing a list component using the -i method of indexing, in e.g. >>> l [1, 2, 3, 4, 5, 6] >>> for i in range(1, len(l)+1): .. print l[-i] .. 6 5 4 3 2 1 is this exceptionally slow? Or the preferred method? In particular, I do not want to reverse the list (this would add greater complexity to other parts of the program) yet I don't really like the expression ``range(1, len(l)+1)''. Thanks guys, Glen From dyoo at hkn.eecs.berkeley.edu Sat Jun 26 06:00:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jun 26 06:00:27 2004 Subject: [Tutor] Speed of accessing list components In-Reply-To: Message-ID: On Sat, 26 Jun 2004, Glen Wheeler wrote: > >>> for i in range(1, len(l)+1): > .. print l[-i] [output cut] > is this exceptionally slow? Or the preferred method? Hi Glen, It shouldn't be too slow. But doing a reverse iteration on a list is, admittedly a little awkward in Python right now. There's a PEP by Raymond Hettinger that makes reverse iteration more pleasant: http://www.python.org/peps/pep-0322.html That PEP proposes to introduce a "reversed()" builtin that will go through the list sequence in backwards order. But that's Python 2.4 stuff, which won't come out officially for a while yet. In the meantime, though, we can write our own version of reversed(): ### def reversed(L): """Returns an iterator that marches through the elements of L in reverse order.""" n = len(L) - 1 while n >= 0: yield L[n] n -= 1 ### Here's reversed() in action: ### >>> for x in reversed(range(10)): ... print x, ... 9 8 7 6 5 4 3 2 1 0 ### Something like reversed() should make the code clearer, as you now don't have to worry so much about maintaining those list indices by hand. Hope this helps! From gew75 at hotmail.com Sat Jun 26 07:35:19 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sat Jun 26 07:40:39 2004 Subject: [Tutor] Speed of accessing list components References: Message-ID: Thanks for the reply Danny. Succinct, informative and well-written -- as usual ;). It turns out that the reverse iteration wasn't too much of a slowdown, but since I really love generators and other wotnot I'm entering in your suggestion as soon as I finish this mail. Thanks again, Glen > > > On Sat, 26 Jun 2004, Glen Wheeler wrote: > > > >>> for i in range(1, len(l)+1): > > .. print l[-i] > > > [output cut] > > > is this exceptionally slow? Or the preferred method? > > > Hi Glen, > > It shouldn't be too slow. > > But doing a reverse iteration on a list is, admittedly a little awkward in > Python right now. There's a PEP by Raymond Hettinger that makes reverse > iteration more pleasant: > > http://www.python.org/peps/pep-0322.html > > That PEP proposes to introduce a "reversed()" builtin that will go through > the list sequence in backwards order. But that's Python 2.4 stuff, which > won't come out officially for a while yet. > > In the meantime, though, we can write our own version of reversed(): > > ### > def reversed(L): > """Returns an iterator that marches through the elements of L > in reverse order.""" > n = len(L) - 1 > while n >= 0: > yield L[n] > n -= 1 > ### > > > Here's reversed() in action: > > ### > >>> for x in reversed(range(10)): > ... print x, > ... > 9 8 7 6 5 4 3 2 1 0 > ### > > Something like reversed() should make the code clearer, as you now don't > have to worry so much about maintaining those list indices by hand. > > Hope this helps! > > From Dragonfirebane at aol.com Sat Jun 26 10:08:34 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jun 26 10:09:37 2004 Subject: [Tutor] Speed of accessing list components Message-ID: <1c3.1af41c92.2e0edd62@aol.com> In a message dated 6/25/2004 8:18:08 PM Eastern Standard Time, gew75@hotmail.com writes: Hi all, This is mainly for curiosity's sake, but when accessing a list component using the -i method of indexing, in e.g. >>> l [1, 2, 3, 4, 5, 6] >>> for i in range(1, len(l)+1): .. print l[-i] .. 6 5 4 3 2 1 is this exceptionally slow? Or the preferred method? In particular, I do not want to reverse the list (this would add greater complexity to other parts of the program) yet I don't really like the expression ``range(1, len(l)+1)''. Thanks guys, Glen _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor It seems to me that one easy(er) way of doing this would be: for i in l: print l[-i] which would achieve the same effect with no discernable slowdown and a less awkward range. Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040626/f7a1acb8/attachment.html From bgailer at alum.rpi.edu Sat Jun 26 11:18:22 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Jun 26 11:23:11 2004 Subject: [Tutor] Speed of accessing list components In-Reply-To: <1c3.1af41c92.2e0edd62@aol.com> References: <1c3.1af41c92.2e0edd62@aol.com> Message-ID: <6.1.0.6.0.20040626091609.03c48e18@mail.mric.net> At 08:08 AM 6/26/2004, Dragonfirebane@aol.com wrote: >[snip] >It seems to me that one easy(er) way of doing this would be: > >for i in l: > print l[-i] > >which would achieve the same effect with no discernable slowdown and a >less awkward range. Only for the special case where the list consists of consecutive integers starting with 1. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From angjohn at rap.midco.net Sat Jun 26 12:33:35 2004 From: angjohn at rap.midco.net (john and angie) Date: Sat Jun 26 12:34:34 2004 Subject: [Tutor] ideas Message-ID: <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> hello, i am extremly new to Python and need some ideas on project that will help me learn. any help is appreciated. i have read every tutorial i can get my hands on and need some ways to put it to use. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040626/73f2f695/attachment.html From gubbs at fudo.org Sat Jun 26 15:38:30 2004 From: gubbs at fudo.org (Conrad Gavin) Date: Sat Jun 26 14:26:08 2004 Subject: [Tutor] ideas In-Reply-To: <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> References: <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> Message-ID: <1088278710.8492.17.camel@drachenfels> I have been considering this myself recently. Certainly, while there is a wealth of resources aimed at teaching python or general programming techniques I found myself (personally) wanting somewhere to get some structured material. Finding excuses to program something in python isnt always the best way to learn quickly. What do people think regarding the creation of a monthly or bi-weekly 'assignment' which could be posted on the list or on it's own list, complete with relevant material/links? The following edition could contain the previous one's solution and invite feedback perhaps. Does anyone have any thoughts or suggestions? I'd be happy to give up a few hours to sketch together a bi-weekly or monthly edition. However being dependant entirely on submissions of a suitable calibre would there be sufficient enthusiasm? I would think it could be done without too much fuss? Specially if the assignments were kept (purposefully) small, 15-20 lines tops? We could concentrate on interesting modules and the kinds of simple things; assignments, loops, arrays, tuples etc. of which all larger programs are composed. Conrad. On Sat, 2004-06-26 at 16:33, john and angie wrote: > hello, > i am extremly new to Python and need some ideas on project that will > help me learn. > any help is appreciated. > i have read every tutorial i can get my hands on and need some ways to > put it to use. > > ______________________________________________________________________ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20040626/d51bf2fb/attachment.bin From soloturku at hotmail.com Sat Jun 26 15:16:22 2004 From: soloturku at hotmail.com (=?iso-8859-1?B?U+liYXN0aWVuIFY=?=) Date: Sat Jun 26 15:16:35 2004 Subject: [Tutor] ideas Message-ID: hello, I m also new to Python and i would like to have a nice project in order to learn this interesting Language.I m student and so far i programmed mainly in C++ or java. i m waiting for all project ideas:something not too difficult since i m not a professional developper. thank you very much for your help Sebastien (sorry for the english mistakes,i m French and you know french are not the best ones for English Language =) ) _________________________________________________________________ MSN Search, le moteur de recherche qui pense comme vous ! http://search.msn.fr/worldwide.asp From bgailer at alum.rpi.edu Sat Jun 26 15:29:20 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Jun 26 15:27:50 2004 Subject: [Tutor] ideas In-Reply-To: <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> <1088278710.8492.17.camel@drachenfels> References: <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> <1088278710.8492.17.camel@drachenfels> Message-ID: <6.1.0.6.0.20040626132515.03c479d0@mail.mric.net> At 10:33 AM 6/26/2004, john and angie wrote: >i am extremly new to Python and need some ideas on project that will help >me learn. >any help is appreciated. >i have read every tutorial i can get my hands on and need some ways to put >it to use. At 01:16 PM 6/26/2004, S?bastien V wrote: >I m also new to Python and i would like to have a nice project in order to >learn this interesting Language.I m student and so far i programmed mainly >in C++ or java. >i m waiting for all project ideas:something not too difficult since i m >not a professional developper. At 01:38 PM 6/26/2004, Conrad Gavin wrote: >I have been considering this myself recently. >Certainly, while there is a wealth of resources aimed at teaching python >or general programming techniques I found myself (personally) wanting >somewhere to get some structured material. Finding excuses to program >something in python isnt always the best way to learn quickly. I have a project or 2 lying about that I'd love some help with. Some of these are non-trivial, and wading through the existing code would provide a tremendous learning opportunity, if that's a way you like to learn. These projects, should they bear fruit, might also have some financial return (no guarantees, of course). Let me know if this whets your appetite. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040626/97ee59ab/attachment.html From Dragonfirebane at aol.com Sat Jun 26 18:36:09 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jun 26 18:36:24 2004 Subject: [Tutor] Speed of accessing list components Message-ID: <129.44d13848.2e0f5459@aol.com> In a message dated 6/26/2004 11:24:37 AM Eastern Standard Time, bgailer@alum.rpi.edu writes: Only for the special case where the list consists of consecutive integers starting with 1. My apologies. You are, of course, correct. However, I also suggested a solution that would work on strings, etc.: >>> i = 0 >>> for x in string.ascii_letters: i -= 1 print string.ascii_letters[i] Z Y X W V U T S R Q P O N M L K J I H G F E D C B A z y x w v u t s r q p o n m l k j i h g f e d c b a Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040626/7acdf712/attachment.html From gew75 at hotmail.com Sat Jun 26 23:55:31 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sat Jun 26 23:55:36 2004 Subject: [Tutor] Speed of accessing list components References: <1c3.1af41c92.2e0edd62@aol.com> <6.1.0.6.0.20040626091609.03c48e18@mail.mric.net> Message-ID: > At 08:08 AM 6/26/2004, Dragonfirebane@aol.com wrote: > >[snip] > >It seems to me that one easy(er) way of doing this would be: > > > >for i in l: > > print l[-i] > > > >which would achieve the same effect with no discernable slowdown and a > >less awkward range. > > Only for the special case where the list consists of consecutive integers > starting with 1. > Also the ``slowdown'' I speak of is related to the [-i] usage. This is slower, in code, than regular indexing. Saving an external variable to use as the index is identical to my earlier solution. Except it uses a (tiny) bit more memory. I am personally in favour of Danny's suggestion. It's also faster ;). Glen From gew75 at hotmail.com Sat Jun 26 23:57:33 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sat Jun 26 23:57:36 2004 Subject: [Tutor] Speed of accessing list components References: <1088261102.17009.11.camel@zaphod.quantumtunnel.net> Message-ID: > Are you specifically looking to print it or are you just looking to > reverse the list? Usually when Python handles things internally it is > quicker than doing it yourself. So I would have to say reversing the > list could best be done w/ the reverse() method. > > Alternatively as of Python 2.2, I believe, you can step through arrays > like so: > > >>> l > [1, 2, 3, 4, 5, 6] > >>> l[::-1] > [6, 5, 4, 3, 2, 1] > > The above is kind of like a slice. The syntax is: > > myList[start:end:step] > > Along the same idea there is also mapping and list comprehension. > According to O'Reily's Learning Python: 2nd Edition. map() is quicker > than 'for' and list comprehension is slightly quicker than map(). > Yes, list comprehensions permute to C code directly. I did not know about your slice-like example above -- thanks for the info. I'll do some profiling later to see how it goes. Reversing the list and then iterating through it (then reversing it again) is really way too slow (time sensitive program). Thanks, Glen From israel at uandmedance.com Sun Jun 27 00:46:04 2004 From: israel at uandmedance.com (israel@uandmedance.com) Date: Sun Jun 27 00:45:15 2004 Subject: [Tutor] Speed of accessing list components In-Reply-To: Message-ID: Anyone know what the speed of something like the following would be? >>> alist = [1,2,3,4,5,6,7,8,9] >>>[alist[-(alist.index(a)+1)] for a in alist] [9, 8, 7, 6, 5, 4, 3, 2, 1] On Saturday, June 26, 2004, at 08:57 PM, Glen Wheeler wrote: >> Are you specifically looking to print it or are you just looking to >> reverse the list? Usually when Python handles things internally it is >> quicker than doing it yourself. So I would have to say reversing the >> list could best be done w/ the reverse() method. >> >> Alternatively as of Python 2.2, I believe, you can step through arrays >> like so: >> >>>>> l >> [1, 2, 3, 4, 5, 6] >>>>> l[::-1] >> [6, 5, 4, 3, 2, 1] >> >> The above is kind of like a slice. The syntax is: >> >> myList[start:end:step] >> >> Along the same idea there is also mapping and list comprehension. >> According to O'Reily's Learning Python: 2nd Edition. map() is quicker >> than 'for' and list comprehension is slightly quicker than map(). >> > > Yes, list comprehensions permute to C code directly. I did not know > about > your slice-like example above -- thanks for the info. I'll do some > profiling later to see how it goes. > Reversing the list and then iterating through it (then reversing it > again) > is really way too slow (time sensitive program). > > Thanks, > Glen > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > ~Israel~ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 1614 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040626/3840a4d6/attachment.bin From adam at monkeez.org Sun Jun 27 04:53:50 2004 From: adam at monkeez.org (Adam) Date: Sun Jun 27 04:53:26 2004 Subject: [Tutor] ideas In-Reply-To: <1088278710.8492.17.camel@drachenfels> References: <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> <1088278710.8492.17.camel@drachenfels> Message-ID: <20040627095350.1c1a8c53@debian> On Sat, 26 Jun 2004 19:38:30 +0000 Conrad Gavin wrote: > What do people think regarding the creation of a monthly > or bi-weekly'assignment' which could be posted on the list > or on it's own list, complete with relevant > material/links? The following edition could contain the > previous one's solution and invite feedback perhaps. I would really relish the idea of taking these on and giving them ago (and the common discussion they would generate). This would also give me the opportunity to become more pythonic, seeing others' solutions, which will almost definitely be different to mine. I would prefer the assignments to be smaller rather than larger so that I have plenty of time to think over the best way of doing it, rather than jumping in and coding straight away. Thanks for a great suggestion. Adam From alan.gauld at blueyonder.co.uk Sun Jun 27 05:08:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 27 05:08:09 2004 Subject: [Tutor] Speed of accessing list components References: Message-ID: <002c01c45c26$4e006d60$6401a8c0@xp> > >>> l > [1, 2, 3, 4, 5, 6] > >>> for i in range(1, len(l)+1): > .. print l[-i] > .. > parts of the program) yet I don't really like the expression ``range(1, > len(l)+1)''. You can probably speed it up slightly by using the range step value: for i in range(len(l)-1,0,-1): print l[i] Simply because you don't need to perform he index negation each time. Alan G. From alex at alexnewby.com Sun Jun 27 07:08:39 2004 From: alex at alexnewby.com (Alex Newby) Date: Sun Jun 27 07:08:44 2004 Subject: [Tutor] Re: ideas In-Reply-To: <20040627085358.211C352640C@frontend2.messagingengine.com> References: <20040627085358.211C352640C@frontend2.messagingengine.com> Message-ID: <1088334519.26730.199252873@webmail.messagingengine.com> From: "john and angie" hello, i am extremely new to Python and need some ideas on project that will help me learn. any help is appreciated. i have read every tutorial i can get my hands on and need some ways to put it to use. ------------------------------ In terms of pedagogical pythonic projects, I must say that I have recently become enamored with twisted.web It isn't the easiest of frameworks to sink your teeth into, but it definitely sustains interest. Try out the various packages available e.g. wxPython, Zope, etc. and find something that fits. Alex Newby From alan.gauld at blueyonder.co.uk Sun Jun 27 07:57:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 27 07:56:45 2004 Subject: [Tutor] ideas References: Message-ID: <004a01c45c3d$e0539130$6401a8c0@xp> > I m also new to Python and i would like to have a nice project in order to > learn this interesting Language.I m student and so far i programmed mainly > in C++ or java. Try the Useless Python web site, it has several projects listed and some interesting acedemic type challenges to solve too. http://www.uselesspython.com/ One you feel more proficient you might try joining one of the sourceforge projects using Python, there are several to choose from. http://www.sourceforge.net/ Search for language=python > french are not the best ones for English Language =) ) It's much btter than most English people's use of French! :-) Alan g. From alan.gauld at blueyonder.co.uk Sun Jun 27 08:01:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jun 27 08:01:32 2004 Subject: [Tutor] Speed of accessing list components References: <129.44d13848.2e0f5459@aol.com> Message-ID: <005401c45c3e$8a74e1a0$6401a8c0@xp> > >>> i = 0 > >>> for x in string.ascii_letters: > i -= 1 > print string.ascii_letters[i] > This is quite close to the canonical way of doing this using a while loop: L = [.......] i = len(L)-1 while i >= 0 print L[i] i -= 1 So much choice... Alan G. From alipolatel at yahoo.com Sun Jun 27 12:57:38 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun Jun 27 12:57:43 2004 Subject: [Tutor] A problem Message-ID: <20040627165738.93452.qmail@web61006.mail.yahoo.com> I have just started to learn python...A problem has arised as I was trying to write a programme which lists the prime numbers up to a definite number. I had problems to create a definition for this... First what I have succeded to do is : >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' ... This lists the prime numbers up to 10 but when I try to create a definition with: >>> def prime(n) : ... """ Hey dirty python! Show me the prime numbers!! """ ... for a in range (2,n): ... for x in range (2,a): ... if a % x != 0 : ... print a ... and then when I type prime(10) or any other number python gives wrong result.What is the right command? My second question is when I achieve to create a definition for that how can i save it into a file so that the programme will just do this.I mean how to save something you do to an exe file or something similar...(I don't know the logic of python clearly yet) --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040627/2214b312/attachment.html From marilyn at deliberate.com Sun Jun 27 19:54:05 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Jun 27 19:54:21 2004 Subject: [Tutor] :0: SyntaxWarning: name 'VAR' is assigned to before global declaration Message-ID: Hello again Python experts! I ran across this warning: #!/usr/bin/env python2.3 VAR = 'xxx' if __name__ == '__main__': global VAR VAR = 'yyy' --- OUTPUT: ./var.py:0: SyntaxWarning: name 'VAR' is assigned to before global declaration ---- But, a little twiddle quiets the warning, and I have no idea why: #!/usr/bin/env python2.3 VAR = 'xxx' def set_var(): global VAR VAR = 'yyy' if __name__ == '__main__': set_var() --- No output. Can anyone explain what is happening? Thank you. Marilyn Davis -- From gew75 at hotmail.com Sun Jun 27 20:25:14 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sun Jun 27 20:25:27 2004 Subject: [Tutor] A problem References: <20040627165738.93452.qmail@web61006.mail.yahoo.com> Message-ID: Hi Ali, The reason there is an error here is because of the seemingly innocent change .. if a % x != 0 : ... print a This prints a every single time there is another number x, where 2 <= x < a and x does not divide a. Obviously, this is not what you want -- for example, 3 does not divide 4, but 4 is not a prime! In fact, this error persists in your first code example -- it tells me that 9 is prime? Perhaps some more thinking is in order ;). Please note that there are many many better ways to accomplish this. A quick search with Google will turn up many prime number generators for your perusal, and hopefuly conversion to python :). HTH, Glen ----- Original Message ----- From: Ali Polatel To: tutor@python.org Sent: Monday, June 28, 2004 2:57 AM Subject: [Tutor] A problem I have just started to learn python...A problem has arised as I was trying to write a programme which lists the prime numbers up to a definite number. I had problems to create a definition for this... First what I have succeded to do is : >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' ... This lists the prime numbers up to 10 but when I try to create a definition with: >>> def prime(n) : ... """ Hey dirty python! Show me the prime numbers!! """ ... for a in range (2,n): ... for x in range (2,a): ... if a % x != 0 : ... print a ... and then when I type prime(10) or any other number python gives wrong result.What is the right command? My second question is when I achieve to create a definition for that how can i save it into a file so that the programme will just do this.I mean how to save something you do to an exe file or something similar...(I don't know the logic of python clearly yet) ------------------------------------------------------------------------------ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040628/6381ff8e/attachment.html From bgailer at alum.rpi.edu Sun Jun 27 20:46:45 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Jun 27 20:45:16 2004 Subject: [Tutor] :0: SyntaxWarning: name 'VAR' is assigned to before global declaration In-Reply-To: References: Message-ID: <6.1.0.6.0.20040627184259.0376bc78@mail.mric.net> At 05:54 PM 6/27/2004, Marilyn Davis wrote: >I ran across this warning: > >#!/usr/bin/env python2.3 >VAR = 'xxx' >if __name__ == '__main__': > global VAR > VAR = 'yyy' >--- >OUTPUT: >./var.py:0: SyntaxWarning: name 'VAR' is assigned to before global declaration >---- >But, a little twiddle quiets the warning, and I have no idea why: > >#!/usr/bin/env python2.3 >VAR = 'xxx' >def set_var(): > global VAR > VAR = 'yyy' >if __name__ == '__main__': > set_var() Global is normally used within a function definition to allow it to assign to names defined outside the function (as in your 2nd example). In your first example global is outside any function definition, and therefore not meaningful, as well as giving a SyntaxWarning. [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jonathan.hayward at pobox.com Sun Jun 27 21:33:32 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Sun Jun 27 21:33:54 2004 Subject: [Tutor] Major computer warning. Message-ID: <40DF756C.7040200@pobox.com> The following is from another list. I've verified it from other sources, including http://slashdot.org. What it means is that if you have a PC, it is VERY DANGEROUS to use Internet Explorer now. I reccommend using http://www.mozilla.org/products/firefox/ . Brethren, The following news articles describe a potentially serious threat to PC's because of a flaw in Internet Explorer. There isn't a lot of detail at this time, but given the history of problems, what they are describing is certainly possible. Two articles: http://www.theregister.com/2004/06/25/virus_hits_websites/ http://www.foxnews.com/story/0,2933,123712,00.html The best way to limit your risk is to use a browser other than Internet Explorer. There are several good options available: Mozilla Firefox: http://mozilla.org/products/firefox/ Opera: http://www.opera.com/download/index.dml?platform=windows Netscape: http://www.netscape,com Any of these three will limit the risk you have when surfing the net. Be sure you enable their pop-up blocking immediately after you install them. It's also very, very important that you have anti-virus software installed and running on your machine, and update it on a daily basis. You might want to also consider getting a firewall like Zone Alarm or Black Ice. Finally, you should, from time to time, scan your machine with AdAware, which will find malicious programs: http://www.lavasoftusa.com/software/adaware/ It does a good job of finding and removing malicious programs, untrustworthy cookies, browser hijacks, etc. This problem does not affects Apple Macintosh or Linux systems. -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From marvboyes at att.net Sun Jun 27 22:13:31 2004 From: marvboyes at att.net (Marv Boyes) Date: Sun Jun 27 22:15:29 2004 Subject: [Tutor] embarrassingly basic Tkinter question... Message-ID: <40DF7ECB.1060200@att.net> Hello, all. I'm roughly a week old as a Python programmer, and this is my first post to the list (both of these facts will become painfully obvious once you've read my question...) I've been through all of the documentation I can get my hands on, and I have yet to find a clear answer-- can anyone tell me a good way to launch an application (under Linux) by clicking on a button created with Tkinter? I've been able to create windows and widgets galore, but they're not much use until I can convince them to DO something. I've been able to make a button labeled 'Close' which (drumroll, please...) closes the window. Beyond that, I'm not having much luck. Basically, I want to create a simple menu application for my wife (who's been lost on this machine since I switched to Xfce4) so she can launch the programs she wants. Sure, I could slap launchers in Xfce4's panel, but I like to keep it relatively clean. Besides, there's a problem that needs solving, and I'd love to be able to do it myself, the way I want. My wife will also be touched by my thoughtfulness, and forget how much I spent on programming books last week. ;) Here's what I have so far: from Tkinter import * from os import system # now what? root = Tk() root.title("Melody's Internet Stuff") root.geometry("280x150") app = Frame(root) app.grid() bttn1 = Button(app, text = "Connect to the Internet") bttn1.grid() bttn2 = Button(app, text = "Get, read, and write e-mail") bttn2.grid() bttn3 = Button(app, text = "Browse the Web") bttn3.grid() bttn4 = Button(app, text = "Close",command = 'exit') bttn4.grid() root.mainloop() Now, what I want to do is launch an application by pressing buttons 1, 2, or 3. I'm guessing that the os module is involved, but I found that a simple command = system('appname') launched the application as soon as I ran the Python script; indeed, my Tk window wouldn't even appear until that application was closed. So I'm obviously missing something. Sorry this is so lengthy--I'll work on brevity. In the meantime, can anyone point me in the right direction? Many thanks in advance. Marv ---------- Help in the research to fight devastating diseases like Huntington's, Parkinson's, and Alzheimer's-- donate your computer's leisure time to Folding@Home. http://www.stanford.edu/group/pandegroup/folding/ ---------- From marilyn at deliberate.com Sun Jun 27 23:29:57 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Jun 27 23:30:06 2004 Subject: [Tutor] :0: SyntaxWarning: name 'VAR' is assigned to before global declaration In-Reply-To: <6.1.0.6.0.20040627184259.0376bc78@mail.mric.net> Message-ID: On Sun, 27 Jun 2004, Bob Gailer wrote: > At 05:54 PM 6/27/2004, Marilyn Davis wrote: > >I ran across this warning: > > > >#!/usr/bin/env python2.3 > >VAR = 'xxx' > >if __name__ == '__main__': > > global VAR > > VAR = 'yyy' > >--- > >OUTPUT: > >./var.py:0: SyntaxWarning: name 'VAR' is assigned to before global declaration > >---- > >But, a little twiddle quiets the warning, and I have no idea why: > > > >#!/usr/bin/env python2.3 > >VAR = 'xxx' > >def set_var(): > > global VAR > > VAR = 'yyy' > >if __name__ == '__main__': > > set_var() > > Global is normally used within a function definition to allow it to assign > to names defined outside the function (as in your 2nd example). In your > first example global is outside any function definition, and therefore not > meaningful, as well as giving a SyntaxWarning. You are so right! I was thinking that I needed it in any indentation. But a test showed that I could do if __name__ == '__main__': var = 'YYY' Great. It all makes sense now. Thank you. Marilyn > [snip] > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > -- From rdmoores at gmail.com Mon Jun 28 02:50:29 2004 From: rdmoores at gmail.com (Dick Moores) Date: Mon Jun 28 02:50:43 2004 Subject: [Tutor] Question about order in a dictionary Message-ID: Python 2.3.4 In IDLE, if I enter D = {"a": "first letter", "b": "second letter", "c": "third letter", "z": "last letter"} and then print D I get {'a': 'first letter', 'c': 'third letter', 'b': 'second letter', 'z': 'last letter'} Why does the order change? I'm just beginning to understand dictionaries, and I suppose the order doesn't matter, but why would it change? Thanks, Dick Moores From dyoo at hkn.eecs.berkeley.edu Mon Jun 28 04:22:40 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 28 04:22:53 2004 Subject: [Tutor] Major computer warning. [META: crossposting / mailing list etiquette] In-Reply-To: <40DF756C.7040200@pobox.com> Message-ID: On Sun, 27 Jun 2004, Jonathan Hayward wrote: > The following is from another list. I've verified it from other sources, > including http://slashdot.org. What it means is that if you have a PC, > it is VERY DANGEROUS to use Internet Explorer now. [Text cut; CC list cut down. Putting on good-cop-admin hat.] Hi Jonathan, Thanks for the concern and the heads up. But please try avoid doing that kind of crossposting. You may not have realized it, but what you just did was a netiquette no-no. http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html The idea about Tutor is to keep the list centered mostly on helping people learn to programming in Python. There are already plenty of other reputable places where security warning stuff is publicized, including CERT: http://www.cert.org/ If Python-Tutor just becomes yet another announcement page for anything and everything technically related, that useful focus of Python-Tutor will be probably get drowned out. (Pot calling kettle black: I have to admit that I've screwed up about this before. I have made announcements about upcoming Bay Area Python User Group meetings on Python-Tutor, and for that, I apologize; I was stupid.) Anyway, I hope this makes sense. We appreciate the gesture, but it was unnecessary here. Crossposting is itself potentially annoying, and we need to do what we can to avoid stressing folks who are already hard pressed to figure out why their Python programs aren't doing what they expect. From project5 at redrival.net Mon Jun 28 04:44:34 2004 From: project5 at redrival.net (Andrei) Date: Mon Jun 28 04:44:43 2004 Subject: [Tutor] Re: Question about order in a dictionary References: Message-ID: Dick Moores gmail.com> writes: > In IDLE, if I enter > D = {"a": "first letter", "b": "second letter", "c": "third letter", > "z": "last letter"} > and then > print D > I get > {'a': 'first letter', 'c': 'third letter', 'b': 'second letter', 'z': > 'last letter'} > > Why does the order change? I'm just beginning to understand For the order to change, there should be an order in the first place. However, dictionary by definition have *no order*, so how can it possibly change if it doesn't exist? Don't be fooled by the fact that things are printed in a certain order; that order is for all intents and purposes meaningless and is there for the simple reason that we are only able to read things when they're presented sequentially (and therefore ordered). > dictionaries, and I suppose the order doesn't matter, but why would it > change? You might have asked the wong question and actually want to know why dictionaries are not ordered. That has to do with their implementation. You can read about that in the FAQ: http://www.python.org/doc/faq/general.html#how-are-dictionaries-implemented By the way, it's possible (and not that hard) to roll your own implementation of dictionary which *is* ordered. In fact, there are several available on the web if you need one and don't much care for coding your own ;). Yours, Andrei From project5 at redrival.net Mon Jun 28 05:03:38 2004 From: project5 at redrival.net (Andrei) Date: Mon Jun 28 05:03:45 2004 Subject: [Tutor] Re: ideas References: <000a01c45b9b$53c95b20$ac61dc18@homesthzxom9ok> Message-ID: john and angie rap.midco.net> writes: > i am extremly new to Python and need some ideas on > project that will help me learn. > any help is appreciated. > i have read every tutorial i can get my hands on > and need some ways to put it to use. This depends a lot on what your interests and/or needs are. Do you like/need games, maths, web stuff, educational tools, text processing, system tools, image processing, database tools, something else? I have an example where you could combine a couple or most of the categories above and do so at a very simple level or a very advanced level: a quiz/quiz generation tool. Pick the favourite subject that you know most about and devise a way to store questions about that subject (can be in plain text files or in some DB) and a way to present those questions to a student or for a teacher to select a number of those questions and print them for a test on paper. You can go for multiple-choice questions, or for ones where some variables can be varied (especially useful for math/sciences) in a manual or automated way, whereby your tool computes the new answer. You could combine this with some web tool (online testing), with pygame (show animations of a physics problem), with a PDF generator (printing), with wxPython/Tkinter (electronic tests), database (store questions in categories, assign points, time-to-solve and difficulty level and allow the teacher to auto-generate complete tests based on certain criteria). Yours, Andrei From dyoo at hkn.eecs.berkeley.edu Mon Jun 28 05:08:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jun 28 05:08:39 2004 Subject: [Tutor] Question about order in a dictionary In-Reply-To: Message-ID: On Sun, 27 Jun 2004, Dick Moores wrote: > if I enter > > D = {"a": "first letter", "b": "second letter", "c": "third letter", > "z": "last letter"} > > and then > > print D > > I get > > {'a': 'first letter', 'c': 'third letter', 'b': 'second letter', 'z': > 'last letter'} > > Why does the order change? I'm just beginning to understand > dictionaries, and I suppose the order doesn't matter, but why would it > change? Hi Dick, You're somewhat right: order isn't so relevant in a dictionary. It turns out that when we create a dictionary, like: ### D = {"a": "first letter", "b": "second letter", "c": "third letter", "z": "last letter"} ### then that actually does two things: it initializing the dictionary, and then it adds an entry to that dictionary, for each key/value pair we've typed in, in left-to-right order. The gory details about this are in the Python Reference manual. For the curious, here's the reference: http://www.python.org/doc/ref/dict.html This left-to-right part can actually make a difference: we might accidently make a typo when we define the dictionary, and reuse a key that we didn't mean to, like: ### D = {"a": "first letter", "b": "second letter", "c": "third letter", "a": "oops!"} ### then the dictionary that we get back is guaranteed to have the following key/value pairs: ('c', 'third letter') ('b', 'second letter') ('a', 'oops!') since Python will overwrite the first key/value pair with the last. So order might possible matter when we're creating a dictionary, but that wasn't exactly your question. *grin* What you're asking is: why does the dictionary display in a different order: why are the entries all scrambled up? Python is doing its own organizing, behind the scenes, and it doesn't guarantee at all what order we'll get back those key/value pairs when we print out a dictionary. That is, we deliberately sacrifice an ordering. It seems harsh, but in return, Python guarantees that if we ask for a specific key from a dictionary, we'll be able to get its corresponding value very very quickly. It becomes a snap for Python to give us: D['a'] almost immediately, because of technical details about how dictionaries are implemented as "hashtables", a data structure from computer science. We can talk about hashtables later, if you'd like. But if we really care about order, we can use a list instead of a dictionary: ### >>> key_values = [ ('a', 'first letter'), ... ('b', 'second letter'), ... ('c', 'third letter'), ... ('z', 'last letter') ] >>> >>> key_values [('a', 'first letter'), ('b', 'second letter'), ('c', 'third letter'), ('z', 'last letter')] ### This list, too, can contain key/value pairs, and once we print it out, we'll see that order's preserved. But searching for a particular value is just slightly more work than a dictionary: ### >>> def find_value(key, key_values): ... """Given a key, and a key/value list, returns the associated ... value. ... If no such key is found, raises KeyError.""" ... for (k, v) in key_values: ... if key == k: ... return v ... raise KeyError, key ... >>> >>> find_value('c', key_values) 'third letter' >>> find_value('b', key_values) 'second letter' ### I hope this helps! Please feel free to ask more questions on any of this. From klappnase at freenet.de Mon Jun 28 06:06:34 2004 From: klappnase at freenet.de (Michael Lange) Date: Mon Jun 28 06:04:57 2004 Subject: [Tutor] embarrassingly basic Tkinter question... In-Reply-To: <40DF7ECB.1060200@att.net> References: <40DF7ECB.1060200@att.net> Message-ID: <20040628120634.7696c3cb.klappnase@freenet.de> On Sun, 27 Jun 2004 22:13:31 -0400 Marv Boyes wrote: > Here's what I have so far: > > from Tkinter import * > from os import system # now what? > > root = Tk() > root.title("Melody's Internet Stuff") > root.geometry("280x150") > app = Frame(root) > app.grid() > > bttn1 = Button(app, text = "Connect to the Internet") > bttn1.grid() > > bttn2 = Button(app, text = "Get, read, and write e-mail") > bttn2.grid() > > bttn3 = Button(app, text = "Browse the Web") > bttn3.grid() > > bttn4 = Button(app, text = "Close",command = 'exit') > bttn4.grid() > > root.mainloop() > > Now, what I want to do is launch an application by pressing buttons 1, > 2, or 3. I'm guessing that the os module is involved, but I found that a > simple command = system('appname') launched the application as soon as I > ran the Python script; indeed, my Tk window wouldn't even appear until > that application was closed. So I'm obviously missing something. > Probably you did something like: os.system('mozilla') within your code and as you told python it launched the browser and then waited until the system command had finished. If you want to run programs in the background use os.system('mozilla &') The second problem is that you of course don't want the program to be started with your app, but just when the corresponding button is pressed. To achieve this you have to define a function for each button callback, like this: def browse_the_web(): os.system('mozilla &') (...) bttn3 = Button(app, text = "Browse the Web", command=browse_the_web) (...) I hope this helped Michael From rdmoores at gmail.com Mon Jun 28 07:25:08 2004 From: rdmoores at gmail.com (Dick Moores) Date: Mon Jun 28 07:25:13 2004 Subject: [Tutor] Question about dictionary method get() Message-ID: This is probably trivial, but it makes me suspect that there's something I don't understand about "None". In _Python in a Nutshell_, on p. 50, I find, under "Dictionary Methods": D.get(k[,x]) -- Returns D[k] if k is a key in D, otherwise returns x (or None, if x is not given) But in my simple D = {'a': 'first letter', 'b': 'second letter', 'c': 'third letter', 'z': 'last letter'} D.get("v") returns nothing, not "None". (with version 2.3.4) The .chm file I have of the Python documentation for 2.3, it says a.get(k[, x]) -- a[k] if k in a, else x Does this imply that that my D.get("v") will return nothing, not "None", and that there might be an error in the wonderful _Python in a Nutshell_? Or am I just confused about something here? Or is this a version difference? Uh, oh. I just now tried print D.get("v") and did get "None". Then why not with the plain D.get("v") ? Maybe I've found the source of my confusion? Thanks again, Dick Moores From rdmoores at gmail.com Mon Jun 28 07:30:59 2004 From: rdmoores at gmail.com (Dick Moores) Date: Mon Jun 28 07:31:02 2004 Subject: [Tutor] Re: Question about order in a dictionary In-Reply-To: References: Message-ID: My thanks to all of you for your very patient and detailed answers. I learned a lot from them. Some of the info was over my head, but I'll save it for later. Dick Moores From Francis.Moore at shaws.co.uk Mon Jun 28 08:07:28 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Mon Jun 28 08:12:57 2004 Subject: [Tutor] Question about dictionary method get() Message-ID: <6081EBC21D52F744B484088BBBE665C3199F0D@sbserver.shaws.local> From: Dick Moores [mailto:rdmoores@gmail.com] >In _Python in a Nutshell_, on p. 50, I find, under "Dictionary Methods": > >D.get(k[,x]) -- Returns D[k] if k is a key in D, otherwise >returns x (or None, if x is not given) >. >. >. Dick, There's a good explanation of the dictionary get() method in Recipe 1.3 of the O'Reilly Python Cookbook. There's a .pdf sample chapter at the following URL with this recipe in which you can download: http://www.oreilly.com/catalog/pythoncook/chapter/ch01.pdf It can probably explain it better than I can ;-) Hope this helps, Francis. CONFIDENTIALITY NOTICE This communication contains information which is confidential and may also be privileged. It is for the exclusive use of the intended recipient(s). If you are not the intended recipient(s) please note that any distribution, copying or use of this communication or the information in it is strictly prohibited. If you have received this communication in error please notify us by e-mail or by telephone (+44(0) 1322 621100) and then delete the e-mail and any copies of it. This communication is from Shaw & Sons Limited whose registered office is at Shaway House, 21 Bourne Park, Bourne Road, Crayford, Kent DA1 4BZ. The views expressed in this communication may not be the views held by Shaw & Sons Limited. This message has been checked for all known viruses by McAfee VirusScan. From alipolatel at yahoo.com Mon Jun 28 08:24:11 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Mon Jun 28 08:24:18 2004 Subject: [Tutor] A simple problem Message-ID: <20040628122411.49383.qmail@web61005.mail.yahoo.com> Dear Friends, I am very new to python and have a problem.I have downloaded programmes written in python from www.hotscripts.com to learn about the coding and such stuff. There are four files one is a dat file the other 2 are py and I don't remember the other one(it is a calculator written in python) when I open it with python I can only view its codes but how will I run the calculator??? which programme needed for that? Regards --------------------------------- Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040628/d60dbe58/attachment.html From olavi at city.ee Mon Jun 28 08:25:41 2004 From: olavi at city.ee (Olavi Ivask) Date: Mon Jun 28 08:27:25 2004 Subject: [Tutor] A simple problem In-Reply-To: <20040628122411.49383.qmail@web61005.mail.yahoo.com> References: <20040628122411.49383.qmail@web61005.mail.yahoo.com> Message-ID: <40E00E45.6010504@city.ee> Open py file with python ->python yourfile.py Olavi Ali Polatel wrote: > Dear Friends, > I am very new to python and have a problem.I have downloaded > programmes written in python from www.hotscripts.com > to learn about the coding and such stuff. > There are four files one is a dat file the other 2 are py and I don't > remember the other one(it is a calculator written in python) when I > open it with python I can only view its codes but how will I run the > calculator??? which programme needed for that? > Regards > > Do you Yahoo!? > Yahoo! Mail is new and improved - Check it out! > > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From rdm at rcblue.com Mon Jun 28 08:34:34 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Jun 28 08:34:41 2004 Subject: [Tutor] Question about dictionary method get() In-Reply-To: <6081EBC21D52F744B484088BBBE665C3199F0D@sbserver.shaws.loca l> References: <6081EBC21D52F744B484088BBBE665C3199F0D@sbserver.shaws.local> Message-ID: <6.1.2.0.2.20040628052641.0242c8a8@rcblue.com> Francis Moore wrote at 05:07 6/28/2004: >Dick, > >There's a good explanation of the dictionary get() method in Recipe 1.3 >of >the O'Reilly Python Cookbook. There's a .pdf sample chapter at the >following URL with this recipe in which you can download: > >http://www.oreilly.com/catalog/pythoncook/chapter/ch01.pdf > >It can probably explain it better than I can ;-) Francis, Wow, what a great resource! Yes, 1.3 is an understandable explanation, EXCEPT FOR: "If you call d.get(x), no exception is thrown: you get d[x] if x is a key in d, and if it's not, you get None (which you can check for or propagate)." How do I "check for or propagate" None? Sorry for the basic questions. Thanks, Dick Moores From Francis.Moore at shaws.co.uk Mon Jun 28 09:47:43 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Mon Jun 28 09:53:19 2004 Subject: [Tutor] Question about dictionary method get() Message-ID: <6081EBC21D52F744B484088BBBE665C3199F0E@sbserver.shaws.local> From: Dick Moores [mailto:rdm@rcblue.com] > How do I "check for or propagate" None? Checking for 'None' is as follows: def func(): d = {} d['a'] = 1 d['b'] = 2 d['c'] = 3 if d.get('d') == None: print 'Key of "d" not found' if __name__ == '__main__': func() This will print 'Key of "d" not found' I don't have my copy of Python In A Nutshell to hand to check the index for propogation of a value but I'm assuming that it means to raise an exception. As the default implementation of the dictionary class does not raise an exception when a key is not found, you can raise your own. Like so: if d.get('d') == None: raise Exception, 'Key of "d" not found' Someone more knowledgeable on the list might want to clarify that my general understanding of propagating 'None' is correct. > Sorry for the basic questions. No problem. Cheers, Francis. CONFIDENTIALITY NOTICE This communication contains information which is confidential and may also be privileged. It is for the exclusive use of the intended recipient(s). If you are not the intended recipient(s) please note that any distribution, copying or use of this communication or the information in it is strictly prohibited. If you have received this communication in error please notify us by e-mail or by telephone (+44(0) 1322 621100) and then delete the e-mail and any copies of it. This communication is from Shaw & Sons Limited whose registered office is at Shaway House, 21 Bourne Park, Bourne Road, Crayford, Kent DA1 4BZ. The views expressed in this communication may not be the views held by Shaw & Sons Limited. This message has been checked for all known viruses by McAfee VirusScan. From bvande at po-box.mcgill.ca Mon Jun 28 10:12:47 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Jun 28 10:35:41 2004 Subject: [Tutor] Question about order in a dictionary In-Reply-To: References: Message-ID: <40E0275F.3050507@po-box.mcgill.ca> Danny Yoo said unto the world upon 28/06/2004 05:08: > That is, we deliberately sacrifice an ordering. It seems harsh, but in > return, Python guarantees that if we ask for a specific key from a > dictionary, we'll be able to get its corresponding value very very > quickly. It becomes a snap for Python to give us: > > D['a'] > > almost immediately, because of technical details about how dictionaries > are implemented as "hashtables", a data structure from computer science. > We can talk about hashtables later, if you'd like. > Hi all, I'm comfortable with mathematics, but not a computer scientist by any means. I've been wanting to learn about the details of hashtables (meaning of the term, how implemented, why allowing for faster search, etc.). Does anyone know of a good presentation that gets the details covered correctly, but doesn't presuppose that I am at least halfway through a comp sci BSc? (I'm not asking someone to wade through google results pages; if that needs to be done I can do my own searching ;-) Rather, I wonder if anyone already knows of a good resource to recommend.) Best to all, Brian vdB PS Since it is my first post to any of the lists since they all went funny last week, thanks to those who worked/are working to heal the python.org mailing list server. I'm very glad things seem back to normal at least as far as I can tell. From jeffpeery at yahoo.com Mon Jun 28 11:22:35 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon Jun 28 11:22:42 2004 Subject: [Tutor] XRCed? Message-ID: <20040628152235.49684.qmail@web60105.mail.yahoo.com> I was checking out the XRCed program, and I am unfamiliar with XML... this is a markup language for web browsers? Is the XRCed a GUI builder for XML? Can someone give me a brief intro to this thing. thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040628/0c44028a/attachment.html From magnus at thinkware.se Mon Jun 28 08:57:03 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Jun 28 11:25:13 2004 Subject: [Tutor] What Eval() Hath Men Wrought In-Reply-To: <00e001c45a06$b4bc7610$6401a8c0@xp> References: <5.2.1.1.0.20040618121728.02716390@www.thinkware.se> Message-ID: <5.2.1.1.0.20040628143607.028592d0@www.thinkware.se> At 17:17 2004-06-24 +0100, Alan Gauld wrote: >You can use the Python apply() function to do a similar thing, >it takes a callable object and a tuple of arguments to be passed >to the callable. There is no longer any need to use apply, since you have the *args and **kwargs constructs since Python 2.0. See http://www.amk.ca/python/2.0/index.html section 9.1. >>> import time >>> def callme(f, *args, **kwargs): print "Function:", f, "called with" print "positional arguments", args, "and" print "named arguments", kwargs start = time.clock() result = f(*args, **kwargs) stop = time.clock() print "It took %f seconds" % (stop-start) return result >>> import math >>> callme(math.sin, 0.7) Function: called with positional arguments (0.69999999999999996,) and named arguments {} It took 0.000017 seconds 0.64421768723769102 >>> callme(dir) Function: called with positional arguments () and named arguments {} It took 0.000029 seconds ['args', 'f', 'kwargs', 'start'] >>> def x(a1, a2, p1=1, p2=1): return a1*p1 + a2*p2 >>> callme(x,3,4,p2=0.5) Function: called with positional arguments (3, 4) and named arguments {'p2': 0.5} It took 0.000033 seconds 5.0 -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From rdm at rcblue.com Mon Jun 28 11:42:42 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Jun 28 11:42:45 2004 Subject: [Tutor] Question about dictionary method get() In-Reply-To: <6081EBC21D52F744B484088BBBE665C3199F0E@sbserver.shaws.loca l> References: <6081EBC21D52F744B484088BBBE665C3199F0E@sbserver.shaws.local> Message-ID: <6.1.2.0.2.20040628083753.024004a0@rcblue.com> Francis Moore wrote at 06:47 6/28/2004: >Checking for 'None' is as follows: > >def func(): > d = {} > d['a'] = 1 > d['b'] = 2 > d['c'] = 3 > > if d.get('d') == None: > print 'Key of "d" not found' > >if __name__ == '__main__': > func() > >This will print 'Key of "d" not found' > >I don't have my copy of Python In A Nutshell to hand to check the >index for propogation of a value but I'm assuming that it means >to raise an exception. As the default implementation of the >dictionary class does not raise an exception when a key is not >found, you can raise your own. Like so: > > if d.get('d') == None: > raise Exception, 'Key of "d" not found' Thanks very much again, Francis. Very clear, except for my not understanding if __name__ == '__main__': func() But that's OK. I'll get to that later. Dick Moores From jeffpeery at yahoo.com Mon Jun 28 11:42:58 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon Jun 28 11:43:01 2004 Subject: [Tutor] boa help? Message-ID: <20040628154258.32724.qmail@web60109.mail.yahoo.com> I'm using Boa constructor to make windows GUIs, I have it running on my labtop although it doesn't seem to be working on my desktop? I get this error message: "global name 'wx' is not defined" thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040628/341c0233/attachment.html From alan.gauld at blueyonder.co.uk Mon Jun 28 13:14:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 13:14:14 2004 Subject: [Tutor] What Eval() Hath Men Wrought References: <5.2.1.1.0.20040618121728.02716390@www.thinkware.se> <5.2.1.1.0.20040628143607.028592d0@www.thinkware.se> Message-ID: <000401c45d33$6fcdf3a0$6401a8c0@xp> > At 17:17 2004-06-24 +0100, Alan Gauld wrote: > >You can use the Python apply() function to do a similar thing, > There is no longer any need to use apply, since you have > the *args and **kwargs constructs since Python 2.0. So you can I keep forgetting about that. Mainly coz I think its horrible and much prefer apply. It fits with the functional model so much more nicely. But there is no doubt it is less efficient and slightly less flexible. Certainly the *args/**kwargs nonsense is the official Pythonic route, no matter how ugly. Alan G. From alan.gauld at blueyonder.co.uk Mon Jun 28 13:22:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 13:21:42 2004 Subject: [Tutor] :0: SyntaxWarning: name 'VAR' is assigned to before globaldeclaration References: Message-ID: <001801c45d34$7a58a990$6401a8c0@xp> > #!/usr/bin/env python2.3 > VAR = 'xxx' > > if __name__ == '__main__': > global VAR > VAR = 'yyy' Here there is only one scope, module or global scope. Therefore there is no need for the global statement because the vVAR will allways be the same one as defined previously. > OUTPUT: > > ./var.py:0: SyntaxWarning: name 'VAR' is assigned to before global declaration And this is true, within the file scope you have already created VAR so it is too late trying to tell Python to look somewhere else. (Even though there is nowhere else it could look in this case!) > But, a little twiddle quiets the warning, and I have no idea why: > > #!/usr/bin/env python2.3 > VAR = 'xxx' > > def set_var(): > global VAR > VAR = 'yyy' Thats a huge twiddle. You have now created a function which defines a new scope or namespace. So the VAR in there will by default be a local VAR unless you use global, as you have done. If you did this you'd get the same error as before: def set_var(): VAR = 'yyy' global VAR Because that's an equivalent error. > Can anyone explain what is happening? Try reading the "What's in a name?" topic in my online tutor for more info and examples. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From Dragonfirebane at aol.com Mon Jun 28 13:23:13 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jun 28 13:23:19 2004 Subject: [Tutor] (IOError: [Errno 9] Bad file descriptor) in IDLE (wrong mailing list?) Message-ID: <50.2de54c10.2e11ae01@aol.com> I'm unsure where to submit this, but there appears to be an error with IDLE. Every so often when i run a module (not a particular one), this comes up and i have to run it again: >>> Exception in Tkinter callback Traceback (most recent call last): File "C:\PROGRA~1\PYTHON~1.4C1\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\PROGRA~1\PYTHON~1.4C1\lib\idlelib\ScriptBinding.py", line 135, in run_module_event code = self.checksyntax(filename) File "C:\PROGRA~1\PYTHON~1.4C1\lib\idlelib\ScriptBinding.py", line 96, in checksyntax return compile(source, filename, "exec") File "C:\PROGRA~1\PYTHON~1.4C1\lib\warnings.py", line 116, in warn_explicit showwarning(message, category, filename, lineno) File "C:\PROGRA~1\PYTHON~1.4C1\lib\idlelib\PyShell.py", line 55, in idle_showwarning file.write(warnings.formatwarning(message, category, filename, lineno)) IOError: [Errno 9] Bad file descriptor I apologize if this is off-topic. Does anyone know, if this isn't the right mailing list, where to submit this? I suspect the issue may be with Tkinter since the exception is in the Tkinter callback, but I have very little experience with Tkinter, so I can't make heads or tails of the error message. Any suggestions would be appreciated. Thanks in advance, Orri Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040628/90a32d98/attachment.html From alan.gauld at blueyonder.co.uk Mon Jun 28 13:28:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 13:27:55 2004 Subject: [Tutor] Question about order in a dictionary References: Message-ID: <002a01c45d35$59ac2400$6401a8c0@xp> > D = {"a": "first letter", "b": "second letter", "c": "third letter", > "z": "last letter"} > print D > {'a': 'first letter', 'c': 'third letter', 'b': 'second letter', 'z': > 'last letter'} > > Why does the order change? Because of the way Python stores the data internally. To make the search fast it doesn't use the sequence that you provide but uses a tree-like structure. When you print D it traverses the tree top to bottom, but the position in the tree is optimised for rapid retrieval of the keys. > I suppose the order doesn't matter, but why would it change? You are right the order doesn't matter to the user, and you can always extract the list of keys and sort them if you need sorted order. You might find my "Raw Materials" topic in my tutor usful it has a section on Dictionaries which discusses these issues a little further. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tpc at csua.berkeley.edu Mon Jun 28 13:40:05 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Jun 28 13:40:20 2004 Subject: [Tutor] print formatting, length of string Message-ID: <20040628103153.H62269-100000@localhost.name> hi everybody, let's say I have a list of dictionaries, and each dictionary, representing a database record, stores a series of key, value pairs, and I want to print out each key, value pair such that: *) each key ends with ': ' *) the length of the longest key determines how many spaces prepend the shorter keys, e.g.,: *************************** 1. row *************************** First_Name: JAMES Last_Name: SMITH Address_Line1: 2525 BANTRY LANE City: NORTH BRUNSWICK State: NJ *************************** 2. row *************************** First_Name: MARY Last_Name: JONES Address_Line1: 1713 RIVER CREEK RD City: PALM HARBOR State: FL In other words, I want my colons to line up. The code I have so far is a kludge: def formatListOfRecordDicts(listOfRecordDicts): count = 0 for recordDict in listOfRecordDicts: count += 1 print "*************************** % s. row ***************************" % count print " First_Name:", recordDict['First_Name'] print " Last_Name:", recordDict['Last_Name'] print "Address_Line1:", recordDict['Address_Line1'] and as you can imagine I'd have to rewrite it if and when I decide to pull out a different set of data from my database. Is there a more elegant way of doing this ? From alan.gauld at blueyonder.co.uk Mon Jun 28 13:43:14 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 13:42:30 2004 Subject: [Tutor] embarrassingly basic Tkinter question... References: <40DF7ECB.1060200@att.net> Message-ID: <003a01c45d37$63abe290$6401a8c0@xp> > I've been through all of the documentation I can get my hands on, and I > have yet to find a clear answer-- can anyone tell me a good way to > launch an application (under Linux) by clicking on a button created with > Tkinter? You need to set the command parameter of the Button widget to a Python function and make the Python function call an external program via os.system() > Basically, I want to create a simple menu application for my wife (who's > been lost on this machine since I switched to Xfce4) Why not just give her a login using her preferred windowmanager? Thats what multi user operating systems are for - each user gets the environment they prefer! > but I like to keep it relatively clean. Besides, there's a problem that > needs solving, and I'd love to be able to do it myself, the way I want. The command parameter is your friend. Check my GUI topic on my tutorial which shows very simple use of Buttons and the command parameter. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythonTutor at venix.com Mon Jun 28 14:12:34 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Jun 28 14:12:59 2004 Subject: [Tutor] print formatting, length of string In-Reply-To: <20040628103153.H62269-100000@localhost.name> References: <20040628103153.H62269-100000@localhost.name> Message-ID: <1088446354.13272.81.camel@laptop.venix.com> Totally untest, but (hopefully) close> def formatListOfRecordDicts(listOfRecordDicts, showKeyList=None): if showKeyList is None: showKeyList = listOfRecordDicts[0].keys() # fails empty keylen = max([len(k) for k in showKeyList]) for i,recordDict in enumerate(listOfRecordDicts): print "**** %s. row *****" % (i+1) for k in showKeyList: On Mon, 2004-06-28 at 13:40, tpc@csua.berkeley.edu wrote: > > def formatListOfRecordDicts(listOfRecordDicts): > count = 0 > for recordDict in listOfRecordDicts: > count += 1 > print "*************************** % s. row ***************************" % count > print " First_Name:", recordDict['First_Name'] > print " Last_Name:", recordDict['Last_Name'] > print "Address_Line1:", recordDict['Address_Line1'] > > > and as you can imagine I'd have to rewrite it if and when I decide to pull > out a different set of data from my database. Is there a more elegant way > of doing this ? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From pythonTutor at venix.com Mon Jun 28 14:24:35 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Jun 28 14:24:46 2004 Subject: [Tutor] print formatting, length of string In-Reply-To: <20040628103153.H62269-100000@localhost.name> References: <20040628103153.H62269-100000@localhost.name> Message-ID: <1088447075.13272.95.camel@laptop.venix.com> (complete this time. Earlier email was sent by accident.) def formatListOfRecordDicts(listOfRecordDicts, showKeyList=None): if showKeyList is None: showKeyList = listOfRecordDicts[0].keys() # fails on empty list keylen = max([len(k) for k in showKeyList]) for i,recordDict in enumerate(listOfRecordDicts): print "**** %s. row *****" % (i+1) for k in showKeyList: print "%*s: %s" % (keylen, k, recordDict[k]) Choosing the keys to print is now outside the function enumerate is used to count the dictionaries in the list the key list is scanned to determine the longest key The format operator is used to control the output width On Mon, 2004-06-28 at 13:40, tpc@csua.berkeley.edu wrote: > > def formatListOfRecordDicts(listOfRecordDicts): > count = 0 > for recordDict in listOfRecordDicts: > count += 1 > print "*************************** % s. row ***************************" % count > print " First_Name:", recordDict['First_Name'] > print " Last_Name:", recordDict['Last_Name'] > print "Address_Line1:", recordDict['Address_Line1'] > > > and as you can imagine I'd have to rewrite it if and when I decide to pull > out a different set of data from my database. Is there a more elegant way > of doing this ? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From project5 at redrival.net Mon Jun 28 14:56:13 2004 From: project5 at redrival.net (Andrei) Date: Mon Jun 28 14:56:43 2004 Subject: [Tutor] Re: boa help? References: <20040628154258.32724.qmail@web60109.mail.yahoo.com> Message-ID: <1tixq0osj43qu$.5ge4pb7tque.dlg@40tude.net> Jeff Peery wrote on Mon, 28 Jun 2004 08:42:58 -0700 (PDT): > I'm using Boa constructor to make windows GUIs, I have it running on my labtop although it doesn't seem to be working on my desktop? I get this error message: > > "global name 'wx' is not defined" Do you have wxPython installed? -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From game at gameweave.com Mon Jun 28 15:07:44 2004 From: game at gameweave.com (K J) Date: Mon Jun 28 15:03:35 2004 Subject: [Tutor] Checking for int only Message-ID: <001801c45d43$32038520$30e57218@basp.phub.net.cable.rogers.com> How do you test for something to make sure that it is an int and not anything else so that when you ask them to enter a number they can only enter a number and not any other character. Thanks Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040628/2f8732f1/attachment.html From project5 at redrival.net Mon Jun 28 15:00:06 2004 From: project5 at redrival.net (Andrei) Date: Mon Jun 28 15:10:53 2004 Subject: [Tutor] Re: XRCed? References: <20040628152235.49684.qmail@web60105.mail.yahoo.com> Message-ID: <1ej7jjaegsbdt$.1ue9alv7q3dvi.dlg@40tude.net> Jeff Peery wrote on Mon, 28 Jun 2004 08:22:35 -0700 (PDT): > I was checking out the XRCed program, and I am unfamiliar >with XML... this is a markup language for web browsers? Is It's a markup language for anything. You can view it in browser, but it's not necessarily aimed at browsers; you can store arbitrary data for arbitrary purposes in XML. >the XRCed a GUI builder for XML? Can someone give me a brief >intro to this thing. thanks. XRCed is a tool which generates an XML file that can be used to show wxPython interfaces. The XML is simply the data format in which a sort of description is stored of the elements your wxPython UI has. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Mon Jun 28 15:13:30 2004 From: project5 at redrival.net (Andrei) Date: Mon Jun 28 15:20:53 2004 Subject: [Tutor] Re: Checking for int only References: <001801c45d43$32038520$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <2dhibfyw96pw$.1dhp76kzfves3$.dlg@40tude.net> K J wrote on Mon, 28 Jun 2004 15:07:44 -0400: > How do you test for something to make sure that it is an int and not anything else > so that when you ask them to enter a number they can only enter a number and > not any other character. Use try-except: while True: number = raw_input('Integer: ') try: number = int(number) # will fail if the input is non-numerical break # stop endless loop except: # int() failed -> not an integer print ' That was not an integer.' Above is assuming that you mean 'integer' when you write 'number'. If you mean to include floats, try float() instead of int(). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From game at gameweave.com Mon Jun 28 17:21:31 2004 From: game at gameweave.com (K J) Date: Mon Jun 28 17:17:22 2004 Subject: [Tutor] Re: Checking for int only References: <001801c45d43$32038520$30e57218@basp.phub.net.cable.rogers.com> <2dhibfyw96pw$.1dhp76kzfves3$.dlg@40tude.net> Message-ID: <000501c45d55$e2777760$30e57218@basp.phub.net.cable.rogers.com> I tried what you said and it work good but when you picked a different char other than an int it would just say Please choose an number: and if you messed up twice then it would say that is not an option. So I did some fooling around with it and came up with this so that it will say that is not an option the first time. So thanks for the help. number = raw_input("Please choose an number: ") while True: try: number = int(number) break except: print ' That is not an option.' number = raw_input("Please choose an number: ") ----- Original Message ----- From: Andrei To: Sent: Monday, June 28, 2004 3:13 PM Subject: [Tutor] Re: Checking for int only > K J wrote on Mon, 28 Jun 2004 15:07:44 -0400: > > > How do you test for something to make sure that it is an int and not anything else > > so that when you ask them to enter a number they can only enter a number and > > not any other character. > > Use try-except: > > while True: > number = raw_input('Integer: ') > try: > number = int(number) # will fail if the input is non-numerical > break # stop endless loop > except: # int() failed -> not an integer > print ' That was not an integer.' > > Above is assuming that you mean 'integer' when you write 'number'. If you > mean to include floats, try float() instead of int(). > > -- > Yours, > > Andrei > > ===== > Real contact info (decode with rot13): > cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq > gur yvfg, fb gurer'f ab arrq gb PP. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From fant at pobox.com Mon Jun 28 18:02:30 2004 From: fant at pobox.com (Andrew Fant) Date: Mon Jun 28 18:02:38 2004 Subject: [Tutor] remote directory verification in python Message-ID: <112060000.1088460150@flux.usg.tufts.edu> Good evening, I am working on a launcher script that will start a process on a remote system for a user. I would like to be able to check and see if the cwd exists on the remote host, and if so, start the remote process in that directory. Otherwise, I will just print a notification and start the process in $HOME. Does anyone have any code snippets that would demonstrate a reasonable way to do this with python? The systems will need to communicate via SSH, but they are configured with public/private keys that allow for passwordless connections. Thanks, Andy From alan.gauld at blueyonder.co.uk Mon Jun 28 18:37:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 18:37:05 2004 Subject: [Tutor] Question about dictionary method get() References: Message-ID: <001b01c45d60$75625a40$6401a8c0@xp> > Uh, oh. I just now tried print D.get("v") and did get "None". > Then why not with the plain D.get("v") ? Maybe I've found the > source of my confusion? Python has two methods __str__ and __repr__ that convert objects to strings. When you evaluate an object >>> x 42 You are calling __repr__ on x When you print an object >>> print x 42 You are calling the __str__ method of x. Often str and repr produce the same result but not always. None is an example of a difference. Notice too the difference when dealing with strings.... Alan G. From alan.gauld at blueyonder.co.uk Mon Jun 28 18:40:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 18:39:54 2004 Subject: [Tutor] Question about dictionary method get() References: <6081EBC21D52F744B484088BBBE665C3199F0D@sbserver.shaws.local> <6.1.2.0.2.20040628052641.0242c8a8@rcblue.com> Message-ID: <002801c45d60$dab86e20$6401a8c0@xp> > How do I "check for or propagate" None? foo = dct.get('x') if foo is None: # do something here HTH Alan G From alan.gauld at blueyonder.co.uk Mon Jun 28 18:55:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 18:54:52 2004 Subject: [Tutor] print formatting, length of string References: <20040628103153.H62269-100000@localhost.name> Message-ID: <006901c45d62$f0ea1f70$6401a8c0@xp> > In other words, I want my colons to line up. The code I have so far is a > kludge: > Check out format strings. You can specify the minimum length of a field using a format specifier, and whether it is right or lefdt justified. That should do what you want. Alan G From alan.gauld at blueyonder.co.uk Mon Jun 28 18:58:28 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jun 28 18:58:18 2004 Subject: [Tutor] Checking for int only References: <001801c45d43$32038520$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <007701c45d63$6ce44060$6401a8c0@xp> > How do you test for something to make sure that it is an int > and not anything else so that when you ask them to enter a > number they can only enter a number and not any other character. One of the Python mantras is that its better to ask forgiveness than permisssion. Try converting it to an int() if that doesn't work get them to try again: try: val = int(raw_input(....)) except ValueError: print "Couldn't read that as a number, try again... HTH Alan G From game at gameweave.com Tue Jun 29 01:51:35 2004 From: game at gameweave.com (K J) Date: Tue Jun 29 01:47:22 2004 Subject: [Tutor] Return to main menu Message-ID: <001001c45d9d$23ee87a0$30e57218@basp.phub.net.cable.rogers.com> Well this is the little program that I have created it is my first one and it works just fine from what I have tested. Only problem I have with it is that, lets say you enter 1 at the prompt it will load the add.py modual. however when it comes to the end of the modual it terminats. How would I go about making it so that it will return to the menu and ask for another choice. Kevin print """ 0 Exit 1 Add 2 Subtract """ number = raw_input("Enter a number: ") while 1: try: number = int(number) break except ValueError: print "That is not an option" number = raw_input("Enter a number: ") if int(number) == 1: import add if int(number) == 2: import subtract -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040629/6a34827c/attachment.html From Dragonfirebane at aol.com Tue Jun 29 02:07:05 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jun 29 02:07:20 2004 Subject: [Tutor] Return to main menu Message-ID: In a message dated 6/29/2004 1:48:01 AM Eastern Standard Time, game@gameweave.com writes: Well this is the little program that I have created it is my first one and it works just fine from what I have tested. Only problem I have with it is that, lets say you enter 1 at the prompt it will load the add.py modual. however when it comes to the end of the modual it terminats. How would I go about making it so that it will return to the menu and ask for another choice. Kevin print """ 0 Exit 1 Add 2 Subtract """ number = raw_input("Enter a number: ") while 1: try: number = int(number) break except ValueError: print "That is not an option" number = raw_input("Enter a number: ") if int(number) == 1: import add if int(number) == 2: import subtract just put the entire thing within a while loop and put a break or change the condition (from True to False) if they select exit, like so: a = True while a: print """ 0 Exit 1 Add 2 Subtract """ number = raw_input("Enter a number: ") while 1: try: number = int(number) break except ValueError: print "That is not an option" number = raw_input("Enter a number: ") if int(number) == 0: a = False if int(number) == 1: import add if int(number) == 2: import subtract by the way: you can just as easily make the menu be part of the number prompt like so: number = raw_input("""Enter a number: 1: Add 2: Subtract 3: Exit ... """) using the above code, you'd have to change the program so that it read: a = True while a: number = raw_input("""Enter a number: 1: Add 2: Subtract 3: Exit ... """) while 1: try: number = int(number) break except ValueError: print "That is not an option" number = raw_input("Enter a number: ") if int(number) == 1: import add if int(number) == 2: import subtract if int(number) == 3: a = False HTH, Orri Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040629/cc84ece4/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Tue Jun 29 02:29:47 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jun 29 02:29:54 2004 Subject: [Tutor] Return to main menu [use functions to collect related statements together, not modules] In-Reply-To: <001001c45d9d$23ee87a0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: On Tue, 29 Jun 2004, K J wrote: > Well this is the little program that I have created it is my first one > and it works just fine from what I have tested. Only problem I have with > it is that, lets say you enter 1 at the prompt it will load the add.py > modual. however when it comes to the end of the modual it terminats. How > would I go about making it so that it will return to the menu and ask > for another choice. Hi Kevin, Ah, I see. It looks like you're using module import to try to execute another program. You have the right idea, but it'll only work once, because of the way that Python avoids reading the same module twice. You'll notice this problem if you change your main program to something really simple like: ### import add import add import add ### The program that's in 'add' will execute the first time... and do absolutely squat for the next two import statements. *grin* The issue is that the program above is trying to use modules to execute a bunch of statements together, but that's not exactly what they supposed to be used for. Instead, we should be using a "function": functions are the basic tools for grouping a bunch of program statements together. Here's an example of a function: ### >>> def sayHello(): ... print "hello world" ... >>> sayHello() hello world >>> def sayHelloTwice(): ... sayHello() ... sayHello() ... >>> sayHelloTwice() hello world hello world ### The 'def' here allows us to create a named function, and we define what should happen when we call the function. If you put everything that's in your 'add' module, and move it into a function, then your program should behave the way that you expect. (Just for your information: modules are used to group related functions together, so it's just a different kind of grouping than the one you were expecting.) I feel that functions are more fundamental than modules, so I'd recommend learning them cold; they'll serve you well. If you want to learn more about functions, you may find something like 'How to Think Like a Computer Scientist' useful: http://www.ibiblio.org/obp/thinkCSpy/chap03.htm The other tutorials on: http://www.python.org/topics/learn/non-prog.html also should cover functions; feel free to ask questions about them here. Hope this helps! From bvande at po-box.mcgill.ca Tue Jun 29 02:38:16 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Jun 29 02:39:39 2004 Subject: [Tutor] Return to main menu In-Reply-To: <001001c45d9d$23ee87a0$30e57218@basp.phub.net.cable.rogers.com> References: <001001c45d9d$23ee87a0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <40E10E58.6070804@po-box.mcgill.ca> K J said unto the world upon 29/06/2004 01:51: K J said unto the world upon 29/06/2004 01:51: > Well this is the little program that I have created it is my first one > and it works just fine from what I have tested. Only problem I have > with it is that, lets say you enter 1 at the prompt it will load the > add.py modual. however when it comes to the end of the modual it > terminats. How would I go about making it so that it will return to the > menu and ask for another choice. > > Kevin > > print """ > 0 Exit > 1 Add > 2 Subtract > > """ > number = raw_input("Enter a number: ") > > while 1: > try: > number = int(number) > break > except ValueError: > print "That is not an option" > number = raw_input("Enter a number: ") > if int(number) == 1: > import add > if int(number) == 2: > import subtract > > Hi Keven, A few things strike this relative newbie: 1) You probably intend the "if int(number) ==" blocks to be nested into the while loop. (I assume you want to do something with the first choice before asking for another one.) 2) If I am right in thinking that you will want to nest the conditional blocks, you will have to do something about the imports. (You can only import a module once per program run; afterwards you have to reload it.) 3) More importantly, it breaks out of the loop because you told it to ;-) (The best thing about computers is they do exactly what you tell them to. The worst thing about computers is they do exactly what you tell them to.) Try replacing the "break" with "continue"; that will keep you in the loop, but not keep asking the user for input. It won't hit the imports either if you indent them. And even if you don't, it won't be having any real effect, as the loop would then continue on its own, anyway. So, better still, remove it entirely. 3) To reprint the menu, put your menu-printing code into a function definition and call that just before number = int(number). I'd also put the "is the input an integer" testing logic into a function. 4) Then, you'd have a while loop which asked for input via your menu and input function, tested it for being an integer and re-requested if not, reloaded the modules as requested and then after they finished went back to the top of the while loop and called the menu function again. 5) If I am right in thinking that you will want to nest the conditional blocks, you will have to do something about the imports. (You can only import a module once per program run; afterwards you have to reload it.) Functions are your friends :-) You typed "number = raw_input("Enter a number: ")" twice. Try this at the start of your code instead: def ask(): input = raw_input("Enter a number: ") return input now you can just type: number = ask() Expand that function to run the test on the input too, and you are on your way. And I see Orri beat me to posting; so this might be redundant in places. Oh well. Best to all, Brian vdB From project5 at redrival.net Tue Jun 29 02:37:50 2004 From: project5 at redrival.net (Andrei) Date: Tue Jun 29 02:40:52 2004 Subject: [Tutor] Re: Checking for int only References: <001801c45d43$32038520$30e57218@basp.phub.net.cable.rogers.com> <2dhibfyw96pw$.1dhp76kzfves3$.dlg@40tude.net> <000501c45d55$e2777760$30e57218@basp.phub.net.cable.rogers.com> Message-ID: K J gameweave.com> writes: > I tried what you said and it work good but when you picked a different char > other than an int it would just say Please choose an number: and if you How can my solution possibly say "Please choose a number" when that string doesn't even apppear in the code? Here's an interactive session I did with my code: Integer: sdfwefafe That was not an integer. Integer: waefawef That was not an integer. Integer: 3.324 That was not an integer. Integer: .23423 That was not an integer. Integer: 3 >>> > messed up twice then it would say that is not an option. So I did some It instructs you that the input is incorrect regardless of how many attempts you do, see demonstration above. I'm not sure what code you have been running, but it doesn't seem to be the one I posted. Are you sure you copied it correctly? > fooling around with it and came up with this so that it will say that is not > an option the first time. > So thanks for the help. > > number = raw_input("Please choose an number: ") > > while True: > try: > number = int(number) > break > except: > print ' That is not an option.' > number = raw_input("Please choose an number: ") Your solution is basically another way of writing exactly what I did, with the added disadvantage of having to maintain the prompt string "please blabla..." in two different places. The solution effectively combines the disadvantage of an endless 'while True' loop (being the necessity to use "break", which has arguable obsfucational qualities) with the disadvantage of a non-endless loop (being that it requires initialization and therefore maintenance of a certain piece of code in two different places). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5 jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. > > Use try-except: > > > > while True: > > number = raw_input('Integer: ') > > try: > > number = int(number) # will fail if the input is non-numerical > > break # stop endless loop > > except: # int() failed -> not an integer > > print ' That was not an integer.' > > > > Above is assuming that you mean 'integer' when you write 'number'. If you > > mean to include floats, try float() instead of int(). From johnnie.blom at protang.se Tue Jun 29 02:41:29 2004 From: johnnie.blom at protang.se (Johnnie Blom) Date: Tue Jun 29 02:41:37 2004 Subject: [Tutor] boa help? Message-ID: <200406290641.i5T6fTX11971@d1o270.telia.com> >I'm using Boa constructor to make windows GUIs, I have it running on my >labtop although it doesn't seem to be working on my desktop? I get this >error message: > >"global name 'wx' is not defined" > >thanks! > >Jeff You can't use boa on the latest release of wxpython, go back one step. Johnnie Blom From dyoo at hkn.eecs.berkeley.edu Tue Jun 29 02:46:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jun 29 02:47:05 2004 Subject: [Tutor] (IOError: [Errno 9] Bad file descriptor) in IDLE (wrong mailing list?) [sending good error reports to idle-dev] In-Reply-To: <50.2de54c10.2e11ae01@aol.com> Message-ID: On Mon, 28 Jun 2004 Dragonfirebane@aol.com wrote: > I'm unsure where to submit this, but there appears to be an error with > IDLE. Every so often when i run a module (not a particular one), this > comes up and i have to run it again: > > >>> Exception in Tkinter callback > Traceback (most recent call last): > File "C:\PROGRA~1\PYTHON~1.4C1\lib\lib-tk\Tkinter.py", line 1345, in > __call__ > return self.func(*args) [traceback cut] Hi Orri, Ok. Send that traceback in the direction of the IDLE developers at: http://mail.python.org/mailman/listinfo/idle-dev My initial impressions is that this is an legitimate IDLE bug; you should never see errors like this as a user. When you send the traceback to idle-dev, mention what version of Python you've installed. From the traceback, I'm guessing that you're running Python 2.3.4 RC1, which is actually a "release candidate". Can you see if the same buggy behavior happens with the official 2.3.4 final release? Also, show the IDLE developers the module that you're trying to run through IDLE, at the point where IDLE goes haywire. It may provide the developers a clue as to why it's doing nuts. As far as I can tell, from the traceback, > return compile(source, filename, "exec") > File "C:\PROGRA~1\PYTHON~1.4C1\lib\warnings.py", line 116, in warn_explicit > showwarning(message, category, filename, lineno) > File "C:\PROGRA~1\PYTHON~1.4C1\lib\idlelib\PyShell.py", line 55, in > idle_showwarning > file.write(warnings.formatwarning(message, category, filename, lineno)) > IOError: [Errno 9] Bad file descriptor that here, IDLE was right in the middle of trying to send a warning message about your module code... but then it itself broke right in the middle of the error reporting. Slightly embarassing. *grin* Your code may help to highlight a bug in IDLE, so it would be invaluable to include your program in your report. Good luck! From dyoo at hkn.eecs.berkeley.edu Tue Jun 29 03:30:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jun 29 03:30:42 2004 Subject: [Tutor] Question about order in a dictionary [how does hashing work?] In-Reply-To: <40E0275F.3050507@po-box.mcgill.ca> Message-ID: > I'm comfortable with mathematics, but not a computer scientist by any > means. I've been wanting to learn about the details of hashtables > (meaning of the term, how implemented, why allowing for faster search, > etc.). Does anyone know of a good presentation that gets the details > covered correctly, but doesn't presuppose that I am at least halfway > through a comp sci BSc? Hi Brian, I wrote an introduction to hashing a long long time ago: http://mail.python.org/pipermail/tutor/2002-January/011281.html But I guess it can't hurt to rehash hashing. *grin* The core idea is that list lookup is really really fast as long as we're dealing with numeric indices. Conceptually, a Python list is a bunch of key-value pairs. When we see: ["zero", "one", "two", "three", "four", "five"] we might imagine that this list represents the same kind of information as the following dictionary: { 0 : "zero", 1 : "one", 2 : "two", 3 : "three", 4 : "four", 5 : "five" } where the "key" part is implied by the index of our list. So lists are excellent for key/value lookup, when our keys are small numbers. Let's make the problem concrete. The list: ### >>> words = ["zero", "one", "two", "three", "four", "five"] ### makes it really easy for us to go from a single digit to its English transliteration: ### >>> words[0] 'zero' >>> words[4] 'four' ### But if our keys aren't numbers, what can we do? What if we want to go the other way? That is, given a word like 'five', is it easy to get back the number 5? Yes, if we're willing to do a search across our list: ### >>> words.index('five') 5 ### The only problem with this approach is that it's doing a linear scan across the list. We can do better than that. Hashing is an approach that uses a "hash" function. This "hash" function transforms a key directly into an integer value, which we then use as an index into some mangled-up list. Python comes with a hash builtin() already: ### >>> words = ["zero", "one", "two", "three", "four", "five"] >>> for w in words: ... print w, hash(w) ... zero -1293135726 one -261223665 two 323309869 three 1505609005 four -1250885616 five 202874452 ### But these are wild looking numbers. *grin* Let's make them look a little nicer by using the remainder "modulo" operator: ### >>> for w in words: ... print w, hash(w), hash(w) % 11 ... zero -1293135726 8 one -261223665 1 two 323309869 3 three 1505609005 10 four -1250885616 9 five 202874452 0 ### (Ignore the magic constant 11 for a moment: we'll revisit it in a moment.) Notice that the third column contains numbers that are all distinct. This is neat because, suddenly, we can do something like this: ### >>> for index, word in enumerate(words): ... hashed_values[hash(word) % 11] = index ... >>> hashed_values [5, 1, None, 2, None, None, None, None, 0, 4, 3] >>> >>> >>> hashed_values[hash('one') % 11] 1 >>> hashed_values[hash('three') % 11] 3 >>> hashed_values[hash('zero') % 11] 0 ### And now we have a fast scheme where we can go back from our arbitrary string key back to our value. No linear scan necessary: just a little bit of arithmetic. And that's what dictionaries do underneath the surface: they maintain a intermediate list --- a "hash table" --- where the elements are scattered around in some wacky order based on the key hash value. Since keys will hash() to a predictable number, when we want to look up a key/value pair later on, we get to later use hash() again, and take advantage of the speed of numeric indxed lookup on that intermediate list. Going back to that magic number: '11' here was cheating. *grin* It's a magic constant number I just pulled out of thin air, and it was chosen for this example just to make all the values distinct. If we chose a smaller constant, we would have gotten not-so-nice results: ### >>> for w in words: ... print w, hash(w), hash(w) % 3, hash(w) % 5, hash(w) % 7, hash(w) % 11 ... zero -1293135726 0 4 6 8 one -261223665 0 0 4 1 two 323309869 1 4 1 3 three 1505609005 1 0 5 10 four -1250885616 0 4 6 9 five 202874452 1 2 4 0 ### Eleven seemed to be the right number here. But real hashing usually doesn't have the benefit of hindsight, so hashtables will often have to deal with the possible situation where two keys will "collide" together with the same hash value. A lot of computer science algorithm books will talk about different ways of resolving hash collisions, but we probably don't need to talk about them here right now. These collision resolution systesm have names like "linear chaining" or "linear probing", both of which sound slightly painful. *grin* They're actually not that bad, but this introduction is already too long. Does the idea of hashing make more sense now? This should make it more clear why the keys in a hash table don't appear to be ordered: they're deliberately scrambled by the hashing function. Hope this helps! From alipolatel at yahoo.com Tue Jun 29 03:38:52 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Tue Jun 29 03:38:57 2004 Subject: [Tutor] problem with format Message-ID: <20040629073852.44475.qmail@web61005.mail.yahoo.com> Friends I have downloaded a calculator programme written in python from www.hotscripts.com ... When I open it with python I can only see its codes but I want to run the programme.How can i do this? Regards, --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040629/e9a60add/attachment.html From dyoo at hkn.eecs.berkeley.edu Tue Jun 29 04:10:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jun 29 04:10:11 2004 Subject: [Tutor] Question about dictionary method get() In-Reply-To: <6.1.2.0.2.20040628083753.024004a0@rcblue.com> Message-ID: > Thanks very much again, Francis. Very clear, except for my not understanding > > if __name__ == '__main__': > func() > > But that's OK. I'll get to that later. Hi Dick, Ah. Unwritten community knowledge. *grin* Take a look at: http://diveintopython.org/getting_to_know_python/testing_modules.html which explains that construct in detail. Here's a three-sentence overview: When a Python program file is executed directly, a special variable called '__name__' is set to the string "__main__". The same program file, however, can be used as a module too, and on an 'import', the '__name__' ends up being something else. So the 'if' statement above lets us do something different if the program is being run directly, as opposed to being imported. Hope this helps! From project5 at redrival.net Tue Jun 29 15:41:19 2004 From: project5 at redrival.net (Andrei) Date: Tue Jun 29 15:41:44 2004 Subject: [Tutor] Re: problem with format References: <20040629073852.44475.qmail@web61005.mail.yahoo.com> Message-ID: <1fqrft5qca8m8$.1k9lxhrqg1unr$.dlg@40tude.net> Ali Polatel wrote on Tue, 29 Jun 2004 00:38:52 -0700 (PDT): > Friends I have downloaded a calculator programme written in python > from www.hotscripts.com ... When I open it with python > I can only see its codes but I want to run the programme. > How can i do this? You have not opened it in Python if you can see the code. You have opened it in some text editor (perhaps IDLE, the default Python editor that comes with every Python distro?). If you've opened it in Idle, go and look for the Run menu option (press F5). If you've opened it in some other text editor, try double-clicking on it in Explorer. If that doesn't work, make a new plain text file in the same directory as that calculator, call it "run.bat" and open it in Notepad. Write in it: start "c:\python23\pythonw.exe" calc.py (replace the python23 path to the path where you installed python and calc.py with whatever the name of that calculator is). Save the changes and then double-click on it. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jeffpeery at yahoo.com Wed Jun 30 00:29:20 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed Jun 30 00:29:25 2004 Subject: [Tutor] help with regular expressions Message-ID: <20040630042920.32887.qmail@web60102.mail.yahoo.com> hello I am having trouble with using the re module. I have a statement: line = FileHandle.readline(-1) test = findall('\d', line) where "line" is a line of text from a file I would like to read and extract numbers from. the line is simply three numbers, example 3.444456 4 84.3546354. I want to put these number in "test" but the findall expression seems to only take whole numbers, so for example test would be for the above numbers [3, 4, 4, 4, 4, 5, 6, 4, 8, ....]. How is this done so that test = [3.444456 4 84.3546354]? thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040629/194bfb45/attachment.html From robinst at MIT.EDU Wed Jun 30 01:50:24 2004 From: robinst at MIT.EDU (Theresa Robinson) Date: Wed Jun 30 01:50:28 2004 Subject: [Tutor] Copying sequences of arbitrary dimension Message-ID: I'm trying to pad a sequence of arbitrary dimension with zeros in order to get a sequence of a given size. This is what I have so far, as an intermediate step. I know exactly why it doesn't work: because things in python get passed by value, not by reference. But can anyone suggest how I might want to tackle this? >>> def recursecopy(x,y): ... if type(x) is IntType: ... y=x ... else: ... for i in range(0,len(x)): ... recursecopy(x[i],y[i]) ... >>> recursecopy(x=A,y=B) >>> A [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> B [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] From project5 at redrival.net Wed Jun 30 02:41:24 2004 From: project5 at redrival.net (Andrei) Date: Wed Jun 30 02:41:51 2004 Subject: [Tutor] Re: Copying sequences of arbitrary dimension References: Message-ID: Theresa Robinson MIT.EDU> writes: > I'm trying to pad a sequence of arbitrary dimension with zeros in order to > get a sequence of a given size. This is what I have so far, as an > intermediate step. I know exactly why it doesn't work: because things in > python get passed by value, not by reference. But can anyone suggest how No they aren't. The distinction is between mutable objects and immutable objects. Lists and dictionaries are mutable objects, while tuples, strings and all kinds of numbers are immutable objects. >>> def modifylist(alist): ... alist.append(5) ... >>> def modifyint(aint): ... aint += 5 ... >>> l = [1,2] >>> modifylist(l) >>> print l [1, 2, 5] >>> i = 2 >>> modifyint(i) >>> i 2 As you can see, modifyint doesn't really modify the int at all, since ints are immutable. Instead, a new integer object is created. If we expand this example to follow what's going on: >>> def modifyint(aint): ... print id(aint) ... aint += 5 ... print id(aint) ... >>> id(i) 7693072 >>> modifyint(i) 7693072 <- same as id(i), so we have two names bound to the same integer object 7701072 <- different id, meaning different object (IOW, it 'points' to a different object now) >>> id(i) 7693072 <- i is still unmodified > I might want to tackle this? > > >>> def recursecopy(x,y): > ... if type(x) is IntType: > ... y=x At this point you've passed an integer object to the function and you can't modify it. You should write the function in such a way that you operate on a list, not on an integer. Yours, Andrei From rdm at rcblue.com Wed Jun 30 05:13:16 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jun 30 05:13:16 2004 Subject: [Tutor] IDLE question Message-ID: <6.1.2.0.2.20040630015549.022d6840@rcblue.com> I'm trying to enter >>>if D.has_key("b"): print "yes" else: print "no" in IDLE v1.0.3. by typing it in, line by line. lines 1 and 2 go OK, but hitting "Enter" after "yes" causes the cursor to move to just under the "p" of "print", as expected. If I use the Backspace key and the space bar to line up and indent "else:" correctly, hitting Enter after that causes the error, "IndentationError: unindent does not match any outer indentation level (, line 3)". Is there no way to get this entered other than typing the 4 lines in a text editor and pasting them all together into IDLE? This is not an idle question. It's really been bugging me. ;-) Thanks, Dick Moores From olavi at city.ee Wed Jun 30 05:20:03 2004 From: olavi at city.ee (Olavi Ivask) Date: Wed Jun 30 05:21:45 2004 Subject: [Tutor] IDLE question In-Reply-To: <6.1.2.0.2.20040630015549.022d6840@rcblue.com> References: <6.1.2.0.2.20040630015549.022d6840@rcblue.com> Message-ID: <40E285C3.1030603@city.ee> after print "yes" press "Enter", and then "Backspace".do not use spacebar here. Then it's correct >>>if D.has_key("b"): print "yes" else: print "no" Olavi ivask Dick Moores wrote: > I'm trying to enter > > >>>if D.has_key("b"): > print "yes" > else: > print "no" > > in IDLE v1.0.3. by typing it in, line by line. lines 1 and 2 go OK, > but hitting "Enter" after "yes" causes the cursor to move to just > under the "p" of "print", as expected. If I use the Backspace key and > the space bar to line up and indent "else:" correctly, hitting Enter > after that causes the error, "IndentationError: unindent does not > match any outer indentation level (, line 3)". Is there no > way to get this entered other than typing the 4 lines in a text editor > and pasting them all together into IDLE? > > This is not an idle question. It's really been bugging me. ;-) > > Thanks, > > Dick Moores > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Wed Jun 30 06:05:30 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jun 30 06:05:48 2004 Subject: [Tutor] IDLE question Message-ID: <6.1.2.0.2.20040630030445.0241a010@rcblue.com> Olavi Ivask wrote at 02:20 6/30/2004: >after print "yes" press "Enter", and then "Backspace".do not use >spacebar here. >Then it's correct > > >>>if D.has_key("b"): > print "yes" >else: > print "no" > > >Olavi ivask Thanks! (Looks terrible, but it works.) Dick From bgailer at alum.rpi.edu Wed Jun 30 08:20:20 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Jun 30 08:21:54 2004 Subject: [Tutor] help with regular expressions In-Reply-To: <20040630042920.32887.qmail@web60102.mail.yahoo.com> References: <20040630042920.32887.qmail@web60102.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040630061856.03ed5dc8@mail.mric.net> At 10:29 PM 6/29/2004, Jeff Peery wrote: >hello I am having trouble with using the re module. I have a statement: > >line = FileHandle.readline(-1) >test = findall('\d', line) > >where "line" is a line of text from a file I would like to read and >extract numbers from. the line is simply three numbers, example >3.444456 4 84.3546354. I want to put these number in "test" but the >findall expression seems to only take whole numbers, so for example test >would be for the above numbers [3, 4, 4, 4, 4, 5, 6, 4, 8, ....]. How is >this done so that test = [3.444456 4 84.3546354]? >>> re.findall(r'\d+.?\d*', '3.444456 4 84.3546354') ['3.444456', '4 ', '84.3546354'] \d+ -> one or more digits .? -> zero or 1 period \d* -> zero or more digits Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From atyss4si at hotmail.com Wed Jun 30 12:11:53 2004 From: atyss4si at hotmail.com (Bernard Lebel) Date: Wed Jun 30 12:13:26 2004 Subject: [Tutor] New Python user on board Message-ID: Hello, I wish to introduce myself, it is my first post on this mailing list. My name is Bernard Lebel, I'm from Montreal (Canada). I currently work in Marseille, France, as a rendering technical director (we are doing a full 3D animation feature film called "Magic Roundabout"). I'm already a JScript user and know VBScript to some capacity, because these two and Python (ActiveX enabled) are available in SOFTIMAGE|XSI (as well as PerlScript), the 3D animation software I use. At this point I'm very new to Python but I have read the tutorial in the documentation, it seems very promising. At this moment I'm mainly looking into Python to in hopes to develop a rendering management software. I apoligize in advance for the tons of newbie questions that will follow, and thank you in advance for your time. Bye Bernard From karthik at james.hut.fi Wed Jun 30 12:16:40 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Wed Jun 30 12:16:44 2004 Subject: [Tutor] Fastest way to write/read numerical data into/from a file? Message-ID: Hi All, i have written a module that saves matrices in a file. Basically, a matrix as A = numarray.array([1,2]) will be saved as 1 2 in the file, and A = numarray.array([[1,2],[3,4]]) as 1 2 3 4 i.e each row is a line and there are spaces between each column. Presntly, when writing i do the following: try: i,j = data.shape for ii in range(0,i): for jj in range(0,j): value = "%s" %data[ii,jj] file.write(value) file.write(' ') file.write('\n') except ValueError: i = data.shape for ii in range(0,i): value = "%s" %data[ii] file.write(value) file.write(' ') file.write('\n') Here, i am doing an element by element access, how can i speed this up? While reading, i do the following: while(line): temp = [] list = string.split(line) for e in list: temp.append(string.atof(e)) x = numarray.concatenate(x,numarray.array(temp)) line = open1.readline() open1.close() So, while reading, i read a complete line, which i guess is faster, any suggestions on improving the speed esp when i am writing to the file. With warm regards karthik ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From project5 at redrival.net Wed Jun 30 14:02:49 2004 From: project5 at redrival.net (Andrei) Date: Wed Jun 30 14:03:16 2004 Subject: [Tutor] Re: Fastest way to write/read numerical data into/from a file? References: Message-ID: Karthikesh Raju wrote on Wed, 30 Jun 2004 19:16:40 +0300: > i have written a module that saves matrices in a file. Basically, a > matrix as > A = numarray.array([1,2]) will be saved as 1 2 in the file, and > A = numarray.array([[1,2],[3,4]]) as > 1 2 > 3 4 I've never used numarray, so I'll just assume there's no built-in method which does this for you :). > i.e each row is a line and there are spaces between each column. > Presntly, when writing i do the following: > > try: > i,j = data.shape > for ii in range(0,i): > for jj in range(0,j): > value = "%s" %data[ii,jj] > file.write(value) > file.write(' ') Don't use "file" as a variable name - you're overwriting a built-in. It would be better to write value = "%s " and drop the write(' '). It probably also wouldn't hurt to skip the value assignment and do the formatting inside the write() method. Otherwise the solution is OK and doesn't seem wasteful in any way. Any idea what the bottleneck is? I/O, the loops or data lookup? If it's the first or the last, I don't see how you can save any time. For the second, you could put it in a list comprehension, but I'm not sure how much of a speed boost that would provide: for ii in range(0, i): [afile.write("%s " % data[ii, jj]) for jj in range(0, j)] afile.write("\n") You could also try iterating directly over the array if numarray supports it - again, not sure how much of a boost it would give: for row in data: [afile.write("%s " % row[jj] for jj in range(j))] afile.write("\n") Or you could go really to the extreme and try this (I've split the list comprehension up over a couple of lines in an attempt to make it slightly more readable - didn't really work :) ): i, j = data.shape ilist = range(i) jlist = range(j) afile.write("\n".join([ " ".join([ str(data[ii, jj]) for jj in jlist ]) for ii in ilist ])) This might consume a lot of memory though - no idea how large your data is. > While reading, i do the following: > > while(line): Use "for line in myfile:" instead of the while loop combined with an explicit readline. > temp = [] > list = string.split(line) Don't use the string module. Use line.split() instead. > for e in list: temp.append(string.atof(e)) > x = numarray.concatenate(x,numarray.array(temp)) > line = open1.readline() > open1.close() How about this: nc = numarray.concatenate na = numarray.array for line in file('location.txt', 'r'): x = nc(x, na([ float(nr) for nr in line.split() ])) If numarray.array can handle more complex (nested) lists, you could also try to build up the entire list in-memory first (the opposite of what I propose for writing) and then convert the whole of it to array at once. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From duncan at mail-gw.estec.esa.int Wed Jun 30 12:20:13 2004 From: duncan at mail-gw.estec.esa.int (Duncan Gibson) Date: Wed Jun 30 14:14:14 2004 Subject: [Tutor] testing new style class properties using pyUnit ? Message-ID: <20040630162013.B73C62D5E@lorentz.thermal.esa.int> I had a class which used get and set methods to access a class variable. I set up some unit tests using pyUnit. After some fiddling about, I managed to get it all working. I've just upgraded the source to use the new style classes with properties instead of explicit get and set methods. However, so far I've been unable to convert the unit tests. I note the error message, but I don't understand why. I include a simple example below, showing the working tests with the old style classes, and the failing tests with the new style classes. [In fact it's worse than this because my real code uses class variables and classmethods, and I want to test the derived classes, but the principle is the same] Can anyone explain the magical incantation that I need to test the property setter? Cheers Duncan #-------------------------------------------------- #!/usr/bin/env python2.3 import unittest #-------------------------------------------------- class A_Old: def __init__(self, x=0): self.x = x def get_x(self): return self.x def set_x(self, x): assert isinstance(x, int) self.x = x #-------------------------------------------------- class A_New(object): __slots__ = ('__x',) def __init__(self, x=0): self.x = x def __get_x(self): return self.__x def __set_x(self, x): assert isinstance(x, int) self.__x = x x = property(__get_x, __set_x) #-------------------------------------------------- class Test_A_Old(unittest.TestCase): def testGet(self): a = A_Old() self.assertEqual(0, a.get_x()) def testSet(self): a = A_Old() self.assertEqual(0, a.get_x()) self.assertEqual(None, a.set_x(1)) self.assertEqual(1, a.get_x()) def testSetFail(self): a = A_Old() self.assertEqual(0, a.get_x()) self.assertRaises(AssertionError, a.set_x, 1.0) #-------------------------------------------------- class Test_A_New(unittest.TestCase): def testGet(self): a = A_New() self.assertEqual(0, a.x) def testSet(self): a = A_New() self.assertEqual(0, a.x) self.assertEqual(None, a.__set_x(1)) # AttributeError: 'A_New' object has no attribute '_Test_A_New__set_x' self.assertEqual(1, a.x) def testSetFail(self): a = A_New() self.assertEqual(0, a.x) self.assertRaises(AssertionError, a.__set_x, 1.0) # AttributeError: 'A_New' object has no attribute '_Test_A_New__set_x' #-------------------------------------------------- unittest.main() From dyoo at hkn.eecs.berkeley.edu Wed Jun 30 14:29:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jun 30 14:29:48 2004 Subject: [Tutor] Re: Fastest way to write/read numerical data into/from a file? In-Reply-To: Message-ID: On Wed, 30 Jun 2004, Andrei wrote: > Karthikesh Raju wrote on Wed, 30 Jun 2004 19:16:40 +0300: > > > i have written a module that saves matrices in a file. Basically, a > > matrix as > > A = numarray.array([1,2]) will be saved as 1 2 in the file, and > > A = numarray.array([[1,2],[3,4]]) as > > 1 2 > > 3 4 > > I've never used numarray, so I'll just assume there's no built-in method > which does this for you :). According to: http://stsdas.stsci.edu/numarray/numarray-0.9.html/node34.html and: http://stsdas.stsci.edu/numarray/numarray-0.9.html/node33.html there is a built-in method called 'tofile()' that does this for us. There's a corresponding 'fromfile()' function in the numarray package that goes the other way. See: http://www.stsci.edu/resources/software_hardware/numarray/userguide and look for the header "tofile and fromfile capability": there's an example of how to save numarray arrays to disk. Caveat: the files that tofile() generates are, unfortunately, platform specific, so if you need to ensure that the files can be read from any computer, we can't use the built-in file stuff. Hope this helps! From alan.gauld at blueyonder.co.uk Wed Jun 30 15:34:33 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 30 15:34:22 2004 Subject: [Tutor] problem with format References: <20040629073852.44475.qmail@web61005.mail.yahoo.com> Message-ID: <005301c45ed9$456f6920$6401a8c0@xp> > Friends I have downloaded a calculator programme written in > python from www.hotscripts.com ... When I open it with python > I can only see its codes but I want to run the programme.How can i do this? I suspect that when you say "open it in Python" you mean you are loading it into IDLE (aka "The Python GUI" - whoever came up with that menu item should be severely smacked about the head, it is a source of endless newbie confusion!). If so you should see a Run menu, you can simply select that and it will run. You should also be able to just double click the file in Windows Explorer (I'm assuming you are running Windows). If mny assumptions are wrong write back with more specific details. Alan G. From alan.gauld at blueyonder.co.uk Wed Jun 30 15:42:44 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 30 15:42:30 2004 Subject: [Tutor] help with regular expressions References: <20040630042920.32887.qmail@web60102.mail.yahoo.com> Message-ID: <006d01c45eda$69c1da50$6401a8c0@xp> > line = FileHandle.readline(-1) > test = findall('\d', line) > > where "line" is a line of text from a file I would like to read > and extract numbers Regular expressions process text, that is characters. Thus there is a difference between a digit and a number. A digit in a regular expression is a *character* that can be interpreted as a number. The regex has no concept of numbers in the mathematical sense, it simply sees these as groups of digits. > example test would be for the above numbers > [3, 4, 4, 4, 4, 5, 6, 4, 8, ....]. > How is this done so that test = [3.444456 4 84.3546354]? You probably don't need regular expressions here at all, since regex are best for extracting complex patterns out of complex test. In this case the string split() method wil likely work better. You can then convert the list of substrings into a list of numbers with the float() function: test = line.split() numbers = [float(n) for n in test] Or all in one line: numbers = [float(n) for n in line.split()] You may need to strip() whitespace off the line before applying split() too. Regex are powerful tools but using them where they aren't needed is a good way to make your programs hard to read! HTH, Alan G. From alan.gauld at blueyonder.co.uk Wed Jun 30 15:51:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 30 15:51:11 2004 Subject: [Tutor] IDLE question References: <6.1.2.0.2.20040630015549.022d6840@rcblue.com> Message-ID: <007401c45edb$a0275ec0$6401a8c0@xp> > I'm trying to enter > > >>>if D.has_key("b"): > print "yes" > else: > print "no" Why? It's not valid Python?! :-) > in IDLE v1.0.3. by typing it in, line by line. lines 1 and 2 go OK, but > hitting "Enter" after "yes" causes the cursor to move to just under the > "p" of "print", as expected. If I use the Backspace key and the space bar > to line up and indent "else:" But the else should not be indented, it lines up with the if. However a bug(at least I think its a bug!) in IDLE means that IDLE ignores the effect of the >>> proimpt and thinks the if is actually at the left margin, so your code needs to look like this: >>> if D.has_key("b"): print "yes" else: print "no" Which is what ISLE is trying to make you do but to a human it doesn't look right... > indentation level (, line 3)". Is there no way to get this > entered other than typing the 4 lines in a text editor and pasting them > all together into IDLE? Well you can use IDLE as that text editor by using File->NEw to create a new window.... But if you want to use the Pyhon prompt you are stuck with IDLEs weird behaviour. Oddly the DOS prompt doesn't do this because it adds ... on lines following the >>> to align everything properly! If you want a >>> prompt with the color coding and other bells of IDLE try the pyShell that comes with wxPython. It is now my preferred Python interactive prompt... Alan G. From rdm at rcblue.com Wed Jun 30 17:07:12 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jun 30 17:07:34 2004 Subject: [Tutor] IDLE question In-Reply-To: <007401c45edb$a0275ec0$6401a8c0@xp> References: <6.1.2.0.2.20040630015549.022d6840@rcblue.com> <007401c45edb$a0275ec0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040630134707.0452b960@rcblue.com> Alan Gauld wrote at 12:51 6/30/2004: > > I'm trying to enter > > > > >>>if D.has_key("b"): > > print "yes" > > else: > > print "no" > >Why? It's not valid Python?! :-) You mean because the indenting has shown up incorrectly in my email? I thought it might. Or do you mean I've used has_key() incorrectly? > > in IDLE v1.0.3. by typing it in, line by line. lines 1 and 2 go OK, >but > > hitting "Enter" after "yes" causes the cursor to move to just under >the > > "p" of "print", as expected. If I use the Backspace key and the >space bar > > to line up and indent "else:" > >But the else should not be indented, it lines up with the if. Yes, I had typed it in my email to line up with the if. >However a bug(at least I think its a bug!) in IDLE means that >IDLE ignores the effect of the >>> proimpt and thinks the if is >actually at the left margin, so your code needs to look like this: > > >>> if D.has_key("b"): > print "yes" >else: > print "no" > >Which is what ISLE is trying to make you do but to a human it >doesn't look right... > > > indentation level (, line 3)". Is there no way to get >this > > entered other than typing the 4 lines in a text editor and pasting >them > > all together into IDLE? > >Well you can use IDLE as that text editor by using File->NEw to create >a new window.... I've been doing this. I should have said I was trying to use IDLE's interactive prompt. >If you want a >>> prompt with the color coding and other bells of IDLE >try the pyShell that comes with wxPython. It is now my preferred >Python interactive prompt... To use the pyShell that comes with wxPython, I'd have to download and install and use all of wxPython, I suppose. I just read about wxPython on it's website, and I'm interested in what is said there about having the best GUI toolkit. But if I switch to wxPython, except for not using tkinter, will I be able to rely on the Python documentation, tutorials and books for learning Python? I'm guessing I can, but can you confirm this? Also, on the wxPython main page it says, "Welcome to the home of wxPython, a blending of the wxWidgets C++ class library with the Python programming language." Does this mean I'd have to know C++ to use the wxWidgets? Or is it the case that I would no more need to know C++ for wxPython than I need to know C to use Python. I'm running Windows XP Pro, and am currently using Python 2.3.4. Thanks, Dick Moores From alan.gauld at blueyonder.co.uk Wed Jun 30 18:23:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 30 18:23:28 2004 Subject: [Tutor] IDLE question References: <6.1.2.0.2.20040630015549.022d6840@rcblue.com> <007401c45edb$a0275ec0$6401a8c0@xp> <6.1.2.0.2.20040630134707.0452b960@rcblue.com> Message-ID: <007f01c45ef0$e6d4e350$6401a8c0@xp> > >Why? It's not valid Python?! :-) > > You mean because the indenting has shown up incorrectly in my email? the email formatting. > >Well you can use IDLE as that text editor by using File->NEw to create > >a new window.... > > I've been doing this. I should have said I was trying to use IDLE's > interactive prompt. We guessed because this is a common problem for newbies with Python. Which is why I think its a bug... maybe someday I'll get annoyed enough to see if I can find a way to patch it. :-) > >If you want a >>> prompt with the color coding and other bells of IDLE > >try the pyShell that comes with wxPython. It is now my preferred > >Python interactive prompt... > > To use the pyShell that comes with wxPython, I'd have to download and > install and use all of wxPython, I suppose. Not at all. I rarelyt use wxPython as a GUI framework I only use the tools that come with it. I prefer Tkinter, I find it easier to work with. wxPython is essentially a set of modules that you can use or not as you like. But it does include some nice tools with PyCrust and PyShell etc. > best GUI toolkit. But if I switch to wxPython, except for not using > tkinter, will I be able to rely on the Python documentation, tutorials > and books for learning Python? I'm guessing I can, but can you confirm this? Sure, you can still use IDLE if you like - I do sometimes for working with whole files and using the IDLE debugger. wxPython doesn't change Python itself just adds some new modules that you can imp[ort and use. It is a big download for just the tools, and you might find that Pythonwin gives you the same benefit(and every windows user should have the winall package installed!). If you only work in Windows I'd go there first but I use Windows, Linux and MacOS so IDLE/PyShell is a better solution. > programming language." Does this mean I'd have to know C++ to use the > wxWidgets? No, but some of the wxWindows documentation is in C++ and you need to read it to understand some bits of wxPython, at least until the Python documentation catches up with the C++ stuff. > Or is it the case that I would no more need to know C++ for > wxPython than I need to know C to use Python. Slightly more the case because the wxPython docs aren't complete yet. Occasionally you have to read the underlyiig C++ stiff, which you never need with standard Python. But if you don't use the wxPython GUI classes and stick with Tkinter then you don't need to worry! :-) Alan G. From pythontut at pusspaws.net Wed Jun 30 18:45:04 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed Jun 30 18:45:14 2004 Subject: [Tutor] strange listed nest behaviour Message-ID: <40E34270.90108@pusspaws.net> I have a problem with lists, As an example the following makes sense to me and works as I would expect ... >>> b=[[0,0,0,0],[0,0,0,0]] >>> b [[0, 0, 0, 0], [0, 0, 0, 0]] >>> b[1][1]=5 >>> b [[0, 0, 0, 0], [0, 5, 0, 0]] >>> However I have to set up a large data list, so I have used "self.startslot=[[float(0)]*110]*36" inside a class. This is supposed to give me 0-35 lists each containing 0-109 floating point 0's which I can index into & change at will. This dos not perform as expected and one write causes the same data to be written to multiple locations. A more managable example being ... >>> a=[[float(0)]*10]*4 >>> a [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]] >>> >>> a[1][1]=5 >>> >>> a [[0.0, 5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]] >>> Printing 'a' gives the generated list as I would expect, but trying to write to one individual 'location' causes multiple 'locations' to be written to. (This caused me a headache before I twigged I can tell you :-) ) It must be something to do with the list definition but I am at a loss as to what is happening. Can anyone tell me what I am doing wrong ? Cheers Dave From dyoo at hkn.eecs.berkeley.edu Wed Jun 30 19:04:09 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jun 30 19:04:25 2004 Subject: [Tutor] testing new style class properties using pyUnit ? In-Reply-To: <20040630162013.B73C62D5E@lorentz.thermal.esa.int> Message-ID: On Wed, 30 Jun 2004, Duncan Gibson wrote: > I had a class which used get and set methods to access a class variable. > I set up some unit tests using pyUnit. After some fiddling about, I > managed to get it all working. > > I've just upgraded the source to use the new style classes with > properties instead of explicit get and set methods. However, so far I've > been unable to convert the unit tests. I note the error message, but I > don't understand why. [some code cut] Hi Duncan, Ok,, what you're running into is actually not so much related properties feature, but actually of the naming-mangling that Python does on any property with leading double underscores. In the 'A_new' class, you have the following methods: > class A_New(object): > __slots__ = ('__x',) > def __init__(self, x=0): > self.x = x > def __get_x(self): > return self.__x > def __set_x(self, x): > assert isinstance(x, int) > self.__x = x Let's concentrate on the names of the getters and setters that you've chosen: '__get_x' and '__get_y'. Python doesn't supports a strict way of defining data privacy (i.e. the 'private', 'protected' keywords in C++ and Java). But Python does provide some token support for encapsulation by making it very difficult to directly accessing attributes with double underscores from outside the defining class. Any method with double underscores in front will get named-manged, so that accessing the methods from outside the class requires deliberate, abusive effort. We can see this by asking what A_New contains, once we've defined it: ### >>> dir(A_New) ['_A_New__get_x', '_A_New__set_x', '_A_New__x', ... ### Note that the '__get_x' method has been name-mangled so that it includes the class name with it. So your test that tries to access the set method: > def testSet(self): > a = A_New() > self.assertEqual(0, a.x) > self.assertEqual(None, a.__set_x(1)) > self.assertEqual(1, a.x) needs to work extra hard to actually call this "private" setter: ### def testSet(self): a = A_New() self.assertEqual(0, a.x) self.assertEqual(None, a._A_New__set_x(1)) self.assertEqual(1, a.x) ### So I hope that explains why we're getting the AttributeError. See: http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 and http://www.python.org/doc/faq/programming.html#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam for more details about this name-mangling. Something strikes me weird though: if you're testing the set/get stuff, why not modify your test to: ### def testSet(self): a = A_New() self.assertEqual(0, a.x) a.x = 1 self.assertEqual(1, a.x) ### The point about properties is to make doing get/set transparent: what looks like property access, a.x = 1 quietly translates to a call to the setter. Isn't that what you want to test? Hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Jun 30 19:21:58 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jun 30 19:22:04 2004 Subject: [Tutor] strange listed nest behaviour In-Reply-To: <40E34270.90108@pusspaws.net> Message-ID: On Wed, 30 Jun 2004, Dave S wrote: > I have a problem with lists, > > As an example the following makes sense to me and works as I would > expect ... > > >>> b=[[0,0,0,0],[0,0,0,0]] > >>> b > [[0, 0, 0, 0], [0, 0, 0, 0]] > >>> b[1][1]=5 > >>> b > [[0, 0, 0, 0], [0, 5, 0, 0]] > >>> > > However I have to set up a large data list, so I have used > "self.startslot=[[float(0)]*110]*36" inside a class. Hi Dave, Today seems like a FAQ-referral day for me. *grin* Here you go: http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list Hope this helps! From alan.gauld at blueyonder.co.uk Wed Jun 30 19:37:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jun 30 19:37:21 2004 Subject: [Tutor] New Python user on board References: Message-ID: <001501c45efb$3786a630$6401a8c0@xp> > I currently work in Marseille, France, as a rendering technical director (we > are doing a full 3D animation feature film called "Magic Roundabout"). Excellent, I heard that they were doing a film version. The Magic Roundabout was one of my favourite puppet shows when I was a kid :-) > At this point I'm very new to Python but I have read the tutorial in the > documentation, it seems very promising. At this moment I'm mainly looking > into Python to in hopes to develop a rendering management software. > > I apoligize in advance for the tons of newbie questions that will follow, > and thank you in advance for your time. Thats OK, its what the list is for. If you read the official tutorial you might be a wee bit more adbvanced a newbie than many of our readers, but you are welcome nonetheless. Also if you know VBScript/JScript you might find my new online tutor useful since it teaches basic Python but using VBscript and JScript as comparison languages... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From xcentric at unixgeek.net Wed Jun 30 23:07:07 2004 From: xcentric at unixgeek.net (Mike) Date: Wed Jun 30 23:38:06 2004 Subject: [Tutor] subclass / superclass methods Message-ID: <1088651226.3910.4.camel@zaphod.quantumtunnel.net> Greetings, I'm trying to find out why the below does not work as I'm expecting. I'm sure there is a good answer, just I'm too green to understand why. Any help would be appreciated. My expected results are for it to say 'Hello other OnTick' Thanks, Mike class object: def __init__(self): print 'Hello object __init__' def EventTick(self): print 'Hello object EventTick' self.OnTick() def OnTick(self): print 'Hello object OnTick' class other(object): def __init__(self): print 'Hello other __init__' def OnEvent(self): print 'Hello other OnTick' if __name__ == '__main__': my = other() my.EventTick() From Dragonfirebane at aol.com Wed Jun 30 23:55:08 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Wed Jun 30 23:55:26 2004 Subject: [Tutor] subclass / superclass methods Message-ID: <1e3.24278287.2e14e51c@aol.com> I, too, am farily new at Python, but it occurs to me that perhaps you meant to have class object: def __init__(self): print 'Hello object __init__' def EventTick(self): print 'Hello object EventTick' self.OnTick() def OnTick(self): print 'Hello object OnTick' class other(object): def __init__(self): print 'Hello other __init__' def OnEvent(self): print 'Hello other OnTick' if __name__ == '__main__': my = other() my.EventTick() be class object: def __init__(self): print 'Hello object __init__' def EventTick(self): print 'Hello object EventTick' self.OnTick() def OnTick(self): print 'Hello object OnTick' class other(object): def __init__(self): print 'Hello other __init__' def OnTick(self): print 'Hello other OnTick' if __name__ == '__main__': my = other() my.EventTick() (change OnEvent(self) in Class other to OnTick(self) so that when my.EventTick() is run, it goes to Class other's OnTick rather than Class object since Class other's OnTick wouldn't exist) the proposed change produces the following in IDLE: Hello other __init__ Hello object EventTick Hello other OnTick I don't know if that's what you wanted, but it has "Hello other OnTick" in it. Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040630/1ed1bee2/attachment.html