From janos.juhasz at VELUX.com Thu Jul 1 01:59:51 2004 From: janos.juhasz at VELUX.com (janos.juhasz@VELUX.com) Date: Thu Jul 1 02:00:00 2004 Subject: [Tutor] help with regular expressions In-Reply-To: Message-ID: Hi Jeff, >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'] I fell that, you are looking for this: >>> re.findall('\S+', '3.444456 4 84.3546354') ['3.444456', '4', '84.3546354'] Yours sincerely, J?nos Juh?sz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040701/01d0f804/attachment.html From project5 at redrival.net Thu Jul 1 02:55:15 2004 From: project5 at redrival.net (Andrei) Date: Thu Jul 1 02:55:31 2004 Subject: [Tutor] Re: 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: Dick Moores rcblue.com> writes: > >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 PyCrust is a really nice Python shell - my favorite in fact - worth downloading wxPython IMO. > it's website, and I'm interested in what is said there about having the > best GUI toolkit. Everyone claims their product is better than the competition :). (I happen to agree on wxPython, but it's very much a matter of taste.) > 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? Yes. wxPython is just a set of libraries and tools like all the other libraries and tools you get with Python. You use whatever you need and ignore the rest. > 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. Nope. I don't know C(++), and I can use it just fine. The docs are C++ oriented (with some Python annotations here and there), but although that's not an ideal situation, they're quite easy to follow after the inital shock :) - plus that it comes with a great demo with a lot of educational value. But anyway, you don't need to read the docs in order to use PyCrust/PyShell. Yours, Andrei From pythontut at pusspaws.net Thu Jul 1 03:04:30 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Jul 1 03:04:43 2004 Subject: [Tutor] strange listed nest behaviour In-Reply-To: References: Message-ID: <40E3B77E.7000509@pusspaws.net> Danny Yoo wrote: >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! > > Its perfect :-) ... I will read the FAQ. I have been learning my Python from o'reilly and did not realise there was a FAQ on line - thats great cheers Dave PS thanks for your patience with us newbes ! From alan.gauld at blueyonder.co.uk Thu Jul 1 03:45:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 1 03:45:22 2004 Subject: [Tutor] subclass / superclass methods References: <1088651226.3910.4.camel@zaphod.quantumtunnel.net> Message-ID: <003901c45f3f$676bc170$6401a8c0@xp> > 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' First, its a bad oidea to create a class called object, since that will hide the builtin class called object which could produce weird results! > class object: > def __init__(self): > def EventTick(self): > print 'Hello object EventTick' > self.OnTick() > def OnTick(self): > > class other(object): > def __init__(self): > def OnEvent(self): You have an OnTick() in object but an OnEvent() in other. I suspect you meant to have an OnTick() in both? Alan G. From duncan at thermal.esa.int Thu Jul 1 04:40:42 2004 From: duncan at thermal.esa.int (Duncan Gibson) Date: Thu Jul 1 04:40:48 2004 Subject: [Tutor] testing new style class properties using pyUnit ? In-Reply-To: Your message of "Wed, 30 Jun 2004 16:04:09 PDT." Message-ID: <200407010840.i618ehgW005903@watt28.thermal.esa.int> dyoo .at. hkn . eecs . berkeley . edu said: > 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) Yes, you are quite right: keep it simple, stupid! In the actual original code I had the more contorted self.assertEqual(None, a.set_x(1)) because I wanted to do as much as possible within the pyUnit context and also because the original setter did a bit more behind the scenes than is obvious from this simplified example. Cheers Duncan From xcentric at unixgeek.net Thu Jul 1 07:09:30 2004 From: xcentric at unixgeek.net (Mike) Date: Thu Jul 1 07:07:43 2004 Subject: [Tutor] subclass / superclass methods In-Reply-To: <003901c45f3f$676bc170$6401a8c0@xp> References: <1088651226.3910.4.camel@zaphod.quantumtunnel.net> <003901c45f3f$676bc170$6401a8c0@xp> Message-ID: <1088680170.23260.1.camel@zaphod.quantumtunnel.net> I named the class object just as an example. In a real world case I wouldn't use that name. And your right... my mistake is because I was up too late and should have been a sleep. Thanks ~Mike On Thu, 2004-07-01 at 03:45, Alan Gauld wrote: > > 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' > > First, its a bad oidea to create a class called object, since that > will hide the builtin class called object which could produce > weird results! > > > class object: > > def __init__(self): > > def EventTick(self): > > print 'Hello object EventTick' > > self.OnTick() > > def OnTick(self): > > > > class other(object): > > def __init__(self): > > def OnEvent(self): > > You have an OnTick() in object but an OnEvent() in other. > I suspect you meant to have an OnTick() in both? > > Alan G. > From Dragonfirebane at aol.com Thu Jul 1 07:35:48 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Thu Jul 1 07:35:55 2004 Subject: [Tutor] Loops Message-ID: Skipped content of type multipart/alternative-------------- next part -------------- ########################################################################## ## Multivert ## ########################################################################## ########################################################################## ## ## ## To - Do: ## ## -------- ## ## ## ## 1. Get converthex(whichconv) to work. CHECK ## ## 2. Change convertnum(whichconv) and convertbin(whichconv) so that ## ## when a carat (^) is seen, that number goes up by enough so that ## ## it is considered uppercase. ## ## 3. Treat decimal numbers separated by a space as separate ## ## (original.split()) so that each separate unit can be converted ## ## to its own letter (includes removing int(original) tests early ## ## on). CHECK ## ## 4. Implement change in spaces around punctuation in all modules so ## ## that 3 will work. ## ## 5. Allow a calculation to be performed after a conversion ## ## until user declines. CHECK ## ## 6. Allow convertbin(whichconv) to recognize punctuation. ## ## 7. Print '\xba' (degrees sign) from string.letters when character ## ## or number isn't recognized (or '[?]' . . . probably easier to ## ## do that one). ## ## 8. Allow default of 10 in multiplication (calc(manip)). CHECK ## ## 9. If no conversions(/calculations), don't prompt for seeing all ## ## of said manipulations. CHECK ## ## ## ########################################################################## ##to see comments, maximize window or scroll all the way to the right def calc(manip): global counter global allcalc if manip == 'exponents': base = float(raw_input("Please enter the base. ")) expon = float(raw_input("Please enter the exponent. ")) results = base ** expon Sitemlist = [] Sitemlist.append("%d to the power of %d equals %d." % (base, expon, results)) Sitemlist = ''.join(Sitemlist) print Sitemlist allcalc.append('____Calculation %d: . . . ' % counter + Sitemlist) manip = 'end' elif manip == 'multiplication': leng = int(raw_input("Please enter number of items to be multiplied: ")) itemlist = [] item1 = float(raw_input("Please enter first item to multiply: ")) itemlist.append(item1) Sitemlist = [] Sitemlist.append(str(item1)) for i in range (1, leng): try: item2 = float(raw_input("Please enter next item to multiply (default is 10): ")) except ValueError: item2 = 10 itemlist.append(item2) Sitemlist.append(str(item2)) for x in itemlist[:]: try: results = itemlist[0] * itemlist[1] itemlist.remove(itemlist[0]) itemlist.remove(itemlist[0]) itemlist.insert(0, results) except IndexError: pass Sitemlist = ' times '.join(Sitemlist) Sitemlist += ' equals ' + str(results) + '.' print Sitemlist allcalc.append('____Calculation %d: . . . ' % counter + str(Sitemlist)) manip = 'end' elif manip == 'division': leng = int(raw_input("Please enter the number of items to be divided: ")) itemlist = [] item1 = float(raw_input("Please enter number to divide. ")) itemlist.append(item1) Sitemlist = [] Sitemlist.append(str(item1)) for i in range (1, leng): try: item2 = float(raw_input("Please enter number to divide by (default is 10). ")) except ValueError: item2 = 10.0 itemlist.append(item2) Sitemlist.append(str(item2)) for x in itemlist[:]: try: results = itemlist[0] / itemlist[1] itemlist.remove(itemlist[0]) itemlist.remove(itemlist[0]) itemlist.insert(0, results) except IndexError: pass Sitemlist = ' divided by '.join(Sitemlist) Sitemlist += ' equals ' + str(results) + '.' print Sitemlist allcalc.append('____Calculation %d: . . . ' % counter + str(Sitemlist)) manip = 'end' elif manip == 'addition': pass manip = 'end' elif manip == 'subtraction': pass manip = 'end' if manip == 'end': more = raw_input("Would you like to perform more calculations [y/n]? ") if more in 'Yy': pass elif more in 'Nn': global again conv = raw_input("Would you like to perform a conversion [y/n]? ") if conv in 'Yy': global cal cal = 'conversion' elif conv in 'Nn': again = False def convertbin(whichconv): global res global original original = original.split() m = 0 j = len(original) for x in original: if whichconv == 'Decimal': asNum = str(long(str(original[m]),2)) res += asNum res += ' ' m += 1 elif whichconv == 'Hexadecimal': asHex = str(long(str(original[m]),2)) if int(asHex) <= 0: res += '-' asHex = -int(asHex) asHex = "%X" % int(asHex) res += asHex res += ' ' m += 1 elif whichconv == 'Text': try: asNum = str(long(str(original[m]),2)) if int(asNum) == 0: res += '%s' % chr(int(asNum) + 32) elif 0 < int(asNum) <= 26: res += '%s' % chr(int(asNum) + 96) elif 26 < int(asNum) <= 52: res += '%s' % chr(int(asNum) + 38) except ValueError: global original if x in punct: res += x else: for char in x: if char == '^': x = ' '.join(x) x = x.split() x.remove(char) x = ''.join(x) asNum = int(long(str(x),2)) asNum += 26 asOctal = "%o" % int(asNum) original[m] = '' for char in asOctal: original[m] += str(binary[char]) original[m] = str(original[m]) m -= 1 m += 1 else: print """Sorry, you didn't enter a valid number. Please enter only numbers between one and 26 """ def convertnum(whichconv): ##converts numbers from string import split if whichconv == 'Binary': ##if user wants to convert to binary global original original = original.split() q = 0 for char in original: asBin = str(original[q]) if int(asBin) <= 0: ##if negative number entered global res ##since res is redefined, tells python to use global res and not try to create a local one res += '-' ##adds a minus sign to res asBin = -int(asBin) ##converts original to a positive number try: int(asBin) ##currently redundant, eventually to discriminate between numbers and punctation except ValueError: x = 0 for char in original: if char in punct: res += char x += 1 else: asOctal = "%o" % int(asBin) for char in asOctal: res += str(binary[char]) q += 1 res += ' ' elif whichconv == 'Hexadecimal': ##if user wants to convert to hex original = original.split() x = 0 for char in original: asHex = str(original[x]) if int(asHex) <= 0: ##global res/original already in module res += '-' asHex = -int(asHex) asHex = "%X" % int(asHex) res += asHex res += ' ' x += 1 elif whichconv == 'Text': ##if user wants to convert to text (only works one letter at a time) original = original.split() x = 0 for char in original: asText = str(original[x]) if int(asText) == 0: ##if number is 0 res += '%s' % chr(int(asText) + 32) ##adds a space to res elif 0 < int(asText) <= 26: ##if the number is 1-26 res += '%s' % chr(int(asText) + 96) ##prints corresponding letter elif 26 < int(asText) <= 52: ##if number is between 26 and 52 res += '%s' % chr(int(asText) + 38) ##prints corresponding letter 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 x += 1 def converthex(whichconv): global res global original original = original.split() m = 0 for x in original: if whichconv == 'Binary': asBin = str(long(str(original[m]),16)) if int(asBin) <= 0: res += '-' asBin = -int(asBin) try: int(asBin) ##currently redundant, eventually to discriminate between numbers and punctation except ValueError: x = 0 for char in original: if char in punct: res += char x += 1 else: asOctal = "%o" % int(asBin) for char in asOctal: res += str(binary[char]) elif whichconv == 'Decimal': asNum = str(long(str(original[m]),16)) res += asNum res += ' ' m += 1 elif whichconv == 'Text': asNum = str(long(str(original[m]),16)) if int(asNum) == 0: res += '%s' % chr(int(asNum) + 32) elif 0 < int(asNum) <= 26: res += '%s' % chr(int(asNum) + 96) elif 26 < int(asNum) <= 52: res += '%s' % chr(int(original) + 38) m += 1 else: print """Sorry, you didn't enter a valid number. Please enter only numbers between one and 26 """ def convertxt(whichconv): global res ##results list is modified, so this tells python to use the global list and not create a local one if whichconv == 'Binary': from string import split ##so split and join work for char in original: ##loops over the entire entry x = 0 ##allows checking every character against the entire alphabet list if char in punct: ##if character is punctuation res += char ##adds punctuation res += ' ' elif char in alphabet: ##if the character is in the alphabet while x == 0: if char in alphabet[x]: asOctal = "%o" % int(ord(char) - 32) for char in asOctal: res += binary[char] res += ' ' x += 1 while 0 < 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(ord(char) - 96) ##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 res += '^' asOctal = "%o" % int(ord(char) - 64) ##converts alphabet number (A = 1) to an unsigned octal for char in asOctal: res += binary[char] if char not in punct: res += ' ' x += 1 elif whichconv == 'Hexadecimal': ##convert text to hexadecimal from string import split for char in original: 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 == 0: if char in alphabet[x]: asHex = "%X" % int(ord(char) - 32) res += asHex res += ' ' x += 1 while 0 < x <= 26: if char in alphabet[x]: asHex = "%X" % int(ord(char) - 96) ##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]: res += '^' asHex = "%X" % int(ord(char) - 64) ##convert alphabet number to corresponding hex number res += asHex if char not in punct: res += ' ' x += 1 elif whichconv == 'Decimal': ##convert text to decimal from string import split for char in original: 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 += '^' res += '%d' % int(ord(char) - 64) ##add corresponding number to string if char not in punct: res += ' ' x += 1 import time ##for time.sleep(1.1) at end import string ##for split(res), etc. in convertxt modules. alphabet = ' ' + string.ascii_letters ##define alphabet string punct = string.punctuation ##define punctation string binary = {'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110','7':'111'} ##define the binary dictionary number = string.digits starmenu = {'1':'Binary','2':'Decimal','3':'Hexadecimal','4':'Text'} bconmenu = {'1':'Decimal','2':'Hexadecimal','3':'Text'} dconmenu = {'1':'Binary','2':'Hexadecimal','3':'Text'} hconmenu = {'1':'Binary','2':'Decimal','3':'Text'} tconmenu = {'1':'Binary','2':'Decimal','3':'Hexadecimal'} counter = 1 manip = '' allcalc = [] allconv = '' ##defines string containing all conversions res = '' ##defines string containing single conversion i = 0 ##beginning condition for loop again = True print """What would you like to do: 1: Calculation 2: Conversion 3: Exit""" cal = raw_input("... ") if cal == '1': cal = 'calculation' if cal == '2': cal = 'conversion' if cal == '3': cal = 'none' while again: if cal == 'calculation': print """Please enter intended manipulation: 1: Exponents 2: Multiplication 3: Division 4: Addition 5: Subtraction 6: None""" manip = raw_input("... ") if manip == '1': manip = 'exponents' if manip == '2': manip = 'multiplication' if manip == '3': manip = 'division' if manip == '4': manip = 'addition' if manip == '5': manip = 'subtraction' if manip == '6': break calc(manip) counter += 1 if cal == 'conversion': res = '' ##empties the string so each conversion begins w/ an empty string print """Which type of text would you like to convert? 1: Binary 2: Decimal 3: Hexadecimal 4: Text""" startype = raw_input("... ") original = raw_input("Please enter %s to be converted. " % starmenu[startype].lower()) ##enter input to be converted startype = starmenu[startype] if startype == 'Binary': print """Convert to: 1: Decimal 2: Hexadecimal 3: Text""" whichconv = raw_input("... ") whichconv = bconmenu[whichconv] convertbin(whichconv) print res elif startype == 'Decimal': print """Convert to: 1: Binary 2: Hexadecimal 3: Text""" whichconv = raw_input("... ") ##which conversion? whichconv = dconmenu[whichconv] convertnum(whichconv) ##convert numbers to whatever print res ##print string containing conversion elif startype == 'Hexadecimal': print """Convert to: 1: Binary 2: Decimal 3: Text""" whichconv = raw_input("... ") whichconv = hconmenu[whichconv] converthex(whichconv) print res elif startype == 'Text': print """Convert to: 1: Binary 2: Decimal 3: Hexadecimal""" whichconv = raw_input("... ") ##which conversion? whichconv = tconmenu[whichconv] convertxt(whichconv) print res ##print the string containing the conversion i += 1 original = ' '.join(str(original)) allconv += ' ____Conversion %d: . . . ' % i + startype + ' => ' + whichconv + ' ... "' + original + '" => "' + res + '"' ##outside of try-except-else, inside while; adds each conversion to a master conversion list per session 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, calcu = raw_input("Would you like to perform a calculation [y/n]? ") if calcu in 'Yy': cal = 'calculation' elif calcu in 'Nn': again = False ##break loop if cal == 'none': break if cal not in ('calculation', 'conversion','none'): cal = raw_input("""You may either perform a conversion or a calculation. Please enter which one you would like to do: """) allcon = 'a' allcal = 'a' if allcalc == []: allcal = '' if allconv == '': allcal = '' if allcal != '': callcalcon = raw_input("""Would you like to see all the calculations and conversions performed during this session [y/n]? """) if callcalcon in 'Yy': print ''.join(allcalc) + allconv elif callcalcon in 'Nn': pass elif allcal == '': if allconv != '': callconv = raw_input("""Would you like to see all the conversions performed during this session [y/n]? """) if callconv in 'Yy': print allconv elif callcalcon in 'Nn': pass elif allconv == '': callcalc = raw_input("""Would you like to see all the calculations performed during this session [y/n]? """) if callcalc in 'Yy': print ''.join(allcalc) try: exit = raw_input("""Hit enter or control-c to exit. ... """) except KeyboardInterrupt: pass 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 atyss4si at hotmail.com Thu Jul 1 09:17:27 2004 From: atyss4si at hotmail.com (Bernard Lebel) Date: Thu Jul 1 09:23:21 2004 Subject: [Tutor] Create text file Message-ID: Hello, I searched througout the Python docs but can't find anything about that. Is there a way to create a text file in Python? So far I'm using a FileSystemObject (wich is an ActiveX object, running inside the Win32 module), in the form of fso.createtextfile( ) But I'd like to stay away from active objects to maximize Windows-Linux compatibility. Any advince would be very welcomed. From bgailer at alum.rpi.edu Thu Jul 1 09:35:48 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Jul 1 09:34:04 2004 Subject: [Tutor] Create text file In-Reply-To: References: Message-ID: <6.1.0.6.0.20040701072809.0271ed30@mail.mric.net> At 07:17 AM 7/1/2004, Bernard Lebel wrote: >Hello, > >I searched througout the Python docs but can't find anything about that. > >Is there a way to create a text file in Python? >So far I'm using a FileSystemObject (wich is an ActiveX object, running >inside the Win32 module), in the form of > >fso.createtextfile( ) > >But I'd like to stay away from active objects to maximize Windows-Linux >compatibility. fileObject = file('c:\\foo.txt', 'w') fileObject.write('This is line 1\n') fileObject.write('This is line 2\n') fileObject.close() Note explicit provision of newline characters (\n) at end of each line. There is also a writelines method that takes a sequence of strings, so, using other Python shortcuts, you could replace the above with one line of code: file('c:\\foo.txt', 'w').writelines(['This is line 1\n', 'This is line 2\n']) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From pythonTutor at venix.com Thu Jul 1 09:36:08 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Jul 1 09:36:20 2004 Subject: [Tutor] Create text file In-Reply-To: References: Message-ID: <1088688967.2178.18.camel@laptop.venix.com> Simply use the Python file object with a t appended to the mode: textfile = file('new_file.txt','wt') This is a link to the tutorial. Note that open also returns file objects. file is a recent addition to the language. http://python.org/doc/2.3.4/tut/node9.html#l2h-30 On Thu, 2004-07-01 at 09:17, Bernard Lebel wrote: > Hello, > > I searched througout the Python docs but can't find anything about that. > > Is there a way to create a text file in Python? > So far I'm using a FileSystemObject (wich is an ActiveX object, running > inside the Win32 module), in the form of > > fso.createtextfile( ) > > But I'd like to stay away from active objects to maximize Windows-Linux > compatibility. > > Any advince would be very welcomed. > > _______________________________________________ > 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 bgailer at alum.rpi.edu Thu Jul 1 09:44:23 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Jul 1 09:43:01 2004 Subject: [Tutor] Create text file In-Reply-To: <1088688967.2178.18.camel@laptop.venix.com> References: <1088688967.2178.18.camel@laptop.venix.com> Message-ID: <6.1.0.6.0.20040701074247.026bda58@mail.mric.net> At 07:36 AM 7/1/2004, Lloyd Kvam wrote: >Simply use the Python file object with a t appended to the mode: > textfile = file('new_file.txt','wt') Interesting (1) that wt is not documented, and (2) apparantly anything can follow the w without error. >[snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From orbitz at ezabel.com Thu Jul 1 10:10:33 2004 From: orbitz at ezabel.com (orbitz) Date: Thu Jul 1 10:10:54 2004 Subject: [Tutor] Loops In-Reply-To: References: Message-ID: <40E41B59.5090307@ezabel.com> I'm a little confused about what you are actually trying to accomplish here. You are representing some things in binary and some not (spaces, punctuation?). I'm not sure why you have the caret to begin with, uppercase letters would simply have a different code than their lowercase counterpart. Dragonfirebane@aol.com wrote: > As part of a program I'm working on, Binary input is taken in > (punctuation included) and text is output-ed. However, to symbolize > capital letters in Binary, a carat (^) is inserted, which makes it > necessary to inclue the part from "else" - down. What isn't shown > here is that the entire section is under a for loop: for x in > original. Original is the binary raw_input. m begins as 0. Therefore, > my problem is that after removing the carat and adding enough to the > number that it will be considered uppercase (done by segment from > "else" - down), even though m stays the same due to m -= 1 and m += > 1, meaning that that part of original will be re-processed, there are > still only a limited number of 'x's in original. Therefore, what > should come out as: > > "'ello Sue. I've got legs!" > > comes out as: > > "'ello Sue 've got legs" > > from: > > " ' 101 001100 001100 001111 000 ^010011 010101 101 . 000 ^001001 ' > 010110 101 000 111 001111 010100 000 001100 101 111 010011 ! " > > most of the relevant code is below. for the full work-in-progress > program (approx. 500 lines), open attachment. the relevant module is > 'convertbin(whichconv)' (line 118) and the global variables are > defined approx. from lines 368-395 > > > try: > asNum = str(long(str(original[m]),2)) > if int(asNum) == 0: > res += '%s' % chr(int(asNum) + 32) > elif 0 < int(asNum) <= 26: > res += '%s' % chr(int(asNum) + 96) > elif 26 < int(asNum) <= 52: > res += '%s' % chr(int(asNum) + 38) > except ValueError: > global original > if x in punct: > res += x > else: > for char in x: > if char == '^': > x = ' '.join(x) > x = x.split() > x.remove(char) > x = ''.join(x) > asNum = int(long(str(x),2)) > asNum += 26 > asOctal = "%o" % int(asNum) > original[m] = '' > for char in asOctal: > original[m] += str(binary[char]) > nbsp; asNum = int(long(str(x),2)) > asNum += 26 > asOctal = "%o" % int(asNum) > original[m] = '' > for char in asOctal: > original[m] += str(binary[char]) > original[m] = str(original[m]) > m -= 1 > m += 1 > any suggestions for how I can reprocess binary minus the carat without > 'wasting' one of the x's (characters) of original would be vastly > appreciated. > > Thanks in advance, > Orri > > Email: dragonfirebane@aol.com > AIM: singingxduck > Programming Python for the fun of it. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From kroos at symbioses.co.za Thu Jul 1 10:13:26 2004 From: kroos at symbioses.co.za (Kerneels Roos) Date: Thu Jul 1 10:13:13 2004 Subject: [Tutor] Is it possible to call Win32 DLLs from Python? Message-ID: Hi, This may be trivial, but I will ask anyway. Is it possible to access functions in Win32 DLLs frow within a Python program? In vbscript one can say, set objFromDLL = CreateObject("some_dll.object_name") and then you can call functions on objFromDLL. Kerneels From project5 at redrival.net Thu Jul 1 10:25:34 2004 From: project5 at redrival.net (Andrei) Date: Thu Jul 1 10:25:40 2004 Subject: [Tutor] Re: Is it possible to call Win32 DLLs from Python? References: Message-ID: > This may be trivial, but I will ask anyway. > Is it possible to access functions in Win32 DLLs frow within a Python > program? You could try Win32All (included in ActiveState distro or, if you have the official distro, you can google for it) or ctypes (http://starship.python.net/crew/theller/ctypes/). Yours, Andrei From atyss4si at hotmail.com Thu Jul 1 11:44:28 2004 From: atyss4si at hotmail.com (Bernard Lebel) Date: Thu Jul 1 11:53:42 2004 Subject: [Tutor] Python to connect to MySql Message-ID: Hello, I'm wondering if there is any way to connect to a MySql server (and retreive information) without the need of an ActiveX object. Right this is what I'm doing, but again I want to get rid of the active objects. I have found few things on the internet, but some are for Unix servers and require a C compiler and things like that. Nothing as simple and straigthforward as an active object. Any suggestion? I'm using MySql 4.0.16 Thanks Bernard # Current code: import win32com.client # Create database ActiveX object oDB = win32com.client.Dispatch( "ADODB.Connection" ) # Send connection instructions to database oDB.ConnectionString = 'driver={MySQL}; server=xxx.xxx.x.x; uid=userid; pwd=password; database=database' oDB.open From duncan at thermal.esa.int Thu Jul 1 12:08:31 2004 From: duncan at thermal.esa.int (Duncan Gibson) Date: Thu Jul 1 12:08:39 2004 Subject: [Tutor] testing new style class properties using pyUnit ? In-Reply-To: Your message of "Wed, 30 Jun 2004 18:20:13 +0200." <20040630162013.B73C62D5E@lorentz.thermal.esa.int> Message-ID: <200407011608.i61G8Vps006522@watt28.thermal.esa.int> In my original question, I wrote: > I had a class which used get and set methods to access a class variable. > I set up some unit tests using pyUnit. > > 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. > > Can anyone explain the magical incantation that I need to test the > property setter? Well, many thanks to Danny Yoo for pointing me in the right direction, explaining the name mangling that gives rise to _className__thingName See his reply for details. However, I also included the oh-so-glib statement: > 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. Boy, oh, boy. The naming principle is certainly the same, but after spending most of the day failing to convert the pyUnit tests to give the results I expected when using the mangled names, it finally hit me. The new Python features involving __slots__ and __var = property(...) apply to instance attributes. Let me say that again: instance attributes. On first sight they appeared to work with my class variables, and had it not been for pyUnit I would have thought they were working perfectly, and six months down the line there would have been a lot of tearing of hair and gnashing of teeth. Cheers Duncan From tpc at csua.berkeley.edu Thu Jul 1 12:08:28 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Jul 1 12:09:59 2004 Subject: [Tutor] Python to connect to MySql In-Reply-To: Message-ID: <20040701090403.A96573-100000@localhost.name> hi Bernard, you might want to look at MySQLdb for win32: http://sourceforge.net/projects/mysql-python Once installed, a simple thing would be to import MySQLdb, and run the following code to test: def mySQLtest(): DB = 'mysql' HOST = 'localhost' DB_USER = 'root' DB_PASSWORD = '' conn = MySQLdb.Connection(db=DB, host=DB_HOST, user=DB_USER, passwd=DB_PASSWORD) cursor = conn.cursor() sql = """show tables;""" cursor.execute(sql) results = cursor.fetchall() cursor.close() conn.close() return results I hope that helps you. On Thu, 1 Jul 2004, Bernard Lebel wrote: > Hello, > > I'm wondering if there is any way to connect to a MySql server (and retreive > information) without the need of an ActiveX object. Right this is what I'm > doing, but again I want to get rid of the active objects. > > I have found few things on the internet, but some are for Unix servers and > require a C compiler and things like that. Nothing as simple and > straigthforward as an active object. > > Any suggestion? > I'm using MySql 4.0.16 > > > Thanks > Bernard > > > > # Current code: > import win32com.client > > # Create database ActiveX object > oDB = win32com.client.Dispatch( "ADODB.Connection" ) > > # Send connection instructions to database > oDB.ConnectionString = 'driver={MySQL}; server=xxx.xxx.x.x; uid=userid; > pwd=password; database=database' > > oDB.open > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythonTutor at venix.com Thu Jul 1 12:28:36 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Jul 1 12:28:47 2004 Subject: [Tutor] Python to connect to MySql In-Reply-To: References: Message-ID: <1088699315.2178.23.camel@laptop.venix.com> I am using MySQLdb on Windows and Linux. Works well. This is a useful set of links. Read the DBI documentation. http://python.org/topics/database/ On Thu, 2004-07-01 at 11:44, Bernard Lebel wrote: > Hello, > > I'm wondering if there is any way to connect to a MySql server (and retreive > information) without the need of an ActiveX object. Right this is what I'm > doing, but again I want to get rid of the active objects. > > I have found few things on the internet, but some are for Unix servers and > require a C compiler and things like that. Nothing as simple and > straigthforward as an active object. > > Any suggestion? > I'm using MySql 4.0.16 > > > Thanks > Bernard > > > > # Current code: > import win32com.client > > # Create database ActiveX object > oDB = win32com.client.Dispatch( "ADODB.Connection" ) > > # Send connection instructions to database > oDB.ConnectionString = 'driver={MySQL}; server=xxx.xxx.x.x; uid=userid; > pwd=password; database=database' > > oDB.open > > _______________________________________________ > 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 rdm at rcblue.com Thu Jul 1 15:00:30 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Jul 1 15:00:35 2004 Subject: [Tutor] Create text file In-Reply-To: <6.1.0.6.0.20040701074247.026bda58@mail.mric.net> References: <1088688967.2178.18.camel@laptop.venix.com> <6.1.0.6.0.20040701074247.026bda58@mail.mric.net> Message-ID: <6.1.2.0.2.20040701115203.02fbc798@rcblue.com> Bob Gailer wrote at 06:44 7/1/2004: >At 07:36 AM 7/1/2004, Lloyd Kvam wrote: >>Simply use the Python file object with a t appended to the mode: >> textfile = file('new_file.txt','wt') > >Interesting (1) that wt is not documented, and (2) apparantly anything >can follow the w without error. I found a mention on p. 188 in _Python in a Nutshell_: "The mode string may also have any of the values just explained followed by a b or t. b denotes binary mode, while t denotes text mode. When the mode string has neither b nor t, the default is text mode (i.e., 'r' is like 'rt', 'wt' is like 'wt', and so on)." Dick Moores From jeffpeery at yahoo.com Thu Jul 1 18:40:15 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu Jul 1 18:40:19 2004 Subject: [Tutor] writing ascii files with Numeric? Message-ID: <20040701224015.9660.qmail@web60107.mail.yahoo.com> Hello I am trying to write my Matrix to to a file in ASCII format. I created the matrix using Numeric, the shape is 600x25. here is the code that produces the error below: filehandle = file("MyFile.txt", 'w') filehandle.write(Matrix) filehandle.close() TypeError: Non-character array cannot be interpreted as character buffer. I am assuming this means that 'Matrix' must be a character string and not a matrix. how would I go about converting an array of floats to a character string so I can print this thing to a file? Or is there a better way to do this? thanks!!! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040701/d3f5dcbf/attachment.html From rdm at rcblue.com Thu Jul 1 20:15:02 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Jul 1 20:15:30 2004 Subject: [Tutor] timer module question Message-ID: <6.1.2.0.2.20040701161630.0464a288@rcblue.com> Today I've been studying the time module using the Python Library Reference. As an exercise I thought I'd make a timer script. What I'd like to get it to do in addition, is tell me every 10 seconds how many seconds have elapsed while the timer is running. Is there a way to do this? Here's what I have. It seems to work well: ===================================== #timer.py import time while True: start = raw_input("Press Enter to start timer; enter 0 to close program " t0 = time.time() if start == "0": print "Timer has been shut down" break time_now = time.ctime() print "Timer has been started at", time_now[11:19], "\n" raw_input("Press Enter to stop timer ") t1 = time.time() elapsed_time = t1 - t0 time_now = time.ctime() print "\nTimer has been stopped at", time_now[11:19] print "Time elapsed was", elapsed_time, "seconds" print "-------------------------------------\n" ====================================== sample output: Press Enter to start timer; enter 0 to close program Timer has been started at 16:37:48 Press Enter to stop timer Timer has been stopped at 16:40:56 Time elapsed was 188.156000137 seconds ------------------------------------- Press Enter to start timer; enter 0 to close program ===================================== (Later I'll want to trim the accuracy of the result, and also convert to hours, minutes, seconds, but I think I'll be able to figure that out. Being able to turn this into a GUI timer is way down the road for me.) If it matters, I'm running Python 2.3.4 on Windows XP Pro Thanks, Dick Moores From rdmoores at gmail.com Thu Jul 1 21:35:34 2004 From: rdmoores at gmail.com (Dick Moores) Date: Thu Jul 1 21:35:37 2004 Subject: [Tutor] Re: IDLE question In-Reply-To: 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: My thanks to Alan Gauld and Andrei for their info re wxPython and its PyCrust and PyShell. If I just want to try out wxPython, can I keep it separate from the regular Python 2.3.4 I have on my system, and use both as I wish? BTW I'm using Windows XP Pro. Thanks, Dick From rdm at rcblue.com Thu Jul 1 23:03:11 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Jul 1 23:03:27 2004 Subject: [Tutor] Rounding to n significant digits? Message-ID: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> Is there something (a function?) in Python 2.3.4 that will round a result to n significant digits, or do I need to roll my own? I don't see one in the math module. I mean something like rounding(float, n) that would do this: float = 123.456789, n = 4, returns 123.5 float = .000000123456789, n = 2, returns .00000012 float = 123456789, n = 5, returns 123460000 Thanks, Dick Moores From flaxeater at yahoo.com Fri Jul 2 00:22:50 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Jul 2 00:22:54 2004 Subject: [Tutor] Re: IDLE question In-Reply-To: Message-ID: <20040702042250.63385.qmail@web52602.mail.yahoo.com> --- Dick Moores wrote: > My thanks to Alan Gauld and Andrei for their info re wxPython and > its > PyCrust and PyShell. > > If I just want to try out wxPython, can I keep it separate from the > regular Python 2.3.4 I have on my system, and use both as I wish? > > BTW I'm using Windows XP Pro. > wxPython is not a python distro it's used *WITH* python. It's a library of fucntions and other stuff. Download it and use the installer it will make it's own group in your program thingy and play around. __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From flaxeater at yahoo.com Fri Jul 2 00:24:38 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Jul 2 00:24:43 2004 Subject: [Tutor] timer module question In-Reply-To: <6.1.2.0.2.20040701161630.0464a288@rcblue.com> Message-ID: <20040702042438.59980.qmail@web52610.mail.yahoo.com> --- Dick Moores wrote: > Today I've been studying the time module using the Python Library > Reference. As an exercise I thought I'd make a timer script. > > What I'd like to get it to do in addition, is tell me every 10 > seconds > how many seconds have elapsed while the timer is running. Is there > a way > to do this? > > Here's what I have. It seems to work well: > > ===================================== > #timer.py > > import time > > while True: > start = raw_input("Press Enter to start timer; enter 0 to > close > program " > t0 = time.time() > > if start == "0": > print "Timer has been shut down" > break > > time_now = time.ctime() > print "Timer has been started at", time_now[11:19], "\n" > > raw_input("Press Enter to stop timer ") > t1 = time.time() > elapsed_time = t1 - t0 > time_now = time.ctime() > print "\nTimer has been stopped at", time_now[11:19] > print "Time elapsed was", elapsed_time, "seconds" > print "-------------------------------------\n" > ====================================== > > sample output: > > Press Enter to start timer; enter 0 to close program > Timer has been started at 16:37:48 > > Press Enter to stop timer > > Timer has been stopped at 16:40:56 > Time elapsed was 188.156000137 seconds > ------------------------------------- > > Press Enter to start timer; enter 0 to close program > ===================================== > > (Later I'll want to trim the accuracy of the result, and also > convert to > hours, minutes, seconds, but I think I'll be able to figure that > out. > Being able to turn this into a GUI timer is way down the road for > me.) > > If it matters, I'm running Python 2.3.4 on Windows XP Pro > Must this be stored by ascii? if not try looking at the pickle module. __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From rdm at rcblue.com Fri Jul 2 00:52:48 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 2 00:52:54 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <51.40a4e788.2e163756@aol.com> References: <51.40a4e788.2e163756@aol.com> Message-ID: <6.1.2.0.2.20040701214753.02314000@rcblue.com> Dragonfirebane@aol.com wrote at 20:58 7/1/2004: >Look at the Python Docs . . . there exists round(number[, ndigits]) -> >floating point number. From the Docs: ================================ round( x[, n]) Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0). ==================================== So that won't do it. "rounded to n digits AFTER the decimal point". But thanks, Dick From rdm at rcblue.com Fri Jul 2 00:59:09 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 2 00:59:19 2004 Subject: [Tutor] Re: IDLE question In-Reply-To: <20040702042250.63385.qmail@web52602.mail.yahoo.com> References: <20040702042250.63385.qmail@web52602.mail.yahoo.com> Message-ID: <6.1.2.0.2.20040701215815.02284158@rcblue.com> Chad Crabtree wrote at 21:22 7/1/2004: >--- Dick Moores wrote: > > My thanks to Alan Gauld and Andrei for their info re wxPython and > > its > > PyCrust and PyShell. > > > > If I just want to try out wxPython, can I keep it separate from the > > regular Python 2.3.4 I have on my system, and use both as I wish? > > > > BTW I'm using Windows XP Pro. > > >wxPython is not a python distro it's used *WITH* python. It's a >library of fucntions and other stuff. Download it and use the >installer it will make it's own group in your program thingy and play >around. OK! I will. Dick From rdm at rcblue.com Fri Jul 2 01:13:45 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 2 01:13:50 2004 Subject: [Tutor] timer module question In-Reply-To: <20040702042415.65433.qmail@web52608.mail.yahoo.com> References: <6.1.2.0.2.20040701161630.0464a288@rcblue.com> <20040702042415.65433.qmail@web52608.mail.yahoo.com> Message-ID: <6.1.2.0.2.20040701221258.02e7eec0@rcblue.com> Chad Crabtree wrote at 21:24 7/1/2004: >Must this be stored by ascii? if not try looking at the pickle >module. I'm afraid pickling is beyond me at this point. Dick From alan.gauld at blueyonder.co.uk Fri Jul 2 02:51:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 2 02:50:52 2004 Subject: [Tutor] Re: 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: <00a001c46000$fdfcb4c0$6401a8c0@xp> > If I just want to try out wxPython, can I keep it separate from the > regular Python 2.3.4 I have on my system, and use both as I wish? wxPython is NOT a separate version of Python it is only a set of modules and tools. It works with your existing Python. There is no magic involved it is just like the winall package or any other set of modules. Nothing changes except that you can now >>> from wxPython.wx import * and not get an error! Similarly PyCrust and PyShell are simply programs written in Python that get *added* to your PC. They do not change your existing Python installation in any way. Alan G. From rdm at rcblue.com Fri Jul 2 03:02:38 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 2 03:02:46 2004 Subject: [Tutor] Re: IDLE question In-Reply-To: <00a001c46000$fdfcb4c0$6401a8c0@xp> References: <6.1.2.0.2.20040630015549.022d6840@rcblue.com> <007401c45edb$a0275ec0$6401a8c0@xp> <6.1.2.0.2.20040630134707.0452b960@rcblue.com> <00a001c46000$fdfcb4c0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040702000108.0226ad68@rcblue.com> Alan Gauld wrote at 23:51 7/1/2004: > > If I just want to try out wxPython, can I keep it separate from the > > regular Python 2.3.4 I have on my system, and use both as I wish? > >wxPython is NOT a separate version of Python it is only a set of >modules and tools. It works with your existing Python. There is >no magic involved it is just like the winall package or any other >set of modules. Nothing changes except that you can now > > >>> from wxPython.wx import * > >and not get an error! > >Similarly PyCrust and PyShell are simply programs written in >Python that get *added* to your PC. They do not change your >existing Python installation in any way. Ok, got it. Thanks! Dick From alan.gauld at blueyonder.co.uk Fri Jul 2 03:05:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 2 03:04:37 2004 Subject: [Tutor] Rounding to n significant digits? References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> Message-ID: <00a501c46002$e8752950$6401a8c0@xp> > Is there something (a function?) in Python 2.3.4 that will round a result > to n significant digits, or do I need to roll my own? I don't see one in > the math module. the round() function is a builtin. > I mean something like rounding(float, n) that would do this: > float = 123.456789, n = 4, returns 123.5 >>> round(123.45678,3) 123.45699999999999 Note that this will result in a new floating point number, that is you actually lose data in the process. (Which is why it prints out with more than 3 digits - it is a float with all the usual imprecision issues that floats have). "print"ing it instead of evaluating it will give the expected result of course: >>> print round(123.45678,3) 123.457 If you just want to display the number at a given precision but to keep the original accuracy internally use a format string instead. >>> print "%6.3f" % 123.456789 123.457 And of course this creates a string rounded to the nearest digit rather than a floating point number. 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 Fri Jul 2 03:15:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 2 03:15:08 2004 Subject: [Tutor] Rounding to n significant digits? References: <51.40a4e788.2e163756@aol.com> <6.1.2.0.2.20040701214753.02314000@rcblue.com> Message-ID: <00b401c46004$62e83fa0$6401a8c0@xp> > ================================ > round( x[, n]) > > Return the floating point value x rounded to n digits after the decimal > ... > So that won't do it. "rounded to n digits AFTER the decimal point". Oops, sorry I got caught out too. I don't know of anything that rounds to n significant digits. Looks ike you need to roll your own, although a quick search on Google or the Vaults of Parnassus might be worthwhile first since its a non trivial task... Alan G. From rdm at rcblue.com Fri Jul 2 03:37:48 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 2 03:37:53 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <00a501c46002$e8752950$6401a8c0@xp> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040702001107.04867e88@rcblue.com> Alan Gauld wrote at 00:05 7/2/2004: > > Is there something (a function?) in Python 2.3.4 that will round a >result > > to n significant digits, or do I need to roll my own? I don't see >one in > > the math module. > >the round() function is a builtin. > > > I mean something like rounding(float, n) that would do this: > > float = 123.456789, n = 4, returns 123.5 > > >>> round(123.45678,3) >123.45699999999999 > >Note that this will result in a new floating point number, >that is you actually lose data in the process. (Which is >why it prints out with more than 3 digits - it is a float >with all the usual imprecision issues that floats have). >"print"ing it instead of evaluating it will give the expected >result of course: > > >>> print round(123.45678,3) >123.457 > >If you just want to display the number at a given precision >but to keep the original accuracy internally use a format string >instead. > > >>> print "%6.3f" % 123.456789 >123.457 > >And of course this creates a string rounded to the nearest >digit rather than a floating point number. No, the 3 examples I gave are exactly what I want: float = 123.456789, n = 4, returns 123.5 float = .000000123456789, n = 2, returns .00000012 float = 123456789, n = 5, returns 123460000 The kind of rounding to n significant digits I'm after is the kind needed for calculations using physical measurements, where an accuracy greater than n significant digits is impossible. A simple example: Let's say we have 2 lengths forming a 90 degree angle. We measure the sides with an instrument that is accurate to 3 sig. digits, and we get 9.2 meters and 8.1 meters. The hypotenuse is the square root of the sum of their squares, of course. It would be absurd to say that the hypotenuse is 12.2577 m. The only number that makes sense is 12 or possibly 12.3 m. Dick From rdm at rcblue.com Fri Jul 2 03:41:22 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 2 03:41:29 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <00b401c46004$62e83fa0$6401a8c0@xp> References: <51.40a4e788.2e163756@aol.com> <6.1.2.0.2.20040701214753.02314000@rcblue.com> <00b401c46004$62e83fa0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040702003933.02abb4b0@rcblue.com> Alan Gauld wrote at 00:15 7/2/2004: > > ================================ > > round( x[, n]) > > > > Return the floating point value x rounded to n digits after the >decimal > > ... > > So that won't do it. "rounded to n digits AFTER the decimal point". > >Oops, sorry I got caught out too. > >I don't know of anything that rounds to n significant digits. >Looks ike you need to roll your own, although a quick search >on Google or the Vaults of Parnassus might be worthwhile first >since its a non trivial task... I'll give it a try. But I am surprised that Python doesn't have what I want. It seems to have everything else.. Thanks, Dick From atyss4si at hotmail.com Fri Jul 2 05:13:59 2004 From: atyss4si at hotmail.com (Bernard Lebel) Date: Fri Jul 2 05:25:48 2004 Subject: [Tutor] writing ascii files with Numeric? References: <20040701224015.9660.qmail@web60107.mail.yahoo.com> Message-ID: Hi Jeff, Just an idea: have you tried... filehandle.write( str(Matrix) ) Cheers Bernard ----- Original Message ----- From: Jeff Peery To: tutor@python.org Sent: Friday, July 02, 2004 12:40 AM Subject: [Tutor] writing ascii files with Numeric? Hello I am trying to write my Matrix to to a file in ASCII format. I created the matrix using Numeric, the shape is 600x25. here is the code that produces the error below: filehandle = file("MyFile.txt", 'w') filehandle.write(Matrix) filehandle.close() TypeError: Non-character array cannot be interpreted as character buffer. I am assuming this means that 'Matrix' must be a character string and not a matrix. how would I go about converting an array of floats to a character string so I can print this thing to a file? Or is there a better way to do this? thanks!!! Jeff _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ibrahim_cevizci at hotmail.com Fri Jul 2 07:41:24 2004 From: ibrahim_cevizci at hotmail.com (ibrahim cevizci) Date: Fri Jul 2 07:41:29 2004 Subject: [Tutor] (no subject) Message-ID: My name is ibrahim , i am computer enginnering student. I probate in any open source software development company. I try to investigate ruleCore but i can't find enough resource about it. I want to find extended resource. Tutorials are only about what is ruleCore , i want to find how ruleCore is used. Could you help me for finding resource about ruleCore and an example of projects. thanks.... _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From learning.python at dbmail.dk Fri Jul 2 08:22:17 2004 From: learning.python at dbmail.dk (Ole Jensen) Date: Fri Jul 2 08:22:22 2004 Subject: [Tutor] listdir() Message-ID: <003301c4602f$36d8be00$91c48f52@allmycore> Hello list I have recently learnt of the os.listdir() function, and I intend to experiment with it using a cgi-page (html). I would like to have a base directive show all the files and folders, so that the user can browse through it all. Now, listdir() returns both the files and folders in one big mess, so I am wondering if there is some ListFolderInDir() function or similar within python that I should use, if so what is its name and location. I realise that if there is no such function it is easy to create one youself using some try: except:statements e.g. >>> for folder in os.listdir(path): try: print os.listdir(path+folder) except: print folder, "is not a folder!" and puting that into a function that outputs the what you need. But for now I was wondering if there is a simpler way to do? like an built in function... TIA Ole Jensen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040702/c2db737b/attachment.html From jmatthews at mcb-inc.com Fri Jul 2 10:54:24 2004 From: jmatthews at mcb-inc.com (John Matthews) Date: Fri Jul 2 10:50:47 2004 Subject: [Tutor] Where should I save my programs? Message-ID: <40E57720.6010705@mcb-inc.com> I am a novice at programming, using Python 2.3.4 on Windows 2000. I have been saving my programs directly in C:\Python23\. When looking through help and listing the available modules, it lists all of my 'programs' along with the modules. Some files I write are destined to be temporary, while others are for permanent projects. I also download examples that I would like to keep seperate from my 'junk'. Can someone suggest a good folder organization that will not clutter up one of the 'official' Python folders and solve these other problems? If I need to give Python a path to my files, how does that work? Thanks! -- John Matthews McDonald, Cassell & Bassett, Inc. 600 West Spring Street Columbus, Ohio 43215 (614) 628-0630 (614) 628-0633 Fax From askoose at sandia.gov Fri Jul 2 11:18:24 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Fri Jul 2 11:18:46 2004 Subject: [Tutor] String question Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F229@es05snlnt.sandia.gov> Hello, I have posted in here a few times asking questions about data filtering. I have part of a code set-up for removing header information and then extracting a column of data (thanks to the python list for help and book recommendations) then writing the column to another file. My question is twofold: How do I maintain a columned format when I write the data to a new file? When I place the data extracting part of my program into the big filter program I receive the error (I am guessing I have an indent problem or syntax): Traceback (most recent call last): File "C:\Python23\filter.py", line 49, in ? input () File "", line 0 ^ SyntaxError: unexpected EOF while parsing. I have included both the extracting code and the filter code I am trying to place the extracting code in. Thank you very much. EXTRACTING import string inp = open("out.txt","r") outp = open("out2.txt","w") for line in inp.readlines(): words = string.split(line) if len(words) >= 1: outp.write(words[0]) WHOLE FILTER CODE def filterFile(infname,outfname): inp = open(infname, "r") #opens the file lmps for reading outp = open(outfname, "w") #creates the file out.txt for writing while 1: #Starts a loop looking for lines with "I" and then writes out all other lines text = inp.readline() if text =="": break #if there is no text break from the while loop and continue if text[0] =="I": #removes all lines starting with I continue if text[0] =="0": #removes all lines starting 0 continue outp.write(text) #writes the remaining lines to out.txt inp.close() #closes lmps.txt outp.close() #closes out.txt return filterFile("lmps.txt","out.txt") #calls the function to execute it print "Header information has been removed" #tells you that the job has been completed input () import string inp = open("out.txt","r") outp = open("out2.txt","r") for line in inp.readlines(): words = string.split(line) if len(words) >= 1: outp.write.(words[0]) Thanks, Ara "There is something to be learned from a rainstorm. When meeting with a sudden shower, you try not to get wet and run quickly along the road. But doing such things as passing under the eaves of houses, you still get wet. When you are resolved from the beginning, you will not be perplexed, though you still get the same soaking." - Yamamoto Tsunetomo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040702/11d1703c/attachment-0001.html From missive at hotmail.com Fri Jul 2 11:19:58 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Jul 2 11:20:02 2004 Subject: [Tutor] ruleCore (was (no subject)) Message-ID: > My name is ibrahim , i am computer enginnering student. I >probate >in >any open source software development company. I try to investigate ruleCore >but i can't find enough resource about it. I want to find extended >resource. >Tutorials are only about what is ruleCore , i want to find how ruleCore is >used. Could you help me for finding resource about ruleCore and an example >of projects. > http://www.google.com/search?q=python+rulecore http://sourceforge.net/projects/rulecore/ http://www.rulecore.com/ http://www.rulecore.com/support/index.html http://www.rulecore.com/docs/index.html Specifically, I recommend joining the ruleCore mailing list ... http://lists.sourceforge.net/lists/listinfo/rulecore-developer They also say ... ''' Talk to us directly! You can reach us on Jabber: rulecore@jabber.org. We are online during office hours in Central European Time. ''' _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From missive at hotmail.com Fri Jul 2 11:34:46 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Jul 2 11:34:59 2004 Subject: [Tutor] Re: listdir() Message-ID: >I have recently learnt of the os.listdir() function, and I intend to >experiment with it using a cgi-page (html). I would like to have a base >directive show all the files and folders, so that the user can browse >through it all. > >But for now I was wondering if there is a simpler way to do? like an >built in function... > I guess it depends on what your purpose is... but I would say the simplest way to do it would be to install twisted python and then ... >mkdir foo >mkdir foo/bar >touch foo/abc >touch foo/bar/defg >mktap web --port 8888 --path foo >twistd -f web.tap Then point your browser at http://localhost:8888/ _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From orbitz at ezabel.com Fri Jul 2 11:50:44 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Jul 2 11:57:42 2004 Subject: [Tutor] String question In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F229@es05snlnt.sandia.gov> References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F229@es05snlnt.sandia.gov> Message-ID: <40E58454.2010001@ezabel.com> For starters, you don't need to import string. string.split(line) can be done with line.split(). line is of type str, which is a built in and contains most of the string members. import string is only necessary rarely. Secondly I could be wrong, but I don't think you have given enough code to really fix the problem. Your error says it's on line 0, but your input() in what you pasted is definitely not. My guess is you have indented someplace you shouldn't, or vice versa, or you have missed a " or something like that. Good luck Kooser, Ara S wrote: > Hello, > > I have posted in here a few times asking questions about data > filtering. I have part of a code set-up for removing header > information and then extracting a column of data (thanks to the python > list for help and book recommendations) then writing the column to > another file. My question is twofold: How do I maintain a columned > format when I write the data to a new file? When I place the data > extracting part of my program into the big filter program I receive > the error (I am guessing I have an indent problem or syntax): > > Traceback (most recent call last): > File "C:\Python23\filter.py", line 49, in ? > input () > File "", line 0 > ^ > SyntaxError: unexpected EOF while parsing. > > I have included both the extracting code and the filter code I am > trying to place the extracting code in. Thank you very much. > > _EXTRACTING_ > import string > > inp = open("out.txt","r") > outp = open("out2.txt","w") > > for line in inp.readlines(): > words = string.split(line) > if len(words) >= 1: > outp.write(words[0]) > > _WHOLE FILTER CODE_ > def filterFile(infname,outfname): > inp = open(infname, "r") #opens the file lmps for reading > outp = open(outfname, "w") #creates the file out.txt for writing > while 1: #Starts a loop looking for lines with "I" and then > writes out all other lines > text = inp.readline() > if text =="": > break #if there is no text break from the while loop > and continue > if text[0] =="I": #removes all lines starting with I > continue > if text[0] =="0": #removes all lines starting 0 > continue > outp.write(text) #writes the remaining lines to out.txt > inp.close() #closes lmps.txt > outp.close() #closes out.txt > return > filterFile("lmps.txt","out.txt") #calls the function to execute it > print "Header information has been removed" #tells you that the > job has been completed > input () > > import string > inp = open("out.txt","r") > outp = open("out2.txt","r") > for line in inp.readlines(): > words = string.split(line) > if len(words) >= 1: > outp.write.(words[0]) > > Thanks, > Ara > > "There is something to be learned from a rainstorm. When meeting with > a sudden shower, you try not to get wet and run quickly along the > road. But doing such things as passing under the eaves of houses, you > still get wet. When you are resolved from the beginning, you will not > be perplexed, though you still get the same soaking." - Yamamoto Tsunetomo > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From Francis.Moore at shaws.co.uk Fri Jul 2 11:56:31 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Fri Jul 2 12:02:14 2004 Subject: [Tutor] Where should I save my programs? Message-ID: <6081EBC21D52F744B484088BBBE665C3199F13@sbserver.shaws.local> From: John Matthews [mailto:jmatthews@mcb-inc.com] John, > I have been saving my programs directly in C:\Python23\. > Can someone suggest a good folder organization that will not clutter up > one of the 'official' Python folders and solve these other problems? Have you got another hard drive? Or another partition on your hard drive? If so, I would suggest placing all your programs there. What you call it is up to you (i.e. D:\Python, D:\MyPython etc...) > If I need to give Python a path to my files, how does that work? Assuming you've got an env variable set for Python, you should just be able to type at the command prompt: 'python d:\MyPython\my_python_file.py' Or set default to the directory where your python script is and just type: 'python my_python_file.py' 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 alan.gauld at blueyonder.co.uk Fri Jul 2 13:10:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 2 13:09:54 2004 Subject: [Tutor] Where should I save my programs? References: <40E57720.6010705@mcb-inc.com> Message-ID: <00e301c46057$7ddec830$6401a8c0@xp> > I have been saving my programs directly in C:\Python23\. When looking > through help and listing the available modules, it lists all of my > 'programs' along with the modules. > > Some files I write are destined to be temporary, while others are for > permanent projects. I also download examples that I would like to keep > seperate from my 'junk'. Personally I have a PROJECTS folder on my E: (Data) drive. Under that I have different languages that I program in: lisp, c, pascal, java, perl, tcl, python etc... Under python I have lib and test I put stuff I might someday use as a module in the lib folder and all my little one-offs in the test folder. I added the E:\PROJECTS\Python\lib folder to my PYTHONPATH environment variable. I usually start off saving to test and if it works and looks useful then move the working version to the lib folder. If I was being fussy (as I was for my book) I used RCS to version control the files too. It works for me :-) If I was doing a large project with lots of files I'd create a separate project structure for it under PROJECTS... Alan G. From alan.gauld at blueyonder.co.uk Fri Jul 2 13:15:44 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 2 13:15:06 2004 Subject: [Tutor] String question References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F229@es05snlnt.sandia.gov> Message-ID: <00eb01c46058$35ab3de0$6401a8c0@xp> > Traceback (most recent call last): > File "C:\Python23\filter.py", line 49, in ? > input () > File "", line 0 > ^ > SyntaxError: unexpected EOF while parsing. The problem is your use of input() It reads the blank line you type and tries to evaluate it, which it can't do. Use raw_input instead, it simply assigns the string (to nothing in this case) without attempting to evaluate it. Try using the interactive prompt to see the same thing: >>> input() <-- Traceback (most recent call last): File "", line 1, in ? File "", line 0 ^ SyntaxError: unexpected EOF while parsing >>> raw_input() <-- '\n' >>> HTH Alan G. From lbblair at adaptisinc.com Fri Jul 2 13:16:54 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Fri Jul 2 13:17:54 2004 Subject: [Tutor] creating variables from the 'key' of a dictionary. Message-ID: I am really new to python and don't have much idea of the possibilities so this may be a stupid idea or I am thinking in the wrong direction. We use a parameters file to drive different scripts. We have parameters like SOURCE_SERVER = 'cm05', TARGET_SERVER = 'ts02', SOURCE_USER = 'master', SOURCE_PSWD = 'password' etc. etc. For a specific set of servers we can use the same parameter file but extract different parameters specific for the script. When we add a new parameter we have to open each script where it is used and declare the variable and extract the value from the parameters file. I think what I want to do is create a function that would load a dictionary with all parameters from the file. Then in the original script use that dictionary in a for loop to create the variables from the key. My question is there a way to create a variable with the name of the key in a dictionary i.e. para = {} para['source_server'] = 'cm05' at this point I want to create a variable with the name source_server and a value of 'cm05'. Thanks Larry __________________________________ 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 adam at monkeez.org Fri Jul 2 13:44:41 2004 From: adam at monkeez.org (Adam) Date: Fri Jul 2 13:44:27 2004 Subject: [Tutor] Pickling objects and then carrying on development Message-ID: <20040702184441.425b7771@debian> OK - I have a kind of strange question. I'm developing an application which acts as a catalogue for magazine articles, storing each piece of information in an OO manner. I've written those objects to disk through pickle, which is an enormously cool feature of python. My question relates to the pickled object and also the code that relates to those objects. If I enter data in and pickle this data, and then later develop my code adding more methods and functionality to each class, will the old data automatically gain all this new functionality when it is unpickled later? The sequence would be: 1) Data entry and pickle... 2) Develop and improve code 3) Load data 4) continue with data entry 5) pickle once more Does the new pickle pick up all the new code that I've been working on, or will it b0rk the whole thing? Any advice greatly received. adam From michele.alzetta at aliceposta.it Fri Jul 2 14:03:04 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Fri Jul 2 14:03:10 2004 Subject: [Tutor] complex iteration over a list Message-ID: <1088791384.10184.37.camel@localhost> Hallo all ! I'm stuck on the following type of code (still working on classes that handle periods of time). I have a list called months: months = [31,28,31,30,31,30,31,31,30,31,30,31] daysinperiod = [] startday, numberofdays, index = 10, 40, 5 # actual value of these has been determined previously # in my program, I am just assigning them directly now to # keep things simple for day in range(startday,numberofdays): # the range is a period of time, in this case, from the 10th # of June to the 20th of July if day <= months[index]: daysinperiod.append(day) if day > months[index]: daysinperiod.append(day-months[index]) print daysinperiod The output I want is a list like this: 10,11,..,30,1,2,...,19 Above code works perfectly in this case, but it doesn't if numberofdays is > 51 of course. To have this work for periods that overlap the end of two or more months I would have to be able to change the value of "index" in my recursion somehow ... ? For all practical purposes I could simply forbid the case where the length of my time period is too long, but supposing in the future I wanted to adapt this class for other things ? Besides, the purpose of this whole thing is learning ! I could also look into the calendar module... (which will probably end up being the simplest way of handling this). But I keep on feeling there ought to be an elegant way to do this even without calendar. Any suggestions ? -- Michele Alzetta From glingl at aon.at Fri Jul 2 14:52:54 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Jul 2 14:52:14 2004 Subject: [Tutor] complex iteration over a list Message-ID: <40E5AF06.1020506@aon.at> Michele Alzetta schrieb: >Hallo all ! > >I'm stuck on the following type of code (still working on >classes that handle periods of time). > >I have a list called months: > >months = [31,28,31,30,31,30,31,31,30,31,30,31] >daysinperiod = [] >startday, numberofdays, index = 10, 40, 5 ># actual value of these has been determined previously ># in my program, I am just assigning them directly now to ># keep things simple > >for day in range(startday,numberofdays): > > > if day <= months[index]: > daysinperiod.append(day) > if day > months[index]: > daysinperiod.append(day-months[index]) > > > Suggestion: Within your for-loop: create a pair of names d, i which initially have the values day and index replace the 2 if-statements with a while loop that calculates the correct day number: you have to subtract months[i] from d as long as d > months[i] and subsequently increment i by 1 (to use the next month in the next execution of the loop body) append d to daysinperiod Does this help? Regards, Gregor From jeff at ccvcorp.com Fri Jul 2 15:02:28 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Jul 2 15:02:44 2004 Subject: [Tutor] listdir() In-Reply-To: <003301c4602f$36d8be00$91c48f52@allmycore> References: <003301c4602f$36d8be00$91c48f52@allmycore> Message-ID: <40E5B144.3030400@ccvcorp.com> Ole Jensen wrote: > Now, listdir() returns both the files and folders in one big mess, so I > am wondering if there is some ListFolderInDir() function or similar > within python that I should use, if so what is its name and location. > [...] > But for now I was wondering if there is a simpler way to do? like an > built in function... Look into the os.isdir() function, which will tell you easily whether a given pathname is a directory or not. You will, however, need to do your own sorting if you want directories to appear before regular files. (Of course, you'd probably want to sort entries anyhow, since IIRC the ordering returned by os.listdir() is arbitrary.) Jeff Shannon Technician/Programmer Credit International From derekp at sentechsa.co.za Fri Jul 2 15:04:36 2004 From: derekp at sentechsa.co.za (Derek Pienaar) Date: Fri Jul 2 15:04:38 2004 Subject: [Tutor] Difference between a class & module? Message-ID: <200407022104.37167.derekp@sentechsa.co.za> Halo Guys. I need to clear up some confusion regarding a class and a module. This question came up when I saw an example in "a byte of python" tutorial, where the join method was used, but (as I saw it) without importing the string module (as I understood it). I thought that some frequently used "modules" were built-in and that string was one of them... not so. I understand what a class does ... among other things, it mainly defines or is a template for an object. I understand the concept of objects & instances but thought that a module was exactly the same as a class. To my surprise, I heard it not to be so. What then is a module? Please try and keep the explanation plain and simple if possible :-) Thanks in advance. Derek From jeff at ccvcorp.com Fri Jul 2 15:13:22 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Jul 2 15:13:51 2004 Subject: [Tutor] creating variables from the 'key' of a dictionary. In-Reply-To: References: Message-ID: <40E5B3D2.9000200@ccvcorp.com> Larry Blair wrote: > I think what I want to do is create a function that would load a dictionary > with all parameters from the file. > Then in the original script use that dictionary in a for loop to create the > variables from the key. > > My question is there a way to create a variable with the name of the key in > a dictionary i.e. > > para = {} > para['source_server'] = 'cm05' Yes, you can do that. The following three code fragments all result in an identical dictionary: para = { 'source_server':'cm05' } para = {} para['source_server'] = 'cm05' key = 'source_server' value = 'cm05' para = {} para[key] = value In addition, there's a couple of things that might make your life even easier. First, consider creating a Python module called settings.py, which contains the definition of your parameters dictionary: ----- settings.py --------- para = { 'source_server':'cm05', 'target_server':'tm02', ... } --------------------------- Now, in your other files, you can simply import settings src = settings.para['source_server'] .... Second, if your settings are very dynamic and change often, it might be useful to investigate the shelve module. This is a library module that will essentially allow you to store the current state of a dictionary as a disk file, and to later reload that dictionary from the file. This would let you have a persistent record of the most recent state of your parameters. Jeff Shannon Technician/Programmer Credit International From glingl at aon.at Fri Jul 2 15:24:23 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Jul 2 15:23:42 2004 Subject: [Tutor] Difference between a class & module? Message-ID: <40E5B667.9040705@aon.at> Derek Pienaar schrieb: >Halo Guys. > >I need to clear up some confusion regarding a class and a module. > >This question came up when I saw an example in "a byte of python" >tutorial, where the join method was used, but (as I saw it) without >importing the string module (as I understood it). > >I thought that some frequently used "modules" were built-in and that >string was one of them... not so. > >I understand what a class does ... among other things, it mainly defines >or is a template for an object. I understand the concept of objects & >instances but thought that a module was exactly the same as a class. > >To my surprise, I heard it not to be so. What then is a module? Please >try and keep the explanation plain and simple if possible :-) > > > A module simply is a file, which contains Python statements. Normally among these there are def statements - so execution of the module defines some functions - and class statements - so execution of the module defines smo classes. A module may also contain names (variables) and other directly executable Python statements. names (of functions, classes, variables) can be imported with the import statement: import or from module import In the latter case you can use the names directly, in the first one you have to qualify them with the module name via dot-notation module.name May be your confusion araouse becaue there was a heavily used module string which has become less often used since strings are built in objects in Python which have their own methods. Old fashioned way: import string s = string.upper(s) Modern way: # no import necessary s = s.upper() Hope this helps. (Certainly additional explanations will follow ;-) ) Regards, Gregor From project5 at redrival.net Fri Jul 2 15:38:37 2004 From: project5 at redrival.net (Andrei) Date: Fri Jul 2 15:39:03 2004 Subject: [Tutor] Re: Difference between a class & module? References: <200407022104.37167.derekp@sentechsa.co.za> Message-ID: Derek Pienaar wrote on Fri, 2 Jul 2004 21:04:36 +0200: > This question came up when I saw an example in "a byte of python" > tutorial, where the join method was used, but (as I saw it) without > importing the string module (as I understood it). That string module is such an everlasting source of confusion :). > I thought that some frequently used "modules" were built-in and that > string was one of them... not so. A module is not built-in. A module may be part of the standard library, but it's by definition external (as in: you don't by definition have access to it, unlike built-ins which are always accessible - unless you overwrite them of course). > I understand what a class does ... among other things, it mainly defines > or is a template for an object. I understand the concept of objects & > instances but thought that a module was exactly the same as a class. Nope. The string module is from before strings had methods (IOW, strings weren't objects) - at least this is what I assume, since I wasn't using Python at the time. If you want to work with raw data (as opposed to objects which combine data and functions), you'll have to define functions which take that data as parameter, do something with it and return a result. So the string module contains a few constants and a lot of functions which can be applied to strings. When strings became objects, they got methods for doing stuff that was done before using the functions in the strings module. OLD way: import strings splitstring = strings.split(mystring) NEW way (split method is provided by a string object): splitstring = mystring.split() > To my surprise, I heard it not to be so. What then is a module? Please > try and keep the explanation plain and simple if possible :-) Modules are simply collections of code (can be classes, constants, functions, whatever): every Python program is also automatically a module. They're most certainly not classes. You can e.g. not subclass a module to add more functionality. -- 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 Fri Jul 2 15:42:13 2004 From: project5 at redrival.net (Andrei) Date: Fri Jul 2 15:50:45 2004 Subject: [Tutor] Re: creating variables from the 'key' of a dictionary. References: Message-ID: <1ehnb96vi4qss.3c9tkubbpx8z.dlg@40tude.net> Larry Blair wrote on Fri, 2 Jul 2004 10:16:54 -0700: > My question is there a way to create a variable with the name of the key in > a dictionary i.e. > > para = {} > para['source_server'] = 'cm05' > > at this point I want to create a variable with the name source_server and a > value of 'cm05'. Use the globals() dictionary (it contains a dictionary mapping all variable names to corresponding objects): >>> globals()['source_server'] = 'cm05' >>> source_server 'cm05' But I think Jeff's suggestions for a settings module shared by all your apps is a better idea. -- 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 learning.python at dbmail.dk Fri Jul 2 16:02:35 2004 From: learning.python at dbmail.dk (Ole Jensen) Date: Fri Jul 2 16:02:39 2004 Subject: [Tutor] listdir() References: <003301c4602f$36d8be00$91c48f52@allmycore> <40E5B144.3030400@ccvcorp.com> Message-ID: <002901c4606f$84dba500$9ec48f52@allmycore> Jeff Shannon wrote: > Look into the os.isdir() function, which will tell you easily whether > a given pathname is a directory or not. You will, however, need to do > your own sorting if you want directories to appear before regular > files. (Of course, you'd probably want to sort entries anyhow, since > IIRC the ordering returned by os.listdir() is arbitrary.) I guess you mean os.path.isdir()... I'll have a look at it. Thanks. IIRC - what's that? Regards Ole From derekp at sentechsa.co.za Fri Jul 2 16:35:46 2004 From: derekp at sentechsa.co.za (Derek Pienaar) Date: Fri Jul 2 16:35:55 2004 Subject: [Tutor] Re: Difference between a class & module? References: <200407022104.37167.derekp@sentechsa.co.za> Message-ID: <004901c46074$4c561800$0300a8c0@winpvt> Guys thank you very much for the reply, it has certainly cleared up some misconceptions that was arising :-). >From Andrei and Greg's replies, I've gathered that the .join method is then a builtin function? I am referring to this code (version 1): http://www.python.g2swaroop.net/byte/ch10s02.html#first-version The .join method is used without importing any string modules ... therefore a builtin function? Many Thanks. Derek From glingl at aon.at Fri Jul 2 16:56:15 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Jul 2 16:55:35 2004 Subject: [Tutor] Re: Difference between a class & module? In-Reply-To: <004901c46074$4c561800$0300a8c0@winpvt> References: <200407022104.37167.derekp@sentechsa.co.za> <004901c46074$4c561800$0300a8c0@winpvt> Message-ID: <40E5CBEF.1040501@aon.at> Derek Pienaar schrieb: >Guys thank you very much for the reply, it has certainly cleared up >some misconceptions that was arising :-). > >>From Andrei and Greg's replies, I've gathered that the .join method >is then a builtin function? > >I am referring to this code (version 1): >http://www.python.g2swaroop.net/byte/ch10s02.html#first-version > >The .join method is used without importing any string modules ... therefore >a builtin function? > > > No. It's a method, which can only be called for a given string and operates on that string, e. g.: >>> l=["a","b","cde","f"] >>> "".join(l) 'abcdef' >>> "---".join(l) 'a---b---cde---f' >>> "\n".join(l) 'a\nb\ncde\nf' >>> print "\n".join(l) a b cde f >>> A method should be viewed as a function, which is bound to a given object - in this case to a string object. (You told us, that you know about classes and objects, the "functions" you define within a class-body (which have self as the first parameter) are called methods of that class (or of the objects created with that class.) Regards, Gregor P.S.: Have a look at http://docs.python.org/lib/string-methods.html >Many Thanks. > >Derek > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From lbblair at adaptisinc.com Fri Jul 2 16:59:50 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Fri Jul 2 17:00:23 2004 Subject: [Tutor] creating variables from the 'key' of a dictionary. Fu rther explainations Message-ID: These are great ideas and starting to get me in the direction I need to go - I think :) What we have are multiple parameter files. Each has the same parameters but with different values. i.e. p_file1 will have source_server = 'cm05' and target_server = 'ts05' - we are backing up data from cm05 to ts05. p_file2 will have source_server = 'pd01' and target_server = 'bk01'. We give the specific parameter file to the script at run time for backing up different sets of servers. As we add new equipment, SANs, databases etc. our list of parameters grows. Now we have to send a session_name, snapshot_name database names, usernames, passwords etc. which are different for the different servers and databases. I like the idea of creating a module but that would be a single set of values wouldn't it? Or is there a way to read the specified parameter file and then 'compile' and import the module on the fly? My intent is 1. to have a function to read the parameters file - create a list or dictionary of each parameter and value 2. and pass it back to the calling script and then have a for loop that would dynamically create all variables( these are the keys in the dictionary) with the matching value. This way if we added a parameter I could add the code only to the function to add the key and value to the dictionary. Then part 2 would automatically create the new variable and I would not have to change code but in one place. the code would look like for pr, item in para.item(): some-magic-function where a variable would appear with a value. i.e. source_server = 'cm05' etc until the end of the dictionary. Thanks Larry -----Original Message----- From: Jeff Shannon [mailto:jeff@ccvcorp.com] Sent: Friday, July 02, 2004 12:13 PM To: tutor@python.org Cc: Larry Blair Subject: Re: [Tutor] creating variables from the 'key' of a dictionary. Larry Blair wrote: > I think what I want to do is create a function that would load a dictionary > with all parameters from the file. > Then in the original script use that dictionary in a for loop to create the > variables from the key. > > My question is there a way to create a variable with the name of the key in > a dictionary i.e. > > para = {} > para['source_server'] = 'cm05' Yes, you can do that. The following three code fragments all result in an identical dictionary: para = { 'source_server':'cm05' } para = {} para['source_server'] = 'cm05' key = 'source_server' value = 'cm05' para = {} para[key] = value In addition, there's a couple of things that might make your life even easier. First, consider creating a Python module called settings.py, which contains the definition of your parameters dictionary: ----- settings.py --------- para = { 'source_server':'cm05', 'target_server':'tm02', ... } --------------------------- Now, in your other files, you can simply import settings src = settings.para['source_server'] .... Second, if your settings are very dynamic and change often, it might be useful to investigate the shelve module. This is a library module that will essentially allow you to store the current state of a dictionary as a disk file, and to later reload that dictionary from the file. This would let you have a persistent record of the most recent state of your parameters. Jeff Shannon Technician/Programmer Credit International __________________________________ 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 tim.peters at gmail.com Fri Jul 2 17:19:02 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri Jul 2 17:19:37 2004 Subject: [Tutor] Pickling objects and then carrying on development In-Reply-To: <20040702184441.425b7771@debian> References: <20040702184441.425b7771@debian> Message-ID: <1f7befae040702141960cf9c17@mail.gmail.com> [Adam] > OK - I have a kind of strange question. I'm developing an > application which acts as a catalogue for magazine articles, > storing each piece of information in an OO manner. I've > written those objects to disk through pickle, which is an > enormously cool feature of python. > > My question relates to the pickled object and also the code > that relates to those objects. If I enter data in and pickle > this data, and then later develop my code adding more > methods and functionality to each class, will the old data > automatically gain all this new functionality when it is > unpickled later? Yes, it will. pickle stores only data, never code. This isn't a necessary behavior, it's just how things are. The code that makes up your class is not pickled. Instead, when an instance of your class is pickled, the *path* to your class (its module and class name) is pickled, as a string. Unpickling effectively imports the (current) class code via the path in that string. Note that this may not always be what you want, though. For example, if you rename your class, or move your class into a different module or package, then you'll no longer be able to load old pickles referencing that class (using its former name or location). > The sequence would be: > 1) Data entry and pickle... > 2) Develop and improve code > 3) Load data > 4) continue with data entry > 5) pickle once more > > Does the new pickle pick up all the new code that I've been > working on, Yes, but because the code was never in the pickle, just the data, and a string recording from where to import the class. From alan.gauld at blueyonder.co.uk Fri Jul 2 18:16:12 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 2 18:16:16 2004 Subject: [Tutor] Difference between a class & module? References: <200407022104.37167.derekp@sentechsa.co.za> Message-ID: <013701c46082$2f4236a0$6401a8c0@xp> > I thought that some frequently used "modules" were built-in and that > string was one of them... not so. Some modules are indeed built in. And the string class is also built in, but that's not the same as the string module! > I understand what a class does ... among other things, it mainly defines > or is a template for an object. I understand the concept of objects & > instances but thought that a module was exactly the same as a class. No, a module is, in its most general form, any kind of reusable code block. Thus a function is a type of module as is a class. However in Python, module has the more specific meaning of a file containing functions, data, (and classes which are a special type of data!). Modules (or more specifically their names or the names inside them) are imported into Python programs. Classes by contrast are instantiated not imported. For a more complete explanation try my tutorial, the topic on "Modules and Functions" and the OOP topic for classes/objects. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From rob.benton at conwaycorp.net Fri Jul 2 18:17:16 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Fri Jul 2 18:17:22 2004 Subject: [Tutor] database access Message-ID: <40E5DEEC.70005@conwaycorp.net> Hey I'm relatively new to Python. I've looked around a little and seen lots of database modules for Oracle. Do any of those work with oracle custom objects? From david at graniteweb.com Fri Jul 2 18:46:47 2004 From: david at graniteweb.com (David Rock) Date: Fri Jul 2 18:46:51 2004 Subject: [Tutor] complex iteration over a list In-Reply-To: <1088791384.10184.37.camel@localhost> References: <1088791384.10184.37.camel@localhost> Message-ID: <20040702224647.GB25342@wdfs.graniteweb.com> * Michele Alzetta [2004-07-02 20:03]: > Hallo all ! > I could also look into the calendar module... (which will probably end > up being the simplest way of handling this). > But I keep on feeling there ought to be an elegant way to do this even > without calendar. > Any suggestions ? I think calendar and datetime are what you want for this. -- 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/20040702/ac19da50/attachment.bin From jeff at ccvcorp.com Fri Jul 2 21:24:30 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Jul 2 21:24:45 2004 Subject: [Tutor] listdir() In-Reply-To: <002901c4606f$84dba500$9ec48f52@allmycore> References: <003301c4602f$36d8be00$91c48f52@allmycore> <40E5B144.3030400@ccvcorp.com> <002901c4606f$84dba500$9ec48f52@allmycore> Message-ID: <40E60ACE.5040403@ccvcorp.com> Ole Jensen wrote: > Jeff Shannon wrote: > >>Look into the os.isdir() function, which will tell you easily whether >>a given pathname is a directory or not. You will, however, need to do >>your own sorting if you want directories to appear before regular >>files. (Of course, you'd probably want to sort entries anyhow, since >>IIRC the ordering returned by os.listdir() is arbitrary.) > > > I guess you mean os.path.isdir()... I'll have a look at it. > Thanks. Ah, yes, I was replying from memory, and the details sometimes slip... > IIRC - what's that? IIRC == if I remember correctly Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Fri Jul 2 21:43:11 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Jul 2 21:43:26 2004 Subject: [Tutor] creating variables from the 'key' of a dictionary. Further explainations In-Reply-To: References: Message-ID: <40E60F2F.7070508@ccvcorp.com> Larry Blair wrote: > This way if we added a parameter I could add the code only to the function > to add the key and value to the dictionary. Then part 2 would automatically > create the new variable and I would not have to change code but in one > place. > > the code would look like > > for pr, item in para.item(): > some-magic-function where a variable would appear with a value. i.e. > source_server = 'cm05' etc until the end of the dictionary. Why would you want to create local/global variables? Why not just use the value straight out of the dictionary? In other words, everywhere where you're thinking of using "source_server", why not just use "param['source_server']" instead? This will save you a step, spare you headaches fiddling with locals()/globals(), and will be much less likely to result in surprising side-effects. For that matter, if you really don't care for dictionary syntax, you can set up your parameters as global to a separate module, like so: -------- param.py -------- source_server = 'cm05' dest_server = 'tm02' -------------------------- -------- main.py --------- import param print param.source_server -------------------------- Either way, whether you do this or use a dictionary, you're conveniently isolating all of your parameters. If you need to change anything, you can edit param.py and reload() it. To quote the Zen of Python, "Namespaces are one honking great idea -- let's do more of those!" By keeping those parameters in a separate file, and deliberately accessing them as a separate thing, you're introducing a separate namespace and thereby helping to keep things nice and organized. And organization is easier to maintain. :) Jeff Shannon Technician/Programmer Credit International From tim.peters at gmail.com Fri Jul 2 23:18:55 2004 From: tim.peters at gmail.com (Tim Peters) Date: Fri Jul 2 23:19:11 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <6.1.2.0.2.20040702001107.04867e88@rcblue.com> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> Message-ID: <1f7befae04070220187944a7ff@mail.gmail.com> [Dick Moores] > ... > No, the 3 examples I gave are exactly what I want: > float = 123.456789, n = 4, returns 123.5 > float = .000000123456789, n = 2, returns .00000012 > float = 123456789, n = 5, returns 123460000 I expect the easiest way to do this in Python is to convert to string using an %e format, then convert that back to float again. Like this: """ def round_to_n(x, n): if n < 1: raise ValueError("number of significant digits must be >= 1") # Use %e format to get the n most significant digits, as a string. format = "%." + str(n-1) + "e" as_string = format % x return float(as_string) print round_to_n(123.456789, 4) print round_to_n(.000000123456789, 2) print round_to_n(123456789, 5) """ That displays 123.5 1.2e-007 123460000.0 Be sure to the read the appendix on floating-point issues in the Python Tutorial too! You clearly have decimal digits in mind, but that's not how your computer's floating-point hardware works. The appendix talks about the consequences of that. From adam at monkeez.org Sat Jul 3 02:02:11 2004 From: adam at monkeez.org (Adam) Date: Sat Jul 3 02:02:22 2004 Subject: [Tutor] Pickling objects and then carrying on development In-Reply-To: <1f7befae040702141960cf9c17@mail.gmail.com> References: <20040702184441.425b7771@debian> <1f7befae040702141960cf9c17@mail.gmail.com> Message-ID: <40E64BE3.8060800@monkeez.org> Tim Peters wrote: > [Adam] > >>OK - I have a kind of strange question. I'm developing an >>application which acts as a catalogue for magazine articles, >>storing each piece of information in an OO manner. I've >>written those objects to disk through pickle, which is an >>enormously cool feature of python. >> >>My question relates to the pickled object and also the code >>that relates to those objects. If I enter data in and pickle >>this data, and then later develop my code adding more >>methods and functionality to each class, will the old data >>automatically gain all this new functionality when it is >>unpickled later? > > > Yes, it will. pickle stores only data, never code. This isn't a > necessary behavior, it's just how things are. The code that makes up > your class is not pickled. Instead, when an instance of your class is > pickled, the *path* to your class (its module and class name) is > pickled, as a string. Unpickling effectively imports the (current) > class code via the path in that string. > > Note that this may not always be what you want, though. For example, > if you rename your class, or move your class into a different module > or package, then you'll no longer be able to load old pickles > referencing that class (using its former name or location). > > >>The sequence would be: >>1) Data entry and pickle... >>2) Develop and improve code >>3) Load data >>4) continue with data entry >>5) pickle once more >> >>Does the new pickle pick up all the new code that I've been >>working on, > > > Yes, but because the code was never in the pickle, just the data, and > a string recording from where to import the class. Many thanks Peter - makes perfect sense. adam From Dragonfirebane at aol.com Sat Jul 3 02:06:05 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jul 3 02:06:21 2004 Subject: [Tutor] findall() Message-ID: Hello list. I'm trying to get the following code to work: def getlog(activity,type,endtype): log = open("Multivert_Log.txt","r") for line in log.readlines(): ac = re.compile(activity) fac = re.findall(ac, line) if fac: print line break else: print "Uh-oh." log.close() logagain = open("Multivert_Log.txt","r") ty = re.compile(type) fty = re.findall(ty,line) for line in logagain.readlines(): if not fty: fty = re.findall(ty,line) elif fty: print line break logagain.close() ex = re.compile("\d") fex = re.findall(ex,line) logain = open("Multivert_Log.txt","r") for line in logain.readlines(): if not fex: fex = re.findall(ex,line) elif fex: print line break If, for example, [readlines():] returns: "CALCULATION EXPONENTS 1 ** 1 = 1 ", the code poduces: "CALCULATION " Any suggestions as to how to go about this, as well as to why the program behaves this way, are welcome. 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/20040703/98f19357/attachment.html From rdm at rcblue.com Sat Jul 3 03:11:03 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 3 03:13:26 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <1f7befae04070220187944a7ff@mail.gmail.com> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> Message-ID: <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com> At 20:18 7/2/2004, Tim Peters wrote: >[Dick Moores] > > ... > > No, the 3 examples I gave are exactly what I want: > > float = 123.456789, n = 4, returns 123.5 > > float = .000000123456789, n = 2, returns .00000012 > > float = 123456789, n = 5, returns 123460000 > >I expect the easiest way to do this in Python is to convert to string >using an %e format, then convert that back to float again. Like this: > >""" >def round_to_n(x, n): > if n < 1: > raise ValueError("number of significant digits must be >= 1") > # Use %e format to get the n most significant digits, as a string. > format = "%." + str(n-1) + "e" > as_string = format % x > return float(as_string) > >print round_to_n(123.456789, 4) >print round_to_n(.000000123456789, 2) >print round_to_n(123456789, 5) >""" > >That displays > >123.5 >1.2e-007 >123460000.0 > >Be sure to the read the appendix on floating-point issues in the >Python Tutorial too! You clearly have decimal digits in mind, but >that's not how your computer's floating-point hardware works. The >appendix talks about the consequences of that. *That* is beautiful. Thank you! And the appendix you mentioned is enlightening. But I realize that I don't need to return a float. Just the string will do. Therefore, this revision of your function will do exactly what I was thinking of, even if I didn't say so: """ def round_to_n(x, n): if n < 1: raise ValueError("number of significant digits must be >= 1") # Use %e format to get the n most significant digits, as a string. format = "%." + str(n-1) + "e" as_string = format % x return as_string """ print round_to_n(123.456789, 4) print round_to_n(.000000123456789, 2) print round_to_n(123456789, 5) That displays 1.235e+002 1.2e-007 1.2346e+008 (this is much better than getting the ".0" of 123460000.0, which implies accuracy to 10 significant digits instead of 5.) Dick Moores From dyoo at hkn.eecs.berkeley.edu Sat Jul 3 03:48:04 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 3 03:48:07 2004 Subject: [Tutor] writing ascii files with Numeric? In-Reply-To: Message-ID: On Fri, 2 Jul 2004, Bernard Lebel wrote: > Just an idea: have you tried... > filehandle.write( str(Matrix) ) Hi Bernard, Although this does write the string representation of the matrix to disk, it's written in a way that might not be so easy to bring back to Numeric matrix object form. The str() of a value is usually only for human consumption. According to: http://www.pfdubois.com/numpy/html2/numpy-12.html#pgfId-67223 we should be able to use the standard 'pickle' module for saving and restoring Numeric arrays. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sat Jul 3 04:27:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 3 04:27:36 2004 Subject: [Tutor] findall() In-Reply-To: Message-ID: On Sat, 3 Jul 2004 Dragonfirebane@aol.com wrote: > I'm trying to get the following code to work: > > def getlog(activity,type,endtype): > log = open("Multivert_Log.txt","r") > for line in log.readlines(): > ac = re.compile(activity) > fac = re.findall(ac, line) > if fac: > print line > break > else: > print "Uh-oh." > log.close() > logagain = open("Multivert_Log.txt","r") > ty = re.compile(type) > fty = re.findall(ty,line) > for line in logagain.readlines(): > if not fty: > fty = re.findall(ty,line) > elif fty: > print line > break > logagain.close() > ex = re.compile("\d") > fex = re.findall(ex,line) > logain = open("Multivert_Log.txt","r") > for line in logain.readlines(): > if not fex: > fex = re.findall(ex,line) > elif fex: > print line > break Hi Dragonfirebane, The code feels like it's doing too much. Since you're asking us to help debug the code, we have to do everything we can to understand the code; this might involve changing the structure of the program so we don't have to read so much at once. I hope you don't mind if I split it up into multiple functions? It may help us to see what the code is really doing. Here's a start: ###### def getlog(activity, type, endtype): tryToPrintActivityLine(activity) tryToPrintTypeLine(type) tryToPrintSomeDigit() def tryToPrintActivityLine(activity): log = open("Multivert_Log.txt","r") for line in log.readlines(): ac = re.compile(activity) fac = re.findall(ac, line) if fac: print line break else: print "Uh-oh." log.close() def trytoPrintTypeLine(type): logagain = open("Multivert_Log.txt","r") ty = re.compile(type) fty = re.findall(ty,line) for line in logagain.readlines(): if not fty: fty = re.findall(ty,line) elif fty: print line break logagain.close() def tryToPrintSomeDigit(): ex = re.compile("\d") fex = re.findall(ex,line) logain = open("Multivert_Log.txt","r") for line in logain.readlines(): if not fex: fex = re.findall(ex,line) elif fex: print line break ###### I'm guessing that the code fits has three distinct blocks of function: 'activity', 'type', and something else that I haven't figured out yet. *grin* Each function does almost the same thing, but with suble differences. In fact, the variation in the three blocks is almost certainly buggy; the third block tries to do a findall() search, but even before it reads in 'logain'. As far as I can tell, the 'endtype' parameter passed into the original getlog() function is never used, so I'd drop it: it's confusing to take in parameter that aren't used. There's probably a bug in the third regular expression: ex = re.compile("\d") Use raw strings when you write regular expression patterns: ex = re.compile(r"\d") There's an explanation of why backslashes are slightly complicated: http://www.amk.ca/python/howto/regex/regex.html#SECTION000420000000000000000 > If, for example, [readlines():] returns: > > "CALCULATION > > > > > > EXPONENTS > > > > 1 ** 1 = 1 > ", > the code poduces: > > "CALCULATION > > > > " Ok, so you showed us a "experimental input", an an "experimental output" from the program. But what was the "expected output"? That is, what did you want to see? Pretend that we don't know what it's supposed to do. Hope this helps! From michele.alzetta at aliceposta.it Sat Jul 3 04:54:21 2004 From: michele.alzetta at aliceposta.it (Michele Alzetta) Date: Sat Jul 3 04:54:26 2004 Subject: [Tutor] complex iteration over a list In-Reply-To: <40E5AEC1.3070806@aon.at> References: <1088791384.10184.37.camel@localhost> <40E5AEC1.3070806@aon.at> Message-ID: <1088844861.8853.17.camel@localhost> Il ven, 2004-07-02 alle 20:51, Gregor Lingl ha scritto: > Suggestion: > Within your for-loop: > create a pair of names d, i which initially have the values day and > index > replace the 2 if-statements with a while loop that calculates the > correct day number: you have to subtract months[i] from d > as long as d > months[i] and subsequently increment i by 1 > (to use the next month in the next execution of the loop > body) > append d to daysinperiod Hmm .. yes, I think that is what I was looking for, and it will come in handy for another thing of the same sort I'll have to code in a while. This particular problem though is more easily solved ! I've found that calendar is useless, but datetime.timedelta does it, as my startday is a timedelta object (and so is my endday, which I had changed to number of days thinking it would make things simpler). startday = datetime(2004,6,1,8) endday = datetime(2004,9,1,8) def daysinperiod(startday,endday): daysinperiod = [] while startday <= endday: daysinperiod.append(startday.day) startday = startday + timedelta(days=1) return daysinperiod Eliminates the need for lists with the length of different months, eliminates the nightmare of leap-years ... Python is always simpler and more powerful than one thinks :-) -- Michele Alzetta From rdm at rcblue.com Sat Jul 3 05:05:37 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 3 05:06:12 2004 Subject: [Tutor] A year's calendar to a text file? Message-ID: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> I'm just beginning to get into learning the use of file methods. I'm wondering what the limits are. One I've thought of is, can I write to a file a year's calendar created using the calendar module? I've got the trivial script for the calendar: """ # print any year's calendar from 1 C.E. through 9999 C.E. import calendar calendar.setfirstweekday(6) # sets first day of week to Sunday year = int(raw_input("Enter year for which to print calendar ")) print "\n\n" calendar.prcal(year) """ If this is possible, could someone tell me so, and get me headed in the right direction without giving me the whole solution? Thanks, tutors Dick Moores From pythonTutor at venix.com Sat Jul 3 12:19:34 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Jul 3 12:19:41 2004 Subject: [Tutor] A year's calendar to a text file? In-Reply-To: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> References: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> Message-ID: <1088871573.2095.25.camel@laptop.venix.com> It looks like prcal (and the other print functions in calendar) use sys.stdout for the output file. There's no real skill to the programming solution. The problem is knowing the name (binding) for the file used in the calendar module. The solution is to assign (bind) your file to the name used in the calendar module. Since sys.stdout is generally the default output file, you will want to bind sys.stdout back to its original file after you are done printing the calendar. try / finally is the python language construct to use to make sure that sys.stdout is restored even if something goes wrong printing the calendar. Also, you need to import sys to be able to reference sys.stdout. Hopefully this is the information you are looking for with the right level of detail. On Sat, 2004-07-03 at 05:05, Dick Moores wrote: > I'm just beginning to get into learning the use of file methods. I'm > wondering what the limits are. One I've thought of is, can I write to a > file a year's calendar created using the calendar module? I've got the > trivial script for the calendar: > > """ > # print any year's calendar from 1 C.E. through 9999 C.E. > > import calendar > > calendar.setfirstweekday(6) # sets first day of week to Sunday > > year = int(raw_input("Enter year for which to print calendar ")) > > print "\n\n" > calendar.prcal(year) > """ > > If this is possible, could someone tell me so, and get me headed in the > right direction without giving me the whole solution? > > Thanks, tutors > > Dick Moores > > > _______________________________________________ > 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 Sat Jul 3 12:44:19 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sat Jul 3 12:44:24 2004 Subject: [Tutor] Difference between a class & module? In-Reply-To: <013701c46082$2f4236a0$6401a8c0@xp> Message-ID: <20040703164419.93702.qmail@web52606.mail.yahoo.com> --- Alan Gauld wrote: > > > I thought that some frequently used "modules" were built-in and > that > > string was one of them... not so. > > Some modules are indeed built in. And the string class is also > built in, but that's not the same as the string module! > > > I understand what a class does ... among other things, it mainly > defines > > or is a template for an object. I understand the concept of > objects > & > > instances but thought that a module was exactly the same as a > class. > > No, a module is, in its most general form, any kind of reusable > code > block. Thus a function is a type of module as is a class. However > in Python, module has the more specific meaning of a file > containing > functions, data, (and classes which are a special type of data!). > Modules (or more specifically their names or the names inside them) > are imported into Python programs. Classes by contrast are > instantiated not imported. > > For a more complete explanation try my tutorial, the topic on > "Modules and Functions" and the OOP topic for classes/objects. > > Alan G > Author of the Learn to Program web tutor > > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 > I just wanted to add a little tid bit incase readers do not know of this. I use this all the time when I'm learning about things. >>> dir("") ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> dir([]) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> This allows me to know what built-in objects can do. Sometimes I go through the list and find the type so that I can know if it's a function or constant like so for x in dir([]): print type(x) then if you need to know the use of a built-in object just type help(''.split) and read on. Many know this already. But it needs to be repeated occasionaly I think. :) __________________________________ Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. http://promotions.yahoo.com/new_mail From Dragonfirebane at aol.com Sat Jul 3 12:47:56 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jul 3 12:48:36 2004 Subject: [Tutor] findall() Message-ID: <75.2d7c3380.2e183d3c@aol.com> In a message dated 7/3/2004 4:28:13 AM Eastern Standard Time, dyoo@hkn.eecs.berkeley.edu writes: On Sat, 3 Jul 2004 Dragonfirebane@aol.com wrote: > I'm trying to get the following code to work: > > def getlog(activity,type,endtype): > log = open("Multivert_Log.txt","r") > for line in log.readlines(): > ac = re.compile(activity) > fac = re.findall(ac, line) > if fac: > print line > break > else: > print "Uh-oh." > log.close() > logagain = open("Multivert_Log.txt","r") > ty = re.compile(type) > fty = re.findall(ty,line) > for line in logagain.readlines(): > if not fty: > fty = re.findall(ty,line) > elif fty: > print line > break > logagain.close() > ex = re.compile("\d") > fex = re.findall(ex,line) > logain = open("Multivert_Log.txt","r") > for line in logain.readlines(): > if not fex: > fex = re.findall(ex,line) > elif fex: > print line > break Hi Dragonfirebane, The code feels like it's doing too much. Since you're asking us to help debug the code, we have to do everything we can to understand the code; this might involve changing the structure of the program so we don't have to read so much at once. I hope you don't mind if I split it up into multiple functions? It may help us to see what the code is really doing. Here's a start: ###### def getlog(activity, type, endtype): tryToPrintActivityLine(activity) tryToPrintTypeLine(type) tryToPrintSomeDigit() def tryToPrintActivityLine(activity): log = open("Multivert_Log.txt","r") for line in log.readlines(): ac = re.compile(activity) fac = re.findall(ac, line) if fac: print line break else: print "Uh-oh." log.close() def trytoPrintTypeLine(type): logagain = open("Multivert_Log.txt","r") ty = re.compile(type) fty = re.findall(ty,line) for line in logagain.readlines(): if not fty: fty = re.findall(ty,line) elif fty: print line break logagain.close() def tryToPrintSomeDigit(): ex = re.compile("\d") fex = re.findall(ex,line) logain = open("Multivert_Log.txt","r") for line in logain.readlines(): if not fex: fex = re.findall(ex,line) elif fex: print line break ###### That's fine. As long as it still does the same thing, it makes little difference. I'm guessing that the code fits has three distinct blocks of function: 'activity', 'type', and something else that I haven't figured out yet. *grin* The reason for the 'endtype' paramater is that activity can be either CALCULATION or CONVERSION. If it is CONVERSION, type is the starting type (Binary, Dec imal, Hexadecimal, or Text) and endtype is the type that the previous type was converted to. However, in CALCULATION there is no need for endtype because once you reach the precision of type, all thats left is the actual manipulation. Each function does almost the same thing, but with suble differences. In fact, the variation in the three blocks is almost certainly buggy; the third block tries to do a findall() search, but even before it reads in 'logain'. As far as I can tell, the 'endtype' parameter passed into the original getlog() function is never used, so I'd drop it: it's confusing to take in parameter that aren't used. There's probably a bug in the third regular expression: ex = re.compile("\d") Use raw strings when you write regular expression patterns: ex = re.compile(r"\d") There's an explanation of why backslashes are slightly complicated: http://www.amk.ca/python/howto/regex/regex.html#SECTION000420000000000000000 The pattern "\d" represents any digit, which is precisely what i want, because that will allow it to pick up only the final manipulation (1 ** 1 = 1 in my example) becuase those are the only times when a digit is present. However, I have also tried using "[0-9]" with as little effect. > If, for example, [readlines():] returns: > > "CALCULATION > > > > > > EXPONENTS > > > > 1 ** 1 = 1 > ", > the code poduces: > > "CALCULATION > > > > " Ok, so you showed us a "experimental input", an an "experimental output" from the program. But what was the "expected output"? That is, what did you want to see? Pretend that we don't know what it's supposed to do. Hope this helps! The expected output was: CALCULATION EXPONENTS 1 ** 1 = 1 because each time a line is printed, the for loop is broken and no more lines are printed, with the exception of the first time (where if fac is not immediately reached, "Uh-oh." is currently printed, merely so i can see that the findall() is working the way i want it to.) 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/20040703/ebc3052f/attachment.html From mdelling at cvcc.edu Sat Jul 3 13:13:04 2004 From: mdelling at cvcc.edu (Marty Dellinger) Date: Sat Jul 3 13:13:36 2004 Subject: [Tutor] Re: Tutor Digest, Vol 5, Issue 5 (Out of Office) Message-ID: I will be out of my office the week of July 5. I will return on Monday, July 12. If you need immediate assistance, please contact Theresa Hicks, the Division Secretary at extension 4307 or thicks@cvcc.edu Thanks! For some reason this rule sends three responses. Sorry! From tim.peters at gmail.com Sat Jul 3 15:09:32 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat Jul 3 15:09:55 2004 Subject: [Tutor] complex iteration over a list In-Reply-To: <1088844861.8853.17.camel@localhost> References: <1088791384.10184.37.camel@localhost> <40E5AEC1.3070806@aon.at> <1088844861.8853.17.camel@localhost> Message-ID: <1f7befae04070312092391da86@mail.gmail.com> [Michele Alzetta] ... > This particular problem though is more easily solved ! > I've found that calendar is useless, but datetime.timedelta does it, as > my startday is a timedelta object (and so is my endday, which I had > changed to number of days thinking it would make things simpler). > > startday = datetime(2004,6,1,8) > endday = datetime(2004,9,1,8) > > def daysinperiod(startday,endday): > daysinperiod = [] > while startday <= endday: > daysinperiod.append(startday.day) > startday = startday + timedelta(days=1) > return daysinperiod > > Eliminates the need for lists with the length of different months, > eliminates the nightmare of leap-years ... > Python is always simpler and more powerful than one thinks :-) Well, often . A more concise way to spell that is: def daysinperiod2(startday, endday): numdays = (endday - startday).days + 1 return [(startday + timedelta(i)).day for i in range(numdays)] If you pass the number of days you want instead of endday, then it can be even shorter: def daysinperiod2(startday, numdays): return [(startday + timedelta(i)).day for i in range(numdays)] From tim.peters at gmail.com Sat Jul 3 15:49:09 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat Jul 3 15:49:29 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com> Message-ID: <1f7befae040703124961bbc204@mail.gmail.com> [Dick Moores] ... > But I realize that I don't need to return a float. Just the string will > do. Therefore, this revision of your function will do exactly what I was > thinking of, even if I didn't say so: > > """ > def round_to_n(x, n): > if n < 1: > raise ValueError("number of significant digits must be >= 1") > # Use %e format to get the n most significant digits, as a string. > format = "%." + str(n-1) + "e" > as_string = format % x > return as_string > """ > print round_to_n(123.456789, 4) > print round_to_n(.000000123456789, 2) > print round_to_n(123456789, 5) > > That displays > > 1.235e+002 > 1.2e-007 > 1.2346e+008 (this is much better than getting the ".0" of 123460000.0, > which implies accuracy to 10 significant digits instead of 5.) Then it's time to learn about one of the more obscure features of string formats: if you put an asterisk in a string format where a precision specifier is expected, the actual precision to use will be taken from the argument tuple. I realize that's confusing; that's why I called it obscure . It should be clearer from this rewrite of your rewrite of my original round_to_n function: def round_to_n(x, n): if n < 1: raise ValueError("number of significant digits must be >= 1") return "%.*e" % (n-1, x) That's probably the end of the line for this problem . A related but harder problem is to get a string rounded to n significant digits, but where the exponent is constrained to be a multiple of 3. This is often useful in engineering work. For example, in computer work, 1e6 and 1e3 are natural units (mega and kilo), but 1e4 isn't -- if I have 15,000 of something, I want to see that as 15e3, not as 1.5e4. I don't know an easy way to get that in Python (or in most other programming languages). From alan.gauld at blueyonder.co.uk Sat Jul 3 19:10:49 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 3 19:10:41 2004 Subject: [Tutor] findall() References: Message-ID: <018601c46152$fb1b2810$6401a8c0@xp> > def getlog(activity,type,endtype): > log = open("Multivert_Log.txt","r") > for line in log.readlines(): > ac = re.compile(activity) This creates an re object so you want to call the findall method of the ac object > fac = re.findall(ac, line) So this becomes fac = ac.findall(line) Same with the ty and ex bits further down. Alan G. From alan.gauld at blueyonder.co.uk Sat Jul 3 19:15:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 3 19:15:11 2004 Subject: [Tutor] A year's calendar to a text file? References: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> Message-ID: <019301c46153$9e38f810$6401a8c0@xp> > I'm just beginning to get into learning the use of file methods. I'm > wondering what the limits are. One I've thought of is, can I write to a > file a year's calendar created using the calendar module? I've not used calendar but I assume you could provided calendar allows you to store its output as a string. The file methods can handle vast amounts of data so that shouldn't be a concern. Have a look at the Files topic in my tutor for more info on using files. (including writing binary data to files!) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From rdm at rcblue.com Sun Jul 4 03:12:17 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 4 03:12:28 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <1f7befae040703124961bbc204@mail.gmail.com> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com> <1f7befae040703124961bbc204@mail.gmail.com> Message-ID: <6.1.2.0.2.20040704001125.02499c50@rcblue.com> Tim Peters wrote at 12:49 7/3/2004: >Then it's time to learn about one of the more obscure features of >string formats: if you put an asterisk in a string format where a >precision specifier is expected, the actual precision to use will be >taken from the argument tuple. I realize that's confusing; that's why >I called it obscure . It should be clearer from this rewrite of >your rewrite of my original round_to_n function: > >def round_to_n(x, n): > if n < 1: > raise ValueError("number of significant digits must be >= 1") > return "%.*e" % (n-1, x) Nice. Thanks very much for all your help. Dick Moores From magnus at thinkware.se Sun Jul 4 04:57:43 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 4 04:55:17 2004 Subject: [Tutor] regular expressions In-Reply-To: Message-ID: <5.2.1.1.0.20040703203644.02884318@www.thinkware.se> At 10:11 2004-06-24 -0700, Larry Blair wrote: >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. That's a file name wildcard pattern, not a regular expression pattern. They are not at all the same thing. (This has really little to do with Python.) I think you might want a word boundry (\b) followed by TEMP possibly followed by any word character (\w*). I.e. pat = re.compile(r"\bTEMP\w*") Note that A-Z, a-z, 0-9 and _ are the word characters, so if you want other characters included as well, you might need to change your pattern. (This also affects \b.) See http://docs.python.org/lib/re-syntax.html If you don't want this to be case sensitive, you need to state that. pat = re.compile(r"\bTEMP\w*", re.IGNORECASE) See http://docs.python.org/lib/node106.html The easiest way to get all matches is to simply do listOfMatches = pat.fetchall(myString) But remember what Jamie Zawinski said: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. You might actually want the fnmatch module rather than the re module. See http://docs.python.org/lib/module-fnmatch.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From derekp at sentechsa.co.za Sun Jul 4 05:20:54 2004 From: derekp at sentechsa.co.za (Derek Pienaar) Date: Sun Jul 4 05:20:30 2004 Subject: [Tutor] Re: Difference between a class & module? References: <200407022104.37167.derekp@sentechsa.co.za> Message-ID: <008401c461a8$4cb69290$0300a8c0@winpvt> I would like to thank Alan Gauld, Gregor Lingi, Andrei and Chad Crabtree for their replies, you have been of great help :-) Thanks again & Warmest Regards Always. Derek From rdm at rcblue.com Sun Jul 4 05:48:55 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 4 05:58:39 2004 Subject: [Tutor] A year's calendar to a text file? In-Reply-To: <019301c46153$9e38f810$6401a8c0@xp> References: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> <019301c46153$9e38f810$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040704024244.02908a00@rcblue.com> I've got it, thanks to both Alan Gauld and Lloyd Kvam: I found this function in the calendar module: ===================== calendar( year[, w[, l[c]]]) Returns a 3-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as set by setfirstweekday(). The earliest year for which a calendar can be generated is platform-dependent. New in version 2.0. ========================== So, """ import calendar calendar.setfirstweekday(6) #sets first day of week to Sunday inp = calendar.calendar(2005) outp = file("c2005.txt","w") for line in inp: outp.write(line) outp.close() print "Year 2005 calendar created as c2005.txt" """ Thank you, tutors! Dick Moores From glingl at aon.at Sun Jul 4 06:44:05 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Jul 4 06:43:26 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <1f7befae040703124961bbc204@mail.gmail.com> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com> <1f7befae040703124961bbc204@mail.gmail.com> Message-ID: <40E7DF75.6000204@aon.at> Tim Peters schrieb: > >Then it's time to learn about one of the more obscure features of >string formats: if you put an asterisk in a string format where a >precision specifier is expected, the actual precision to use will be >taken from the argument tuple. > O.k. I took the opportunity to do so. > I realize that's confusing; that's why >I called it obscure . It should be clearer from this rewrite of >your rewrite of my original round_to_n function: > >def round_to_n(x, n): > if n < 1: > raise ValueError("number of significant digits must be >= 1") > return "%.*e" % (n-1, x) > >That's probably the end of the line for this problem . > > Since long I appreciate very much the beauty and elegance of Tim's solutions, even to quasi "every day problems". (Yes, I know, 20+ years of experience ... ;-) ) >A related but harder problem is to get a string rounded to n >significant digits, but where the exponent is constrained to be a >multiple of 3. This is often useful in engineering work. For >example, in computer work, 1e6 and 1e3 are natural units (mega and >kilo), but 1e4 isn't -- if I have 15,000 of something, I want to see >that as 15e3, not as 1.5e4. I don't know an easy way to get that in >Python (or in most other programming languages). > > > I suppose if Tim says this, there *is no* easy way. However, the result of my tinkering around with string formats (see remark above - and assuming that using regular expressions is not 'easy' (at least for me) - ) is: def eng_round_to_n(x,n): man,exp = round_to_n(x, n).split("e") # contains error-handling sh=int(exp)%3 return "%.*fe%+04i" % (n-1-sh,float(man)*10**sh,int(exp)-sh) 1. is it correct? 2. doesn't it call for a pinch of elegance and streamlining? Regards, Gregor From project5 at redrival.net Sun Jul 4 08:49:59 2004 From: project5 at redrival.net (Andrei) Date: Sun Jul 4 08:50:31 2004 Subject: [Tutor] Re: creating variables from the 'key' of a dictionary. Fu rther explainations References: Message-ID: Larry Blair wrote on Fri, 2 Jul 2004 13:59:50 -0700: > These are great ideas and starting to get me in the direction I need to go - > I think :) > What we have are multiple parameter files. Each has the same parameters but Well, you can have multiple configuration modules just as well as you can have multiple parameter files. > with different values. i.e. p_file1 will have source_server = 'cm05' and > target_server = 'ts05' - we are backing up data from cm05 to ts05. p_file2 > will have source_server = 'pd01' and target_server = 'bk01'. We give the > specific parameter file to the script at run time for backing up different > sets of servers. As we add new equipment, SANs, databases etc. our list of You can use __import__ to load a module the name of which you'll get as a command line argument or something. > I like the idea of creating a module but that would be a single set of > values wouldn't it? Or is there a way to read the specified parameter file > and then 'compile' and import the module on the fly? What is the difference between specifying things in some kind of configuration file, reading them and making them into variables and specifying things in a configuration file, reading them in a dictionary and then getting the values from that dictionary? The two methods have no effect whasoever on your configuration file. The difference is in how you handle the data. Creating variables based on a configuration file is not something that I think is very wise. You might at some point use a variable for some other purpose and then without noticing it, overwrite it with some variable you read from the configuration - this danger does not exist if you keep stuff in a module or dictionary.. > My intent is > 1. to have a function to read the parameters file - create a list or > dictionary of each parameter and value Good. > 2. and pass it back to the calling script and then have a for loop that > would dynamically create all variables( these are the keys in the > dictionary) with the matching value. Not good for the reason outlined above. Why not just keep and access the dictionary instead of creating a variable at runtime? If you feel you really, really must, use the method I mentioned in my previous message. But accessing the params dictionary really is a better idea. -- 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 mjekl at clix.pt Sun Jul 4 10:49:00 2004 From: mjekl at clix.pt (mjekl) Date: Sun Jul 4 10:46:45 2004 Subject: [Tutor] Re: Record Locking & Access - newbye References: <003001c456f8$17ba9b00$6601a8c0@clixdialupadapt> <1088088669.3929.23.camel@laptop.venix.com> Message-ID: Thanks all for the help. mjekl From alan.gauld at blueyonder.co.uk Sun Jul 4 13:14:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 4 13:13:44 2004 Subject: [Tutor] Rounding to n significant digits? References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com><1f7befae040703124961bbc204@mail.gmail.com> <40E7DF75.6000204@aon.at> Message-ID: <01e801c461ea$53062650$6401a8c0@xp> Hi Gregor, > def eng_round_to_n(x,n): > man,exp = round_to_n(x, n).split("e") # contains error-handling > sh=int(exp)%3 > return "%.*fe%+04i" % (n-1-sh,float(man)*10**sh,int(exp)-sh) Eek! Are you sure that last line is Python and not Perl? Winner of this months obfuscated tutor code I think... I'll take your word for it that it works. ;-) Alan G From glingl at aon.at Sun Jul 4 13:43:57 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Jul 4 13:43:18 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <01e801c461ea$53062650$6401a8c0@xp> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com><1f7befae040703124961bbc204@mail.gmail.com> <40E7DF75.6000204@aon.at> <01e801c461ea$53062650$6401a8c0@xp> Message-ID: <40E841DD.80207@aon.at> Alan Gauld schrieb: >Hi Gregor, > > > >>def eng_round_to_n(x,n): >> man,exp = round_to_n(x, n).split("e") # contains error-handling >> sh=int(exp)%3 >> return "%.*fe%+04i" % (n-1-sh,float(man)*10**sh,int(exp)-sh) >> >> > >Eek! Are you sure that last line is Python and not Perl? >Winner of this months obfuscated tutor code I think... > > Hi Alan! What a nice reply! You are certainly right ... nevertheless I've been laughing about it for at least 5 minutes . (Although: it's only the 4th of July today, who knows what will follow ...) Of course I'd be interested in a more elegant solution ... Unfortunately I cannot work on it right now, because it's only one hour to the beginning of the finale of then European football chamionship. I'm going to visit friends to watch it in television ... Last week at the Linuxtag in Germany I participated (by accident) in a so called "coding contest". (Of course I didn't win!) We had to write a program to solve a certain problem with the sourcecode as short as possible (!? - strange task!). Later after some correspondence about it we arrived at: import sys for i in range(3): r='' for c in sys.argv[1]: n=int('2l7y202nn6lx6xh0ve',36)//8**(3*int(c)+i)%8;r+=' |_ _ _| |_|'[2*n:2*n+3] print r You may guess what it does. Input has to be an arbitrary sequence of digits from 0 to 9, ( a so called integer) eg.: 1237583490 ... ... or try it out. The winning program had less than 140 bytes, as far as I know it was in Ruby.(Didn't see it) Regards, Gregor P.S.: Which code will win the obfuscated code prize now? From rdm at rcblue.com Sun Jul 4 17:02:32 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 4 17:02:36 2004 Subject: [Tutor] A year's calendar to a text file? In-Reply-To: <6.1.2.0.2.20040704024244.02908a00@rcblue.com> References: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> <019301c46153$9e38f810$6401a8c0@xp> <6.1.2.0.2.20040704024244.02908a00@rcblue.com> Message-ID: <6.1.2.0.2.20040704132819.02902ec0@rcblue.com> Here's the latest version of my script. I'm pleased that the script works, but I'd appreciate some tips on how I could do this in a more Pythonesque way. And I'm particularly concerned about the section where I tell the user the name of the file created (Alan Gauld in his tutorial recommends this kind of user feedback). Isn't there a better or easier way to print the filename without the spaces that would appear if I'd used print "\nYear", year, "calendar created as c", year, ".txt" Maybe using something like backspace to eliminate the two unneeded spaces? I've tried experimenting with \b, but I can't get it to work. (I'm using Windows XP.) The script prints (for 1942): Year 1942 calendar created as c1942.txt Full path is C:\Documents and Settings\Dick\Desktop\Year Calendars\cal1942.txt This is pretty trivial, I suppose, but I'd like to know. """ # calendar_to_textfile.py # create year calendar for year of user's choice (from 1 C.E. thru 9999 C.E.) import calendar # get from user the year for which he wants a calendar year = raw_input("Enter year you want calendar for ") # partial path for text file for calendar s = "C:\Documents and Settings\Dick\Desktop\Year Calendars\cal" # copy s to path path = "" for x in s: path += x # add year to path for x in year[0:4]: path += x #add ".txt" to path txt = ".txt" for x in txt[0:4]: path += x calendar.setfirstweekday(6) #sets first day of week to Sunday inp = calendar.calendar(int(year)) outp = file(path,"w") for line in inp: outp.write(line) outp.close() # build filename for printing filename = "c" for x in year: filename += x for x in ".txt": filename += x print "\nYear", year, "calendar created as", filename print "Full path is", path """ Thanks, tutors, Dick Moores From glingl at aon.at Sun Jul 4 18:10:50 2004 From: glingl at aon.at (Gregor Lingl) Date: Sun Jul 4 18:10:10 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <1de.240b274e.2e19a570@aol.com> References: <1de.240b274e.2e19a570@aol.com> Message-ID: <40E8806A.2050804@aon.at> Hello Dragonfirebane! You have to start the code from the commandline: Do you run windows? - Open a MSDOS-Window - go to the directory, where the program, say: contest.py, is located - be sure that Python is in your path then write something like: C:\mycode> python contest.py 1526985643 and you will get the output. The integer 1526985643 (or any other one) is the input to the program and (automatically) stored in sys.argv[1] (I think argv stands for argument-vector) C:\mycode> c:\python23\python.exe contest.py 1526985643 If python isn't on your path you have to write something like: Alternately you can use the Pythonwin IDE, where you can input arguments to a program in a special dialog when you run it. If all this doesn't work for you, last resort is to replace sys.argv[1] directly by the input-string: for c in "1526985643": .... HTH, Gregor Dragonfirebane@aol.com schrieb: > I tried out your code (for the contest) and it says that there is no > sys.argv[1] (List index out of range). When i try it with sys.argv[0] > it says "invalid literal for int(): C". > > Email: dragonfirebane@aol.com > AIM: singingxduck > Programming Python for the fun of it. From dyoo at hkn.eecs.berkeley.edu Sun Jul 4 20:22:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jul 4 20:22:41 2004 Subject: [Tutor] findall() In-Reply-To: <75.2d7c3380.2e183d3c@aol.com> Message-ID: On Sat, 3 Jul 2004 Dragonfirebane@aol.com wrote: > > > I'm trying to get the following code to work: [text cut] Hi Dragonfirebane, [Mailing list ettiquette issue: Please quote only the part of message that you're responding to; you're making it difficult for me to find your response within the older message. Whenever you're replying to someone else's message on a mailing list, try to be concise in consideration for the others on the list.] > > I hope you don't mind if I split it up into multiple functions? It > > may help us to see what the code is really doing. Here's a start: [refactored code cut] > That's fine. As long as it still does the same thing, it makes little > difference. Actually, it doesn't. Work the same way, that is. *grin* The way I refactored it is deliberately broken, in the sense that the second and third subfunctions should raise a particular NameError. Did you try running the new code yet? I hinted at the bug earlier with: > Each function does almost the same thing, but with suble differences. > In fact, the variation in the three blocks is almost certainly buggy; > the third block tries to do a findall() search, but even before it reads > in 'logain'. In any case, I strongly recommend that you use the refactored code so that we can a common base to talk. Here's the code again, but slightly revised so that the NameErrors shouldn't occur. I'm also cutting out the third subfunction for the moment: ### def getlog(activity, type, endtype): tryToPrintActivityLine(activity) ## this works tryToPrintTypeLine(type) ## this doesn't work yet. def tryToPrintActivityLine(activity): log = open("Multivert_Log.txt","r") for line in log.readlines(): ac = re.compile(activity) fac = re.findall(ac, line) if fac: print line break else: print "Uh-oh." log.close() def trytoPrintTypeLine(type): logagain = open("Multivert_Log.txt","r") ty = re.compile(type) fty = [] ## buggy line modified for line in logagain.readlines(): if not fty: fty = re.findall(ty,line) elif fty: print line break logagain.close() ### Once we get the program working to detect the two lines you want, we can then augment the working program to detect the math equation. > The expected output was: > > CALCULATION > EXPONENTS > 1 ** 1 = 1 > > because each time a line is printed, the for loop is broken and no more > lines are printed, with the exception of the first time (where if fac is > not immediately reached, "Uh-oh." is currently printed, merely so i can > see that the findall() is working the way i want it to.) Ok, now we have a goal: we want our program to output that expected text. The value of doing that refactoring of that getlog() function into three smaller functions, > def getlog(activity, type, endtype): > tryToPrintActivityLine(activity) ## this works > tryToPrintTypeLine(type) ## this doesn't work is this: since we know that the first part is working, we can now concentrate your efforts on the second part, and we can do our debugging on the second function alone, in isolation from the first subfunction. There are some possible reasons why the 'EXPONENTS' line isn't being printed. If we look at the second subfunction 'tryToPrintTypeLine()': > def trytoPrintTypeLine(type): > logagain = open("Multivert_Log.txt","r") > ty = re.compile(type) > fty = [] > for line in logagain.readlines(): > if not fty: > fty = re.findall(ty,line) > elif fty: > print line > break > logagain.close() we may want to make sure that the right 'type' variable is being passed to this function. If the 'type' is incorrect, then the function won't print a thing, since the regular expression is incorrect. Are you passing the uppercased string "EXPONENTS" as the 'type', or are you passing the lowercased string "exponents"? Also, the following point is important: the loop logic is broken in the sense that the code, in effect, will _always_ skip looking at the last line of input. Imagine what happens if "Multivert_log.txt" contains just two lines of input, like: CALCULATION EXPONENT If you trace out the code, you will see that the loop does not provide a chance to print out the 'EXPONENT' line, even if a match is made, because the status report on the search is done on all lines, up to --- but not including! --- the last line of the log file. The defect in the loop here probably doesn't account for 'EXPONENTS' not being printed, but it DOES account for the equation '1 ** 1 = 1' not being printed. The same looping bug occurs in all three subfunctions. Rewrite the loop to: ### def trytoPrintTypeLine(type): logagain = open("Multivert_Log.txt","r") ty = re.compile(type) for line in logagain.readlines(): fty = re.findall(ty,line) if fty: print line break logagain.close() ### Not only does the code end up shorter, but it's more correct: it doesn't skip the last line of the file, and if a match occurs on the last line, this code has the opportunity to report that to the user. Does this make sense? Please feel free to ask any questions on this. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Sun Jul 4 20:33:20 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jul 4 20:33:25 2004 Subject: [Tutor] findall() In-Reply-To: Message-ID: > The defect in the loop here probably doesn't account for 'EXPONENTS' not > being printed, but it DOES account for the equation '1 ** 1 = 1' not being > printed. The same looping bug occurs in all three subfunctions. ^^^^^ Hi Dragonfirebane, Argh. I can't count, can I. *grin* I meant to say that the looping bug affects both the function that prints 'EXPONENTS', as well as the '1 ** 1 = 1' finding function. My apologies. From isrgish at fastem.com Mon Jul 5 01:11:41 2004 From: isrgish at fastem.com (Isr Gish) Date: Mon Jul 5 01:12:51 2004 Subject: [Tutor] listdir() Message-ID: Hi Ole, -----Original Message----- >From: "Ole Jensen" >Sent: 7/2/04 8:22:17 AM >To: "tutor@python.org" >Subject: [Tutor] listdir() > >Hello list > >I have recently learnt of the os.listdir() function, and I intend to experiment with it using a cgi-page (html). I would like to have a base directive show all the files and folders, so that the user can browse through it all. >Now, listdir() returns both the files and folders in one big mess, so I am wondering if there is some ListFolderInDir() function or similar within python that I should use, if so what is its name and location. There is a function called os.walk (not os.path.walk) that returns a tuple of, (dirpath, dirnames, filenames) [snip] >Ole Jensen All the best, Isr From glingl at aon.at Mon Jul 5 02:16:23 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Jul 5 02:15:43 2004 Subject: [Tutor] Rounding to n significant digits? In-Reply-To: <40E841DD.80207@aon.at> References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com><1f7befae040703124961bbc204@mail.gmail.com> <40E7DF75.6000204@aon.at> <01e801c461ea$53062650$6401a8c0@xp> <40E841DD.80207@aon.at> Message-ID: <40E8F237.2040002@aon.at> Gregor Lingl schrieb: As it happens sometimes the code below got corrupted. print statement should appear within the body of the for-loop. Please use the attached code. Sorry for the inconvenience. Gregor > > Later after some correspondence about it we arrived at: > > import sys > for i in range(3): > r='' > for c in sys.argv[1]: > n=int('2l7y202nn6lx6xh0ve',36)//8**(3*int(c)+i)%8;r+=' |_ _ _| > |_|'[2*n:2*n+3] > print r > -------------- next part -------------- import sys for i in range(3): r='' for c in sys.argv[1]: n=int('2l7y202nn6lx6xh0ve',36)//8**(3*int(c)+i)%8;r+=' |_ _ _| |_|'[2*n:2*n+3] print r From gew75 at hotmail.com Mon Jul 5 03:41:43 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Mon Jul 5 03:41:48 2004 Subject: [Tutor] Rounding to n significant digits? References: <6.1.2.0.2.20040701194546.0257f640@rcblue.com> <00a501c46002$e8752950$6401a8c0@xp> <6.1.2.0.2.20040702001107.04867e88@rcblue.com> <1f7befae04070220187944a7ff@mail.gmail.com> <6.1.2.0.2.20040702235118.024b9ec0@rcblue.com><1f7befae040703124961bbc204@mail.gmail.com> <40E7DF75.6000204@aon.at><01e801c461ea$53062650$6401a8c0@xp> <40E841DD.80207@aon.at> <40E8F237.2040002@aon.at> Message-ID: Hey, it worked for me. Gregor; you don't mind if I use this code in a class demonstration? I find it extremely instructive ;). Glen ----- Original Message ----- From: "Gregor Lingl" To: "Python Tutor Mailing List" Sent: Monday, July 05, 2004 4:16 PM Subject: Re: [Tutor] Rounding to n significant digits? > > > Gregor Lingl schrieb: > > As it happens sometimes the code below got > corrupted. print statement should appear within the > body of the for-loop. > > Please use the attached code. > Sorry for the inconvenience. > > Gregor > > > > > Later after some correspondence about it we arrived at: > > > > import sys > > for i in range(3): > > r='' > > for c in sys.argv[1]: > > n=int('2l7y202nn6lx6xh0ve',36)//8**(3*int(c)+i)%8;r+=' |_ _ _| > > |_|'[2*n:2*n+3] > > print r > > > ---------------------------------------------------------------------------- ---- > import sys > for i in range(3): > r='' > for c in sys.argv[1]: > n=int('2l7y202nn6lx6xh0ve',36)//8**(3*int(c)+i)%8;r+=' |_ _ _| |_|'[2*n:2*n+3] > print r > ---------------------------------------------------------------------------- ---- > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python at kc.rr.com Mon Jul 5 05:52:42 2004 From: python at kc.rr.com (python@kc.rr.com) Date: Mon Jul 5 05:52:51 2004 Subject: [Tutor] downloading from a list Message-ID: <0EA86126-CE69-11D8-A15F-0003934BF52E@kc.rr.com> Hi, all. Still a Python newbie and messing around with urllib at the moment. Here's the particulars... I'm attempting to come up with a script which will download the mp3's listed in a .m3u (playlist) file[1]. The heavy lifting is already done and the script, as it stands looks like so: import os, urllib # ask for a url here... print "enter the URL you want to download something from:" # get the url and assign to 'url' variable url = raw_input() # declare the app to download with downloader = '/sw/bin/wget ' # parse each line from the .m3u file for line in urllib.urlopen(url).readlines(): # tell the system to use wget to download each item in the list os.system (downloader + line) # be polite like mom said print "All done. Enjoy!" I was wondering, however, if there was any way for Python to just do all the magic itself without relying on an outside application (like wget), sorta like: import os, urllib print "enter the URL you want to download something from:" url = raw_input() for line in urllib.urlopen(url).readlines(): # something incredibly clever right about here! print "All done. Enjoy!" I didn't see anything, but it's getting rather late (0500 CST) and I'm feeling sleepy. Any hints on how to download those items in a list without relying on an external application? Many thanks for a hint or two! tom [1] Lots of musicians encourage downloading their tracks, just automating it a bit for personal use and to stretch my python wings tad. Check out magnatune.com for all sorts of musical goodness. Weinberg's Law: "If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization" From orbitz at ezabel.com Mon Jul 5 12:05:26 2004 From: orbitz at ezabel.com (orbitz) Date: Mon Jul 5 12:05:49 2004 Subject: [Tutor] downloading from a list In-Reply-To: <0EA86126-CE69-11D8-A15F-0003934BF52E@kc.rr.com> References: <0EA86126-CE69-11D8-A15F-0003934BF52E@kc.rr.com> Message-ID: <40E97C46.3060400@ezabel.com> Why don't you just use the incredibly clever urllib module that you are already using? By the way you probably should be usign urllib2 python@kc.rr.com wrote: > Hi, all. Still a Python newbie and messing around with urllib at the > moment. Here's the particulars... > > I'm attempting to come up with a script which will download the mp3's > listed in a .m3u (playlist) file[1]. The heavy lifting is already done > and the script, as it stands looks like so: > > import os, urllib > > # ask for a url here... > print "enter the URL you want to download something from:" > # get the url and assign to 'url' variable > url = raw_input() > # declare the app to download with > downloader = '/sw/bin/wget ' > # parse each line from the .m3u file > for line in urllib.urlopen(url).readlines(): > # tell the system to use wget to download each item in the list > os.system (downloader + line) > # be polite like mom said > print "All done. Enjoy!" > > I was wondering, however, if there was any way for Python to just do > all the magic itself without relying on an outside application (like > wget), sorta like: > > import os, urllib > > print "enter the URL you want to download something from:" > url = raw_input() > for line in urllib.urlopen(url).readlines(): > # something incredibly clever right about here! > print "All done. Enjoy!" > > I didn't see anything, but it's getting rather late (0500 CST) and I'm > feeling sleepy. Any hints on how to download those items in a list > without relying on an external application? > > Many thanks for a hint or two! > > tom > > [1] Lots of musicians encourage downloading their tracks, just > automating it a bit for personal use and to stretch my python wings > tad. Check out magnatune.com for all sorts of musical goodness. > > 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 pythonTutor at venix.com Mon Jul 5 13:15:35 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Jul 5 13:15:41 2004 Subject: [Tutor] A year's calendar to a text file? In-Reply-To: <6.1.2.0.2.20040704132819.02902ec0@rcblue.com> References: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> <019301c46153$9e38f810$6401a8c0@xp> <6.1.2.0.2.20040704024244.02908a00@rcblue.com> <6.1.2.0.2.20040704132819.02902ec0@rcblue.com> Message-ID: <1089047734.2096.64.camel@laptop.venix.com> On Sun, 2004-07-04 at 17:02, Dick Moores wrote: > Here's the latest version of my script. I'm pleased that the script > works, but I'd appreciate some tips on how I could do this in a more > Pythonesque way. > > And I'm particularly concerned about the section where I tell the user > the name of the file created (Alan Gauld in his tutorial recommends this > kind of user feedback). Isn't there a better or easier way to print the > filename without the spaces that would appear if I'd used > > print "\nYear", year, "calendar created as c", year, ".txt" Use the string format operator: print "\nYear %s calendar created as c%s.txt" % (year, year) (snipped) > """ > # calendar_to_textfile.py > # create year calendar for year of user's choice (from 1 C.E. thru 9999 C.E.) > > import calendar > > # get from user the year for which he wants a calendar > year = raw_input("Enter year you want calendar for ") > > # partial path for text file for calendar > s = "C:\Documents and Settings\Dick\Desktop\Year Calendars\cal" For DOS/Windows paths, you will usually be better served with raw strings: s = r"C:\Documents and Settings\Dick\Desktop\Year Calendars\cal" The backslash is used to mark "special" characters like backspace, return, and linefeed. s = "C:\boot" will NOT refer to your boot directory! > > # copy s to path > path = "" > > for x in s: > path += x > You can simply bind s to path: path = s If it was essential for path to refer to a copy of s, then: path = s[:] # uses the slice notation to create copy would be better than copying one character at a time. Since strings are immutable, it is very rare for you to need to explicitly copy a string. > # add year to path > for x in year[0:4]: > path += x > > #add ".txt" to path > txt = ".txt" > for x in txt[0:4]: > path += x Again there is no need to work one character at a time: path = path + year + ".txt" If you were sticking with the += operator: path += year path += ".txt" > > calendar.setfirstweekday(6) #sets first day of week to Sunday > inp = calendar.calendar(int(year)) > > outp = file(path,"w") > > for line in inp: > outp.write(line) In general, you could simply write the whole calendar at once: outp.write(inp) > > outp.close() > > # build filename for printing > filename = "c" > for x in year: > filename += x > for x in ".txt": > filename += x Repeating the same logic in multiple spots can often lead to bugs from typos or failures to change all spots together. I'd recommend using os.path.basename to extract the filename from path: filename = os.path.basename(path) Looking back at your code, I do not believe that the filename you're printing is actually the same as the basename, but I think that was your intent. Should this piece have really started with: filename = "cal" ? > > print "\nYear", year, "calendar created as", filename > print "Full path is", path > """ > > Thanks, tutors, > > Dick Moores > > > > _______________________________________________ > 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 Jul 5 13:19:39 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Jul 5 13:19:45 2004 Subject: [Tutor] database access In-Reply-To: <40E5DEEC.70005@conwaycorp.net> References: <40E5DEEC.70005@conwaycorp.net> Message-ID: <1089047979.2096.69.camel@laptop.venix.com> Since no one answered, you might be better off posting to the db-sig list. They are responsive. (I use MySQL and simply don't know.) http://mail.python.org/mailman/listinfo On Fri, 2004-07-02 at 18:17, Rob Benton wrote: > Hey I'm relatively new to Python. I've looked around a little and seen > lots of database modules for Oracle. Do any of those work with oracle > custom objects? > > _______________________________________________ > 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 atyss4si at hotmail.com Mon Jul 5 22:46:00 2004 From: atyss4si at hotmail.com (Bernard Lebel) Date: Tue Jul 6 03:22:54 2004 Subject: [Tutor] The % operator Message-ID: Hello, I have been reading many examples where the % operator is used, and I know I have read in the docs its meaning. However I can't seem to be able to retrieve it, and a search doesn't return interesting results. So I'm turning to you, honorable people: could someone be kind to explain to me what is doing the % operator, how it works, or at least point me to the appropriate page in the Python documentation? Thank you Bernard From rdm at rcblue.com Tue Jul 6 01:58:49 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Jul 6 03:45:22 2004 Subject: [Tutor] A year's calendar to a text file? In-Reply-To: <1089047734.2096.64.camel@laptop.venix.com> References: <6.1.2.0.2.20040703015458.020f1ec0@rcblue.com> <019301c46153$9e38f810$6401a8c0@xp> <6.1.2.0.2.20040704024244.02908a00@rcblue.com> <6.1.2.0.2.20040704132819.02902ec0@rcblue.com> <1089047734.2096.64.camel@laptop.venix.com> Message-ID: <6.1.2.0.2.20040705165319.0224cec0@rcblue.com> Thank you very much, Lloyd Kvam. I learned a lot from your criticism of my script. Dick Moores From bvande at po-box.mcgill.ca Tue Jul 6 04:24:17 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Jul 6 04:25:07 2004 Subject: [Tutor] The % operator In-Reply-To: References: Message-ID: <40EA0D51.2020500@po-box.mcgill.ca> Bernard Lebel said unto the world upon 05/07/2004 16:46: > Hello, > > I have been reading many examples where the % operator is used, and I > know I have read in the docs its meaning. However I can't seem to be > able to retrieve it, and a search doesn't return interesting results. > So I'm turning to you, honorable people: could someone be kind to > explain to me what is doing the % operator, how it works, or at least > point me to the appropriate page in the Python documentation? > > > Thank you > Bernard > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Bernard, In the Python Library reference, try: 2.3.6.2 String Formatting Operations. There are more details to it than I am about to mention, and I am giving my intuitive understanding rather than an "official" explanation (I am a relative newbie, too). But the rough idea is that it that string formatting lets you define a text string with some "holes" in it. The holes are marked by the % character and have various sorts. %s marks a hole to be filled by a string, %i a hole to be filled by an integer, %03i a hole for an integer with at least 3 places, leading 0's added if need be, etc. You use it by having a string with n %-holes followed by "%" and either a single element of an n-tuple of elements (of the right sorts). String formatting lets you build "string templates" and allows you to fit long string definitions onto an 80-character line, etc. Some examples: IDLE 1.0.3 >>> h = "It is my very favourite language. I'd be lost without it." >>> print "%s is fun! I use it %s day. %s" %("Python", "every", h) Python is fun! I use it every day. It is my very favourite language. I'd be lost without it. >>> a = 1 >>> m = "This is a %s. It has had %i iterations so far." >>> while a < 6: print m %("While loop", a) a = a + 1 This is a While loop. It has had 1 iterations so far. This is a While loop. It has had 2 iterations so far. This is a While loop. It has had 3 iterations so far. This is a While loop. It has had 4 iterations so far. This is a While loop. It has had 5 iterations so far. >>> c = "This is a %s. It has had %03i iterations so far." >>> for b in range(5): print c %("For loop", b + 1) This is a For loop. It has had 001 iterations so far. This is a For loop. It has had 002 iterations so far. This is a For loop. It has had 003 iterations so far. This is a For loop. It has had 004 iterations so far. This is a For loop. It has had 005 iterations so far. >>> Best, Brian vdB From jeffpeery at yahoo.com Tue Jul 6 07:30:56 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue Jul 6 07:30:59 2004 Subject: [Tutor] stand alone python applications Message-ID: <20040706053056.43931.qmail@web60106.mail.yahoo.com> hello, does anyone know if you can do something to the effect of compiling python so that it will act as a stand alone application - ie., can I write an application in python, create a wxpython interface and distribute it to my customers without them having to install python or anything else but my application? thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040705/ed8eb03e/attachment.html From orbitz at ezabel.com Tue Jul 6 08:06:35 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Jul 6 08:06:55 2004 Subject: [Tutor] stand alone python applications In-Reply-To: <20040706053056.43931.qmail@web60106.mail.yahoo.com> References: <20040706053056.43931.qmail@web60106.mail.yahoo.com> Message-ID: <40EA416B.5090904@ezabel.com> Currently there is no real means of hiding your source from those who have your compiled python applications. It is fairly trivial to go from byte code -> .py. You can bundle your application though, which will include an interpreter and all of the modules required to use it, that way they don't need to download everything. Jeff Peery wrote: > hello, does anyone know if you can do something to the effect of > compiling python so that it will act as a stand alone application - > ie., can I write an application in python, create a wxpython interface > and distribute it to my customers without them having to install > python or anything else but my application? thanks. > > Jeff > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From glingl at aon.at Tue Jul 6 08:17:23 2004 From: glingl at aon.at (Gregor Lingl) Date: Tue Jul 6 08:16:43 2004 Subject: [Tutor] The % operator In-Reply-To: References: Message-ID: <40EA43F3.2010305@aon.at> Bernard Lebel schrieb: > Hello, > > I have been reading many examples where the % operator is used, and I > know I have read in the docs its meaning. However I can't seem to be > able to retrieve it, and a search doesn't return interesting results. > So I'm turning to you, honorable people: could someone be kind to > explain to me what is doing the % operator, how it works, or at least > point me to the appropriate page in the Python documentation? > There are two % operators in Python. One for numeric types: http://docs.python.org/lib/typesnumeric.html the other one for string formatting: http://docs.python.org/lib/typesseq-strings.html Regards, Gregor > > Thank you > Bernard > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From Pawel_Kraszewski at wp.pl Tue Jul 6 08:16:57 2004 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Tue Jul 6 08:17:10 2004 Subject: [Tutor] stand alone python applications In-Reply-To: <20040706053056.43931.qmail@web60106.mail.yahoo.com> References: <20040706053056.43931.qmail@web60106.mail.yahoo.com> Message-ID: <200407060816.57638.Pawel_Kraszewski@wp.pl> Dnia wto 6. lipca 2004 07:30, Jeff Peery napisa?: |hello, does anyone know if you can do something to the effect of compiling | python so that it will act as a stand alone application - ie., can I write | an application in python, create a wxpython interface and distribute it to | my customers without them having to install python or anything else but my | application? thanks. Just tell, for which system? For Windows, you have a cute "py2exe", which works perfectly with most wxPython applications. -- Pawel Kraszewski FreeBSD/Linux E-Mail/Jabber Phone ICQ GG Pawel_Kraszewski@wp.pl +48 604 777447 45615564 69381 From python at kc.rr.com Tue Jul 6 08:25:43 2004 From: python at kc.rr.com (python@kc.rr.com) Date: Tue Jul 6 08:25:48 2004 Subject: [Tutor] stand alone python applications In-Reply-To: <40EA416B.5090904@ezabel.com> References: <20040706053056.43931.qmail@web60106.mail.yahoo.com> <40EA416B.5090904@ezabel.com> Message-ID: <4F155FC8-CF15-11D8-9016-0003934BF52E@kc.rr.com> Jeff, it's out there, just have to dig a bit... Py2exe http://starship.python.net/crew/theller/py2exe/ cx-freeze http://sourceforge.net/projects/cx-freeze/ Gordon McMillan wrote "installer" for python. unfortunately, his page is no more, but I found one link with the windows checkout... http://paulbaranowski.org/modules.php?name=News&file=article&sid=76 good luck, hope it helps! On Jul 6, 2004, at 1:06 AM, orbitz wrote: > Currently there is no real means of hiding your source from those who > have your compiled python applications. It is fairly trivial to go > from byte code -> .py. You can bundle your application though, which > will include an interpreter and all of the modules required to use it, > that way they don't need to download everything. > > Jeff Peery wrote: > >> hello, does anyone know if you can do something to the effect of >> compiling python so that it will act as a stand alone application - >> ie., can I write an application in python, create a wxpython >> interface and distribute it to my customers without them having to >> install python or anything else but my application? thanks. >> Jeff >> >> ---------------------------------------------------------------------- >> -- >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Weinberg's Law: "If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization" From alan.gauld at blueyonder.co.uk Tue Jul 6 09:07:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 6 09:06:28 2004 Subject: [Tutor] stand alone python applications References: <20040706053056.43931.qmail@web60106.mail.yahoo.com> Message-ID: <024601c46327$e325b4b0$6401a8c0@xp> > hello, does anyone know if you can do something to the effect > of compiling python so that it will act as a stand alone application > - ie., can I write an application in python, create a wxpython > interface and distribute it to my customers without them having > to install python or anything else but my application? There are several ways to achieve this. 1) Include Python in an install script and get the script to check whether a suitable version of Python already exists before installing your version. That way you don't mess up your customers machine. (Alternatively be like the Java community and just dump yet another copy of the Python interpreter on their PC and let the user figure out where all their disk space has gone and how to fix the PATH conflicts...) 2) Use a packaging tool like Gordon McMillan's installer or py2exe to bundle up the Python engine plus libraries into a pseudo exe file. This is better behaved that just installing multiple copies of Python, but does mean you load the customers machines with lots of hidden copies and still takes up lots of disk space, which may or may not be an issue. 3) Just bundle up the program bits they need and provide a link to the Python site for downloading Python if they need to, (or include it in a separate folder on your CD...) Option 1 (with the checks in place) is the most user friendly option provided your users have the bandwidth to download it. If your users are computer literate option 3 is second best and option 2 is only suitable if your users have lots of spare disk space and bandwidth. For users whjo are short of bandwidth option 3 is best. Depends on what your user community is like really. As someone who hates programs that install stuff I don't need I usually use option 3. But my 'customers' are fellow programmers! Alan G. From rdm at rcblue.com Tue Jul 6 12:08:55 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Jul 6 12:10:50 2004 Subject: [Tutor] How to enable pausing my stop_watch.py ? Message-ID: <6.1.2.0.2.20040706025053.02376ec0@rcblue.com> See script below. I would like to enable pausing and then resuming stop_watch.py. For example, say I've set it to beep after 30 minutes. I start it, but then discontinue the activity I'm timing. I want to pause the stopwatch by pressing a key and then resume later by pressing (another?) key, just as I could do with a real stopwatch. Is this possible? And I'd also really appreciate a close critique of the code I have so far. """ # stop_watch.py import time, winsound def hms(seconds): """Convert seconds to tuplet (hours, minutes, seconds)""" import time hours, minutes = 0, 0 if seconds >= 60 and seconds < 3600: minutes = divmod(seconds,60)[0] seconds = divmod(seconds,60)[1] elif seconds >= 3600: hours = divmod(seconds,3600)[0] seconds = divmod(seconds,3600)[1] minutes = divmod(seconds,60)[0] seconds = divmod(seconds,60)[1] return hours, minutes, seconds # returns a tuple, e.g. (1, 40, 8.5) hours = raw_input("Enter the number of hours to time ") if hours == "": h_seconds = 0 else: h_seconds = 3600 * int(hours) minutes = raw_input("And the number of minutes ") if minutes == "": m_seconds = 0 else: m_seconds = 60 * int(minutes) seconds = raw_input("And the number of seconds ") t0 = time.time() if seconds == "": seconds = 0 seconds = h_seconds + m_seconds + int(seconds) print "Seconds total is", seconds t = hms(seconds) print "Beep will sound after %d hours %d minutes %d seconds\n" \ % (t[0], t[1], t[2]) r = 10 # get report of time-passed and time-left every r seconds k = r while True: t1 = time.time() seconds_passed = t1 - t0 seconds_left = seconds - int(seconds_passed) if seconds_passed >= seconds: break if seconds_passed > k: p = hms(seconds_passed) l = hms(seconds_left) print "%d hours %d minutes %d seconds have passed" \ % (p[0], p[1], p[2]) print "%d hours %d minutes %d seconds are left\n" \ % (l[0], l[1], l[2]) k += r print "seconds elapsed:", (t1 - t0) # as a check on accuracy print "TIME'S UP!" # winsound.Beep(frequency, duration in milliseconds) - only for Windows winsound.Beep(500,5) """ Thanks, tutors, Dick Moores From karthik at james.hut.fi Tue Jul 6 12:20:02 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Tue Jul 6 12:20:04 2004 Subject: [Tutor] Config Files and Thankx (Reading Numerical Data) Message-ID: Hi All, Thankx for the responses for my earlier mail. Somehow, i did not get the responses, but when i checked the archives i found them. It was quite useful (Andrei's esp). Now suppose i have a config file like say [userful] no_of_sources 10 no_of_users 20 result_dir '/share/wonderful/result/' antenna 12 # ideally i would want to write no_of_sources+2 [useless] no_of_sources 2 no_of_users 4 result_dir '/share/notsowonderful/result' antenna 4 Now i want them to be read into two dictionaries userful, useless with no_of_sources etc as keys and values corresponding to the RHS entry. Ofcourse, 10, 20 should be numerals and '/share..' a string. To read a single block i am trying something like: config = {} f = open('configFileName.ini','r') for line in f: if len(line) > 0 and line[0] != "#" and line[0] != "\n": lst = line.split() config[lst[0]] = lst[1] f.close() - this can be made to handle two or many blocks too, but a) How do i convert the numbers to int (numerals) and not string b) can i do math inside a config file c) suppose i have 4 sections, and read then in dictionaries as config{'section1':{},'section2':{}, 'section3':{},'section4':{}} and call this with: source, jammer = readConfig('config.file'), i should be able to get just section1 and section2 in source and jammer Thankx in advance 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 cspears2002 at yahoo.com Tue Jul 6 18:51:18 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue Jul 6 18:56:54 2004 Subject: [Tutor] random numbers Message-ID: <20040706165118.69148.qmail@web51608.mail.yahoo.com> Is there a Python function somewhere that can generate a number randomly? Something that would give me an integer after inputing a range would be great. From dyoo at hkn.eecs.berkeley.edu Tue Jul 6 19:18:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 6 19:18:51 2004 Subject: [Tutor] random numbers In-Reply-To: <20040706165118.69148.qmail@web51608.mail.yahoo.com> Message-ID: On Tue, 6 Jul 2004, Christopher Spears wrote: > Is there a Python function somewhere that can generate a number > randomly? Something that would give me an integer after inputing a > range would be great. Hi Christopher, Ah, then the 'randrange()' function within the 'random' Standard Library module should do the trick. The documentation on 'random' is here: http://www.python.org/doc/lib/module-random.html Try it out; if you have questions on it, please feel free to ask on the list. Good luck! From project5 at redrival.net Tue Jul 6 20:53:11 2004 From: project5 at redrival.net (Andrei) Date: Tue Jul 6 20:53:36 2004 Subject: [Tutor] Re: Config Files and Thankx (Reading Numerical Data) References: Message-ID: Karthikesh Raju wrote on Tue, 6 Jul 2004 13:20:02 +0300: > Thankx for the responses for my earlier mail. Somehow, i did not get > the responses, but when i checked the archives i found them. It was > quite useful (Andrei's esp). Glad it helped. > Now suppose i have a config file like say > [userful] > no_of_sources 10 > no_of_users 20 If you add equal signs or colons in between name and value, you can use the ConfigParser module to parse what is essential an INI file. E.g. you can use the sections() method to get all categories [blabla]. ConfigParser has built-in conversion, e.g. the getint() method which returns an integer. > a) How do i convert the numbers to int (numerals) and not string Use int(sometext). Or use the appropriate method provided by the ConfigParser module. > b) can i do math inside a config file Um... not as such and I'm not sure that's a very good idea anyway. You can use eval() when reading the data, so if e.g. you have a configuration entry which says: [section] c=5+6 you could read the value of c as string and say something along the lines: settings['c'] = eval(settings['c']) However, don't do this if you don't fully trust the code in the config file. If there is a chance that a malicious user could get to it and modify it, eval()-ing it is dangerous, because you're basically giving that malicious user the right to run arbitrary code on your machine. Note that if the persons who have access to the config files also by definition have access to the program, there is no extra danger from eval - if one of these persons is malicious, he could modify your .py directly instead of messing around with the config file. > c) suppose i have 4 sections, and read then in dictionaries as > > config{'section1':{},'section2':{}, 'section3':{},'section4':{}} > > and call this with: > > source, jammer = readConfig('config.file'), > > i should be able to get just section1 and section2 in source and jammer That wouldn't work, because readConfig would have to return a 2-tuple, not a dictionary (dictionaries can't be unpacked). But you could rewrite readConfig to return a tuple - it would need more parameters though. Or, of course, you could use ConfigParser (hint, hint ;). Never do yourself what the Python batteries can do for you. -- 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 bernardlebel.com Tue Jul 6 22:00:56 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Jul 6 20:59:03 2004 Subject: [Tutor] test Message-ID: <001801c46393$f56e10b0$0095fea9@atyss> this is a test! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040706/6e421201/attachment.html From alex at alexnewby.com Tue Jul 6 21:21:18 2004 From: alex at alexnewby.com (Alex Newby) Date: Tue Jul 6 21:21:24 2004 Subject: [Tutor] Creating functions with Ming Message-ID: <1089141678.6752.199839751@webmail.messagingengine.com> I've been toying with Ming with intent to make language skill-building exercises on the web. Currently, I've been translating the Astral Trespassers example in O'Reilly's "Perl Graphics Programming" Chapter 9 freebie for Ming. All went well until I encountered the following function: sub drawRect { my shape = shift; my ($w, $h, $dx, $dy) = @_; $shape->movePen($dx, $dy) $shape->drawLine($w, 0) $shape->drawLine(0, $h) $shape->drawLine(-$w, 0) $shape->drawLine(0, -$h) } I have little idea how to approximate this in Python. The Perl rendition is essentially procedural. Whereas, the Python version I've slapped together isn't so much. This is the essential snippet: from ming import * def drawRect(self, w, h, x, y): movePenTo(x, y) drawLineTo(w, 0) drawLineTo(0, h) drawLineTo(-w, 0) drawLineTo(0, -h) s = SWFShape() s.setLeftFill(s.addFill(255, 0, 0)) s.drawRect(10, 10, -5, 0) s.drawRect(40, 10, -20, 10) I am aware that my function doesn't really do anything. This is a snippet from ming.py: class SWFShape(SWFBase): def movePenTo(self, x, y): mingc.SWFShape_movePenTo(self.this, x, y) def drawLineTo(self, x, y): mingc.SWFShape_drawLineTo(self.this, x, y) #Coincidentally, there is also a function called drawRect. #I thought to sub-class and received critical errors. def drawRect(self, rect): mingc.SWFShape_drawRect(self.this, rect.this); If I don't sub-class I hear about drawFoo not being an attribute of SWFShape. Any suggestions on what may be happening here. --------------------------------- Sincerely, Alex Newby E-mail: alex@alexnewby.com Website: http://www.alexnewby.com From isrgish at fastem.com Wed Jul 7 04:43:06 2004 From: isrgish at fastem.com (Isr Gish) Date: Wed Jul 7 04:43:15 2004 Subject: [Tutor] Unicode to string Message-ID: <20040707024314.C85301E400D@bag.python.org> I'm having problems with printing a uicode string. I'm getting an error. TypeError: Write() argument 1 must be string without null bytes, not unicode So I was trying to convert the unicode object to a string. This is what I'm doing. >>> uni = u'\\\x00M\x00y\x00 \x00D\x00o\x00c\x00u\x00m\x00e\x00n\x00t\x00s\x00\\\x00P\x00o\x00c\x00k\x00e\x00t\x00C\x00\\\x00T\x00r\x00i\x00a\x00l\x00s\x00.\x00a\x00p\x00p\x00\x00' >>> tmp = uni.encode('mbcs') >>> tmp = tmp.decode('utf-16', 'ignore') Only then can I print "tmp". All this seems to be a big mess I'm sure there must be some better way. Any help would be aprreciated. Isr From python at bernardlebel.com Wed Jul 7 09:30:58 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Jul 7 09:40:28 2004 Subject: [Tutor] The % operator References: <002601c463e3$09228600$e85518d2@pcmaster> Message-ID: <000001c463f5$a9f8f8e0$0d01a8c0@studioaction.local> Thanks Bill. I meant the % operator at large. When I say that I couldn't retrieve it I meant I couldn't retrieve its description in the documentation (wich is the case for at 50% of the things I search!). Bernard ----- Original Message ----- From: "William Rance" To: "Bernard Lebel" Sent: Wednesday, July 07, 2004 7:27 AM Subject: Re: [Tutor] The % operator > I assume you mean the %(modulo) operator. > e.g. if a%b == 0, a is divisible by b.e.g 15%2 == 1; 25%23 == 2; that is it > gives you the remainder. > It is not clear why you cannot retrieve it. Best way is provide your code > and we can see what is going on. > Bill > ----- Original Message ----- > From: "Bernard Lebel" > To: > Sent: Tuesday, July 06, 2004 4:46 AM > Subject: [Tutor] The % operator > > > > Hello, > > > > I have been reading many examples where the % operator is used, and I know > I > > have read in the docs its meaning. However I can't seem to be able to > > retrieve it, and a search doesn't return interesting results. > > So I'm turning to you, honorable people: could someone be kind to explain > to > > me what is doing the % operator, how it works, or at least point me to the > > appropriate page in the Python documentation? > > > > > > Thank you > > Bernard > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > From rdm at rcblue.com Wed Jul 7 10:59:45 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jul 7 11:01:13 2004 Subject: [Tutor] How to enable pausing my timer.py ? Message-ID: <6.1.2.0.2.20040707015256.029c0300@rcblue.com> I just realized that my stopwatch was really a timer: you set it to beep after a length of time you enter; it stops and beeps when that time is up. I'm taking the liberty of correcting the script name and reposting. I've also changed the length of the beep to 500 milliseconds (from 5). See script below. I would like to enable pausing and then resuming timer.py. For example, say I've set it to beep after 30 minutes. I start it, but then discontinue the activity I'm timing. I want to pause the stopwatch by pressing a key and then resume later by pressing (another?) key, just as I could do with a real stopwatch. Is this possible? And I'd also really appreciate a close critique of the code I have so far. """ # timer.py import time, winsound def hms(seconds): """Convert seconds to tuplet (hours, minutes, seconds)""" import time hours, minutes = 0, 0 if seconds >= 60 and seconds < 3600: minutes = divmod(seconds,60)[0] seconds = divmod(seconds,60)[1] elif seconds >= 3600: hours = divmod(seconds,3600)[0] seconds = divmod(seconds,3600)[1] minutes = divmod(seconds,60)[0] seconds = divmod(seconds,60)[1] return hours, minutes, seconds # returns a tuple, e.g. (1, 40, 8.5) hours = raw_input("Enter the number of hours to time ") if hours == "": h_seconds = 0 else: h_seconds = 3600 * int(hours) minutes = raw_input("And the number of minutes ") if minutes == "": m_seconds = 0 else: m_seconds = 60 * int(minutes) seconds = raw_input("And the number of seconds ") t0 = time.time() if seconds == "": seconds = 0 seconds = h_seconds + m_seconds + int(seconds) print "Seconds total is", seconds t = hms(seconds) print "Beep will sound after %d hours %d minutes %d seconds\n" \ % (t[0], t[1], t[2]) r = 10 # get report of time-passed and time-left every r seconds k = r while True: t1 = time.time() seconds_passed = t1 - t0 seconds_left = seconds - int(seconds_passed) if seconds_passed >= seconds: break if seconds_passed > k: p = hms(seconds_passed) l = hms(seconds_left) print "%d hours %d minutes %d seconds have passed" \ % (p[0], p[1], p[2]) print "%d hours %d minutes %d seconds are left\n" \ % (l[0], l[1], l[2]) k += r print "seconds elapsed:", (t1 - t0) # as a check on accuracy print "TIME'S UP!" # winsound.Beep(frequency, duration in milliseconds) - only for Windows winsound.Beep(500,500) """ Thanks, tutors, Dick Moores From m at mongers.org Wed Jul 7 12:36:40 2004 From: m at mongers.org (Morten Liebach) Date: Wed Jul 7 12:41:53 2004 Subject: [Tutor] Dictionary of dictionaries of dictionaries of lists. Message-ID: <20040707103602.GC11721@mongers.org> Hi I'm writing code to generate my static weblog pages, later rsync'ed to the server (I can't and won't run serverside programs on it), from a PostgreSQl database. Each entry have a 'id' and 'date' field, and I want a datastructure of a dictionary (named "entries") with years as keys, values of a dictionary with months as keys, holding a dictionary with days as keys, value of a list of id's for entries that day. I have the following code: """ import psycopg connection = psycopg.connect("dbname=blog user=m") cursor = connection.cursor() cursor.execute("SELECT id, date FROM blog") idx = cursor.fetchall() entries = {} for i in range(len(idx)): entries[idx[i][1].year] = \ {idx[i][1].month : {idx[i][1].day : [].append(idx[i][0])}} print idx[23] print entries[2004] """ The output: """ (30, ) {4: {20: None}} """ The first line is OK, but in the second one I expected something more like: """ {1: {1: [67], 3: [68], 4: [69, 70]}, 2: {17: [71]}} """ (Not exactly the entries in my database, there's a lot more, but you get the picture I hope) I'm clearly doing something wrong. Something's missing, but what, and (more important) why? I might have stared myself blind on this problem by now, so I need a push. :-) Maybe even a rethink of it all. I'm a python beginner, but not new to programming. I've been doing mostly perl and some C# the last year. I use OpenBSD 3.5-current, Python 2.3.3, psycopg 1.1.11, mxDateTime 2.0.5 and PostgreSQL 7.4.2. Have a nice day Morten -- http://m.mongers.org/ -- http://gallery.zentience.org/ __END__ From karthik at james.hut.fi Wed Jul 7 13:03:14 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Wed Jul 7 13:03:15 2004 Subject: [Tutor] Config Files Message-ID: Hi All Thankx Andrei for your suggestion. i have now altered the config files as [user] K = 8 [userless] K1 = 2 etc etc and loaded then using configParser module, and unpacked the dictionaries so now i will have two dictionaries user, userless with keys K and K1, but the keys are converted to lowercase, which i dont want, so a key like simulateK becomes simulatek. Why is this so? How do i solve it? With regards to the the int problem i used string.atof in a try-except loop. Is this fine? 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 lonetwin at gmail.com Wed Jul 7 16:15:38 2004 From: lonetwin at gmail.com (Steve) Date: Wed Jul 7 16:16:09 2004 Subject: [Tutor] Dictionary of dictionaries of dictionaries of lists. In-Reply-To: <20040707103602.GC11721@mongers.org> References: <20040707103602.GC11721@mongers.org> Message-ID: <5a309bd30407070715149de02e@mail.gmail.com> Hi Morten, This is what happens when one tries to do too many things in a single statement :) .... > import psycopg > > connection = psycopg.connect("dbname=blog user=m") > cursor = connection.cursor() > > cursor.execute("SELECT id, date FROM blog") > idx = cursor.fetchall() > entries = {} > for i in range(len(idx)): > entries[idx[i][1].year] = \ > {idx[i][1].month : {idx[i][1].day : [].append(idx[i][0])}} when you do this: {idx[i][1].day : [].append(idx[i][0])} or more generally something like this: >>> {'k' : somelist.append(blah)} your are assigning the *return value* of the function 'somelist.append()', which is 'None', to the key 'k'. what you could instead do is, something like: >>> {'k' : [blah]} or >>> { 'k' : list(blah) } in your case that would be: {idx[i][1].day : [ idx[i][0] ]} or {idx[i][1].day : list(idx[i][0])} HTH Steve From n.a.vogelpoel at chello.nl Wed Jul 7 16:26:39 2004 From: n.a.vogelpoel at chello.nl (Jeroen Vogelpoel) Date: Wed Jul 7 16:30:08 2004 Subject: [Tutor] Exception thrown by socket.recv() and whacking threads Message-ID: <40EC081F.7080907@chello.nl> Good day, I'm currently busy with a script that involves some simple multithreading and sockets, however, I've run into some minor problems regarding exception handling and shutting down/killing threads. Here is a simple snippet of code with some of the relevant code: === def run( self ): if self.boolConnected == False: return 0 while True: try: strReceived = self.socket.recv( 1024 ) except Exception: exit() else: self.intTotalBytesRecv += len( strReceived ) self.strBuffer += strReceived for strMessage in self._parseNewlines(): self.funcOutput( strMessage ) === socket.recv() throwns an Exception "error" when the socket is being disconnected if it's still trying to read from the socket. Is there not a nice and clean way to catch and handle "error" exceptions, other then catching "Exception"? Besides, I'd expect an "IOError" when reading from a disconnected socket, not some uncatchable semi-exception thingamajig... What gives? Also, I wonder wether it's possible to shut down/kill threads ( threading.Thread to be precise ) outside of the main run() method. That way, the entire deal with aforementioned exceptions can be ignore as I can just kill the thread, then disconnect the socket. Cheers, - Jeroen Vogelpoel From dyoo at hkn.eecs.berkeley.edu Wed Jul 7 19:55:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 7 19:55:48 2004 Subject: [Tutor] The % operator In-Reply-To: <000001c463f5$a9f8f8e0$0d01a8c0@studioaction.local> Message-ID: On Wed, 7 Jul 2004, Bernard Lebel wrote: > I meant the % operator at large. When I say that I couldn't retrieve it > I meant I couldn't retrieve its description in the documentation (wich > is the case for at 50% of the things I search!). Hi Bernard, Here are pointers to the documentation that talks about the '%' operator: http://www.python.org/doc/lib/typesnumeric.html http://www.python.org/doc/lib/typesseq-strings.html Good luck! From project5 at redrival.net Wed Jul 7 19:56:28 2004 From: project5 at redrival.net (Andrei) Date: Wed Jul 7 19:56:53 2004 Subject: [Tutor] Re: Config Files References: Message-ID: <2vz8mld17bbr$.eah05r84gft7$.dlg@40tude.net> Karthikesh Raju wrote on Wed, 7 Jul 2004 14:03:14 +0300: > Thankx Andrei for your suggestion. i have now altered the config files > as > > [user] > K = 8 > > [userless] > K1 = 2 > > etc etc and loaded then using configParser module, and unpacked the > dictionaries so now i will have two dictionaries user, userless with > keys K and K1, but the keys are converted to lowercase, which i dont want, > so a key like simulateK becomes simulatek. Well, the ConfigParser is case insensitive, so it doesn't matter if you ask it for 'simulateK' or 'simulatek'. This is generally a good thing (I'm not very fond of case sensitivity, not even in Python), but if you do need it, it seems quite easy to implement. > Why is this so? How do i solve it? If you look at the source code of ConfigParser.py, you'll see that ConfigParser inherits from RawConfigParser and RawConfigParser has a method "optionxform" which converts a string to its lowercase equivalent. It's called whenever you ask the config parser for an option. It's easy to get around it by subclassing ConfigParser and overriding this one method: >>> from ConfigParser import ConfigParser >>> class CaseConfigParser(ConfigParser): ... """A case sensitive configparser.""" ... def optionxform(self, optionstr): ... # used to say: return optionstr.lower() ... return optionstr ... >>> cp = CaseConfigParser() >>> cp.add_section('section 1') >>> cp.add_section('Section 1') >>> cp.sections() ['section 1', 'Section 1'] >>> cp.set('section 1', 'first entry', '5') >>> cp.set('Section 1', 'second entry', 'Abc') >>> cp.set('Section 1', 'Second entry', 'deF') >>> cp.get('Section 1', 'Second entry') 'deF' >>> cp.get('Section 1', 'second entry') 'Abc' > With regards to the the int problem i used string.atof in a try-except > loop. Is this fine? try-except is fine, string.atof is not really. You should avoid the string module, it's deprecated. It's only useful if you need one of the constants contained within. Use the built-in functions instead, like int() and float() depending on whather you need integers or floating-point numbers. -- 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 Jul 7 20:38:52 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed Jul 7 20:38:56 2004 Subject: [Tutor] global variables and getting/setting control values/variables between frames?? In-Reply-To: <4F155FC8-CF15-11D8-9016-0003934BF52E@kc.rr.com> Message-ID: <20040707183852.61202.qmail@web60107.mail.yahoo.com> Hello, I have an application I am writing with wxpython and the boa constructor. I am unsure how to "talk between frames and dialogs". Global variables don't seem to be passed into child dialog and other frames from the parent frame, and I am unsure as to how to get a value from a control in the parent dialog from the child dialog. for example I use the following line to get the value from a text field: myValue = self.textCtrl2.GetValue() but what if the above line is in a different dialog or frame than the text field? how do I reference that frame and control box? thanks! Jeff "python@kc.rr.com" wrote: Jeff, it's out there, just have to dig a bit... Py2exe http://starship.python.net/crew/theller/py2exe/ cx-freeze http://sourceforge.net/projects/cx-freeze/ Gordon McMillan wrote "installer" for python. unfortunately, his page is no more, but I found one link with the windows checkout... http://paulbaranowski.org/modules.php?name=News&file=article&sid=76 good luck, hope it helps! On Jul 6, 2004, at 1:06 AM, orbitz wrote: > Currently there is no real means of hiding your source from those who > have your compiled python applications. It is fairly trivial to go > from byte code -> .py. You can bundle your application though, which > will include an interpreter and all of the modules required to use it, > that way they don't need to download everything. > > Jeff Peery wrote: > >> hello, does anyone know if you can do something to the effect of >> compiling python so that it will act as a stand alone application - >> ie., can I write an application in python, create a wxpython >> interface and distribute it to my customers without them having to >> install python or anything else but my application? thanks. >> Jeff >> >> ---------------------------------------------------------------------- >> -- >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040707/6a86bc03/attachment.htm From alan.gauld at blueyonder.co.uk Wed Jul 7 21:04:52 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 7 21:04:33 2004 Subject: [Tutor] How to enable pausing my stop_watch.py ? References: <6.1.2.0.2.20040706025053.02376ec0@rcblue.com> Message-ID: <026901c46455$48b51040$6401a8c0@xp> > I would like to enable pausing and then resuming stop_watch.py. For > example, say I've set it to beep after 30 minutes. I start it, but then > discontinue the activity I'm timing. I want to pause the stopwatch by > pressing a key and then resume later by pressing (another?) key, just as > I could do with a real stopwatch. Is this possible? Yes, you might want to look at the getch() function. Windows has it in msvcrt module Linux in the curses module An example in my event driven programming topic in my tutor > And I'd also really appreciate a close critique of the code I have so far. > Not very close but... > # stop_watch.py > import time, winsound > > def hms(seconds): > """Convert seconds to tuplet (hours, minutes, seconds)""" > import time Buy convention move import outside the function, otherwise you waste a little time importing it every time the function is called and although Python does smart imports it still uses a little bit of effort... > hours, minutes = 0, 0 > > if seconds >= 60 and seconds < 3600: if 60 <= seconds < 3600: # python trickery... > minutes = divmod(seconds,60)[0] > seconds = divmod(seconds,60)[1] minutes, seconds = divmod(seconds,60) > elif seconds >= 3600: else: # since if outside the range above it must be else... > hours = divmod(seconds,3600)[0] > seconds = divmod(seconds,3600)[1] hours,seconds = divmod(seconds,3600) > minutes = divmod(seconds,60)[0] > seconds = divmod(seconds,60)[1] > return hours, minutes, seconds # returns a tuple, e.g. (1, 40, 8.5) return hours, divmod(seconds,60) # h, m, s Cuts it to 6 lines... > hours = raw_input("Enter the number of hours to time ") > if hours == "": > h_seconds = 0 > else: > h_seconds = 3600 * int(hours) h_seconds = (hours and 3600*int(hours)) or 0 # shorter but more obscure Works like this: Only evaluate 3600*hours if hours NOT "" If result is False(ie hours was "") then evaluate second part of OR - ie 0 > minutes = raw_input("And the number of minutes ") > if minutes == "": > m_seconds = 0 > else: > m_seconds = 60 * int(minutes) Same trick as above > seconds = raw_input("And the number of seconds ") > t0 = time.time() > if seconds == "": > seconds = 0 > seconds = h_seconds + m_seconds + int(seconds) > print "Seconds total is", seconds > > t = hms(seconds) # delete this line!!!!! > print "Beep will sound after %d hours %d minutes %d seconds\n" \ > % (t[0], t[1], t[2]) replace line immediately above with % hms(seconds) > r = 10 # get report of time-passed and time-left every r seconds > k = r > while True: > t1 = time.time() > seconds_passed = t1 - t0 > seconds_left = seconds - int(seconds_passed) > > if seconds_passed >= seconds: > break > > if seconds_passed > k: > p = hms(seconds_passed) ## delete these two lines > l = hms(seconds_left) > print "%d hours %d minutes %d seconds have passed" \ > % (p[0], p[1], p[2]) % hms(seconds_passed) > print "%d hours %d minutes %d seconds are left\n" \ > % (l[0], l[1], l[2]) % hms(seconds_left) > k += r k += 10 # not sure what value r adds? The loop will repeat very very rapidly and use a lot of CPU. Try inserting a time.sleep() call to cut CPU activity. Try a value of, say 0.25. Add your call to getch() here too. Set a guard condition (called paused?) and put an if statement in front of the t1 = ... line above. > print "seconds elapsed:", (t1 - t0) # as a check on accuracy > print "TIME'S UP!" > > # winsound.Beep(frequency, duration in milliseconds) - only for Windows > winsound.Beep(500,5) > """ HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Wed Jul 7 21:19:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 7 21:19:33 2004 Subject: [Tutor] The % operator References: <002601c463e3$09228600$e85518d2@pcmaster> <000001c463f5$a9f8f8e0$0d01a8c0@studioaction.local> Message-ID: <027601c46457$61d81520$6401a8c0@xp> Hi Bernard, > I meant the % operator at large. When I say that I couldn't retrieve it I > meant I couldn't retrieve its description in the documentation (wich is the > case for at 50% of the things I search!). How are you searching? In the case of % it is an operator so it won't be in the module help pages so you need to look in the Standard Library. If you go to the index page and click Symbols you will find the formatting version listed. The other use for % is as a numeric operation so you go to the Number types in the table of contents. There it is listed as a modulo operator. Of course to do that search I had to know: a) % is an operator - I can deduce that from sample code and I can confirm it by looking at the list of operators in the Language Reference help page. b) operators are in the standard library help not the modules help - I know that from past experience gained fom trial and error! c) the modulo version is a numeric operator - I might have deduced that from sample code... How does that compare to your search approach? Alan G (In "teaching to fish" mode :-) From askoose at sandia.gov Wed Jul 7 21:23:34 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Wed Jul 7 21:23:57 2004 Subject: [Tutor] Data format question Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F239@es05snlnt.sandia.gov> Hello, I am writing a filter program that reads a column of data, converts it and then writes it to another file. I was wondering how do you convert a column of data (for example multiply the column by a number or replace the letter A with a number) and how does one maintain a column format in the new output file? Also any suggested readings either on-line or books on text file handling in Python would be appreciated. I have read through some of the tutorials on python.org and read the python grimore. Thanks. Ara Here is a part of the code for pulling out a column of data and then writing it to new file. inp = open("out.txt","r") outp = open("out2.txt","w") for line in inp.readlines(): words = line.split() #thanks to orbitz for this line if len(words) >= 1: outp.write(words[0]) "There is something to be learned from a rainstorm. When meeting with a sudden shower, you try not to get wet and run quickly along the road. But doing such things as passing under the eaves of houses, you still get wet. When you are resolved from the beginning, you will not be perplexed, though you still get the same soaking." - Yamamoto Tsunetomo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040707/7e88dce8/attachment.htm From alan.gauld at blueyonder.co.uk Wed Jul 7 21:25:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 7 21:25:05 2004 Subject: [Tutor] How to enable pausing my timer.py ? References: <6.1.2.0.2.20040707015256.029c0300@rcblue.com> Message-ID: <027d01c46458$27d35f00$6401a8c0@xp> > I just realized that my stopwatch was really a timer: you set it to beep > after a length of time you enter; it stops and beeps when that time is up. You could make it even more general purpose buy putting the guts of it in a function called say, doAfter() def doAfter(t,f): ''' t is the time required and f is a function to be executed after t expires.''' Thus in your current case you would call doAfter( t, lambda : winsound.beep(500) ) Just a thought... :-) Alan G. From alan.gauld at blueyonder.co.uk Wed Jul 7 21:48:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 7 21:48:33 2004 Subject: [Tutor] Dictionary of dictionaries of dictionaries of lists. References: <20040707103602.GC11721@mongers.org> Message-ID: <028e01c4645b$6f144f20$6401a8c0@xp> > I have the following code: > > """ > import psycopg > > connection = psycopg.connect("dbname=blog user=m") > cursor = connection.cursor() > > cursor.execute("SELECT id, date FROM blog") > idx = cursor.fetchall() > entries = {} > for i in range(len(idx)): Might make it slightly clearer if you use for id in idx: entries[id[1].year] = .... using a for loop with a range(len combo is usually wrong, either you would be better with a while or to iterate over the collection itself. > entries[idx[i][1].year] = \ > {idx[i][1].month : {idx[i][1].day : [].append(idx[i][0])}} I'm not sure I understand this bit. You are creating a new dictionary with a single key which has another new dictionary also with a single key with a list with a single value? Would a simple tuple not be a better solution? Or are you (as I suspect you are) trying to add new entries to the existing ones? So that you can evaluate entries[2004][03][21] and get back a list? > I'm clearly doing something wrong. Something's missing, but what, and > (more important) why? I might have stared myself blind on this problem > by now, so I need a push. :-) Maybe even a rethink of it all. The problem is you are creating a brand new dictionary each time and nuking the previous entry... You need to add to the existing dictionary not replace it. Because you have such a deeply nested structure you will probably need to do this in multiple steps I suspect. HTH, Alan G. From alan.gauld at blueyonder.co.uk Wed Jul 7 21:59:25 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 7 21:59:05 2004 Subject: [Tutor] global variables and getting/setting controlvalues/variables between frames?? References: <20040707183852.61202.qmail@web60107.mail.yahoo.com> Message-ID: <029c01c4645c$e7e7bf30$6401a8c0@xp> > Hello, I have an application I am writing with wxpython and the > boa constructor. Dunno anything about Boa so that might invalidate my reply... > I am unsure how to "talk between frames and dialogs". > Global variables don't seem to be passed into child dialog > and other frames from the parent frame, Global variables exist at the file level and should be visible within any function within that file. However global variables are almnost certainly the wrong answer! :-) > I am unsure as to how to get a value from a control in the parent > dialog from the child dialog. Just to be clear, we are talking about GUI control here not class inheritance or widget containment? ie You have a dialog whereby you hit a button and a new "child" dialog opens? > > myValue = self.textCtrl2.GetValue() > > but what if the above line is in a different dialog or frame > than the text field? If its in a different object then one of two situations arises: 1) If you know the new dialog needs to know it you pass a refernce to the parent dialog into the child dialog constructor when you call it. The child dialog can then call parent.textCtrl2.GetValue() OR 2) If the parent needs to know the value from the child dialog you return it as a result. Without knowing more about the design of your application its hard to be definite. But one thing you should never be doing is mixing up GUI widget code and application logic... So if its an application object that needs to know then pass a reference to the app object to the dialog or a reference to the dialog to the app (latter is best for reuse). HTH Alan G. From Christian.Wyglendowski at greenville.edu Wed Jul 7 22:56:31 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Jul 7 22:56:53 2004 Subject: [Tutor] How to enable pausing my timer.py ? Message-ID: > -----Original Message----- > > I just realized that my stopwatch was really a timer: you set it to > beep > > after a length of time you enter; it stops and beeps when that time > is up. > > You could make it even more general purpose buy putting the > guts of it in a function called say, doAfter() > > def doAfter(t,f): > ''' t is the time required and f is a function to be executed > after t expires.''' > > Thus in your current case you would call > > doAfter( t, lambda : winsound.beep(500) ) Which is I believe what the Timer object in the threading module lets you do: >>> import threading, sys >>> t = threading.Timer(10, sys.stdout.write, ['Done']) >>> t.start() ...(waits for 10 secs)... >>> Done Documentation for the threading.Timer object can be found here: http://docs.python.org/lib/timer-objects.html In order to pause one, I think you would need to send the thread a signal, but that sort of magic is beyond the skill of *this* python hack ;-) Maybe I'll play around with it and see if I can figure it out. Christian http://www.dowski.com > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alex at alexnewby.com Thu Jul 8 04:49:39 2004 From: alex at alexnewby.com (Alex Newby) Date: Thu Jul 8 04:49:45 2004 Subject: [Tutor] Passing objects Message-ID: <1089254979.17109.199940811@webmail.messagingengine.com> Continuing on my quest to understand how to pass around objects with ming(anything?)... >>> def foo(shape): shape = SWFShape() return shape >>> r = "" >>> foo(r) >>> r '' >>> I am somewhat mystified by the above behaviour. A class instance is instantiated, but r remains a string. How can I pass an instance of an object to a function, that will permit the objects methods applied in the function? I was exploring the utility of the following. def bar(Object): Object.MainClassFunction(args) return anObject instance = MainClass() bar(instance) This clearly fails. Suggestions, comments, wit and sarcasm are appreciated... --------------------------------- Sincerely, Alex Newby E-mail: alex@alexnewby.com Website: http://www.alexnewby.com From marvboyes at att.net Thu Jul 8 05:06:30 2004 From: marvboyes at att.net (Marv Boyes) Date: Thu Jul 8 05:07:14 2004 Subject: [Tutor] Cut, Copy, and Paste in Tkinter Message-ID: <40ECBA36.2020709@att.net> Hello, all. I'm trying to get a Paste function to work in a little Tkinter notepad-type application I'm working on (I hate Linux's Knotes and want to replace it on my machine). I've been using Martin Ultima's PyWord for inspiration and guidance, and I've had success adapting the Cut and Copy routines he used, but for some reason I can't manage a Paste. Here's what I have to define cut and copy (where "text" is the name of my text widget); these are working for me: def cut_text(text): try: text._clipboard = text.get("sel.first", "sel,last") text.delete("sel.first", "sel.last") except: pass def copy_text(text): try: text = text.get("sel.first", "sel.last") except: pass [I don't know whether or not it's pertinent, but text cut and/or copied from my application successfully pastes into other applications.] I'm not getting anywhere with paste, no matter what I try. I've tried more-or-less copying (in spirit, adapted for my purpose) the PyWord paste routine, but that doesn't even work. I've made sure that my keybindings are correct. 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 glingl at aon.at Thu Jul 8 08:48:16 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Jul 8 08:47:36 2004 Subject: [Tutor] Passing objects In-Reply-To: <1089254979.17109.199940811@webmail.messagingengine.com> References: <1089254979.17109.199940811@webmail.messagingengine.com> Message-ID: <40ECEE30.10703@aon.at> Alex Newby schrieb: >Continuing on my quest to understand how to pass around objects with >ming(anything?)... > > > >>>>def foo(shape): >>>> >>>> > shape = SWFShape() > return shape > > >>>>r = "" >>>>foo(r) >>>> >>>> > > > >>>>r >>>> >>>> >'' > > > > > You define a function with 1 parameter: shape. In Python parameters are local names - so this name will not exist any more, when foo() is done. When you call foo(r), shape refers to the empty string. Interestingly you don't make use of this object now called shape in the body of foo(). Instead, in the next statement, which is an assignment, this is changed and shape now refers to the object constructed by the call SWFShape(). So shape is a name for this object. The next statement returns that reference. If you now want r to be a name for this object, you simply have to write: r = foo(r) Alas, you could as well write r = foo("something") or r = foo(1001) with the same result. ... or redefine foo: def foo(): shape = SWFShape() return shape and call r = foo() foo within its body cannot replace the object r refers to. It could - in principle - change that object, but (1) not by an assignment, which assigns another object to the parameter and (2) only if that object were mutable - which is not the case for strings. (But although the concept of mutable and immutable objects is crucial in Python that's probably beyond the scope of your question) 2 more comments to the following: >I am somewhat mystified by the above behaviour. A class instance is >instantiated, but r remains a string. How can I pass an instance of an >object to a function, that will permit the objects methods applied in >the function? > >I was exploring the utility of the following. > >def bar(Object): > Object.MainClassFunction(args) > return anObject > > 1. here anObject is not a name which refers to something, so a nameErrpr will occur > >instance = MainClass() >bar(instance) > > 2. it generally doesn't make much sense to call a function, which returns something without using this returned object - be it in an assignment statement like obj = bar(instance) or in an expression like makeUseof(bar(instance)) Regards, Gregor > > From project5 at redrival.net Thu Jul 8 09:04:57 2004 From: project5 at redrival.net (Andrei) Date: Thu Jul 8 09:05:09 2004 Subject: [Tutor] Re: Data format question References: <9A4B2157EFDBE546BECD68C62AC3B1C81738F239@es05snlnt.sandia.gov> Message-ID: Kooser, Ara S sandia.gov> writes: > I am writing a filter program that reads a column of data, converts it and then writes it to another file. > Here is a part of the code for pulling out a column of data and then writing it to new file. > inp = open("out.txt","r")outp = open("out2.txt","w") > for line in inp.readlines(): words = line.split() #thanks to orbitz for this line if len(words) >= 1: outp.write(words[0]) Ugh, look at how that code turned out. Are you using a weird mail client? You've got the code which reads the first column and writes it away already. All you need to do is process the data before writing it. So instead of writing words[0] directly, assign it to a variable, then modify that variable in the way you need it to be modified and finally write it to outp. Yours, Andrei From rdm at rcblue.com Thu Jul 8 10:16:33 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Jul 8 10:18:38 2004 Subject: [Tutor] How to enable pausing my stop_watch.py ? In-Reply-To: <026901c46455$48b51040$6401a8c0@xp> References: <6.1.2.0.2.20040706025053.02376ec0@rcblue.com> <026901c46455$48b51040$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040708010914.0275bea0@rcblue.com> Alan Gauld wrote at 12:04 7/7/2004: > > I would like to enable pausing and then resuming stop_watch.py. For > > example, say I've set it to beep after 30 minutes. I start it, but >then > > discontinue the activity I'm timing. I want to pause the stopwatch >by > > pressing a key and then resume later by pressing (another?) key, >just as > > I could do with a real stopwatch. Is this possible? > >Yes, you might want to look at the getch() function. > >Windows has it in msvcrt module >Linux in the curses module > >An example in my event driven programming topic in my tutor Here's that page without the frame: http://www.freenetpages.co.uk/hp/alan.gauld/tutevent.htm I'm afraid I don't understand enough to know where to put this line: self.txtBox.bind("", self.doKeyEvent) Could you please do a copy and paste and shoot back the whole script so I can see what it does? And thanks VERY much for your other detailed comments and suggestions. Dick Moores From alan.gauld at blueyonder.co.uk Thu Jul 8 10:32:10 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 8 10:31:41 2004 Subject: [Tutor] Passing objects References: <1089254979.17109.199940811@webmail.messagingengine.com> Message-ID: <02bc01c464c6$10589700$6401a8c0@xp> > >>> def foo(shape): > shape = SWFShape() > return shape > >>> r = "" > >>> foo(r) > > >>> r > '' > >>> > > I am somewhat mystified by the above behaviour. A class instance is > instantiated, but r remains a string. Of course. You create the shape inside the function, after the function finishes the shape is lost. If you want to keep it you need to assign the function return value to a variable: >>> r = foo(r) >>> r > How can I pass an instance of an object to a function, that will > permit the objects methods applied in the function? Just pass the object into the function. The function can call the objects methods. I assume you tried that and had a roblem? > I was exploring the utility of the following. > > def bar(Object): > Object.MainClassFunction(args) > return anObject I assume this should read return Object > > instance = MainClass() > bar(instance) > > This clearly fails. No, it should succeed(with the fixed return statement). What happened that made you think it fails? But notice that once again you throw away the result of your function. 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 Jul 8 10:35:29 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 8 10:35:00 2004 Subject: [Tutor] Cut, Copy, and Paste in Tkinter References: <40ECBA36.2020709@att.net> Message-ID: <02c101c464c6$8694afd0$6401a8c0@xp> > I'm not getting anywhere with paste, no matter what I try. I've tried > more-or-less copying (in spirit, adapted for my purpose) the PyWord > paste routine, but that doesn't even work. Since I don't know pyWord I can't comment, but a littele bit of sample code would help us. You've posted the code that works but left us to guess at what doesn't work! The Tkinter text widget's insert method should be the key to it, but how you use it is up to you... A clue please? Alan G. From rdm at rcblue.com Thu Jul 8 10:39:17 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Jul 8 10:39:18 2004 Subject: [Tutor] How to enable pausing my stop_watch.py ? Message-ID: <6.1.2.0.2.20040708013746.0295cd58@rcblue.com> Dick Moores wrote at 01:16 7/8/2004: >Alan Gauld wrote at 12:04 7/7/2004: >>An example in my event driven programming topic in my tutor > >Here's that page without the frame: >http://www.freenetpages.co.uk/hp/alan.gauld/tutevent.htm > >I'm afraid I don't understand enough to know where to put this line: >self.txtBox.bind("", self.doKeyEvent) I've got it now: """ from Tkinter import * class KeysApp(Frame): def __init__(self): Frame.__init__(self) self.txtBox = Text(self) self.txtBox.bind("", self.doQuitEvent) self.txtBox.pack() self.pack() self.txtBox.bind("", self.doKeyEvent) def doKeyEvent(self,event): str = "%d\n" % event.keycode self.txtBox.insert(END, str) return "break" def doQuitEvent(self,event): import sys sys.exit() myApp = KeysApp() myApp.mainloop() "" Sorry about that. Dick Moores From visional_freeman at yahoo.com Thu Jul 8 11:42:32 2004 From: visional_freeman at yahoo.com (ivan low) Date: Thu Jul 8 11:41:02 2004 Subject: [Tutor] ebooks for python? Message-ID: <40ED1708.8070500@yahoo.com> Hi, I had been searching on the net for the python ebooks but there don't seem to be any of them. I was thinking maybe some member in the list will be able to provide some of this infomation. I don't mind if I have to pay for the material cause I'm very busy working out side and I can't really bring around those big books where ever I go. So I was thinking of getting a PDA. So I can download all those information and read everywhere I go. Ivan From alan.gauld at blueyonder.co.uk Thu Jul 8 13:13:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 8 13:12:59 2004 Subject: [Tutor] ebooks for python? References: <40ED1708.8070500@yahoo.com> Message-ID: <02e801c464dc$9a2eaf30$6401a8c0@xp> > Hi, I had been searching on the net for the python ebooks but there > don't seem to be any of them. Not sure about proper ebooks but there are several Python web resources available to download and several in PDF format. My own web tutor is available in HTML(zipped), PDF, Palm DOC format The PDF(*) and Palm versions are quite old, the HTML version is the current edition. Hopefully by August the new all singing tutor will be ready with both HTML and PDF for download... Other downloadable resources include Dive Into Python Text processing in Python(??) Bruce Eckel's Python pages (I think?) Also lots of sample chapters at verious publisher sites And of course there is the official dpocumentation too. It should keep you reading for quite a while. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld (*)The PDF version seems to have gone missing, I'll try to reinstate that later this week! From fusco_john at yahoo.com Thu Jul 8 13:24:12 2004 From: fusco_john at yahoo.com (John Fusco) Date: Thu Jul 8 13:24:15 2004 Subject: [Tutor] greyscale bitmaps with python Message-ID: <20040708112412.60670.qmail@web52204.mail.yahoo.com> I'm looking for a quick and dirty way to display a greyscale bitmap from a list of integers. I don't think I can do this with Tkinter. Any ideas? Thanks, John __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From Christian.Wyglendowski at greenville.edu Thu Jul 8 15:29:41 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu Jul 8 15:29:48 2004 Subject: [Tutor] ebooks for python? Message-ID: > -----Original Message----- > > > Hi, I had been searching on the net for the python ebooks but there > > don't seem to be any of them. > .....snipped..... > > Other downloadable resources include > > Dive Into Python > Text processing in Python(??) > Bruce Eckel's Python pages (I think?) You can also check out "How to Think Like a Computer Scientist". I found it quite helpful, coming from a non-programming background: http://www.ibiblio.org/obp/thinkCSpy/dist/thinkCSpy.pdf Christian http://www.dowski.com From askoose at sandia.gov Thu Jul 8 16:20:06 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Jul 8 16:20:34 2004 Subject: [Tutor] ebooks for python? Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F23E@es05snlnt.sandia.gov> This one http://www.ibiblio.org/obp/thinkCSpy/dist/thinkCSpy.pdf And also http://www.freenetpages.co.uk/hp/alan.gauld Ara "There is something to be learned from a rainstorm. When meeting with a sudden shower, you try not to get wet and run quickly along the road. But doing such things as passing under the eaves of houses, you still get wet. When you are resolved from the beginning, you will not be perplexed, though you still get the same soaking." - Yamamoto Tsunetomo -----Original Message----- From: ivan low [mailto:visional_freeman@yahoo.com] Sent: Thursday, July 08, 2004 3:43 AM To: python Subject: [Tutor] ebooks for python? Hi, I had been searching on the net for the python ebooks but there don't seem to be any of them. I was thinking maybe some member in the list will be able to provide some of this infomation. I don't mind if I have to pay for the material cause I'm very busy working out side and I can't really bring around those big books where ever I go. So I was thinking of getting a PDA. So I can download all those information and read everywhere I go. Ivan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From John.Ertl at fnmoc.navy.mil Thu Jul 8 19:41:50 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Jul 8 19:35:15 2004 Subject: [Tutor] Parsing XML with minidom? Message-ID: I am trying to use minidom to parse a small XML string. This is the test before I move onto bigger and better parsing but I am not getting the results I expected. I am trying to make a list of integers from the XML. def parsexml(xmlstring): import xml.dom.minidom doc = xml.dom.minidom.parseString(xmlstring) print doc.toxml() intlist = [] modlist = doc.getElementsByTagName("element") for each in modlist: intlist.append(each.data) return intlist if __name__ == "__main__": xml = """ 1 2 3 4 5 6 7 8 9 10 """ intlist = parsexml(xml) print intlist Output is : 1 2 3 4 5 6 7 8 9 10 Traceback (most recent call last): File "./MyHandler.py", line 81, in ? value = parsexml(xml) File "./MyHandler.py", line 15, in parsexml print each.data AttributeError: Element instance has no attribute 'data' If I instead of try to get the data I just : for each in modlist: print each.toxml() I get the following...This makes me think that I am indeed looking for data in the correct place? 1 2 3 4 5 6 7 8 9 10 [] Thanks John Ertl From dyoo at hkn.eecs.berkeley.edu Thu Jul 8 20:14:52 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 8 20:14:58 2004 Subject: [Tutor] Passing objects [return statements and OUTPUT parameters] In-Reply-To: <02bc01c464c6$10589700$6401a8c0@xp> Message-ID: On Thu, 8 Jul 2004, Alan Gauld wrote: > > >>> def foo(shape): > > shape = SWFShape() > > return shape > > >>> r = "" > > >>> foo(r) > > > > >>> r > > '' > > >>> > > > > I am somewhat mystified by the above behaviour. A class instance is > > instantiated, but r remains a string. > > Of course. You create the shape inside the function, > after the function finishes the shape is lost. If you want to keep > it you need to assign the function return value to a variable: > > >>> r = foo(r) > >>> r > Hi Alex, There's some confusion here; I think that you may be thinking of "OUTPUT" parameters, like the ones provided in Fortran or C. If we want to get back several results from a function, in those other languages, we'd set aside a few parameters that aren't used for input, but rather, for storing the results of some process. For example, let's say we were writing a 'divmod()' function in C that provides both the quotient and remainder of some division: /*** C code ***/ #include void divmod(int m, int n, int *q, int *r) { *q = m / n; *r = m % n; } int main() { int x, y; int q, r; printf("Enter two integers, each on a separate line:\n"); scanf("%d %d", &x, &y); divmod(x, y, &q, &r); printf("The quotient and remainder is: %d, %d", q, r); return 0; } /******/ In this C code, 'q' and 'r' are used as OUTPUT variables, just to store the results of 'divmod()'. We'd say that we're using 'divmod' for its side-effect of modifying the last two parameters. Fortran supports a similar effect. But Python programs typically do not use OUTPUT-style parameters, primarily because it's easy to return multiple values with a 'return' statement: ### Python code ### def divmod(m, n): """Given integers m, n, returns the quotient and remainder of dividing m by n as a 2-tuple.""" q = m / n r = m % n return (q, r) def main(): print "Input two integers, each on a separate line:" x = input() y = input() q, r = divmod(x, y) print "The quotient and remainder is: %d, %d" % (q, r) ###### The advantage of avoiding OUTPUT parameters is that we are not necessarily constrained to set aside variables just for doing things. If we were minimalistic, we could even reduce the program above to: ### def divmod(m, n): """Given integers m, n, returns the quotient and remainder of dividing m by n as a 2-tuple.""" return (m/n, m%n) def main(): print "Input two integers, each on a separate line:" print "The quotient and remainder is: %d, %d" % divmod(input(), input()) ### And here we don't even do any assignments. This might be a little extreme, though. *grin* Going back to your original function: ### def foo(shape): shape = SWFShape() return shape r = "" foo(r) ### the bug here is a misunderstanding of how 'return' works --- the code is trying to treat 'shape' as an OUTPUT parameter, but that's not how 'return' is intended to be used. Try: ### def foo(): shape = SWFShape() return shape r = foo() ### or even: ### def foo(): return SWFShape() r = foo() ### Hope this helps! From John.Ertl at fnmoc.navy.mil Thu Jul 8 21:07:08 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Jul 8 21:00:21 2004 Subject: [Tutor] Parsing XML with minidom - problem solved Message-ID: I guess to get to the data I need to look at the childNode of each. each.childNodes[0].data John I am trying to use minidom to parse a small XML string. This is the test before I move onto bigger and better parsing but I am not getting the results I expected. I am trying to make a list of integers from the XML. def parsexml(xmlstring): import xml.dom.minidom doc = xml.dom.minidom.parseString(xmlstring) print doc.toxml() intlist = [] modlist = doc.getElementsByTagName("element") for each in modlist: intlist.append(each.data) return intlist if __name__ == "__main__": xml = """ 1 2 3 4 5 6 7 8 9 10 """ intlist = parsexml(xml) print intlist Output is : 1 2 3 4 5 6 7 8 9 10 Traceback (most recent call last): File "./MyHandler.py", line 81, in ? value = parsexml(xml) File "./MyHandler.py", line 15, in parsexml print each.data AttributeError: Element instance has no attribute 'data' If I instead of try to get the data I just : for each in modlist: print each.toxml() I get the following...This makes me think that I am indeed looking for data in the correct place? 1 2 3 4 5 6 7 8 9 10 [] Thanks John Ertl From alex at alexnewby.com Thu Jul 8 21:03:34 2004 From: alex at alexnewby.com (Alex Newby) Date: Thu Jul 8 21:03:38 2004 Subject: [Tutor] Passing objects - okay now I get it. Message-ID: <1089313414.8576.199994833@webmail.messagingengine.com> >(But although the concept of mutable and immutable objects is >crucial in Python that's probably beyond the scope of your question) Okay, I get it. As to immutability of strings etc. I more or less get it, but have not had sufficient reason to study it in great detail. I reminded myself of these details by reading the python2.3 docs again to the effect that the notions of mutability and immutability etc., i.e. what the rules are, is clearer. Umm, I hate to say it but the problem seems an error in my actionscript :( This became clear when I took the occassion to run the code segment line by line from the command line, with no problems when compiling the movie. def thisFunc(thisObject): thisObject.MainClassFunc() return Object o = MainClassObject() thisFunc(o) Thank you Alan, Gregor, and Danny. Alex Newby. A further instance of UNIX love... >>> ls Traceback (most recent call last): File "", line 1, in ? ls NameError: name 'ls' is not defined From dyoo at hkn.eecs.berkeley.edu Thu Jul 8 22:04:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 8 22:04:24 2004 Subject: [Tutor] Parsing XML with minidom - problem solved In-Reply-To: Message-ID: On Thu, 8 Jul 2004, Ertl, John wrote: > I guess to get to the data I need to look at the childNode of each. > > each.childNodes[0].data Hi John, Yeah; the weird thing that trips everyone up at least once (... or twice... *grin*) in DOM xml is this: the text within each element is itself a node. In fact, it's very possible for something like: this is a test. can you see this? to be made up of several child "text" nodes. It's not sufficient just to look at the first child node to get at the text --- although it works for simple cases, it'll break if the text is long enough to be split into separate child nodes. See: http://www.python.org/doc/lib/dom-example.html and, in particular, take a look at the "getText()" function and the way that the example uses getText(). Hope this helps! From klappnase at freenet.de Thu Jul 8 22:15:07 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Jul 8 22:13:07 2004 Subject: [Tutor] Cut, Copy, and Paste in Tkinter In-Reply-To: <40ECBA36.2020709@att.net> References: <40ECBA36.2020709@att.net> Message-ID: <20040708221507.4ef7effc.klappnase@freenet.de> On Wed, 07 Jul 2004 23:06:30 -0400 Marv Boyes wrote: > Hello, all. I'm trying to get a Paste function to work in a little > Tkinter notepad-type application I'm working on (I hate Linux's Knotes > and want to replace it on my machine). I've been using Martin Ultima's > PyWord for inspiration and guidance, and I've had success adapting the > Cut and Copy routines he used, but for some reason I can't manage a Paste. > Does this code snippet what you want? ################ from Tkinter import * class Test(Text): def __init__(self, master, **kw): Text.__init__(self, master, **kw) self.bind('', self.copy) self.bind('', self.cut) self.bind('', self.paste) def copy(self, event=None): self.clipboard_clear() text = self.get("sel.first", "sel.last") self.clipboard_append(text) def cut(self, event): self.copy() self.delete("sel.first", "sel.last") def paste(self, event): text = self.selection_get(selection='CLIPBOARD') self.insert('insert', text) def test(): r = Tk() t = Test(r) t.pack(fill='both', expand=1) r.mainloop() if __name__ == '__main__': test() ###################### The selection is copied to the window manager's clipboard if you call copy() or cut(), the paste() method shows how you get it back; I think it's the same that happens when you use the mouse to copy & paste. I hope this helps Michael From klappnase at freenet.de Thu Jul 8 22:28:39 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Jul 8 22:26:38 2004 Subject: [Tutor] greyscale bitmaps with python In-Reply-To: <20040708112412.60670.qmail@web52204.mail.yahoo.com> References: <20040708112412.60670.qmail@web52204.mail.yahoo.com> Message-ID: <20040708222839.027c2559.klappnase@freenet.de> On Thu, 8 Jul 2004 04:24:12 -0700 (PDT) John Fusco wrote: > I'm looking for a quick and dirty way to display a > greyscale bitmap from a list of integers. I don't > think I can do this with Tkinter. Any ideas? > > Thanks, > John > Hi John, I'm not sure if that is what you need: # 7x4 xbm bitmap: arrow_up = '#define incr_width 7\n#define incr_height 4\nstatic char incr_bits[] = { 0x08, 0x1c, 0x3e, 0x7f};' self._arrow_up = Tkinter.BitmapImage(data=arrow_up, foreground=button_fg) self.up = Tkinter.Button(self._bframe, image=self._arrow_up) The arrow_up string is simply the contents of an xbm Bitmap file opened with a text editor. Michael From magnus at thinkware.se Thu Jul 8 23:10:59 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 8 23:07:55 2004 Subject: [Tutor] greyscale bitmaps with python In-Reply-To: <20040708112412.60670.qmail@web52204.mail.yahoo.com> Message-ID: <5.2.1.1.0.20040708231001.027bea78@www.thinkware.se> At 04:24 2004-07-08 -0700, John Fusco wrote: >I'm looking for a quick and dirty way to display a >greyscale bitmap from a list of integers. I don't >think I can do this with Tkinter. Any ideas? You can probably use PIL: http://www.pythonware.com/products/pil/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From dyoo at hkn.eecs.berkeley.edu Fri Jul 9 00:13:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 9 00:13:26 2004 Subject: [Tutor] Parsing XML with minidom - problem solved In-Reply-To: Message-ID: On Thu, 8 Jul 2004, Ertl, John wrote: > It [XML DOM parsing] is never as easy as it look at first glance. > > Thanks for explaining the behavior I was seeing...It is not clear. Hi John, Yeah. *grin* If there's anything that the XML libraries need, it is better beginner documentation. Much of the documentation for XML in the Standard Library already assumes some prior XML knowledge, which can be a bit infuriating at times. There's a great set of tutorials that IBM developerworks published on XML and Python, a few months ago; a Google search for "developerworks python xml" should come up with several excellent articles by David Mertz. Mark Pilgrim's book, "Dive into Python", also has a section on parsing XML: http://diveintopython.org/xml_processing/parsing_xml.html From bvande at po-box.mcgill.ca Fri Jul 9 00:38:10 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Jul 9 00:38:46 2004 Subject: [Tutor] help with setting Python Path under WinMe Message-ID: <40EDCCD2.8080902@po-box.mcgill.ca> Hi all, I'm feeling pretty lame about it :-( but I cannot figure out how to configure my Python Path as I'd like. I am using Python 2.3.4 under Windows Me. My Python installation is on my C: partition and I have my own Python files on my D: partition. I want to add the two directories: D:\Python Files\MyModules D:\Python Files in that order to the *end* of my Python Path. (This preference is explained below.) I have seen the advice for Windows users to employ the Environment Settings tab of the Control Panel->System, but Windows Me does not appear to offer this. I tried running regedit and searching the registry for PythonPath, and the only relevant key I found was: My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.3\PythonPath which was set to ('<' added for email): <"C:\PYTHON23\Lib;C:\PYTHON23\DLLs;C:\PYTHON23\Lib\lib-tk"> I tried both of the following additions to that key (rebooting after each change): <"C:\PYTHON23\Lib;C:\PYTHON23\DLLs;C:\PYTHON23\Lib\lib-tk;D:\Python Files\MyModules;D:\Python Files"> <"C:\PYTHON23\Lib;C:\PYTHON23\DLLs;C:\PYTHON23\Lib\lib-tk;D:\Python~1\MyModu~1;D:\Python~1"> In each case when I tested, I got: IDLE 1.0.3 >>> import sys >>> for i in sys.path: print i C:\PYTHON23\Lib\idlelib C:\WINDOWS\SYSTEM\PYTHON23.zip C:\Python23 C:\PYTHON23\DLLs C:\PYTHON23\lib C:\PYTHON23\lib\plat-win C:\PYTHON23\lib\lib-tk C:\PYTHON23\Lib\site-packages\win32 C:\PYTHON23\Lib\site-packages\win32\lib C:\PYTHON23\Lib\site-packages\Pythonwin C:\PYTHON23\lib\site-packages So, no effect. (This is exactly what I had before making any changes at all.) I then tried modifying my autoexec.bat to include the line: SET PYTHONPATH=D:\Python~1\MyModu~1;D:\Python~1 On reboot, this resulted in: IDLE 1.0.3 >>> import sys >>> for i in sys.path: print i C:\PYTHON23\Lib\idlelib C:\Python23 D:\Python~1\MyModu~1 D:\Python~1 C:\WINDOWS\SYSTEM\PYTHON23.zip C:\PYTHON23\DLLs C:\PYTHON23\lib C:\PYTHON23\lib\plat-win C:\PYTHON23\lib\lib-tk C:\PYTHON23\Lib\site-packages\win32 C:\PYTHON23\Lib\site-packages\win32\lib C:\PYTHON23\Lib\site-packages\Pythonwin C:\PYTHON23\lib\site-packages This works in that it lets me import my own files. But, as I said, I want my additions to appear at the end of my PythonPath. I am a bit concerned that I might save foo.py to one of the dirs I added where there is a foo.py already in existence further down the path. If I were to later run a python prog which wanted to import foo.py from one of those subsequent directories, I worry that it could well take me a long time to work out what the error was. I certainly don't know the contents of these dirs so as to be sure of avoiding a conflict, and checking each time seems a bit much. Am I worrying for nothing? It does seem to me that there ought to be a way to do what I want, though. (As a side issue, I am also puzzled as to why the change to autoexec.bat switched the order of C:\Python23 and C:\WINDOWS\SYSTEM\PYTHON23.zip.) Thanks for any suggestions and best to all, Brian vdB From jeffpeery at yahoo.com Fri Jul 9 01:19:44 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Fri Jul 9 01:19:47 2004 Subject: [Tutor] help with global variables? In-Reply-To: <029c01c4645c$e7e7bf30$6401a8c0@xp> Message-ID: <20040708231944.85882.qmail@web60109.mail.yahoo.com> one more question... I think I have a problem with my globals, I have some constants that I use throughout my application; however they do not work, I receive error messages that the "global is not defined", it is defined, which makes me think I defined it in the wrong place. where do you put globals? you say the "file level," could you be more specific? I have one script per dialog/frame, do I need to redefine the globals for each frame and dialog, shouldn't I be able to place them in the application file and have the globals available for each frame and dialog? thanks. Jeff Alan Gauld wrote: > Hello, I have an application I am writing with wxpython and the > boa constructor. Dunno anything about Boa so that might invalidate my reply... > I am unsure how to "talk between frames and dialogs". > Global variables don't seem to be passed into child dialog > and other frames from the parent frame, Global variables exist at the file level and should be visible within any function within that file. However global variables are almnost certainly the wrong answer! :-) > I am unsure as to how to get a value from a control in the parent > dialog from the child dialog. Just to be clear, we are talking about GUI control here not class inheritance or widget containment? ie You have a dialog whereby you hit a button and a new "child" dialog opens? > > myValue = self.textCtrl2.GetValue() > > but what if the above line is in a different dialog or frame > than the text field? If its in a different object then one of two situations arises: 1) If you know the new dialog needs to know it you pass a refernce to the parent dialog into the child dialog constructor when you call it. The child dialog can then call parent.textCtrl2.GetValue() OR 2) If the parent needs to know the value from the child dialog you return it as a result. Without knowing more about the design of your application its hard to be definite. But one thing you should never be doing is mixing up GUI widget code and application logic... So if its an application object that needs to know then pass a reference to the app object to the dialog or a reference to the dialog to the app (latter is best for reuse). HTH Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040708/619d590d/attachment.html From jeffpeery at yahoo.com Fri Jul 9 01:20:52 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Fri Jul 9 01:20:55 2004 Subject: Fwd: Re: [Tutor] global variables and getting/setting controlvalues/variables between frames?? Message-ID: <20040708232052.22880.qmail@web60110.mail.yahoo.com> ok, thanks that makes some sense. I am still confused about one thing. if I pass a reference to the parent frame into the child dialog, what does the reference look like? I am using the below line for example. this is a definition of a button from by main frame. when I hit the button I want the dialog to appear. I am confused is to what actually calls the dialog, I assume its: wxDialog1.wxDialog1(self), because that assigns the handle. would I then replace the arguement "self" with my reference to the parent frame? def OnButton1Button(self, event): dlg = wxDialog1.wxDialog1(self) try: dlg.ShowModal() finally: dlg.Destroy() Is this stuff discussed in a good book? thanks. thanks. Jeff Alan Gauld wrote: > Hello, I have an application I am writing with wxpython and the > boa constructor. Dunno anything about Boa so that might invalidate my reply... > I am unsure how to "talk between frames and dialogs". > Global variables don't seem to be passed into child dialog > and other frames from the parent frame, Global variables exist at the file level and should be visible within any function within that file. However global variables are almnost certainly the wrong answer! :-) > I am unsure as to how to get a value from a control in the parent > dialog from the child dialog. Just to be clear, we are talking about GUI control here not class inheritance or widget containment? ie You have a dialog whereby you hit a button and a new "child" dialog opens? > > myValue = self.textCtrl2.GetValue() > > but what if the above line is in a different dialog or frame > than the text field? If its in a different object then one of two situations arises: 1) If you know the new dialog needs to know it you pass a refernce to the parent dialog into the child dialog constructor when you call it. The child dialog can then call parent.textCtrl2.GetValue() OR 2) If the parent needs to know the value from the child dialog you return it as a result. Without knowing more about the design of your application its hard to be definite. But one thing you should never be doing is mixing up GUI widget code and application logic... So if its an application object that needs to know then pass a reference to the app object to the dialog or a reference to the dialog to the app (latter is best for reuse). HTH Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040708/6abd493d/attachment.htm From jeffpeery at yahoo.com Fri Jul 9 01:21:03 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Fri Jul 9 01:21:06 2004 Subject: Fwd: Re: [Tutor] global variables and getting/setting controlvalues/variables between frames?? Message-ID: <20040708232103.69023.qmail@web60106.mail.yahoo.com> ok, thanks that makes some sense. I am still confused about one thing. if I pass a reference to the parent frame into the child dialog, what does the reference look like? I am using the below line for example. this is a definition of a button from by main frame. when I hit the button I want the dialog to appear. I am confused is to what actually calls the dialog, I assume its: wxDialog1.wxDialog1(self), because that assigns the handle. would I then replace the arguement "self" with my reference to the parent frame? def OnButton1Button(self, event): dlg = wxDialog1.wxDialog1(self) try: dlg.ShowModal() finally: dlg.Destroy() Is this stuff discussed in a good book? thanks. thanks. Jeff Alan Gauld wrote: > Hello, I have an application I am writing with wxpython and the > boa constructor. Dunno anything about Boa so that might invalidate my reply... > I am unsure how to "talk between frames and dialogs". > Global variables don't seem to be passed into child dialog > and other frames from the parent frame, Global variables exist at the file level and should be visible within any function within that file. However global variables are almnost certainly the wrong answer! :-) > I am unsure as to how to get a value from a control in the parent > dialog from the child dialog. Just to be clear, we are talking about GUI control here not class inheritance or widget containment? ie You have a dialog whereby you hit a button and a new "child" dialog opens? > > myValue = self.textCtrl2.GetValue() > > but what if the above line is in a different dialog or frame > than the text field? If its in a different object then one of two situations arises: 1) If you know the new dialog needs to know it you pass a refernce to the parent dialog into the child dialog constructor when you call it. The child dialog can then call parent.textCtrl2.GetValue() OR 2) If the parent needs to know the value from the child dialog you return it as a result. Without knowing more about the design of your application its hard to be definite. But one thing you should never be doing is mixing up GUI widget code and application logic... So if its an application object that needs to know then pass a reference to the app object to the dialog or a reference to the dialog to the app (latter is best for reuse). HTH Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040708/2a7b0955/attachment-0001.html From alan.gauld at blueyonder.co.uk Fri Jul 9 01:44:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 9 01:44:05 2004 Subject: [Tutor] help with global variables? References: <20040708231944.85882.qmail@web60109.mail.yahoo.com> Message-ID: <032b01c46545$89567530$6401a8c0@xp> > the "global is not defined", it is defined, which makes me think > I defined it in the wrong place. where do you put globals? If I'm forced to use globals - which is rare - I put them in a separae module which I import into every other module that needs to see them. But this of course renders those modules unreusable - one good reason for avoiding globals. > you say the "file level," could you be more specific? global scope in Python means global to the file. They won't be seen outside the file(module) unless you import the module. HTH, Alan G. From karthik at james.hut.fi Fri Jul 9 09:56:45 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Fri Jul 9 09:56:47 2004 Subject: [Tutor] switch statements Message-ID: Hi All, We were implementing a switch satetement like testfile.py dec = 1 perf = { \ 1:bigfile.func1(), \ 2:bigfile.fun2()}[dec] now bigfile.py has def func1(): print "In func1" return 5 def func2(): print "In func2" return 42 Now when we run the testfile.py we get: In func1 In func2 which implies that the switch does not actually switch, as it goes through both the functions and retains the one that we asked for. Am I missing something here, why should it step into every function. 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 glingl at aon.at Fri Jul 9 11:23:11 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri Jul 9 11:22:32 2004 Subject: [Tutor] switch statements In-Reply-To: References: Message-ID: <40EE63FF.5090301@aon.at> Karthikesh Raju schrieb: >Hi All, > >We were implementing a switch satetement like > >testfile.py >dec = 1 >perf = { \ > 1:bigfile.func1(), \ > 2:bigfile.fun2()}[dec] > >now bigfile.py has > >def func1(): > print "In func1" > return 5 > >def func2(): > print "In func2" > return 42 > >Now when we run the testfile.py we get: > >In func1 >In func2 > > > Certainly! You will get a clueon what's going on, if you delete [dec] and have a look at perf: def func1(): print "In func1" return 5 def func2(): print "In func2" return 42 dec = 1 perf = { \ 1:func1(), \ 2:func2()} will output: In func1 In func2 >>> perf {1: 5, 2: 42} Clearly perf[1] outputs 5. What you intended was, that your perf dictionary contains function object. Then you must not evaluate the functions (which is done, if you attach a pair of parentheses) : dec = 1 perf = { \ 1:func1, \ 2:func2} Look at perf: >>> perf {1: , 2: } So perf contains two functions. The first one is: >>> perf[1] You can call it >>> perf[1]() In func1 5 To summarize, your program will do what you expected - if I understand you right - , if you change it that way: testfile.py dec = 1 perf = { \ 1:bigfile.func1, \ 2:bigfile.fun2}[dec]() Regards, Gregor From adam at monkeez.org Fri Jul 9 11:36:10 2004 From: adam at monkeez.org (adam) Date: Fri Jul 9 11:36:15 2004 Subject: [Tutor] Little pickle playing up on me Message-ID: <16940.217.206.168.163.1089365770.spork@webmail.monkeez.org> I've got two functions (see below) which load pickled objects in to memory - one (loadcollection) which worked by querying the user for a string to provide a file name and unpickling it. The second function (load_existing_function) takes a command line argument, which has been tested for and turned into a string. I'm getting the error: Traceback (most recent call last): File "D:\cygwin\home\rdgac2\cvs\newmag\newmag.py", line 505, in ? mainmenu() # Kicks the whole thing off File "D:\cygwin\home\rdgac2\cvs\newmag\newmag.py", line 468, in mainmenu load_existing_collection(filepassed) File "D:\cygwin\home\rdgac2\cvs\newmag\newmag.py", line 450, in load_existing_collection instance = pickle.load(openfile) File "C:\Python23\lib\pickle.py", line 1390, in load return Unpickler(file).load() File "C:\Python23\lib\pickle.py", line 872, in load dispatch[key](self) KeyError: '#' Any ideas? Thanks adam 429 def loadcollection(): 430 """This function will load a file which is a cpickled object of a- 431 magazine collection.- 432 """ 433 filename = raw_input("What is the filename?") 434 try: 435 436 file = open (filename, 'r') 437 except IOError: 438 print "That file was not found!"- 439 loadcollection() 440 instance = pickle.load(file) 441 #instance.collectionmenu() This used to take you to the instances menu 442 # but now we are going to a new edit/search menu-- 443 edit_or_search(instance) 444 445 def load_existing_collection(file): 446 >---print type (file) 447 >---print file 448 >---try: 449 >--->---openfile = open(file, 'r') 450 >--->---instance = pickle.load(openfile) 451 >--->---edit_or_search(instance) 452 >---except IOError: 453 >--->---print "That file doesn't exist, please try again" 454 >--->---loadcollection() 455 >---#instance = pickle.load(openfile) 456 >---#edit_or_search(instance) 459 def mainmenu(): 460 >---"""This method is the main entry point method that the user will first see. 461 >---It asks them whether they want to create a new collection, or load- 462 >---an existing one 463 >---""" 464 465 >---if sys.argv: 466 >--->---filepassed = str(sys.argv[0]) 467 >--- 468 >--->---load_existing_collection(filepassed) 469 470 >---else: 471 >--->---print ''' 472 >--->---################################### 473 >--->---# Main Menu # 474 >--->---################################### 475 476 477 >--->---What would you like to do?- ... ... From lonetwin at gmail.com Fri Jul 9 12:09:50 2004 From: lonetwin at gmail.com (Steve) Date: Fri Jul 9 12:10:11 2004 Subject: [Tutor] Little pickle playing up on me In-Reply-To: <16940.217.206.168.163.1089365770.spork@webmail.monkeez.org> References: <16940.217.206.168.163.1089365770.spork@webmail.monkeez.org> Message-ID: <5a309bd304070903097095a3de@mail.gmail.com> Hi Adam, looking at the error, I noticed: > File "C:\Python23\lib\pickle.py", line 872, in load > dispatch[key](self) > KeyError: '#' This suggests that pickle.py is trying to interpret a string that starts with '#'. The second thing I noticed is that, you mentioned that when you provide the filename on prompting it seems to work but when you pass it as a command line argument it seems to fail. So, I looked at your command line argument handling code and saw the problem: > 465 >---if sys.argv: > 466 >--->---filepassed = str(sys.argv[0]) sys.argv[0] is actually the name of your script when you execute it. The command line arguments passed to the script start from sys.argv[1]. This is because sometimes it is useful to know how the script was called (ie: using it's full path name as opposed to invoking from the current directory). In any case, if you need a proper full blown command line argument handling module you may look at the getopt module ...tho' it *is* a bit of an over kill for what you might want to do. HTH Steve On Fri, 9 Jul 2004 09:36:10 -0000 (GMT), adam wrote: > I've got two functions (see below) which load pickled objects in to memory > - one (loadcollection) which worked by querying the user for a string to > provide a file name and unpickling it. The second function > (load_existing_function) takes a command line argument, which has been > tested for and turned into a string. > > I'm getting the error: [...snip...] From rdm at rcblue.com Fri Jul 9 14:08:55 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 9 14:08:59 2004 Subject: [Tutor] IDLE question Message-ID: <6.1.2.0.2.20040709050231.0247fec0@rcblue.com> Don't know what to call it, but I'd like to know how to delete all variables I've created, un-import all modules I've imported, etc., with one command, when using IDLE interactively. Of course I know I could just close IDLE and open it again, but is there a command to do what I want? (I'm also not sure "command" is the right word here--sorry) Thanks, Dick Moores From lonetwin at gmail.com Fri Jul 9 14:47:31 2004 From: lonetwin at gmail.com (Steve) Date: Fri Jul 9 14:47:34 2004 Subject: [Tutor] IDLE question In-Reply-To: <6.1.2.0.2.20040709050231.0247fec0@rcblue.com> References: <6.1.2.0.2.20040709050231.0247fec0@rcblue.com> Message-ID: <5a309bd3040709054745d5eb5c@mail.gmail.com> Hi, On Fri, 09 Jul 2004 05:08:55 -0700, Dick Moores wrote: > Don't know what to call it, but I'd like to know how to delete all > variables I've created, un-import all modules I've imported, etc., with > one command, when using IDLE interactively. It is called deleting all the variables you have created, or modules you have imported from the current 'namespace', which btw at the interactive prompt is the 'global' namespace. The names of the elements in the global namespace can be seen using the builtin function "dir()" at the python prompt. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Python 2.3.3 (#2, Feb 17 2004, 11:45:40) [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> dir() ['__builtins__', '__doc__', '__file__', '__name__'] >>> a = 10 >>> dir() ['__builtins__', '__doc__', '__file__', '__name__', 'a'] >>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Also, the actual contents of the global namespace can be seen using the builtin function globals(), which returns a dictionary containing the names of the elements as keys and the actual elements as the values. Eg: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Python 2.3.3 (#2, Feb 17 2004, 11:45:40) [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> globals() {'__builtins__': , '__file__': '/home/steve/.pystartup', '__name__': '__main__', '__doc__': None} >>> >>> import os >>> a = 10 >>> >>> globals() {'__builtins__': , '__file__': '/home/steve/.pystartup', '__name__': '__main__', 'os': , '__doc__': None, 'a':10} >>> >>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To delete any element from a namspace you can use the keyword del. For eg: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >>> a = 10 >>> dir() ['__builtins__', '__doc__', '__file__', '__name__', 'a'] >>> del a >>> dir() ['__builtins__', '__doc__', '__file__', '__name__'] >>> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ So, to do what you asked for, you can simply do something like: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >>> for i in globals().keys(): ... if i not in ['__builtins__', '__doc__', '__file__', '__name__']: ... del globals()[i] ... >>> del i ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HTH Steve From rdm at rcblue.com Fri Jul 9 16:13:22 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 9 16:13:26 2004 Subject: [Tutor] IDLE question In-Reply-To: <5a309bd3040709054745d5eb5c@mail.gmail.com> References: <6.1.2.0.2.20040709050231.0247fec0@rcblue.com> <5a309bd3040709054745d5eb5c@mail.gmail.com> Message-ID: <6.1.2.0.2.20040709071147.02635ca8@rcblue.com> Steve wrote at 05:47 7/9/2004: >So, to do what you asked for, you can simply do something like: > >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > >>> for i in globals().keys(): >... if i not in ['__builtins__', '__doc__', '__file__', '__name__']: >... del globals()[i] Thanks very much, Steve. That works fine, even though it's more typing than I was hoping for.. Dick From lonetwin at gmail.com Fri Jul 9 16:35:00 2004 From: lonetwin at gmail.com (Steve) Date: Fri Jul 9 16:35:06 2004 Subject: [Tutor] IDLE question In-Reply-To: <6.1.2.0.2.20040709071147.02635ca8@rcblue.com> References: <6.1.2.0.2.20040709050231.0247fec0@rcblue.com> <5a309bd3040709054745d5eb5c@mail.gmail.com> <6.1.2.0.2.20040709071147.02635ca8@rcblue.com> Message-ID: <5a309bd30407090735345022b8@mail.gmail.com> Hi Dick, > Thanks very much, Steve. That works fine, even though it's more typing > than I was hoping for.. you could always wrap it in a function and add the function to the list in the if statement. Also you may want to add this function to a startup file (eg: ".pystartup") and then set the environment variable "PYTHONSTARTUP=.pystartup". This would load make the function available each time you fire up python. HTH Steve On Fri, 09 Jul 2004 07:13:22 -0700, Dick Moores wrote: > Steve wrote at 05:47 7/9/2004: > >So, to do what you asked for, you can simply do something like: > > > >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > >>> for i in globals().keys(): > >... if i not in ['__builtins__', '__doc__', '__file__', '__name__']: > >... del globals()[i] > > Thanks very much, Steve. That works fine, even though it's more typing > than I was hoping for.. > > Dick From rdm at rcblue.com Fri Jul 9 17:50:22 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 9 17:50:28 2004 Subject: [Tutor] IDLE question In-Reply-To: <5a309bd30407090735345022b8@mail.gmail.com> References: <6.1.2.0.2.20040709050231.0247fec0@rcblue.com> <5a309bd3040709054745d5eb5c@mail.gmail.com> <6.1.2.0.2.20040709071147.02635ca8@rcblue.com> <5a309bd30407090735345022b8@mail.gmail.com> Message-ID: <6.1.2.0.2.20040709084906.02d19668@rcblue.com> Steve wrote at 07:35 7/9/2004: > > Thanks very much, Steve. That works fine, even though it's more typing > > than I was hoping for.. >you could always wrap it in a function and add the function to the >list in the if statement. Also you may want to add this function to a >startup file (eg: ".pystartup") and then set the environment variable >"PYTHONSTARTUP=.pystartup". This would load make the function >available each time you fire up python. Steve, would you know how to do this with Windows XP? Thanks, Dick From dyoo at hkn.eecs.berkeley.edu Fri Jul 9 19:29:20 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 9 19:29:33 2004 Subject: [Tutor] IDLE question In-Reply-To: <6.1.2.0.2.20040709071147.02635ca8@rcblue.com> Message-ID: On Fri, 9 Jul 2004, Dick Moores wrote: > Steve wrote at 05:47 7/9/2004: > >So, to do what you asked for, you can simply do something like: > > > >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > >>> for i in globals().keys(): > >... if i not in ['__builtins__', '__doc__', '__file__', '__name__']: > >... del globals()[i] > > Thanks very much, Steve. That works fine, even though it's more typing > than I was hoping for.. Hi Steve, How about the "Restart Shell" command in the Shell menu, though? Does that do the same thing for you? It should also be accessible through the "Control-F6" keystroke. Good luck to you! From rob.benton at conwaycorp.net Fri Jul 9 19:31:15 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Fri Jul 9 19:31:24 2004 Subject: [Tutor] How-to for writing modules Message-ID: <40EED663.1020206@conwaycorp.net> I'm trying to find some good documentation for writing modules. I've been looking at the C/API docs but I'd like to find a step-by-step guide for module creation. Anyone know where I could find something like that (online or books)? From rdm at rcblue.com Fri Jul 9 19:43:43 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 9 19:43:46 2004 Subject: [Tutor] IDLE question Message-ID: <6.1.2.0.2.20040709104326.04426b70@rcblue.com> Danny Yoo wrote at 10:29 7/9/2004: >How about the "Restart Shell" command in the Shell menu, though? Does >that do the same thing for you? It should also be accessible through the >"Control-F6" keystroke. Yes! Thanks! There it is right on the Shell menu on IDLE's menu bar. But I also learned a lot from Steve's help. Dick From project5 at redrival.net Fri Jul 9 21:22:16 2004 From: project5 at redrival.net (Andrei) Date: Fri Jul 9 21:22:43 2004 Subject: [Tutor] Re: How-to for writing modules References: <40EED663.1020206@conwaycorp.net> Message-ID: Rob Benton wrote on Fri, 09 Jul 2004 12:31:15 -0500: > I'm trying to find some good documentation for writing modules. I've > been looking at the C/API docs but I'd like to find a step-by-step guide Any Python program is automatically a module as well. Just make sure that no code is executed when you import it (unless you need it to be executed to initilize or whatever). Or do you really really really need it to be in C? -- 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 Jul 9 21:52:28 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 9 21:51:34 2004 Subject: [Tutor] switch statements References: Message-ID: <034b01c465ee$43ce9390$6401a8c0@xp> > We were implementing a switch satetement like > > testfile.py > dec = 1 > perf = { \ > 1:bigfile.func1(), \ > 2:bigfile.fun2()}[dec] What this does is create a dictionary with keys 1 and 2 and values the *results* of the two function calls. You need to lose the parentheses to store references to the functions themselves. > Now when we run the testfile.py we get: > > In func1 > In func2 > > which implies that the switch does not actually switch, as it goes through > both the functions and retains the one that we asked for. Am I missing > something here, why should it step into every function. What you are seeing is the functions being called as the dictionary is defined. The actuall call to the dictionary(your switch) returns a number value which is not seen because you don't print it. HTH< Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Fri Jul 9 22:24:45 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 9 22:24:50 2004 Subject: [Tutor] How to enable pausing my stop_watch.py ? In-Reply-To: <026901c46455$48b51040$6401a8c0@xp> References: <6.1.2.0.2.20040706025053.02376ec0@rcblue.com> <026901c46455$48b51040$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040709132113.02fe7ec0@rcblue.com> Alan Gauld wrote at 12:04 7/7/2004: > > hours = raw_input("Enter the number of hours to time ") > > if hours == "": > > h_seconds = 0 > > else: > > h_seconds = 3600 * int(hours) > > h_seconds = (hours and 3600*int(hours)) or 0 # shorter but more >obscure > >Works like this: >Only evaluate 3600*hours if hours NOT "" >If result is False(ie hours was "") then evaluate >second part of OR - ie 0 I'm very glad to know about these uses of "and" and "or", but why is your way better? Is fewer lines better? Is it faster? More Pythonesque? (I'm not defending my code; I'd just like to know.) Thanks, Dick Moores From rob.benton at conwaycorp.net Fri Jul 9 22:36:09 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Fri Jul 9 22:36:20 2004 Subject: [Tutor] Re: How-to for writing modules In-Reply-To: References: <40EED663.1020206@conwaycorp.net> Message-ID: <40EF01B9.607@conwaycorp.net> Andrei wrote: >Rob Benton wrote on Fri, 09 Jul 2004 12:31:15 -0500: > > > >>I'm trying to find some good documentation for writing modules. I've >>been looking at the C/API docs but I'd like to find a step-by-step guide >> >> > > >Any Python program is automatically a module as well. Just make sure that >no code is executed when you import it (unless you need it to be executed >to initilize or whatever). Or do you really really really need it to be in >C? > > > > I'm going to be working on an existing module that is written in C. So any tutorials or guides would help a lot. From alan.gauld at blueyonder.co.uk Fri Jul 9 23:19:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 9 23:19:31 2004 Subject: [Tutor] How to enable pausing my stop_watch.py ? References: <6.1.2.0.2.20040706025053.02376ec0@rcblue.com> <026901c46455$48b51040$6401a8c0@xp> <6.1.2.0.2.20040709132113.02fe7ec0@rcblue.com> Message-ID: <035401c465fa$68396dc0$6401a8c0@xp> > > h_seconds = (hours and 3600*int(hours)) or 0 # shorter but more > >obscure > > > >Works like this: > >Only evaluate 3600*hours if hours NOT "" > >If result is False(ie hours was "") then evaluate > >second part of OR - ie 0 > > I'm very glad to know about these uses of "and" and "or", but why is your > way better? Is fewer lines better? Is it faster? More Pythonesque? (I'm > not defending my code; I'd just like to know.) It's not better, just an alternative way of doing it. Indeed as the comment says its more obscure and so could be regarded as worse! However it is also very slightly faster. If you are a C (or Perl or Java/Javascript) you might be familiar with the tertiary ?: operator, if so the and/or pair will present a familiar shortcut and for those programmers the obscurity is not a problem. I prefer it simply because it is shorter and doesn't clutter up my main program with if/elses that are tangential to the main purpose of the program. But tastes differ and I would never claim the and/or option was better. Indeed part of the zen of Python is that explicit is better than implicit... Alan G. From alan.gauld at blueyonder.co.uk Fri Jul 9 23:36:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 9 23:36:13 2004 Subject: [Tutor] How-to for writing modules References: <40EED663.1020206@conwaycorp.net> Message-ID: <037701c465fc$bc575320$6401a8c0@xp> > I'm trying to find some good documentation for writing modules. I've > been looking at the C/API docs but I'd like to find a step-by-step guide > for module creation. Anyone know where I could find something like that > (online or books)? My tutorial contains a topic on writing Python modules, but I assume from what you are saying about the C API that you want to create a C module? My suggestion would be to write in in Python first to check you really need it in C. If you do, go to the extending & embedding topic in the standard documentation. Programming Python also has a chapter or so on writing C modules, as do several other books. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From dyoo at hkn.eecs.berkeley.edu Sat Jul 10 00:30:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 10 00:30:12 2004 Subject: [Tutor] Re: How-to for writing modules In-Reply-To: <40EF01B9.607@conwaycorp.net> Message-ID: > >>I'm trying to find some good documentation for writing modules. I've > >>been looking at the C/API docs but I'd like to find a step-by-step guide > > > > > I'm going to be working on an existing module that is written in C. So > any tutorials or guides would help a lot. Hi Rob, Hmmm, then the "Extending and Embedding" tutorial on Python.org is probably what you're looking for: http://docs.python.org/ext/ext.html This tutorial explains how to write C/C++ code that interacts with Python. You may also want to look at the Pyrex system: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ which allows for fairly easy access to C libraries from Python. One alternative to Pyrex is SWIG: http://www.swig.org/ http://www.swig.org/tutorial.html Hope this helps! From fusco_john at yahoo.com Sat Jul 10 01:27:55 2004 From: fusco_john at yahoo.com (John Fusco) Date: Sat Jul 10 01:27:57 2004 Subject: [Tutor] greyscale bitmaps with python Message-ID: <20040709232755.38359.qmail@web52204.mail.yahoo.com> Thanks for the tips, but neither passed the "quick and dirty" test. The xbitmap is monochrome so that won't work (too dirty). PIL works, but I'm stuck with Python 1.5.2 and I need full source to build for Python 1.5.2 (not quick enough). I finally settled on the pattern below, which creates a PGM file and uses 'ee' to display. Regards, John import os def pgmhdr(rows,cols,depth): return "P2\n%d %d\n%d\n" % (cols,rows,depth) class PgmImage: def __init__(self,num_rows,num_cols,depth,pixels): assert(num_rows*num_cols==len(pixels)) self.num_rows = num_rows self.num_cols = num_cols self.depth = depth self.pixels = pixels self.fmt = ("%d " * num_cols + "\n") * num_rows def show(self): fn = "/tmp/foo.pgm" file = open(fn,"wb") print file file.write(self.pgmdata()) file.close() os.system("ee " + fn) def pgmdata(self): return pgmhdr(num_rows,num_cols,256) + self.fmt % tuple(self.pixels) if __name__ == "__main__": num_rows=256 num_cols=256 pixels = range(num_rows)*num_cols PgmImage(num_rows,num_cols,256,pixels).show() __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From kyeser at earthlink.net Sat Jul 10 02:13:24 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Sat Jul 10 02:13:29 2004 Subject: [Tutor] raw_input Message-ID: Is there a way to make 'raw_input' accept multiple arguments? For example, I wrote this short program which converts temperature to C or F, but I have to enter the temperature and the conversion on two separate lines: % python conv.py Enter temperature: 30 Is this in C or F?: C 86.00 F I did this by doing: temp = raw_input("Enter temerature: ") conv = raw_input("Is this in C or F?: ") How would I be able to enter these two arguments in one line? Like: % python conv.py Enter temperature: 30 C 86.00 F Thanks for your help! From rdm at rcblue.com Sat Jul 10 02:36:13 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 10 02:36:19 2004 Subject: [Tutor] How to enable pausing my stop_watch.py ? In-Reply-To: <035401c465fa$68396dc0$6401a8c0@xp> References: <6.1.2.0.2.20040706025053.02376ec0@rcblue.com> <026901c46455$48b51040$6401a8c0@xp> <6.1.2.0.2.20040709132113.02fe7ec0@rcblue.com> <035401c465fa$68396dc0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040709173219.03015ec0@rcblue.com> Alan Gauld wrote at 14:19 7/9/2004: > > > h_seconds = (hours and 3600*int(hours)) or 0 # shorter but more > > >obscure > > > > > >Works like this: > > >Only evaluate 3600*hours if hours NOT "" > > >If result is False(ie hours was "") then evaluate > > >second part of OR - ie 0 > > > > I'm very glad to know about these uses of "and" and "or", but why is >your > > way better? Is fewer lines better? Is it faster? More Pythonesque? >(I'm > > not defending my code; I'd just like to know.) > >It's not better, just an alternative way of doing it. Indeed as the >comment says its more obscure and so could be regarded as worse! >However it is also very slightly faster. > >If you are a C (or Perl or Java/Javascript) you might be familiar >with the tertiary ?: operator, if so the and/or pair will present >a familiar shortcut and for those programmers the obscurity is >not a problem. I prefer it simply because it is shorter and doesn't >clutter up my main program with if/elses that are tangential to >the main purpose of the program. But tastes differ and I would never >claim the and/or option was better. > >Indeed part of the zen of Python is that explicit is better than >implicit... Yes, I vaguely remember the ?: operator from learning some C years ago. Thanks very much. I'm glad explicit is better than implicit, ATBE or almost.. Dick Moores From mcbrides9 at comcast.net Fri Jul 9 21:52:33 2004 From: mcbrides9 at comcast.net (Jerry McBride) Date: Sat Jul 10 02:50:40 2004 Subject: [Tutor] Exception attributes? Message-ID: <1l93s1xvog.ln2@spinner.my.domain> I'm a new Python hacker and I could use a little help. I'm in the process of figuring out try: clauses and I've run into a hitch. It seems that each exception has different attributes. How can I discover what attributes are? TIA, Jerry -- ****************************************************************************** Registered Linux User Number 185956 FSF Associate Member number 2340 since 05/20/2004 Join me in chat at #linux-users on irc.freenode.net Buy an Xbox for $149.00, run linux on it and Microsoft loses $150.00! 3:44pm up 80 days, 18:26, 7 users, load average: 0.25, 0.17, 0.10 From bill.mill at gmail.com Sat Jul 10 03:33:12 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sat Jul 10 03:33:34 2004 Subject: [Tutor] raw_input In-Reply-To: References: Message-ID: <797fe3d4040709183327745f57@mail.gmail.com> On Fri, 9 Jul 2004 20:13:24 -0400, Hee-Seng Kye wrote: > > I did this by doing: > temp = raw_input("Enter temerature: ") > conv = raw_input("Is this in C or F?: ") > > How would I be able to enter these two arguments in one line? Like: > You could try: temp, conv = raw_input("Enter temperature: ").split() if you really wanted it on one line, but keep in mind that this is not going to be very tolerant of errors at all. Peace Bill Mill bill.mill@@gmail...com From kyeser at earthlink.net Sat Jul 10 03:42:01 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Sat Jul 10 03:42:07 2004 Subject: [Tutor] raw_input In-Reply-To: <797fe3d4040709183327745f57@mail.gmail.com> References: <797fe3d4040709183327745f57@mail.gmail.com> Message-ID: <56F6011C-D212-11D8-8088-000393479EE8@earthlink.net> Thanks a lot. You made my day! Best, Kye On Jul 9, 2004, at 9:33 PM, Bill Mill wrote: > On Fri, 9 Jul 2004 20:13:24 -0400, Hee-Seng Kye > wrote: >> >> I did this by doing: >> temp = raw_input("Enter temerature: ") >> conv = raw_input("Is this in C or F?: ") >> >> How would I be able to enter these two arguments in one line? Like: >> > > You could try: > > temp, conv = raw_input("Enter temperature: ").split() > > if you really wanted it on one line, but keep in mind that this is not > going to be very tolerant of errors at all. > > Peace > Bill Mill > bill.mill@@gmail...com > From david at graniteweb.com Sat Jul 10 06:45:28 2004 From: david at graniteweb.com (David Rock) Date: Sat Jul 10 06:45:31 2004 Subject: [Tutor] Exception attributes? In-Reply-To: <1l93s1xvog.ln2@spinner.my.domain> References: <1l93s1xvog.ln2@spinner.my.domain> Message-ID: <20040710044528.GA18422@wdfs.attbi.com> * Jerry McBride [2004-07-09 19:52]: > > I'm a new Python hacker and I could use a little help. > > > I'm in the process of figuring out try: clauses and I've run into a hitch. > > It seems that each exception has different attributes. How can I discover > what attributes are? sys.exc_info() will give you information about the exception that was just raised. -- 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/20040709/046ad66a/attachment.pgp From magnus at thinkware.se Sat Jul 10 10:35:50 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Jul 10 10:51:29 2004 Subject: [Tutor] Exception attributes? In-Reply-To: <1l93s1xvog.ln2@spinner.my.domain> Message-ID: <5.2.1.1.0.20040710095605.027d8ff8@www.thinkware.se> At 19:52 2004-07-09 +0000, Jerry McBride wrote: >It seems that each exception has different attributes. How can I discover >what attributes are? In practice you will typically only catch particular exceptions that you expect to occur in that situation. If you don't know what kind of exception it is, you can't be expected to be able to handle it properly. E.g. try: x = a / b except ZeroDivisionError: x = None or try: char = aString[pos] except IndexError: char = '' There are certainly situations where you might want to do something like... except (KeyError, NameError, IndexError), e: ...but you very rarely catch exceptions in production code without knowing what class (or set of classes) they are, and thus what attributes you are interested in. I imagine that you might want to catch unexpected exceptions on a high level in the application so that you can give some generic error message about program error or an unexpected condition, log the error and shut down the application in an ordered way. You can probably have a look at the cgitb module to see how that could be handled. Showing a decorated traceback in a log similar to the way cgitb does it is probably much better than to show whatever attributes the excption object might have. I think a plain, simple traceback is better than exception object attributes in a log. Besides, you can always show the attributes in any instance object o through o.__dict__. You can print the traceback from the last exception through import traceback; traceback.print_last() -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From bvande at po-box.mcgill.ca Sat Jul 10 11:18:43 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 10 11:20:09 2004 Subject: [Tutor] Re: help with setting Python Path under WinMe Message-ID: <40EFB473.2020903@po-box.mcgill.ca> Hi all, RECENTLY I posted a question about configuring Python's search path. (I don't get my own so can't preserve the thread, but its here What I was trying to do was use the PYTHONPATH environment variable in either the Windows Registry settings (no luck at all) or autoexec.bat (partial success) to add some directories to the end of Python's search path (the result of sys.path). The autoexec.bat way left my added directories ahead of the standard library dirs; this is what I wanted to change. I've mostly answered my own question, so am posting for future googlers. Well, according to section 4.1 Modifying Python's Search Path of Installing Python Modules this cannot work. PYTHONPATH additions to the search path are added "to the beginning" of sys.path. However, of .pth files, documented in this same section, allows you to add directories after the standard library directory. On my system, with a bit of tinkering, it still puts them before C:\PYTHON23\lib\site-packages. But this is a big improvement. (The tinkering was needed to get my .pth file named and located such that it was read after the .pth files that various 3rd party packages had placed on my system.) The only remaining oddity is that the docs seem to imply that the .pth files can be located anywhere on sys.path. But I tried to add a directory D:\PyPath using the autoexec.bat method for the sole purpose of holding a .pth file (this way, I wouldn't have to remember to do anything when updating to future version of Python). But my .pth file was ignored unless I put it somewhere that was on the sys.path independently of my PYTHONPATH setting. Odd, but no biggie. Best to all, Brian vdB From ps_python at yahoo.com Sat Jul 10 13:07:50 2004 From: ps_python at yahoo.com (kumar s) Date: Sat Jul 10 13:07:55 2004 Subject: [Tutor] striping whitespace from files Message-ID: <20040710110750.25956.qmail@web90006.mail.scd.yahoo.com> Hi all , I am learning programming using python. I have a question about striping white spaces from a file. my logic is that each element of the list [i] iterates and the whitespace it encounters is stripped by strip function. I do not know where I am going wrong. Is my logic incorrect or it is the way that my syntax is wrong. Can any one please help. Thank you. SP >>> f1 = open("citrate.txt",'r') >>> f2 = f1.read() >>> from string import strip, split >>> f2 = f1.readlines() >>> list = split(f2,'\n') >>> for i in fstrings: f1strings = string.split([i]) print f1strings Traceback (most recent call last): File "", line 2, in -toplevel- f1strings = string.split([i]) File "C:\Python23\lib\string.py", line 121, in split return s.split(sep, maxsplit) AttributeError: 'list' object has no attribute 'split' >>> __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From missive at hotmail.com Sat Jul 10 17:00:39 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Jul 10 17:00:42 2004 Subject: [Tutor] Re: striping whitespace from files Message-ID: >question about striping white spaces from a file. my >logic is that each element of the list [i] iterates >and the whitespace it encounters is stripped by strip >function. >I do not know where I am going wrong. Is my logic >incorrect or it is the way that my syntax is wrong. >Can any one please help. >>>f1 = open("citrate.txt",'r') >>>f2 = f1.read() >>>from string import strip, split >>>f2 = f1.readlines() >>>list = split(f2,'\n') >>>for i in fstrings: f1strings = string.split([i]) print f1strings Use the interactivity of the interpreter to your advantage: >>>f1 = open('afile.txt') >>>f2 = f1.read() >>>f2 '12345\n22345\n32345\n' >>>lines = f2.split('\n') >>>lines ['12345', '22345', '32345', ''] >>>f2 = f1.readlines() >>>f2 [] >>>f1.close() >>>f1 = open('afile.txt') >>>f2 = f1.readlines() >>>f2 ['12345\n', '22345\n', '32345\n'] >>>f1.close() >>>for line in open('afile.txt'): ... line ... '12345\n' '22345\n' '32345\n' >>>f1.close() >>>for line in open('afile.txt'): ... stripped = line.strip() ... stripped ... '12345' '22345' '32345' _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From aztech1200 at yahoo.com Sat Jul 10 18:18:43 2004 From: aztech1200 at yahoo.com (Aztech Guy) Date: Sat Jul 10 18:18:47 2004 Subject: [Tutor] xtopdf: an open source Python project to convert other file formats to PDF Message-ID: <20040710161843.82421.qmail@web53307.mail.yahoo.com> Hi list, I recently started an open source Python project with the goal of providing ways to convert other file formats to PDF (Portable Document Format). The URL of the project is: http://sourceforge.net/projects/xtopdf The xtopdf software has two prerequisites: 1. Python (version 2.2 or later) 2. The open source version of the ReportLab toolkit (version 1.16 or higher). Both are fairly small downloads. Of course, most people reading this list would already have installed Python :-) Currently xtopdf can convert .DBF files and text files to PDF. It's not limited to only converting standalone text or DBF files. Because I've provided a mini-API for reading text, reading DBF metadata and data records, and writing them to PDF using ReportLab, you can use these API's (methods of classes) as is, or modify them, to do more complicated things with it. I've given a few examples of such stuff - one shows how to create PDF books in a simple format using the classes in xtopdf. Posting the news to this list (Tutor) list because its a list for people wanting to learn about Python. I thought the code - which is a complete, working program - in fact several programs - could be of interest to Python beginners who would like to look at the source code of some complete working applications. Also would welcome any comments on the software, either questions about why something was done in a certain way, or comments about improvement, or suggestions on adding new features. The code is quite straightforward. It doesn't make much use of advanced features. File handling, dicts and lists are three language features used, apart from the ReportLab toolkit's APIs. I've used ReportLab a little for this project and also in general and I can recommend it as worth checking out if you have a need (or interest) in generating PDF from Python programs. It's also written in Python. HTH Aztech. "Winter brings penguins" __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kyeser at earthlink.net Sat Jul 10 18:37:21 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Sat Jul 10 18:37:26 2004 Subject: [Tutor] Adding a search path PERMANENTLY? Message-ID: <6AB1D68A-D28F-11D8-8682-000393479EE8@earthlink.net> Could anyone tell me how to set a Python search path PERMANENTLY? If I do: >>> import sys >>> sys.path.append('/users/kyeser/python/module') It's only valid while the interpreter is active and goes away when I restart the interpreter. Every manual I've read said something about setting PYTHONPATH, but I'm not sure how. I'm also curious how to set PYTHONSTARTUP. I've tried creating '.pythonrc.py' at my home directory, but it didn't do anything. If I wanted to do something like: >>> import sys >>> sys.ps1 = '--> ' How would I make this permanent? Many thanks, Kye From bvande at po-box.mcgill.ca Sat Jul 10 20:36:13 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 10 20:36:47 2004 Subject: [Tutor] Adding a search path PERMANENTLY? In-Reply-To: <6AB1D68A-D28F-11D8-8682-000393479EE8@earthlink.net> References: <6AB1D68A-D28F-11D8-8682-000393479EE8@earthlink.net> Message-ID: <40F0371D.5040108@po-box.mcgill.ca> Hee-Seng Kye said unto the world upon 10/07/2004 12:37: > Could anyone tell me how to set a Python search path PERMANENTLY? If I do: > > >>> import sys > >>> sys.path.append('/users/kyeser/python/module') > > It's only valid while the interpreter is active and goes away when I > restart the interpreter. Every manual I've read said something about > setting PYTHONPATH, but I'm not sure how. > > I'm also curious how to set PYTHONSTARTUP. I've tried creating > '.pythonrc.py' at my home directory, but it didn't do anything. If I > wanted to do something like: > > >>> import sys > >>> sys.ps1 = '--> ' > > How would I make this permanent? > > Many thanks, > > Kye > Hi Kye, I've just been posting about this the last few days. Here's what I (think I) know: 1) Setting the PYTHONPATH environment variable will put the specified dirs ahead of the standard lib dirs in sys.path. On Windows, you can set this with autoexec.bat or, with more recent version, through the Control Panel->System->Environment Variables. Your msg headers say your a Mac person; I've no idea for Macs. You might try , though. 2) Using .pth files will put your new dirs towards the end of sys.path. .pth files are plain text files, one dir per line. Put them somewhere in the unmodified sys.path. (The docs imply anywhere is sys.path, but I had no luck with placing them in dirs added to sys.path via PYTHONPATH.) 3) PYTHONSTARTUP has effect only for interactive prompt sessions. For more, see . I may also have had some details in my recent (last 2-3 days) Tutor posts that I've here omitted. HTH, Brian vdB From alan.gauld at blueyonder.co.uk Sat Jul 10 20:47:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 10 20:49:29 2004 Subject: [Tutor] Exception attributes? References: <1l93s1xvog.ln2@spinner.my.domain> Message-ID: <03a601c466ae$602d2310$6401a8c0@xp> > I'm in the process of figuring out try: clauses and I've run into a hitch. > > It seems that each exception has different attributes. How can I discover > what attributes are? I assume you mean the different exception types? You can have attributes of exceptions too but I don't see those used all that often. For the error type I use the >>> prompt and simply force an error then see what kind of exception the error message gives. eg: >>> 7/0 -> ZeroDivisionError: integer division or modulo by zero So I use except ZeroDivisionError >>> "fred" + 42 -> TypeError: cannot concatenate 'str' and 'int' objects So I use except TypeError: The >>> prompt is your friend. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kyeser at earthlink.net Sat Jul 10 20:58:47 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Sat Jul 10 20:58:52 2004 Subject: [Tutor] Adding a search path PERMANENTLY? In-Reply-To: <40F0371D.5040108@po-box.mcgill.ca> References: <6AB1D68A-D28F-11D8-8682-000393479EE8@earthlink.net> <40F0371D.5040108@po-box.mcgill.ca> Message-ID: <2C7B795A-D2A3-11D8-AE88-000393479EE8@earthlink.net> Hi, Brian. Thanks for your response. Yes, I'm on Mac, but I mainly work on UNIX shell (tcsh). Someone else (a.k.a orbitz) replied and directed me to the source, so the problem is solved. I do have a question for you though. You specifically mention that 'setting the PYTHONPATH will put the specified dirs ahead of the standard lib dirs in sys.path,' and that's exactly what I experienced. Is new path supposed be placed where it is placed? Does it have any meaning other than the fact that it will be searched before the standard lib paths? You seem to be very specific about it, so I'm just wondering. Thanks a lot for your response. Best, Kye p.s. For those who might be asking the same question in the future, this is how it's done on tcsh. Put the following line in .tcshrc (or .cshrc if you are on csh, I think...): setenv PYTHONPATH "your desired path here" It was confusing to me at first due to the absence of the '=' sign. The above syntax should work. On Jul 10, 2004, at 2:36 PM, Brian van den Broek wrote: > Hee-Seng Kye said unto the world upon 10/07/2004 12:37: >> Could anyone tell me how to set a Python search path PERMANENTLY? If >> I do: >> >>> import sys >> >>> sys.path.append('/users/kyeser/python/module') >> It's only valid while the interpreter is active and goes away when I >> restart the interpreter. Every manual I've read said something about >> setting PYTHONPATH, but I'm not sure how. >> I'm also curious how to set PYTHONSTARTUP. I've tried creating >> '.pythonrc.py' at my home directory, but it didn't do anything. If I >> wanted to do something like: >> >>> import sys >> >>> sys.ps1 = '--> ' >> How would I make this permanent? >> Many thanks, >> Kye > > Hi Kye, > > I've just been posting about this the last few days. Here's what I > (think I) know: > > 1) Setting the PYTHONPATH environment variable will put the specified > dirs ahead of the standard lib dirs in sys.path. On Windows, you can > set this with autoexec.bat or, with more recent version, through the > Control Panel->System->Environment Variables. Your msg headers say > your a Mac person; I've no idea for Macs. You might try > , though. > > 2) Using .pth files will put your new dirs towards the end of > sys.path. .pth files are plain text files, one dir per line. Put them > somewhere in the unmodified sys.path. (The docs imply anywhere is > sys.path, but I had no luck with placing them in dirs added to > sys.path via PYTHONPATH.) > > 3) PYTHONSTARTUP has effect only for interactive prompt sessions. > > For more, see . I may > also have had some details in my recent (last 2-3 days) Tutor posts > that I've here omitted. > > HTH, > > Brian vdB > From orbitz at ezabel.com Sat Jul 10 22:04:21 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Jul 10 22:05:12 2004 Subject: [Tutor] Adding a search path PERMANENTLY? In-Reply-To: <2C7B795A-D2A3-11D8-AE88-000393479EE8@earthlink.net> References: <6AB1D68A-D28F-11D8-8682-000393479EE8@earthlink.net> <40F0371D.5040108@po-box.mcgill.ca> <2C7B795A-D2A3-11D8-AE88-000393479EE8@earthlink.net> Message-ID: <40F04BC5.9000507@ezabel.com> It is meaningful in that if you have a module named..say..urllib in your PYTHONPATH, and you do import urllib in a program you will get the one in yoru PYTHONPATH *not* the standard one. Hee-Seng Kye wrote: > Hi, Brian. Thanks for your response. Yes, I'm on Mac, but I mainly > work on UNIX shell (tcsh). Someone else (a.k.a orbitz) replied and > directed me to the source, so the problem is solved. > > I do have a question for you though. You specifically mention that > 'setting the PYTHONPATH will put the specified dirs ahead of the > standard lib dirs in sys.path,' and that's exactly what I > experienced. Is new path supposed be placed where it is placed? Does > it have any meaning other than the fact that it will be searched > before the standard lib paths? You seem to be very specific about it, > so I'm just wondering. > > Thanks a lot for your response. > > Best, > > Kye > > p.s. For those who might be asking the same question in the future, > this is how it's done on tcsh. Put the following line in .tcshrc (or > .cshrc if you are on csh, I think...): > > setenv PYTHONPATH "your desired path here" > > It was confusing to me at first due to the absence of the '=' sign. > The above syntax should work. > > > On Jul 10, 2004, at 2:36 PM, Brian van den Broek wrote: > >> Hee-Seng Kye said unto the world upon 10/07/2004 12:37: >> >>> Could anyone tell me how to set a Python search path PERMANENTLY? >>> If I do: >>> >>> import sys >>> >>> sys.path.append('/users/kyeser/python/module') >>> It's only valid while the interpreter is active and goes away when I >>> restart the interpreter. Every manual I've read said something >>> about setting PYTHONPATH, but I'm not sure how. >>> I'm also curious how to set PYTHONSTARTUP. I've tried creating >>> '.pythonrc.py' at my home directory, but it didn't do anything. If >>> I wanted to do something like: >>> >>> import sys >>> >>> sys.ps1 = '--> ' >>> How would I make this permanent? >>> Many thanks, >>> Kye >> >> >> Hi Kye, >> >> I've just been posting about this the last few days. Here's what I >> (think I) know: >> >> 1) Setting the PYTHONPATH environment variable will put the specified >> dirs ahead of the standard lib dirs in sys.path. On Windows, you can >> set this with autoexec.bat or, with more recent version, through the >> Control Panel->System->Environment Variables. Your msg headers say >> your a Mac person; I've no idea for Macs. You might try >> , though. >> >> 2) Using .pth files will put your new dirs towards the end of >> sys.path. .pth files are plain text files, one dir per line. Put them >> somewhere in the unmodified sys.path. (The docs imply anywhere is >> sys.path, but I had no luck with placing them in dirs added to >> sys.path via PYTHONPATH.) >> >> 3) PYTHONSTARTUP has effect only for interactive prompt sessions. >> >> For more, see . I may >> also have had some details in my recent (last 2-3 days) Tutor posts >> that I've here omitted. >> >> HTH, >> >> Brian vdB >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From gustabares at verizon.net Sat Jul 10 23:36:12 2004 From: gustabares at verizon.net (Gus Tabares) Date: Sat Jul 10 23:36:25 2004 Subject: [Tutor] Adding a search path PERMANENTLY? In-Reply-To: <2C7B795A-D2A3-11D8-AE88-000393479EE8@earthlink.net> Message-ID: <000901c466c5$ef9534e0$0200a8c0@blackbetty> -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Hee-Seng Kye Sent: Saturday, July 10, 2004 2:59 PM To: Brian van den Broek Cc: tutor@python.org Subject: Re: [Tutor] Adding a search path PERMANENTLY? >p.s. For those who might be asking the same question in the future, >this is how it's done on tcsh. Put the following line in .tcshrc (or >.cshrc if you are on csh, I think...): >setenv PYTHONPATH "your desired path here" I'm pretty sure that if you want this to be global to all users, you would add the above line to /etc/csh.login Gus From bvande at po-box.mcgill.ca Sat Jul 10 22:10:48 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 10 23:47:20 2004 Subject: [Tutor] Adding a search path PERMANENTLY? In-Reply-To: <2C7B795A-D2A3-11D8-AE88-000393479EE8@earthlink.net> References: <6AB1D68A-D28F-11D8-8682-000393479EE8@earthlink.net> <40F0371D.5040108@po-box.mcgill.ca> <2C7B795A-D2A3-11D8-AE88-000393479EE8@earthlink.net> Message-ID: <40F04D48.7070706@po-box.mcgill.ca> Hee-Seng Kye said unto the world upon 10/07/2004 14:58: > Hi, Brian. Thanks for your response. Yes, I'm on Mac, but I mainly > work on UNIX shell (tcsh). Someone else (a.k.a orbitz) replied and > directed me to the source, so the problem is solved. > > I do have a question for you though. You specifically mention that > 'setting the PYTHONPATH will put the specified dirs ahead of the > standard lib dirs in sys.path,' and that's exactly what I experienced. > Is new path supposed be placed where it is placed? Does it have any > meaning other than the fact that it will be searched before the standard > lib paths? You seem to be very specific about it, so I'm just wondering. > > Thanks a lot for your response. > > Best, > > Kye > > p.s. For those who might be asking the same question in the future, this > is how it's done on tcsh. Put the following line in .tcshrc (or .cshrc > if you are on csh, I think...): > > setenv PYTHONPATH "your desired path here" > > It was confusing to me at first due to the absence of the '=' sign. The > above syntax should work. > > Hi Kye, my understanding is that PYTHONPATH places the new dirs in sys.path before the standard lib dirs and .pth files after. (This is from the docs.) This mattered to me as I had wanted after to prevent accidentally over-riding standard lib, etc modules if I were to inadvertently give one of my modules the same name as an existing module. So, use PYTHONPATH if you want to allow the possibility of over-riding standard modules (or if you are not worried about doing so by accident) and use .pth files if you want to guard against naming conflicts. Since .pth additions come after you can use the same names as standard lib modules without breaking anything. Of course your same named modules won't get imported because the standard lib ones will be found first. But this seems the sort of thing you'd realize at the time; the other way round, I worried that weeks or months later I could be bit by a naming conflict and have a hard time figuring it out at the time. I'm not sure that that answers your question. But it seems to me that the two options so differ precisely so as to allow for this sort of choice in behaviour. (Note though that I am merely reading the docs and drawing what are, I hope, reasonable inferences; I am no Python-guru ;-) You mentioned being directed to the sources. That didn't come through the list. Was it site.py or somewhere else? Best to all, Brian vdB From alan.gauld at blueyonder.co.uk Sun Jul 11 00:46:59 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 11 00:48:47 2004 Subject: [Tutor] striping whitespace from files References: <20040710110750.25956.qmail@web90006.mail.scd.yahoo.com> Message-ID: <03c301c466cf$cfad48c0$6401a8c0@xp> > >>> f1 = open("citrate.txt",'r') > >>> f2 = f1.read() This reads the entire file into f2 > >>> from string import strip, split > >>> f2 = f1.readlines() This reads an empty line since you are already at the end of the file. It overwrites all the data you previously read! YOu probably want to go straight to the split/strip operation now... A list comprehension might be a useful construct to think about... > >>> list = split(f2,'\n') Using a builtin name(list is the conversion to list function) is a bad idea. Also you could use the more modern version: lines = f2.split('\n') But since the line is empty it will still have no effect. > >>> for i in fstrings: > f1strings = string.split([i]) This tries to split a list containing i, I'm not sure what you even expect here. I'm even less sure what will actually be happening! > print f1strings > > > > Traceback (most recent call last): > File "", line 2, in -toplevel- > f1strings = string.split([i]) > File "C:\Python23\lib\string.py", line 121, in split > return s.split(sep, maxsplit) > AttributeError: 'list' object has no attribute 'split' > >>> The error being because of the list construct... HTH, Alan G. From alan.gauld at blueyonder.co.uk Sun Jul 11 00:53:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 11 00:55:10 2004 Subject: [Tutor] Adding a search path PERMANENTLY? References: <000901c466c5$ef9534e0$0200a8c0@blackbetty> Message-ID: <03d201c466d0$b3dfb5f0$6401a8c0@xp> > >p.s. For those who might be asking the same question in the future, > >this is how it's done on tcsh. Put the following line in .tcshrc (or > >.cshrc if you are on csh, I think...): > > >setenv PYTHONPATH "your desired path here" > > > I'm pretty sure that if you want this to be global to all users, you > would add the above line to /etc/csh.login True, although only for csh/tcsh users, bash users wouldn't see it. But it's unlikely you'd want to make a user's own modules available to all. If a module is intended to be available to all it should be put in the site specific section of the standard libs not referenced through PYTHONPATH, which, like most environment variables, is best left user specific - that's where control of the *environment* should reside after all - with the users. Alan g. From kyeser at earthlink.net Sun Jul 11 00:58:07 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Sun Jul 11 00:58:12 2004 Subject: [Tutor] Adding a search path PERMANENTLY? In-Reply-To: <40F04D48.7070706@po-box.mcgill.ca> References: <6AB1D68A-D28F-11D8-8682-000393479EE8@earthlink.net> <40F0371D.5040108@po-box.mcgill.ca> <2C7B795A-D2A3-11D8-AE88-000393479EE8@earthlink.net> <40F04D48.7070706@po-box.mcgill.ca> Message-ID: <9BC45D28-D2C4-11D8-97C8-000393479EE8@earthlink.net> Thanks again for detailed information, Brian. The source I was referring to is about how to setup environment variables in UNIX shell (specifically tcsh as I recall) and isn't about Python. I left the link out for that reason, but I figure it would be helpful for others as well, so here it is ('orbitz' directed me to this site): http://farside.ph.utexas.edu/teaching/329/lectures/node29.html Thanks for all your help! On Jul 10, 2004, at 4:10 PM, Brian van den Broek wrote: > Hee-Seng Kye said unto the world upon 10/07/2004 14:58: > >> Hi, Brian. Thanks for your response. Yes, I'm on Mac, but I mainly >> work on UNIX shell (tcsh). Someone else (a.k.a orbitz) replied and >> directed me to the source, so the problem is solved. >> I do have a question for you though. You specifically mention that >> 'setting the PYTHONPATH will put the specified dirs ahead of the >> standard lib dirs in sys.path,' and that's exactly what I >> experienced. Is new path supposed be placed where it is placed? >> Does it have any meaning other than the fact that it will be searched >> before the standard lib paths? You seem to be very specific about >> it, so I'm just wondering. >> Thanks a lot for your response. >> Best, >> Kye >> p.s. For those who might be asking the same question in the future, >> this is how it's done on tcsh. Put the following line in .tcshrc (or >> .cshrc if you are on csh, I think...): >> setenv PYTHONPATH "your desired path here" >> It was confusing to me at first due to the absence of the '=' sign. >> The above syntax should work. > > > > Hi Kye, > > my understanding is that PYTHONPATH places the new dirs in sys.path > before the standard lib dirs and .pth files after. (This is from the > docs.) This mattered to me as I had wanted after to prevent > accidentally over-riding standard lib, etc modules if I were to > inadvertently give one of my modules the same name as an existing > module. > > So, use PYTHONPATH if you want to allow the possibility of over-riding > standard modules (or if you are not worried about doing so by > accident) and use .pth files if you want to guard against naming > conflicts. Since .pth additions come after you can use the same names > as standard lib modules without breaking anything. Of course your same > named modules won't get imported because the standard lib ones will be > found first. But this seems the sort of thing you'd realize at the > time; the other way round, I worried that weeks or months later I > could be bit by a naming conflict and have a hard time figuring it out > at the time. > > I'm not sure that that answers your question. But it seems to me that > the two options so differ precisely so as to allow for this sort of > choice in behaviour. (Note though that I am merely reading the docs > and drawing what are, I hope, reasonable inferences; I am no > Python-guru ;-) > > You mentioned being directed to the sources. That didn't come through > the list. Was it site.py or somewhere else? > > Best to all, > > Brian vdB > From david at graniteweb.com Sun Jul 11 05:57:51 2004 From: david at graniteweb.com (David Rock) Date: Sun Jul 11 05:57:54 2004 Subject: [Tutor] Re: striping whitespace from files In-Reply-To: References: Message-ID: <20040711035751.GA21684@wdfs.attbi.com> * Lee Harr [2004-07-10 19:30]: > > Use the interactivity of the interpreter to your advantage: Also, I was recently made aware of an enhanced interactive shell called ipython. I highly recommend looking into it. It has a LOT of nice features above the builtin interactive shell. http://ipython.scipy.org/ -- 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/20040710/adae82c3/attachment.pgp From rdm at rcblue.com Sun Jul 11 12:29:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 11 12:30:00 2004 Subject: [Tutor] Please critique my temperature_conversion.py Message-ID: <6.1.2.0.2.20040711031041.02741150@rcblue.com> """ # temperature_conversion.py # temperature conversion of Fahrenheit <---> Celsius from string import upper F_or_C = "" while (F_or_C != "F" and F_or_C != "C"): t0 = raw_input("Enter temperature as 70F or 70 F or -12.47C: ") F_or_C = upper(t0[-1]) # store the F or C and ensure upper case t0 = t0[0:-1] # strip entered temp of the F or C t = t0 # get a string number to do the conversion calculation if F_or_C == "F": t = 5/9. * (float(t) - 32) t = round(t,2) print (t0 + "F"), "is", (str(t) + "C") else: # i.e., F_or_C is "C" t = 9/5. * float(t) + 32 t = round(t,2) print (t0 + "C"), "is", (str(t) + "F") """ Thanks, tutors. Dick Moores From bill.mill at gmail.com Mon Jul 12 01:40:25 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Jul 12 01:40:35 2004 Subject: [Tutor] Please critique my temperature_conversion.py In-Reply-To: <6.1.2.0.2.20040711031041.02741150@rcblue.com> References: <6.1.2.0.2.20040711031041.02741150@rcblue.com> Message-ID: <797fe3d404071116407655eef4@mail.gmail.com> On Sun, 11 Jul 2004 03:29:05 -0700, Dick Moores wrote: > """ > # temperature_conversion.py > # temperature conversion of Fahrenheit <---> Celsius > > from string import upper > F_or_C = "" > > while (F_or_C != "F" and F_or_C != "C"): > t0 = raw_input("Enter temperature as 70F or 70 F or -12.47C: ") > F_or_C = upper(t0[-1]) # store the F or C and ensure upper case > t0 = t0[0:-1] # strip entered temp of the F or C > t = t0 # get a string number to do the conversion calculation > > if F_or_C == "F": > t = 5/9. * (float(t) - 32) > t = round(t,2) > print (t0 + "F"), "is", (str(t) + "C") > else: # i.e., F_or_C is "C" > t = 9/5. * float(t) + 32 > t = round(t,2) > print (t0 + "C"), "is", (str(t) + "F") > """ > > Thanks, tutors. > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > thoughts: your variable names besides F_or_C are not very descriptive. Also, I would use forc or f_or_c instead of F_or_C; generally only class or function names should start with capital letters. I would combine the last two lines of the first loop to be one line as such: t = float(t0[:-1]) note that if you leave a number out of a string slicing operation, it is assumed to be zero. I prefer using C-style print statements, so your first print statement would look like: print "%s F is %d C" % (t, t0) I feel that this is cleaner and easier to read. your comment after the else statement is nothing but distracting; it's unnecessary and obvious. Delete it. Peace Bill Mill From kumanna at myrealbox.com Mon Jul 12 08:13:52 2004 From: kumanna at myrealbox.com (Adayapalam Appaiah Kumaraswamy) Date: Mon Jul 12 08:05:33 2004 Subject: [Tutor] [ann] CGI Link Checker 0.1 Message-ID: <40F22C20.1060300@myrealbox.com> Dear Python users, I am new to Python. As I learnt a bit more on coding in Python, I decided to try out a simple project: to write a CGI script in Python to check links on a single HTML page on the web. Although I am just a hobby programmer, I thought I could show it to others and ask for their comments and suggestions. It is my first CGI script as well as my first Python application. I looked about around the net, but found only a few link-checking details related to Python. So, I thought I could write a no-frills one myself. BTW the W3C Link Checker is written in Perl. I don't know Perl, so I couldn't look at it for ideas. I am working on a slow dial-up connection. I had to face the following problems: 1.Delayed responses for large pages: I worked around this by flushing sys.stdout after every three links checked; that might lead to inefficiency, but it does throw the results three at a time to the impatient user. Otherwise, the Python interpreter would wait until the output buffer is filled till dumping it to the web server's output. 2.Slow: I don't know how to make the script perform better. I've tried to look into the code to make it run faster, but I couldn't do so. Also, I think the hosting server's bandwidth may contribute to this. Still, it takes only about 5 to 10 seconds more than the W3C validator for very large pages, and 2 to 3 seconds more for smaller ones. Your results may vary, I'd love to know. 3.HTML parsing: I have made no attempt to (and I do not propose to) check pages with incorrect HTML/XHTML. This means that if the Python HTMLParser fails, my script exits gracefully. An example of invalid HTML is www.yahoo.com. Finally, since this is my first Python program, I might not have properly adapted to the style of programming experienced Python users may be accustomed to. So, I request you to please correct me in this regard as well. In all, it was an good experience, and gave me more than a glimpse of the power offered by Python. Please read the instructions on the page before entering your URL to test the script. You can spawn the script from: http://kumar.travisbsd.org/pyprogs/example.html Personally, I have tried the following sites with this script: http://www.w3.org/ - Works 100% perfect. http://www.yahoo.com/ - Invalid HTML. Exits gracefully. Source code only (meaning without the fancy images and CSS I have used): http://kumar.travisbsd.org/pyprogs/cgilink.txt If you want to try hosting the script on your own server, get this and see the README (This includes all the images and fancy CSS): http://kumar.travisbsd.org/pyprogs/cgilink-0.1.tar.gz Thank you. Kumar -- Adayapalam Appaiah Kumaraswamy (Kumar Appaiah) Web: http://www.ee.iitm.ac.in/~ee03b091/ 1, Balaji Apartments, 32, Third Street, East Abhiramapuram, Mylapore, Chennai - 600004 India From project5 at redrival.net Mon Jul 12 08:42:10 2004 From: project5 at redrival.net (Andrei) Date: Mon Jul 12 08:42:23 2004 Subject: [Tutor] Re: Please critique my temperature_conversion.py References: <6.1.2.0.2.20040711031041.02741150@rcblue.com> Message-ID: Dick Moores rcblue.com> writes: > from string import upper Don't use the string module. Use string method instead, e.g. mystring.upper() instead of string.upper(mystring). > F_or_C = "" As said by the previous poster, this isn't a very great name. I'd prefer something like original_unit or from_unit. > while (F_or_C != "F" and F_or_C != "C"): > t0 = raw_input("Enter temperature as 70F or 70 F or -12.47C: ") I don't particulary like the name t0 neither. To me, this suggests "initial time". Why not just call it e.g. temperature or even temp (although that suggests something temporary). > F_or_C = upper(t0[-1]) # store the F or C and ensure upper case If the user hits a space after the unit, this code won't recognise it. I'd recommend stripping the input first. > t0 = t0[0:-1] # strip entered temp of the F or C > t = t0 # get a string number to do the conversion calculation Ah, but how do you know that it is a number? The user might have written "kjanvkanvdf". > if F_or_C == "F": > t = 5/9. * (float(t) - 32) And here the lack of input validation will bite you. If t is now "kjanvkanvd", the program will crash with a not particularly user-friendely error message. It's better to validate the input using try-except and make sure that by the time you end up in here, it's certainly a number. > t = round(t,2) > print (t0 + "F"), "is", (str(t) + "C") As already recommended, use format instrings instead. They're much clearer. You didn't ask for them, but here are two other suggestions for improvements anyway :) - allow more than one conversion: run a potentially endless loop allowing the user to convert a value and present her with a new prompt once the conversion is done (or failed because of invalid input), so a new one can be done. A bit like a very simple version of the Python interactive interpreter. - add command line support, so it's possible to start e.g. "converttemp.py 32F" and get the result in Celsius immediately, after which the program shuts itself down. Yours, Andrei From magnus at thinkware.se Mon Jul 12 12:12:47 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Jul 12 12:08:52 2004 Subject: [Tutor] Please critique my temperature_conversion.py In-Reply-To: <797fe3d404071116407655eef4@mail.gmail.com> References: <6.1.2.0.2.20040711031041.02741150@rcblue.com> <6.1.2.0.2.20040711031041.02741150@rcblue.com> Message-ID: <5.2.1.1.0.20040712115622.028c2ac8@www.thinkware.se> At 19:40 2004-07-11 -0400, Bill Mill wrote: >note that if you leave a number out of a string slicing operation, it >is assumed to be zero. Not quite. A left out value is equvalent with None. See below: >>> l = list("abcdefgh") >>> l ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] >>> l[:2] ['a', 'b'] >>> l[0:2] ['a', 'b'] >>> l[None:2] So far it's all the same...but not for the other places in the slice. ['a', 'b'] >>> l[2:] ['c', 'd', 'e', 'f', 'g', 'h'] >>> l[2:0] [] >>> l[2:None] ['c', 'd', 'e', 'f', 'g', 'h'] >>> l[:2:] ['a', 'b'] >>> l[:2:0] Traceback (most recent call last): File "", line 1, in -toplevel- l[:2:0] ValueError: slice step cannot be zero >>> l[:2:None] ['a', 'b'] As you see, 0 and None differ for the second and third number in the slice. The third digit in the slice is for stepping: >>> l[2:None:2] ['c', 'e', 'g'] >>> l[2::2] ['c', 'e', 'g'] So, if you don't hardcode you slice values, but use something like "l[start:stop:step]" you need to use "None", not "0", for default values. You could use... import sys start,stop,step=0,sys.maxint,1 ...as default values instead of None, but I think None is simpler... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From alan.gauld at blueyonder.co.uk Mon Jul 12 12:53:12 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jul 12 12:54:34 2004 Subject: [Tutor] Please critique my temperature_conversion.py References: <6.1.2.0.2.20040711031041.02741150@rcblue.com> Message-ID: <03fc01c467fe$6d3795d0$6401a8c0@xp> Subject: [Tutor] Please critique my temperature_conversion.py Looks good! Only change I'd make is using string format operators: > if F_or_C == "F": > t = 5/9. * (float(t) - 32) > t = round(t,2) > print (t0 + "F"), "is", (str(t) + "C") print "%.2fF is %.2fC" % (t0,t) > else: # i.e., F_or_C is "C" > t = 9/5. * float(t) + 32 > t = round(t,2) > print (t0 + "C"), "is", (str(t) + "F") print "%.2fC is %.2fF" % (t0,t) In fact by making the unit part of the format string you could have a single print line which might be easier to maintain should you add more conversions later (Kelvin anyone?!)... It also removes the need for the rounding operation. if F_or_C == "F": unit = "C" else: unit = "F" print "%.2f%s is %.2f%s" % (t0, F_or_C, t, unit) HTH, Alan G. From rdm at rcblue.com Mon Jul 12 15:05:26 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Jul 12 15:06:19 2004 Subject: [Tutor] Please critique my temperature_conversion.py Message-ID: <6.1.2.0.2.20040712051355.02a30ec0@rcblue.com> Thanks, tutors, for all the criticism! I've been up all night (Pacific Time) trying to incorporate all of your advice into my script. Variable names, print formatting, exception catching, an outer while loop, eliminating the need for importing from string. Learned a lot. Exception handling is new to me, and I haven't succeeded here yet, as you can see. One problem is that if after one successful conversion, the user next enters something that creates an exception, this repeats the previous correct result and presents the prompt again. Presenting the prompt again is fine, but I don't want the previous result repeated. This doesn't happen if the user has yet to make a correct entry (such as 86F--getting "86F is 30C"). The exceptions I've tried to handle are: qwert, 2134qwer, asdf, zxc, (these 2 end in f or c), "", " ". And how to provide a smooth exit from the program? I experimented with the exception that Ctrl+C raises, but doing this seems to make my computer go crazy. Available RAM goes to almost zero (from a usual 250-300 megabytes), and I have to reboot. (I'm using Windows XP.) No command line execution yet. And Kelvin? Later! Dick Moores """ # temperature_conversion.py # temperature conversion: Fahrenheit <---> Celsius. User enters temperature # as a number followed by a unit of either F or C. The program uses the variable "number" # to hold this original number, and the variable "unit" to hold the original F or the C. print """ temperature_conversion.py This program will convert Fahrenheit to Celsius or Celsius to Fahrenheit. Enter a number followed by F or C, such as 70F, 70 f, -12.47C, etc. To exit program, press Ctrl+C """ while True: unit = "" # the Fahrenheit "F" or the Celsius "C" converted_unit = "" temperature = "" while (unit != "F" and unit != "C"): temperature = raw_input("Enter temperature (70F, 70 F, -12.47C, etc.): ") temperature = temperature.strip() try: unit = (temperature[-1]).upper() except: IndexError break try: number = float(temperature[0:-1]) # get just the number part of temperature except: ValueError break try: number_to_convert = number # and save the original number except: NameError break if unit == "F": try: converted_number = 5/9. * (float(number_to_convert) - 32) except: NameError break else: try: converted_number = 9/5. * float(number_to_convert) + 32 except: NameError break if unit == "F": converted_unit = "C" else: converted_unit = "F" print '%s %.2f%s is %.2f%s' % ((" " * 44), number, unit, converted_number, converted_unit) """ From Janssen at rz.uni-frankfurt.de Mon Jul 12 17:10:59 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Jul 12 17:11:01 2004 Subject: [Tutor] Please critique my temperature_conversion.py In-Reply-To: <6.1.2.0.2.20040712051355.02a30ec0@rcblue.com> References: <6.1.2.0.2.20040712051355.02a30ec0@rcblue.com> Message-ID: On Mon, 12 Jul 2004, Dick Moores wrote: > Exception handling is new to me, and I haven't succeeded here yet, as you > can see. > One problem is that if after one successful conversion, the user next > enters something that creates an exception, this repeats the previous > correct result and presents the prompt again. Presenting the prompt again > is fine, but I don't want the previous result repeated. so to say, you want the user stay within the second while-loop, when she enters something "exceptional". To archive this, you need to "continue" instead of "break": the break statements within your code breaks out of the second while-loop and go on with the main while-loop. A "continue" statement would stay within the loop but restart it from the beginn or rather start the next iteration of the loop. Replacing break with continue perhaps doesn't solve all your problems, introduced by upgrading your user-input-while-loop with exceptions ;-) First of all, make shure, you use an try-exception clause only when needed. In your case, only when checking the user input. Since the (very cool, by the way) while condition should be enough to check the temperature_unit, you will need *one* try-exception for checking the numberness of the user provided temperature. try: float(temperature) except ValueError: print "%s is not a number" % temperature continue will do this. (By this way, I've shown, where to put the Error-thingie :-) Few remarks: * float(temperature) needn't be assigned to a variable. You can in order to reuse it later (and do the float-conversion only once), but you don't need to. Nevertheless ValueError is raised, when temperature is an improper value for float. * You need to mentally keep track of which variables get assigned during the second while loop: say you need "unit" and "temperatue" for later processing, the second while-loop *must not* end unless *both* of these are defined. Otherwise it may happens what you've experienced with old values getting "recycled". Using "continue" instead of break is one key to make shure the while-loop doesn't stops before *something* is done. Additionally you have to figure out a way to process unit and temperature, that assures the while-loop is only ended when both (or how many you need) variables are "freshly" asigned. * Don't use except NameError clauses that much. A missing variable is often a sever programm-logic error and should not occur in the final programm. With other words: improve your second while-loop so that it will either "continue" or successfully assign (and test) all needed variables. The follwing code (where you actually do the conversions) can then assume that everything is there and needn't catch NameError's. * On Exceptions print a message, otherwise you might misunderstand what happens within and between your while-loops. And a innocent user might never figure out what to do to make it run. * Try to keep the code-lines short (<80chars). Helps reading & testing your code... > And how to provide a smooth exit from the program? I experimented with > the exception that Ctrl+C raises, but doing this seems to make my > computer go crazy. Available RAM goes to almost zero (from a usual > 250-300 megabytes), and I have to reboot. (I'm using Windows XP.) Mind sharing your code with us? Allways fun to wreak havoc ;-) import sys sys.exit() regards Michael From bill.mill at gmail.com Mon Jul 12 17:24:22 2004 From: bill.mill at gmail.com (Bill Mill) Date: Mon Jul 12 17:24:41 2004 Subject: [Tutor] Please critique my temperature_conversion.py In-Reply-To: <6.1.2.0.2.20040712051355.02a30ec0@rcblue.com> References: <6.1.2.0.2.20040712051355.02a30ec0@rcblue.com> Message-ID: <797fe3d4040712082477557b67@mail.gmail.com> On Mon, 12 Jul 2004 06:05:26 -0700, Dick Moores wrote: > Thanks, tutors, for all the criticism! I've been up all night (Pacific > Time) trying to incorporate all of your advice into my script. Variable > names, print formatting, exception catching, an outer while loop, > eliminating the need for importing from string. Learned a lot. > Dick, I rewrote your script with some of the changes we've suggested. Michael gives good advice on what to do. I tried to keep from inputting too much of my own style, and stick closely to your intentions. My only disagreement with Michael is that I think there should be two except clauses, because an IndexError occurs if the user enters a blank line. Do note that the two exceptions can be handled on one line, since their result is the same, but that I separated them for clarity. """ temperature_conversion.py temperature conversion: Fahrenheit <---> Celsius. User enters temperature as a number followed by a unit of either F or C. """ import sys print """ temperature_conversion.py This program will convert Fahrenheit to Celsius or Celsius to Fahrenheit. Enter a number followed by F or C, such as 70F, 70 f, -12.47C, etc. To exit the program, simply enter "exit" """ while True: unit = "" converted_unit = "" temperature = "" while (unit != "F" and unit != "C"): input_string = "Enter temperature (70F, 70 F, -12.47C, etc.): " temperature = raw_input(input_string).strip().upper() if temperature == "EXIT": sys.exit(0) try: unit = (temperature[-1]) temperature = float(temperature[:-1]) # get just the number part except IndexError: print "please enter a temperature in the format " except ValueError: print "please enter a temperature in the format " if unit == "F": new_temp = 5/9. * (temperature - 32) print '%44.2fF is %.2fC' % (temperature, new_temp) else: new_temp = 9/5. * temperature + 32 print '%44.2fC is %.2fF' % (temperature, new_temp) From project5 at redrival.net Mon Jul 12 17:34:22 2004 From: project5 at redrival.net (Andrei) Date: Mon Jul 12 17:34:30 2004 Subject: [Tutor] Re: Please critique my temperature_conversion.py References: <6.1.2.0.2.20040712051355.02a30ec0@rcblue.com> Message-ID: Dick Moores rcblue.com> writes: > Exception handling is new to me, and I haven't succeeded here yet, as you > can see. I think you've gone a bit overboard on the exception handling :). All you need to check is three things: 0. there is input 1. the temperature unit is known 2. the input is a number Raw outline, doesn't use your variable names since it's just for demonstration purposes (continue breaks the current iteration and starts again at the top of the loop): while True: temperature = raw_input('Temp:').strip() # make sure there is input at all try: temp_unit = temperature[-1].upper() temp_value = temperature[:-1].strip() except: # input is too short print "Wrong input! Specify a value followed by a unit." continue # make sure we know the unit if not (temp_unit in ['F', 'C']): print "Unknown unit (%s)." % temp_unit continue # make sure the value is a number try: temp_value = float(temp_value) except: print "The value you specified (%s) is not a number!" % temp_value continue print "OK" # Here comes the code which performs the conversion. You don't # have to do any more try-excepts here, because you're sure # that your input is valid. > And how to provide a smooth exit from the program? I experimented with > the exception that Ctrl+C raises, but doing this seems to make my Ctrl+Break should terminate it. Or you could build in an option to specify e.g. "X" to exit. You then check if the (stripped and uppercased) input is X and if that is the case, use break to terminate the loop (and therefore stop the program). I'd recommend checking for more than one exit command (e.g. 'quit', 'exit', 'stop', 'q' and 'x') so the user can press whatever seems logical to her and gets the desired result - the program terminates. > No command line execution yet. Hint: sys.argv. It's very handy for this type of programs. Yours, Andrei From Janssen at rz.uni-frankfurt.de Mon Jul 12 19:17:06 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Jul 12 19:17:11 2004 Subject: [Tutor] Please critique my temperature_conversion.py In-Reply-To: <797fe3d4040712082477557b67@mail.gmail.com> References: <6.1.2.0.2.20040712051355.02a30ec0@rcblue.com> <797fe3d4040712082477557b67@mail.gmail.com> Message-ID: On Mon, 12 Jul 2004, Bill Mill wrote: > Dick, I rewrote your script with some of the changes we've suggested. > Michael gives good advice on what to do. I tried to keep from > inputting too much of my own style, and stick closely to your > intentions. > My only disagreement with Michael is that I think there should be two > except clauses, because an IndexError occurs if the user enters a > blank line. Yes, beside my suggestion, to use only one try-except to verify input, you can/must use any exception necessary to do the programm ;-) OTOH I would prefer an if-test for input instead of catching an IndexError: where ValueError is the "natural" thing to expect when float'ing a non-number, IndexError isn't that straightforward for non-input. You can even have a ValueError for non-input when you first do the float-check. OTOOH it's completly okey to not test for empty string but rather run into some error and catch it. A more important remark: KeyboardInterrupt and EOFError should be catched: At least on Unix or Linux you can interrupt a raw_input prompt with ctrl-C (KeyboardInterrupt) or ctrl-D (EndOfFile). Since a python traceback might nervous some users especially because it takes some noticeable time to get printed out, you will hide it: try: temperature = raw_input("Enter temperature: ") except (KeyboardInterrupt, EOFError): # user nervously typing ctrl-C or ctrl-D sys.exit() (note the syntax for catching two error-classes at once) A last tip to beautify raw_input: Put import readline # beautifies raw_input somewhere at top of the script. raw_input will now make use of the readline module. The cursor keys and many keybindings are now operational. regards Michael From noix at sphere.pl Mon Jul 12 23:28:48 2004 From: noix at sphere.pl (Tomek =?ISO-8859-2?Q?Noi=F1ski?=) Date: Mon Jul 12 23:29:22 2004 Subject: [Tutor] online judge with Python Message-ID: <20040712232848.752b2065@noix.tornado.lan> There has recently been some talk on the question of online judges for Python, and contestants at http://uselesspython.com/programmingcontests.html are actually looking for one. So perhaps you might be interested to know that for several weeks now a new online judge with Python support has been open to the public. The Sphere Online Judge (SPOJ) is available at http://spoj.sphere.pl, and supports solutions written in 20 different programming languages including Python. At present, nearly half of the rapidly expanding problemset (currently more than 100 tasks) can be solved using Python easily within the time-limit. To improve speed, the Psyco extension module is available for use. It is possible to add tasks dedicated to specific languages and the development team are glad to cooperate if you are willing to create some new interesting Python problems. With best wishes, Adrian Kosowski, Micha? Ma?afiejski, Tomasz Noi?ski, Gdansk University of Technology, Poland -------------- 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/20040712/28acf8e2/attachment-0001.pgp From snehangshu_k at rediffmail.com Tue Jul 13 09:36:57 2004 From: snehangshu_k at rediffmail.com (Snehangshu Karmakar) Date: Tue Jul 13 09:37:02 2004 Subject: [Tutor] (no subject) Message-ID: <20040713073657.5511.qmail@webmail17.rediffmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040713/75224dfe/attachment.html -------------- next part -------------- ? looking for a good case studies in Python to present it to beginners. Snehangshu From rdm at rcblue.com Tue Jul 13 12:00:09 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Jul 13 12:00:40 2004 Subject: [Tutor] Please critique my temperature_conversion.py Message-ID: <6.1.2.0.2.20040713021349.048289a8@rcblue.com> Wow, is this a great list or what? Thanks again, tutors. By golly, I think I've got it! I decided to use Andrei's basic framework, and added some cool features suggested by others. Thank you all for your kindness and patience. Or if there's still room for improvement, please keep sending those cards and letters! (I have yet to dig into sys.argv yet. Soon) BTW I'm using Windows, so it seems I can't use/don't have the readline module. BTW2 Ctrl+Break doesn't do anything, on my computer. Dick #TempConverter.py """ temperature conversion: Fahrenheit <---> Celsius. User enters temperature as a value (number) followed by a unit of either F or C. The program uses the variable "temp_value" to hold this original temperature value, and the variable "temp_unit" to hold the original F or the C. """ print """ TempConverter.py TempConverter will convert Fahrenheit to Celsius or Celsius to Fahrenheit. Enter a temperature as a value followed by a unit (F or C), such as 70F, 70 f, -12.47C, 34c, etc. To exit program, enter exit, quit, stop, q, or x """ import sys, time def exit(): print "Thank you for using TempConverter. TempConverter will now close" time.sleep(1.1) # to provide the user with enough time to read the message while True: temperature = "" # for exiting via ^C or ^D try: temperature = raw_input('Temperature: ').strip() except (TypeError, EOFError): break if temperature.lower() in ["exit", "quit", "stop", "q", "x"]: break # make sure there is input at all, i.e., catch ""; (" " already stripped) try: temp_unit = temperature[-1] temp_value = temperature[:-1] except: # input is too short print "Wrong input! Specify a value followed by a unit." continue # make sure we know the unit if not (temp_unit in ['F', 'C']): print "Unknown unit (%s)." % temp_unit continue # make sure the value is a number try: temp_value = float(temp_value) except: print "The value you specified (%s) is not a number!" % temp_value continue #calculate new value now that sure have good value and unit if temp_unit == "F": new_value = 5/9. * (temp_value - 32) print "%.2fF is %.2fC" % (temp_value, new_value) else: new_value = 9/5. * temp_value + 32 print "%.2fC is %.2fF" % (temp_value, new_value) exit() From Francis.Moore at shaws.co.uk Tue Jul 13 12:26:24 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Tue Jul 13 12:27:23 2004 Subject: [Tutor] Please critique my temperature_conversion.py Message-ID: <6081EBC21D52F744B484088BBBE665C3199F1D@sbserver.shaws.local> Dick, Funnily enough, 2 temperature conversion programs have appeared on the Daily Python URL in the last couple of days (http://www.pythonware.com/daily). http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286221 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286226 They're worth checking out, if only to see how other people have handled the same problems you're having to deal with. HTH, 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 rdm at rcblue.com Tue Jul 13 12:51:12 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Jul 13 12:51:12 2004 Subject: [Tutor] Please critique my temperature_conversion.py In-Reply-To: <6081EBC21D52F744B484088BBBE665C3199F1D@sbserver.shaws.loca l> References: <6081EBC21D52F744B484088BBBE665C3199F1D@sbserver.shaws.local> Message-ID: <6.1.2.0.2.20040713034827.02ca6ae8@rcblue.com> Francis Moore wrote at 03:26 7/13/2004: >Dick, > >Funnily enough, 2 temperature conversion programs >have appeared on the Daily Python URL in the last >couple of days (http://www.pythonware.com/daily). > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286221 >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286226 > >They're worth checking out, if only to see how other people >have handled the same problems you're having to deal with. Thanks very much, Francis. They both look interesting, and well worth studying. Especially the second, because it uses classes, which I have yet to get into. And I didn't even know about the Daily Python-URL. I'll check the page frequently from now on. Dick From ps_python at yahoo.com Tue Jul 13 14:20:02 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Jul 13 14:20:09 2004 Subject: [Tutor] Automation In-Reply-To: <6.1.2.0.2.20040713034827.02ca6ae8@rcblue.com> Message-ID: <20040713122002.40615.qmail@web90003.mail.scd.yahoo.com> Dear all, I have ~ 50 tar gzipped files and they have thousands of files with .dta and .out extensions. These files are from mass spectrometer runs. I have another program that combines all the .dta files in to one large combined program. Until now what I am doing is - taking one tar gzipped file, unzipping and untar it in to a directory. Then using the small program that combines all the .dta files in to one single .dta file. After this I am cleaning all small .dta and .out files. Doing this for each tar gzipped file is pain in the neck. Is it easy to write a small python program? How should I write. Please can you provide some help. Thank you SP __________________________________ Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! http://promotions.yahoo.com/new_mail From rdm at rcblue.com Tue Jul 13 16:33:53 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Jul 13 16:33:59 2004 Subject: [Tutor] Please critique my temperature_conversion.py Message-ID: <6.1.2.0.2.20040713072929.024bc8a0@rcblue.com> Oops! forgot one line. Left out this line: temp_unit = temp_unit.upper() (which enables user to enter lower-case c and f, as in 70f and 45c) in this section: # make sure we know the unit temp_unit = temp_unit.upper() if not (temp_unit in ['F', 'C']): print "Unknown unit (%s)." % temp_unit continue Sorry. So the script now is: #temperature_conversion.py """ temperature conversion: Fahrenheit <---> Celsius. User enters temperature as a number followed by a unit of either F or C. The program uses the variable "number" to hold this original number, and the variable "unit" to hold the original F or the C. """ print """ TempConverter.py TempConverter will convert Fahrenheit to Celsius or Celsius to Fahrenheit. Enter a temperature as a value followed by a unit (F or C), such as 70F, 70 f, -12.47C, 34c, etc. To exit program, enter exit, quit, stop, q, or x """ import sys, time def exit(): print "Thank you for using TempConverter. TempConverter will now close" time.sleep(1.1) # to provide the user with enough time to read the message while True: temperature = "" # for exiting via ^C or ^D try: temperature = raw_input('Temperature: ').strip() except (TypeError, EOFError): break if temperature.lower() in ["exit", "quit", "stop", "q", "x"]: break # make sure there is input at all, i.e., catch ""; (" " already stripped) try: temp_unit = temperature[-1] temp_value = temperature[:-1] except: # input is too short print "Wrong input! Specify a value followed by a unit." continue # make sure we know the unit temp_unit = temp_unit.upper() if not (temp_unit in ['F', 'C']): print "Unknown unit (%s)." % temp_unit continue # make sure the value is a number try: temp_value = float(temp_value) except: print "The value you specified (%s) is not a number!" % temp_value continue #calculate new value now that sure have good value and unit if temp_unit == "F": new_value = 5/9. * (temp_value - 32) print "%.2fF is %.2fC" % (temp_value, new_value) else: new_value = 9/5. * temp_value + 32 print "%.2fC is %.2fF" % (temp_value, new_value) exit() From dyoo at hkn.eecs.berkeley.edu Tue Jul 13 19:52:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 13 19:53:01 2004 Subject: [Tutor] (no subject) [case studies in Python] In-Reply-To: <20040713073657.5511.qmail@webmail17.rediffmail.com> Message-ID: On 13 Jul 2004, Snehangshu Karmakar wrote: > looking for a good case studies in Python to present it to beginners. Hi Snehangshu, Have you had a chance to look at the Livewires project? http://www.livewires.org.uk/python/ Good luck to you! From dyoo at hkn.eecs.berkeley.edu Tue Jul 13 20:03:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 13 20:03:38 2004 Subject: [Tutor] Automation In-Reply-To: <20040713122002.40615.qmail@web90003.mail.scd.yahoo.com> Message-ID: On Tue, 13 Jul 2004, kumar s wrote: > I have ~ 50 tar gzipped files and they have thousands of files with > .dta and .out extensions. These files are from mass spectrometer runs. > > I have another program that combines all the .dta files in to one large > combined program. Until now what I am doing is - taking one tar gzipped > file, unzipping and untar it in to a directory. Then using the small > program that combines all the .dta files in to one single .dta file. > After this I am cleaning all small .dta and .out files. > > Doing this for each tar gzipped file is pain in the neck. Is it easy to > write a small python program? How should I write. Please can you > provide some help. Hi Kumar, Yes, you can do this kind of automation in Python. Here are example articles that talk about automating common system administration tasks: http://www.unixreview.com/documents/s=9083/sam0401d/ http://www.samag.com/documents/s=8964/sam0312a/0312a.htm You'll probably want to use some functions from the Standard Library to call out to 'tar', and to cull out your '.dta' files. The functions: 'os.system()' and 'glob.glob()' should be helpful here: http://www.python.org/doc/lib/os-process.html#l2h-1520 http://www.python.org/doc/lib/module-glob.html#l2h-2183 Hope this helps! From smith-matt at tiscali.co.uk Tue Jul 13 20:36:53 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Tue Jul 13 20:32:17 2004 Subject: [Tutor] Please critique my guessing game program. Message-ID: <20040713193653.67bb24fb@localhost> I just started reading about python a couple of days ago and have just written my first program, a guessing game (project suggested b o by the Python Bibliothecha). I intend to extend the program to make it more user friendly but I'd like to get some initial feedback to catch any poor programming or bad habits as soon as possible. Here's the program: # A guessing game program. # By Matt Smith import random # Function to create a random number between 1 and 100. def Random100(): return random.randint(1,100) # Game loop. def Game(guess): guesses = 1 while guess != number: if guess > number: guess = input("Too high, try again. ") else: guess = input("Too low, try again. ") guesses = guesses + 1 print "Well done, you got it in",guesses,"goes." # Main program. # Introduce the program. print "*****************" print "* Guessing Game *" print "*****************" print # Think of a number. number = Random100() # Play the game. print "I am thinking of a number between 1 and 100" guess = input ("What is your first guess? ") Game(guess) # End of program. Thanks for the help, Matt. From python at bernardlebel.com Tue Jul 13 23:24:30 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Jul 13 22:22:43 2004 Subject: [Tutor] Iterating writing in a file Message-ID: <005c01c4691f$ca631410$0095fea9@atyss> Hello, I wish to do an iteration that will write something on each new line in a text file. Something like this: sFile = 'C:\\myFile.txt' oFile = file( sFile, 'rw' ) for oLine in range(1,10): oFile.write( 'text' ) However when I run this I get an IO error for the oFile.write() line. Any suggestion? Thanks Bernard -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040713/c001c05b/attachment.htm From Christian.Wyglendowski at greenville.edu Tue Jul 13 23:20:45 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue Jul 13 23:20:53 2004 Subject: [Tutor] Iterating writing in a file Message-ID: To open a file for writing, the syntax is as follows: sFile = 'C:\\myFile.txt' oFile = file(sFile, 'w') See the documentation on the built-in funtion "file" for more information: http://docs.python.org/lib/built-in-funcs.html#built-in-funcs Christian http://www.dowski.com ________________________________ From: tutor-bounces+christian.wyglendowski=greenville.edu@python.org [mailto:tutor-bounces+christian.wyglendowski=greenville.edu@python.org] On Behalf Of Bernard Lebel Sent: Tuesday, July 13, 2004 4:25 PM To: tutor@python.org Subject: [Tutor] Iterating writing in a file Hello, I wish to do an iteration that will write something on each new line in a text file. Something like this: sFile = 'C:\\myFile.txt' oFile = file( sFile, 'rw' ) for oLine in range(1,10): oFile.write( 'text' ) However when I run this I get an IO error for the oFile.write() line. Any suggestion? Thanks Bernard From rgordon9 at swbell.net Tue Jul 13 23:28:01 2004 From: rgordon9 at swbell.net (Bob Gordon) Date: Tue Jul 13 23:28:04 2004 Subject: [Tutor] Use of POPEN Message-ID: <20040713212801.39759.qmail@web81110.mail.yahoo.com> I am trying to redirect a spawned program's input stream using the following: import os pipe = os.popen('myprog.exe', 'w') pipe.write('stuff\n') pipe.close() when I perform the write, I receive the following error msg: Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 22] Invalid argument I am running under Windows2000. When launched, myprog.exe starts by printing some information to stdout and then waits for input from stdin. Do I also have to redirect stdout using popen2, for example, or will the output from myprog go to the bit bucket? If the later, then why do I receive the error dealing with stdin? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040713/08d4447f/attachment.htm From marvboyes at att.net Wed Jul 14 05:14:30 2004 From: marvboyes at att.net (Marv Boyes) Date: Wed Jul 14 05:14:48 2004 Subject: [Tutor] Best book(s) for learning Tkinter? Message-ID: <40F4A516.5060603@att.net> Hello, everyone. Here's my dilemma: 1) I want to learn Tkinter as thoroughly as would be necessary to be able to write decent Python GUI applications that I (and maybe others) might find useful. I plan on moving on to pyGTK as soon as possible, but Tkinter strikes me as a good start from a conceptual point of view (if I'm wrong, someone please disabuse me of this notion). 2) It's a shortcoming on my part, but I have a heck of a time teaching myself anything by reading from a monitor. I've run across plenty of excellent online tutorials, and have learned a lot from them, but I simply drive myself buggy within an hour. And if it's not something that I can save locally as a PDF or flat HTML, forget it. :) For me, fiction is the e-book's best genre. If it's something I have to learn and retain, and (especially) refer back to from time to time, I need a piece of treeware that I can hold in my hands and carry around. 3) I realize that I'm going to get the best, most up-to-date information online (most of the Python books in my local bookstores are woefully outdated); that being said, I like to get the basics from books and later fill in the gaps and bring myself current online. So, these things being said, can anyone suggest a good book (or books) for a serviceable knowledge of Tkinter? It's doesn't necessarily have to be a book devoted to Tkinter (if there is such a thing); a Python book with a really solid chapter or two on Tkinter would be fine. Most of the Python books I've been able to thumb through have offered very skimpy coverage, if any. Any guidance would be greatly appreciated. Thanks very much 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 milgrom at gmail.com Wed Jul 14 07:13:02 2004 From: milgrom at gmail.com (Alfred Milgrom) Date: Wed Jul 14 07:13:09 2004 Subject: [Tutor] Best book(s) for learning Tkinter? In-Reply-To: <40F4A516.5060603@att.net> References: <40F4A516.5060603@att.net> Message-ID: <50eadd0a04071322137ee8631b@mail.gmail.com> New Mexico tech has (in my opinion) the best manual for programming Tkinter. It's a relatively comprehensive manual covering all the options available. You can download the manual in PDF format from http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html There are also a couple of other useful links there. HTH Fred Milgrom On Tue, 13 Jul 2004 23:14:30 -0400, Marv Boyes wrote: > Hello, everyone. Here's my dilemma: > > 1) I want to learn Tkinter as thoroughly as would be necessary to be > able to write decent Python GUI applications that I (and maybe others) > might find useful. I plan on moving on to pyGTK as soon as possible, but > Tkinter strikes me as a good start from a conceptual point of view (if > I'm wrong, someone please disabuse me of this notion). > > 2) It's a shortcoming on my part, but I have a heck of a time teaching > myself anything by reading from a monitor. I've run across plenty of > excellent online tutorials, and have learned a lot from them, but I > simply drive myself buggy within an hour. And if it's not something that > I can save locally as a PDF or flat HTML, forget it. :) For me, fiction > is the e-book's best genre. If it's something I have to learn and > retain, and (especially) refer back to from time to time, I need a piece > of treeware that I can hold in my hands and carry around. > > 3) I realize that I'm going to get the best, most up-to-date information > online (most of the Python books in my local bookstores are woefully > outdated); that being said, I like to get the basics from books and > later fill in the gaps and bring myself current online. > > So, these things being said, can anyone suggest a good book (or books) > for a serviceable knowledge of Tkinter? It's doesn't necessarily have to > be a book devoted to Tkinter (if there is such a thing); a Python book > with a really solid chapter or two on Tkinter would be fine. Most of the > Python books I've been able to thumb through have offered very skimpy > coverage, if any. > > Any guidance would be greatly appreciated. Thanks very much 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/ > ---------- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- All the best, Fred From Francis.Moore at shaws.co.uk Wed Jul 14 11:37:39 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Wed Jul 14 11:38:34 2004 Subject: [Tutor] Best book(s) for learning Tkinter? Message-ID: <6081EBC21D52F744B484088BBBE665C3199F1E@sbserver.shaws.local> From: Marv Boyes [mailto:marvboyes@att.net] > So, these things being said, can anyone suggest a good book (or books) > for a serviceable knowledge of Tkinter? It's doesn't necessarily have to > be a book devoted to Tkinter (if there is such a thing); a Python book > with a really solid chapter or two on Tkinter would be fine. A book devoted to Tkinter: Python & Tkinter Programming: Graphical User Interfaces for Python Programs Grayson, John E. Manning Publications 1884777813 An online book: http://www.effbot.org/zone/tkinter-index.htm A book with 4 chapters devoted to Tkinter: Programming Python, 2nd Edition Object-Oriented Scripting Mark Lutz ISBN: 0-596-00085-5 A book with an online chapter (Chapter 20) about Python GUI programming including Tkinter: Python Programming on Win32 Help for Windows Programmers By Mark Hammond, Andy Robinson ISBN: 1-56592-621-8 http://www.onlamp.com/pub/a/python/excerpts/chpt20/index.html 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 project5 at redrival.net Wed Jul 14 13:20:54 2004 From: project5 at redrival.net (Andrei) Date: Wed Jul 14 13:21:19 2004 Subject: [Tutor] Re: Please critique my guessing game program. References: <20040713193653.67bb24fb@localhost> Message-ID: Matt Smith tiscali.co.uk> writes: > I just started reading about python a couple of days ago and have just > written my first program, a guessing game (project suggested b o by the > Python Bibliothecha). I intend to extend the program to make it more > user friendly but I'd like to get some initial feedback to catch any > poor programming or bad habits as soon as possible. Here's the program: Here is a session with the program, which illustrates the main problem: What is your first guess? asdf Traceback (most recent call last): File "temp.py", line 38, in ? guess = input ("What is your first guess? ") File "", line 0, in ? NameError: name 'asdf' is not defined No error handling! See the discussion started by Dick Moores, it contains examples on how to properly handle users who don't play nice with your program (you should generally assume that your users are A) malicious or B) stupid ;), so don't trust them to give you valid input). Another thing is the use of tabs for indentation. Although it's perfectly valid, the preferred style is to use 4 spaces per indentation level. You can set up your editor to automatically convert a Tab press to 4 spaces. Taste plays a role here, but IMO it's better to just stick with the preferred style even if your personal bias is towards tabs. I'd also suggest using if __name__ == '__main__': at the bottom of the program so it only automatically runs the game if the script is started standalone (as opposed to imported in a different program, e.g. when you write a collection of games accessible from a menu). You'll have to rewrite the initialization (probably just put it inside Game()) in order to make the game usable from such a collection. Yours, Andrei From dyoo at hkn.eecs.berkeley.edu Wed Jul 14 19:48:51 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 14 19:48:56 2004 Subject: [Tutor] (no subject) [case studies in Python] In-Reply-To: <20040714052807.24694.qmail@webmail27.rediffmail.com> Message-ID: On Tue, 13 Jul 2004 Danny Yoo wrote : >>Have you had a chance to look at the Livewires project? >> >> http://www.livewires.org.uk/python/ On 14 Jul 2004, Snehangshu Karmakar wrote: > Thanks for the reply it was quite nice surfing the site but i want a > scenario to be presented which very precisely comapres Python with other > OOP languages.If u can suggest me something in this regard. Hi Snehangshu, In that case, you may want to look at Alan Gauld's "Learning to Program": http://www.freenetpages.co.uk/hp/alan.gauld/ His tutorial uses several programming languages, including VBScript and Javascript, to better illustrate the ideas of programming. As far as a general point-by-point comparison between Python and other languages, you may want to look at the Language Comparsons page: http://www.python.org/cgi-bin/moinmoin/LanguageComparisons From israel at uandmedance.com Thu Jul 15 00:13:04 2004 From: israel at uandmedance.com (israel@uandmedance.com) Date: Thu Jul 15 00:12:05 2004 Subject: [Tutor] Long and Nasty List Comprehensions... for fun. Message-ID: I've recently cooked up a very long list comprehension (1027 characters!) out of sheer perversity that creates a simple html image gallery script. It's got a few quirks like requiring a specific directory structure, specific file types, as well as asking for the desired base directory twice. I was wondering if any of you had any tips for improving this monstrosity of mine. I'd also be interested in seeing any of your absurdly long one liners. I know I'm only an artist posing as a programmer, so I feel assured there are other out there who are far more insane than me. I think this exercise has tempered my love for list comprehensions into something a little more manageable. debugging something this long and all on one line grew to be a big pain, fun though it was. :) #-------------------------------------------------------------------- #!/usr/local/bin/python import os '''This Super Long List Comprehension Simple and Ugly Image Gallery requires you to have a directory structure as follows root directory |--Any Amount of Directories set up like so. ( filled with the full sized .png images. ) |--Thumbnail directory called 'thumb' ( filled with small identically named thumbnail .jpg images ) You merely cd to the directory and call 'python gallery.py' and answer the two requests for the directory you want to use. Usually this is './' The resulting html page will look for two stylesheets. base.css highpass.css They aren't provided, but you can use them to style your fabulous new image gallery script. ''' if __name__ == '__main__': file(os.path.join(raw_input('What is the base directory?'),'gallery.html'),'w').write('\n\n\n\nSimple, Ugly and Super Long List Comprehension Image Gallery\n\n\n\n\n\n'+'\n'.join(['
\n%s\n
\n' % (os.path.basename(dirname[0]),'\n'.join(['%s' % (os.path.join(dirname[0],image),image[:- 4],os.path.join(dirname[0],'thumb',image[:-4]+'.jpg'),image[:-4]) for image in dirname[2] if image[0] not in ['.'] and image[-4:] in ['.png','.jpg']])) for dirname in os.walk(raw_input('What is the base directory?')) if os.path.basename(dirname[0]) not in ['thumb'] and dirname[2] ])+'\n\n') #--------------------------------------------------------------------- ~Israel~ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 3066 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040714/443ab1d1/attachment.bin From punya_big at yahoo.com.sg Thu Jul 15 01:46:49 2004 From: punya_big at yahoo.com.sg (=?iso-8859-1?q?Gde=20Dony?=) Date: Thu Jul 15 01:46:52 2004 Subject: [Tutor] Need help in Glade+Kiwi In-Reply-To: <20040713212057.23ABD1E400D@bag.python.org> Message-ID: <20040714234649.77389.qmail@web53803.mail.yahoo.com> hello, iwant to buid a simple file explorer in Linux like nautilus or konquror that do file editing, exploring directories, and change file owner. with graphical interface. i already read Kiwi doc but did'n understand if i want to make a larger apps with lot of windows and menu. Thanks, Gde __________________________________________________ Do You Yahoo!? Download the latest ringtones, games, and more! http://sg.mobile.yahoo.com From dyoo at hkn.eecs.berkeley.edu Thu Jul 15 04:25:55 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 15 04:26:00 2004 Subject: [Tutor] Please critique my guessing game program. In-Reply-To: <20040713193653.67bb24fb@localhost> Message-ID: Hi Matt, Ok, let's take a look: > import random > > # Function to create a random number between 1 and 100. > > def Random100(): > return random.randint(1,100) Small note: it looks like you're using tab characters for your indentation; you may want to switch to 4 spaces, as that seems to be more prevalent these days. You can embed that comment about Random100 right in the definition of the program, as a "documentation string." For example: ### def sayHello(): """Function that says 'hello!'""" print "hello!" ### If there's a literal string in the first line of a function definition, Python will grab it and use it as documentation for the function. What's nice is that folks can later on ask Python for that documentation string through the 'help()' builtin: ### >>> help(sayHello) Help on function sayHello in module __main__: sayHello() Function that says 'hello!' ### > # Game loop. > > def Game(guess): > guesses = 1 > while guess != number: > if guess > number: > guess = input("Too high, try again. ") > else: > guess = input("Too low, try again. ") > guesses = guesses + 1 > print "Well done, you got it in",guesses,"goes." Looks ok here. As Andrei mentions, input() is a little unsafe, but I think it's fine here as a quick way to check numbers into the system. Just as an aside: It might make a good project to write a nice, polished value-inputting routine. The C language provides a scanf() function that makes it pretty easy to read in numbers and words without having to worry much about whitespace. Wouldn't it be nice to have the same facility in Python? It might look something like: ### """scan.py: provides a nice way to scan integers and words from stdin.""" ## module level global keeps a store of elements ready to be scanned out. _BUFFER = [] def get_int(prompt): """Returns an integer from standard input.""" while not _BUFFER: _fill_buffer(prompt) return int(_BUFFER.pop()) def get_word(prompt): """Returns a word from standard input.""" while not _BUFFER: _fill_buffer(prompt) return _BUFFER.pop() def _fill_buffer(prompt): line = raw_input(prompt) elements = line.split() elements.reverse() _BUFFER.extend(elements) ### and we can work with it like this: ### >>> import scan >>> scan.get_int("more input please: ") more input please: 43 44 45 43 >>> scan.get_int("more input please: ") 44 >>> scan.get_int("more input please: ") 45 ### This is really rough and dirty though, of course... *grin* But would something like this be useful? From project5 at redrival.net Thu Jul 15 08:51:14 2004 From: project5 at redrival.net (Andrei) Date: Thu Jul 15 08:51:23 2004 Subject: [Tutor] Re: Long and Nasty List Comprehensions... for fun. References: Message-ID: israel uandmedance.com uandmedance.com> writes: > I've recently cooked up a very long list comprehension (1027 > characters!) out of sheer perversity that creates a simple html image > gallery script. I think you've been cheating a bit :). Your entire script is around that size, but that includes a LOT of HTML text and a bunch of chained methods, which are outside the list comprehension. Now although that has obsfucational qualities, it doesn't increase the complexity of the list comprehension as such. The way to make horrendous list comprehensions is to nest and nest and nest and preferably mix in some lambdas and extremely short variable names :). > I was wondering if any of you had any tips for improving this > monstrosity of mine. You mean for making it even uglier? Add some CSS definitions, preferably configurable ones (like background color, border style, etc.). > I'd also be interested in seeing any of your absurdly long one liners. > I know I'm only an artist posing as a programmer, so I feel assured > there are other out there who are far more insane than me. I must confess I've never written a one-liner that long. I've written two or three-lined list comprehensions (2 or 3 levels deep), but the debugging and maintenance gets so painful, I don't go around chaining them in chained methods :). I saw at some point a site with some large obsfucated python code pieces, but I can't find it now. Actually, now I think about it, I did at some point abuse the facilities Python offers quite badly, but in a different way. I wrote an application where this was a valid (and useful!) command line (had to split it over several lines, but the whole thing is actually a single line): --- script.py R=5.125 S=19 E=2 D=0.5 C=2*sqrt((float(Args['R']))**2-(9/16*(float(Args['R'])-float(Args['D'])/2)**2)) O=0 N=STD L=str(2*3/4*(float(Args['R'])-float(Args['D'])/2))+'- self.Begin.x';self.Begin.y;100;100*(sin(self.PhiMiddle))**2; 100*(cos(self.PhiMiddle))**2 --- I was almost literally putting a square peg in a round hole. The application (with a more decent command line) drew a circle with a polygon inside it and with the modified command line, it drew two partly overlapping circles with two polygons inside them, sharing a side which was drawn between the two points where the two circles crossed. Yours, Andrei From smith-matt at tiscali.co.uk Thu Jul 15 18:04:35 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Thu Jul 15 18:11:23 2004 Subject: [Tutor] Re: Please critique my guessing game program. References: <20040713193653.67bb24fb@localhost> Message-ID: Hi, Thanks fo the help, I've made some changes to the program (please see below) and I intend to write a function to test the type of the variable guess (will have to use raw_input insted of input). I've got a couple of queries at this stage of developing the program: 1) Would it be preferable to have the main game loop as part of the main body of the program at this stage? At the moment it doesn't seam logical to me to split off the section that I have as a function. 2) Should I use the newline character in my print statements as opposed to having empty print statements? I guess this would look neater and take up less lines of code. Thanks again for the help, Matt. # A guessing game program. # By Matt Smith import random def Random100(): """function to return a random number between 1 and 100""" return random.randint(1,100) # Game loop. def Game(guess): guesses = 1 while guess != number: if guess > number: guess = input("Too high, try again. ") else: guess = input("Too low, try again. ") guesses = guesses + 1 print "Well done, you got it in",guesses,"goes." # Main program. # Introduce the program. print print "*****************" print "* Guessing Game *" print "*****************" print # Play the game. playagainflag = 1 while playagainflag == 1: print print "I am thinking of a number between 1 and 100" number = Random100() guess = input ("What's your first guess? ") Game(guess) print playagain = raw_input("Do you want to play again? (y/n) ") if playagain == "y" or playagain == "Y": playagainflag = 1 else: playagainflag = 0 print "Goodbye!" print # End of program. From leomandy at hotmail.com Thu Jul 15 18:45:05 2004 From: leomandy at hotmail.com (mandy bowen) Date: Thu Jul 15 18:45:13 2004 Subject: [Tutor] Program Questions Message-ID: Can someone tell me what I am doing wrong?? I cannot get this program to run and I want to add exception-handling, GUI, text processing, etc., but none of these will work unless the base program runs and I cannot figure out where I have made the mistake... Please Help! Program as follows: import time class Account: def _init_(self, initial): self.balance = initial self.strdeposit = [] self.strwithdraw = [] def deposit(self, amt): self.balance = self.balance + amt self.strdeposit.append(str(time.strftime(“%d %b %Y”)) + ‘ $’ + str(amt)) def withdraw(self, amt): self.balance = self.balance – amt self.strwithdraw.append(str(time.strftime(“%d %b %Y”)) + ‘ $’ + str(amt)) def trans(self): for i in range(len(self.strdeposit)): print self.strdeposit[i] + “ +” for i in range(len(self.strwithdraw)): print self.strwithdraw[i] + “ –“ def getbalance(self): # print self.balance print str(time.strftime(“%d %b %Y”) + ‘ $’ + str(self.balance)) class Menu: def DisplayMenu(self): print ‘--------------------------------‘ print ‘- Main Menu -‘ print ‘--------------------------------‘ print ‘1. Make A Deposit’ print ‘2. Make A Withdrawal’ print ‘3. View Transactions’ print ‘4. View Account Balance’ print ‘5. Exit’ def MenuOption(self, option, Account): if option == 1: print ‘\n’ Account.deposit(input(“Deposit amount: $”)) print ‘\n’ print ‘TRANSACTION COMPLETED’ print ‘\n’ elif option == 2: print ‘\n’ Account.withdraw(input(“Withdraw amount: $”)) print ‘\n’ print ‘TRANSACTION COMPLETED’ print ‘\n’ elif option == 3: print ‘\n’ Account.trans() print ‘\n’ print ‘QUERY COMPLETED’ print ‘\n’ elif option == 4: print ‘\n’ Account.getbalance() print ‘\n’ print ‘QUERY COMPLETED’ print ‘\n’ elif option == 5: exit() a = Account(1000.00) menu = Menu() menu.DisplayMenu() print ‘\n’ menuitem = input(“Enter Your Selection --> “) while menuitem < 5: menu.MenuOption(menuitem, a) menu.DisplayMenu() print ‘\n’ menuitem = input(“Enter Your Selection --> “) Any help I can get would be greatly appreciated! Thanks! Mandy _________________________________________________________________ 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 pythonTutor at venix.com Thu Jul 15 18:58:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Jul 15 18:58:36 2004 Subject: [Tutor] Program Questions In-Reply-To: References: Message-ID: <1089910711.4835.28.camel@laptop.venix.com> How does it fail??? What's wrong? It's easier to help if we can see the error message, the traceback, and the relevant pieces of program code. On Thu, 2004-07-15 at 12:45, mandy bowen wrote: > Can someone tell me what I am doing wrong?? I cannot get this program to > run and I want to add exception-handling, GUI, text processing, etc., but > none of these will work unless the base program runs and I cannot figure out > where I have made the mistake... Please Help! > Program as follows: > > > import time > > class Account: > def _init_(self, initial): > self.balance = initial > self.strdeposit = [] > self.strwithdraw = [] > > def deposit(self, amt): > self.balance = self.balance + amt > self.strdeposit.append(str(time.strftime(%d %b %Y)) + $ + str(amt)) > > def withdraw(self, amt): > self.balance = self.balance amt > self.strwithdraw.append(str(time.strftime(%d %b %Y)) + $ + str(amt)) > > def trans(self): > for i in range(len(self.strdeposit)): > print self.strdeposit[i] + + > > for i in range(len(self.strwithdraw)): > print self.strwithdraw[i] + > > def getbalance(self): > # print self.balance > print str(time.strftime(%d %b %Y) + $ + str(self.balance)) > > class Menu: > def DisplayMenu(self): > print -------------------------------- > print - Main Menu - > print -------------------------------- > print 1. Make A Deposit > print 2. Make A Withdrawal > print 3. View Transactions > print 4. View Account Balance > print 5. Exit > > def MenuOption(self, option, Account): > if option == 1: > print \n > Account.deposit(input(Deposit amount: $)) > print \n > print TRANSACTION COMPLETED > print \n > elif option == 2: > print \n > Account.withdraw(input(Withdraw amount: $)) > print \n > print TRANSACTION COMPLETED > print \n > elif option == 3: > print \n > Account.trans() > print \n > print QUERY COMPLETED > print \n > elif option == 4: > print \n > Account.getbalance() > print \n > print QUERY COMPLETED > print \n > elif option == 5: > exit() > > a = Account(1000.00) > menu = Menu() > menu.DisplayMenu() > print \n > menuitem = input(Enter Your Selection --> ) > while menuitem < 5: > menu.MenuOption(menuitem, a) > menu.DisplayMenu() > print \n > menuitem = input(Enter Your Selection --> ) > > > > > Any help I can get would be greatly appreciated! > Thanks! > Mandy > > _________________________________________________________________ > MSN Toolbar provides one-click access to Hotmail from any Web page FREE > download! http://toolbar.msn.click-url.com/go/onm00200413ave/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 leomandy at hotmail.com Thu Jul 15 19:25:11 2004 From: leomandy at hotmail.com (mandy bowen) Date: Thu Jul 15 19:25:15 2004 Subject: [Tutor] Program Questions Message-ID: It tells me for the line: a = Account(1000.00) this constructor takes no arguments. It also says for all of the "print" lines following the class call in MenuOption that "print" is invalid syntax. >From: Lloyd Kvam >To: mandy bowen >CC: tutor@python.org >Subject: Re: [Tutor] Program Questions >Date: 15 Jul 2004 12:58:31 -0400 > >How does it fail??? >What's wrong? > >It's easier to help if we can see the error message, the traceback, and >the relevant pieces of program code. > > > >On Thu, 2004-07-15 at 12:45, mandy bowen wrote: > > Can someone tell me what I am doing wrong?? I cannot get this program >to > > run and I want to add exception-handling, GUI, text processing, etc., >but > > none of these will work unless the base program runs and I cannot figure >out > > where I have made the mistake... Please Help! > > Program as follows: > > > > > > import time > > > > class Account: > > def _init_(self, initial): > > self.balance = initial > > self.strdeposit = [] > > self.strwithdraw = [] > > > > def deposit(self, amt): > > self.balance = self.balance + amt > > self.strdeposit.append(str(time.strftime(%d %b %Y)) + $ + str(amt)) > > > > def withdraw(self, amt): > > self.balance = self.balance amt > > self.strwithdraw.append(str(time.strftime(%d %b %Y)) + $ + str(amt)) > > > > def trans(self): > > for i in range(len(self.strdeposit)): > > print self.strdeposit[i] + + > > > > for i in range(len(self.strwithdraw)): > > print self.strwithdraw[i] + > > > > def getbalance(self): > > # print self.balance > > print str(time.strftime(%d %b %Y) + $ + str(self.balance)) > > > > class Menu: > > def DisplayMenu(self): > > print -------------------------------- > > print - Main Menu - > > print -------------------------------- > > print 1. Make A Deposit > > print 2. Make A Withdrawal > > print 3. View Transactions > > print 4. View Account Balance > > print 5. Exit > > > > def MenuOption(self, option, Account): > > if option == 1: > > print \n > > Account.deposit(input(Deposit amount: $)) > > print \n > > print TRANSACTION COMPLETED > > print \n > > elif option == 2: > > print \n > > Account.withdraw(input(Withdraw amount: $)) > > print \n > > print TRANSACTION COMPLETED > > print \n > > elif option == 3: > > print \n > > Account.trans() > > print \n > > print QUERY COMPLETED > > print \n > > elif option == 4: > > print \n > > Account.getbalance() > > print \n > > print QUERY COMPLETED > > print \n > > elif option == 5: > > exit() > > > > a = Account(1000.00) > > menu = Menu() > > menu.DisplayMenu() > > print \n > > menuitem = input(Enter Your Selection --> ) > > while menuitem < 5: > > menu.MenuOption(menuitem, a) > > menu.DisplayMenu() > > print \n > > menuitem = input(Enter Your Selection --> ) > > > > > > > > > > Any help I can get would be greatly appreciated! > > Thanks! > > Mandy > > > > _________________________________________________________________ > > MSN Toolbar provides one-click access to Hotmail from any Web page FREE > > download! http://toolbar.msn.click-url.com/go/onm00200413ave/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 > _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar – get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From leomandy at hotmail.com Thu Jul 15 19:31:33 2004 From: leomandy at hotmail.com (mandy bowen) Date: Thu Jul 15 19:31:37 2004 Subject: [Tutor] Program Questions Message-ID: I do not have the exact tracebacks because I am at work and do not have the software with me(cannot download it here). >From: Lloyd Kvam >To: mandy bowen >CC: tutor@python.org >Subject: Re: [Tutor] Program Questions >Date: 15 Jul 2004 12:58:31 -0400 > >How does it fail??? >What's wrong? > >It's easier to help if we can see the error message, the traceback, and >the relevant pieces of program code. > > > >On Thu, 2004-07-15 at 12:45, mandy bowen wrote: > > Can someone tell me what I am doing wrong?? I cannot get this program >to > > run and I want to add exception-handling, GUI, text processing, etc., >but > > none of these will work unless the base program runs and I cannot figure >out > > where I have made the mistake... Please Help! > > Program as follows: > > > > > > import time > > > > class Account: > > def _init_(self, initial): > > self.balance = initial > > self.strdeposit = [] > > self.strwithdraw = [] > > > > def deposit(self, amt): > > self.balance = self.balance + amt > > self.strdeposit.append(str(time.strftime(%d %b %Y)) + $ + str(amt)) > > > > def withdraw(self, amt): > > self.balance = self.balance amt > > self.strwithdraw.append(str(time.strftime(%d %b %Y)) + $ + str(amt)) > > > > def trans(self): > > for i in range(len(self.strdeposit)): > > print self.strdeposit[i] + + > > > > for i in range(len(self.strwithdraw)): > > print self.strwithdraw[i] + > > > > def getbalance(self): > > # print self.balance > > print str(time.strftime(%d %b %Y) + $ + str(self.balance)) > > > > class Menu: > > def DisplayMenu(self): > > print -------------------------------- > > print - Main Menu - > > print -------------------------------- > > print 1. Make A Deposit > > print 2. Make A Withdrawal > > print 3. View Transactions > > print 4. View Account Balance > > print 5. Exit > > > > def MenuOption(self, option, Account): > > if option == 1: > > print \n > > Account.deposit(input(Deposit amount: $)) > > print \n > > print TRANSACTION COMPLETED > > print \n > > elif option == 2: > > print \n > > Account.withdraw(input(Withdraw amount: $)) > > print \n > > print TRANSACTION COMPLETED > > print \n > > elif option == 3: > > print \n > > Account.trans() > > print \n > > print QUERY COMPLETED > > print \n > > elif option == 4: > > print \n > > Account.getbalance() > > print \n > > print QUERY COMPLETED > > print \n > > elif option == 5: > > exit() > > > > a = Account(1000.00) > > menu = Menu() > > menu.DisplayMenu() > > print \n > > menuitem = input(Enter Your Selection --> ) > > while menuitem < 5: > > menu.MenuOption(menuitem, a) > > menu.DisplayMenu() > > print \n > > menuitem = input(Enter Your Selection --> ) > > > > > > > > > > Any help I can get would be greatly appreciated! > > Thanks! > > Mandy > > > > _________________________________________________________________ > > MSN Toolbar provides one-click access to Hotmail from any Web page FREE > > download! http://toolbar.msn.click-url.com/go/onm00200413ave/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 > _________________________________________________________________ Get fast, reliable Internet access with MSN 9 Dial-up – now 2 months FREE! http://join.msn.click-url.com/go/onm00200361ave/direct/01/ From c-ng at northwestern.edu Thu Jul 15 19:34:05 2004 From: c-ng at northwestern.edu (Carla A. Ng) Date: Thu Jul 15 19:34:19 2004 Subject: [Tutor] generating list of arguments for lin alg Message-ID: <200407151734.i6FHYGea011920@hecky.it.northwestern.edu> I'm fairly new to Python and have just gotten into using numarray... I have a large system of equations I need to solve simultaneously (92 eqn's and unknowns) but haven't found a handy way to generate a list of the 92 unknowns, and I certainly don't want to have to type them all in to do it... The system I'm trying to solve is essentially: dNi=sum(Wij * dNj) Where dN is a 92x1 vector and W is a 92x92 matrix. since the value of each dNi depends on the value of the dNj that it is related to via the matrix W, I can't see an easy way to do this by simply inverting W. Also, only a handful of the elements of dN are known at the beginning. Any suggestions? Thanks! Carla From jeff at ccvcorp.com Thu Jul 15 20:20:28 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Jul 15 20:17:25 2004 Subject: [Tutor] Program Questions In-Reply-To: References: Message-ID: <40F6CAEC.7070108@ccvcorp.com> mandy bowen wrote: > It tells me for the line: > a = Account(1000.00) > this constructor takes no arguments. > It also says for all of the "print" lines following the class call in > MenuOption that "print" is invalid syntax. >> > import time >> > >> > class Account: >> > def _init_(self, initial): >> > self.balance = initial >> > self.strdeposit = [] >> > self.strwithdraw = [] Here's a tricky error that is often hard to spot, especially if you're learning from a book. Magic methods in Python, like the init method, require *two* underscores on each side -- you have only a single underscore on each side. You need to change that _init_() to be __init__(). >> > class Menu: >> > def DisplayMenu(self): >> > print -------------------------------- >> > print - Main Menu - >> > print -------------------------------- The problem here is that 'print' can take either variable names (in which case it prints the contents of the variable) or literal strings, which it prints as-is. How does Python know which is which? By how they're marked -- literal strings need to be surrounded by quotes. You can use either single quotes (') or double quotes (") -- that flexibility can be useful if you want printing a string that contains one of those characters. If you go through each of your print statements and put quotes around the parts that are meant to be printed as-is, this should work. For example, the bit I quoted above should become: class Menu: def DisplayMenu(self): print "--------------------------------" print "- Main Menu -" print "--------------------------------" Things get a little bit more complicated when you want to intermix literal strings with variables, as you do in the methods of your Account class. For example, your getbalance() method should be something like this: def getbalance(self): # print self.balance print time.strftime(%d %b %Y) + " $" + str(self.balance) Here you have three parts (the time, the literal dollar sign, and the balance) which you're putting together into a single string (by using the + operator), and 'print' then acts on that single string. (You also had a str() call around the whole thing, but that call is redundant -- the result of adding strings is already a string, so converting it into a *new* string accomplishes nothing.) There's actually better ways to put variable values into a string. There's a nice-looking introduction into using the % operator for string formatting in "Dive Into Python" (http://diveintopython.org/native_data_types/formatting_strings.html) which might be worth checking out. There should also be something about this in whatever tutorial or book that you're using already -- check the contents/index for "string formatting". Jeff Shannon Technician/Programmer Credit International From project5 at redrival.net Thu Jul 15 20:34:17 2004 From: project5 at redrival.net (Andrei) Date: Thu Jul 15 20:34:46 2004 Subject: [Tutor] Re: Program Questions References: Message-ID: mandy bowen wrote on Thu, 15 Jul 2004 17:25:11 +0000: > It tells me for the line: > a = Account(1000.00) > this constructor takes no arguments. Here's an interactive session demonstrating what you did wrong (assuming that's the only error, I haven't read all your code): >>> class Account(object): ... def __init__(self, val): ... print val >>> a = Account(4) 4 >>> class Bccount(object): ... def _init_(self, val): ... print val >>> b = Bccount(4) Traceback (most recent call last): File "", line 1, in ? TypeError: default __new__ takes no parameters >>> b = Bccount() >>> b._init_(4) 4 You've spelled __init__ incorrectly. It's got TWO underscores on each side, but you've written a single one. > It also says for all of the "print" lines following the class call in > MenuOption that "print" is invalid syntax. >>> print \n And what is \n according to you? Right, it's nothing. \ is a line continuation character, n would be a non-existant variable which is put after a line continuation character - so you've got two errors. I presume you want to print an empty line (or two, to be precise). You do that by printing the *string* "\n": >>> print "\n" -- 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 smith-matt at tiscali.co.uk Thu Jul 15 21:35:56 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Thu Jul 15 21:31:22 2004 Subject: [Tutor] Why can't I make this function work? Message-ID: I have written the following function as part of my guessing game program (as discussed in another thread): def Get_int(): "Function to collect an integer from the user" type_check = 0 while type_check == 0: int = raw_input() if type(int) != type(1): print "Invalid input" else: type_check = 1 return int I think the function should keep taking input until an integer is input, at which point it should return the value to the main program. The function does not cause the program to crash but it doesn't accept any input (returns "Invalid input" whatever I type). Changing the type_check variable should cause the while loop to exit, shouldn't it? Thanks for all the help, Matt. From Christian.Wyglendowski at greenville.edu Thu Jul 15 22:26:51 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu Jul 15 22:26:55 2004 Subject: [Tutor] Why can't I make this function work? Message-ID: > -----Original Message----- > > I have written the following function as part of my guessing > game program (as discussed in another thread): > > def Get_int(): > "Function to collect an integer from the user" > type_check = 0 > while type_check == 0: > int = raw_input() Something to avoid - "int" is a built-in function and type in Python. By assigning a value to "int" in your funtion, you have overwritten the built-in in your function's namespace. Thus, calls to int() from within your function will not behave as expected. Which leads us to the next issue... > if type(int) != type(1): > print "Invalid input" > else: > type_check = 1 > return int Raw_input() always returns a string. To get the integer value of a string, you need to call int() on it - which would present a problem in your current function with a variable named "int". After you get your variable name situation squared away, you'll find that calling int() on something that can't be converted to an integer raises an exception: >>> myval = 'this' >>> int(myval) Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): this You'll need to implement some exception handling in your function to deal with this. Perhaps this example from the interactive interpreter will get you moving in the right direction: >>> try: int(myval) ... except ValueError: print 'Not an integer' ... Not an integer > I think the function should keep taking input until an > integer is input, at which point it should return the value > to the main program. The function does not cause the program > to crash but it doesn't accept any input (returns "Invalid > input" whatever I type). Changing the type_check variable > should cause the while loop to exit, shouldn't it? The loop logic of your function looks good. You just weren't reaching the case that would end the loop. Exceptions...namespaces...weren't you just asking how to fix a simple function? :-) For more on exceptions, see http://docs.python.org/tut/node10.html#SECTION0010200000000000000000 If you are curious about namespaces, check out the tutor archives (you can put this search string into google "namespace tutor site:mail.python.org"). > Thanks for all the help, > Matt. I hope it is helpful! Christian http://www.dowski.com From project5 at redrival.net Thu Jul 15 22:58:53 2004 From: project5 at redrival.net (Andrei) Date: Thu Jul 15 22:59:21 2004 Subject: [Tutor] Re: Please critique my guessing game program. References: <20040713193653.67bb24fb@localhost> Message-ID: Matt Smith wrote on Thu, 15 Jul 2004 17:04:35 +0100: > 1) Would it be preferable to have the main game loop as part of the main > body of the program at this stage? At the moment it doesn't seam logical > to me to split off the section that I have as a function. Yes, but it won't actually gain you anything in this case (program is too short to become unmaintainable), except for better style. But it's also fine if you think "ok, I know I can do it like that, and I make the conscious decision to keep it as it is". > 2) Should I use the newline character in my print statements as opposed to > having empty print statements? I guess this would look neater and take up > less lines of code. In my opinion, yes. -- 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 Thu Jul 15 23:09:16 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu Jul 15 23:09:21 2004 Subject: [Tutor] web applications?? Message-ID: <20040715210916.59871.qmail@web60101.mail.yahoo.com> hello, I would like to put my wxpython application up on the web for our customers to use. I don't want them to download it because it's sort of a one time use application. they just need it to calculate a number they need to use our products. Is it possible to just execute my wxpython application from our server? or do I need to write the application in some sort of web-python variation. If customers can simply execute the application from the web, how do I learn about how to set this up - is it as simple as uploading the executable and creating a link? thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040715/ae388a3f/attachment.htm From leomandy at hotmail.com Fri Jul 16 00:25:42 2004 From: leomandy at hotmail.com (mandy bowen) Date: Fri Jul 16 00:25:46 2004 Subject: [Tutor] Program Questions Message-ID: I just tried a few of the suggestions I received here, but I still get an invalid syntax error when I try to run the program in this section: def MenuOption(self, option, Account): if option == 1: print ‘\n’ Account.deposit(input(“Deposit amount: $”)) print ‘\n’ print ‘TRANSACTION COMPLETED’ print ‘\n’ elif option == 2: print ‘\n’ Account.withdraw(input(“Withdraw amount: $”)) print ‘\n’ print ‘TRANSACTION COMPLETED’ print ‘\n’ elif option == 3: print ‘\n’ Account.trans() print ‘\n’ print ‘QUERY COMPLETED’ print ‘\n’ The error says that the invalid syntax is in the print command! If I take all of those print statements out, it tells me the invalid syntax is the elif??? What is going on here? I'm new to Python, but I know elif is supposed to be valid... _________________________________________________________________ Check out the latest news, polls and tools in the MSN 2004 Election Guide! http://special.msn.com/msn/election2004.armx From leomandy at hotmail.com Fri Jul 16 00:30:04 2004 From: leomandy at hotmail.com (mandy bowen) Date: Fri Jul 16 00:30:25 2004 Subject: [Tutor] Program Questions Message-ID: The def and if statement are indented properly in the program - they just came out wrong in the email. _________________________________________________________________ MSN Life Events gives you the tips and tools to handle the turning points in your life. http://lifeevents.msn.com From pythonTutor at venix.com Fri Jul 16 02:08:36 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Jul 16 02:09:44 2004 Subject: [Tutor] Program Questions In-Reply-To: References: Message-ID: <1089936516.6659.30.camel@laptop.venix.com> print "\n" print "TRANSACTION COMPLETED" You need quotes around string literals, pieces of text that were never assigned a name. I suspect the elif problems come from using a mix of tabs and spaces in lining things up. Python uses 8 spaces per tab, but your editor could be different. If your editor was using tab stops of four spaces, you could mix tabs and spaces in a way that looked reasonable in your editor, but looks unreasonable to the Python compiler. I you edit your source code with pythonwin or idle, you should be able to eyeball the problem. Some editors will include a command to convert all tabs to spaces (or vice versa) which is handy for python files. On Thu, 2004-07-15 at 18:25, mandy bowen wrote: > I just tried a few of the suggestions I received here, but I still get an > invalid syntax error when I try to run the program in this section: > > def MenuOption(self, option, Account): > if option == 1: > print \n > Account.deposit(input(Deposit amount: $)) > print \n > print TRANSACTION COMPLETED > print \n > elif option == 2: > print \n > Account.withdraw(input(Withdraw amount: $)) > print \n > print TRANSACTION COMPLETED > print \n > elif option == 3: > print \n > Account.trans() > print \n > print QUERY COMPLETED > print \n > > The error says that the invalid syntax is in the print command! If I take > all of those print statements out, it tells me the invalid syntax is the > elif??? What is going on here? I'm new to Python, but I know elif is > supposed to be valid... > > _________________________________________________________________ > Check out the latest news, polls and tools in the MSN 2004 Election Guide! > http://special.msn.com/msn/election2004.armx > > _______________________________________________ > 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 adeleinandjeremy at yahoo.com Fri Jul 16 03:28:44 2004 From: adeleinandjeremy at yahoo.com (Adelein and Jeremy) Date: Fri Jul 16 03:28:47 2004 Subject: [Tutor] Program Questions Message-ID: <20040716012844.85085.qmail@web50304.mail.yahoo.com> --- Lloyd Kvam wrote: > print "\n" > print "TRANSACTION COMPLETED" > > You need quotes around string literals, pieces of text that were > never assigned a name. > She did have quotes. This is what you apparently saw: > > def MenuOption(self, option, Account): > > if option == 1: > > print \n > > Account.deposit(input(Deposit amount: $)) > > print \n > > print TRANSACTION COMPLETED > > print \n > > elif option == 2: > > print \n > > Account.withdraw(input(Withdraw amount: $)) > > print \n > > print TRANSACTION COMPLETED > > print \n > > elif option == 3: > > print \n > > Account.trans() > > print \n > > print QUERY COMPLETED > > print \n This is what I saw (there are single quotes around each string literal): def MenuOption(self, option, Account): if option == 1: print ‘\n’ Account.deposit(input(“Deposit amount: $”)) print ‘\n’ print ‘TRANSACTION COMPLETED’ print ‘\n’ elif option == 2: print ‘\n’ Account.withdraw(input(“Withdraw amount: $”)) print ‘\n’ print ‘TRANSACTION COMPLETED’ print ‘\n’ elif option == 3: print ‘\n’ Account.trans() print ‘\n’ print ‘QUERY COMPLETED’ print ‘\n’ > I suspect the elif problems come from using a mix of tabs and > spaces in > lining things up. Python uses 8 spaces per tab, but your editor > could > be different. If your editor was using tab stops of four spaces, > you > could mix tabs and spaces in a way that looked reasonable in your > editor, but looks unreasonable to the Python compiler. If indeed that is the problem, then this is also the problem with the print statement. I see no other error - could be missing something though. HTH Jeremy __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From leomandy at hotmail.com Fri Jul 16 04:40:46 2004 From: leomandy at hotmail.com (mandy bowen) Date: Fri Jul 16 04:40:51 2004 Subject: [Tutor] Program Problems Message-ID: If you see a problem, can you tell me? http://rafb.net/paste/results/88yf5V76.html I cannot figure out the errors. Or this list. _________________________________________________________________ Get tips for maintaining your PC, notebook accessories and reviews in Technology 101. http://special.msn.com/tech/technology101.armx From amonroe at columbus.rr.com Fri Jul 16 05:10:55 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Jul 16 05:07:19 2004 Subject: [Tutor] Program Problems In-Reply-To: References: Message-ID: <145795071922.20040715231055@columbus.rr.com> > If you see a problem, can you tell me? Lines 39 and 42 look like they have mismatched numbers of left and right parentheses. Alan From missive at hotmail.com Fri Jul 16 07:20:31 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Jul 16 07:20:36 2004 Subject: [Tutor] Re: Program Questions Message-ID: >This is what I saw (there are single quotes around each string >literal): > heh. Yours looks like this to me (question marks, not quotation marks.) Maybe those are those strange "smart quotes" that some word processors create. What editor are you using to write the code? Are you saving as plain text? def MenuOption(self, option, Account): if option == 1: print ?\n? Account.deposit(input(?Deposit amount: $?)) print ?\n? print ?TRANSACTION COMPLETED? print ?\n? elif option == 2: print ?\n? Account.withdraw(input(?Withdraw amount: $?)) print ?\n? print ?TRANSACTION COMPLETED? print ?\n? elif option == 3: print ?\n? Account.trans() print ?\n? print ?QUERY COMPLETED? print ?\n? _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From project5 at redrival.net Fri Jul 16 08:11:20 2004 From: project5 at redrival.net (Andrei) Date: Fri Jul 16 08:11:26 2004 Subject: [Tutor] Re: Program Questions References: <20040716012844.85085.qmail@web50304.mail.yahoo.com> Message-ID: Adelein and Jeremy yahoo.com> writes: > > You need quotes around string literals, pieces of text that were > > never assigned a name. > She did have quotes. > This is what you apparently saw: I saw no quotes in the message. Something odd going on with the editor? > This is what I saw (there are single quotes around each string > literal): I see question marks in this one. Some encoding issue? On to the original poster: The code at http://rafb.net/paste/results/88yf5V76.html looks a lot better though. Except for the mismatched parens already mentioned (line 39 and 42), you're trying to subclass something called "base" in Account. This "base" doesn't exist - it's not a built-in and you haven't defined it. You should instead subclass object. If you fix these issues, the program seems to work nicely. You might want to have a look at the lines using str(time.strftime("%d %b %Y")) + '$' + str(amt) I think you'd be better off pulling it out into a function and/or using a format string and certainly putting a space between the date and the amount. Yours, Andrei From project5 at redrival.net Fri Jul 16 08:18:54 2004 From: project5 at redrival.net (Andrei) Date: Fri Jul 16 08:18:57 2004 Subject: [Tutor] Re: web applications?? References: <20040715210916.59871.qmail@web60101.mail.yahoo.com> Message-ID: Jeff Peery yahoo.com> writes: > Is it possible to just execute my wxpython application from our server? or do I need to write the application in some sort of web-python variation. No. Well, you can execute it on your server machine, but it won't help anyone. You can't serve wxPython dialogs over the web. > If customers can simply execute the application from the web, how do I learn about how to set this up - is it as simple as uploading the executable and creating a link? You'll need to forget the wxPython part, pull out the engine and wrap it up in something suitable for the web. You could use e.g. Zope or a simple CGI script. Either way, your server will have to have Python (or Zope) installed. You'll also need to write a HTML form to allow users to input whatever data they need to provide. Look in the Python docs for the cgi module (paragraph 11.2). And if that's too hard for you, you might consider doing it in Javascript - unless of course it's something complex. Yours, Andrei From rdm at rcblue.com Fri Jul 16 12:19:20 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Jul 16 12:20:18 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? Message-ID: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> I was just fooling around writing a script (below) that would show how fast my computer can count. I was pleased with the speed, but dismayed that counting to a mere 15 or 20 million reduced available memory from about 300 to close to zero, forcing a reboot; and sometimes upon rebooting I would find some important Win XP settings changed. Do I have to get a CS degree to understand what's going on? Or can someone point me to an explanation? Some results: 0 to 9999999 in 7.641 seconds! 0 to 1000000 in 0.766 seconds! 0 to 100000 in 0.078 seconds! 0 to 50000 in 0.031 seconds! 0 to 10000 in 0.000 seconds! Thanks, tutors. Dick Moores ==================================== #spin.py import time print """ Enter an integer to count to from zero. To quit, enter x or q. """ while True: # for exiting via ^C or ^D try: max = raw_input("integer: ") except (TypeError, EOFError): print "Bye." break if len(max) == 0: print "Hey, don't just hit Enter, type an integer first!" continue if max in ["q", "x"]: print "Bye." break try: max = int(max) + 1 except: print "That's not an integer!" continue if max > 10000000: print "For the health of this computer," print "better keep integer under 10 million." continue print "Counting.." t0 = time.time() for k in range(max): k += 1 print "0 to %d in %.3f seconds!" % ((k - 1), (time.time() - t0)) ================================== From magnus at thinkware.se Fri Jul 16 13:16:13 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 16 13:12:11 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> Message-ID: <5.2.1.1.0.20040716130642.02892ea8@www.thinkware.se> At 03:19 2004-07-16 -0700, Dick Moores wrote: > Why does counting to 20 million stress my computer? Beause you are building very big lists that exhausts your RAM. "range(x)" will return a list with x pointers to x integers. I assume both the pointers and the integer items use 4 bytes each, so besides various overhead you are allocating (4+4)*20 000 000 = 160 MB of main memory for the counter. Not very effective, is it? Try replacing "range(max)" with "xrange(max)". No need for a degree, just read the manual: http://docs.python.org/lib/built-in-funcs.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Fri Jul 16 13:43:32 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 16 13:39:29 2004 Subject: [Tutor] web applications?? In-Reply-To: <20040715210916.59871.qmail@web60101.mail.yahoo.com> Message-ID: <5.2.1.1.0.20040716132457.028db140@www.thinkware.se> At 14:09 2004-07-15 -0700, Jeff Peery wrote: >hello, I would like to put my wxpython application up on the web for our >customers to use. I don't want them to download it because it's sort of a >one time use application. they just need it to calculate a number they >need to use our products. If we're talking vanilla MS Windows, wxPython applications can only run locally. There are certainly ways to run such applications remotely (e.g. Citrix or VNC), but in Windows that will require other installation efforts, lead to more security issues to consider, and possibly require expansive licenses. In Unix it's much simpler (using X), but there are still serious security issues here. >Is it possible to just execute my wxpython application from our server? or >do I need to write the application in some sort of web-python variation. Not if you are talking about WWW. One option which might be viable (but I haven't really done that) is to use Jython and Java's Swing for the user interface. Then you might be able to make your program into a Java applet. For a more traditional web solution, you might want to look at Quixote http://www.mems-exchange.org/software/quixote/ etc. A solution which only assumes a vanilla web browser on the client side is certainly a good thing, unless you know for sure what platforms your users use when they want to run this thingie... >If customers can simply execute the application from the web, how do I >learn about how to set this up - is it as simple as uploading the >executable and creating a link? The simplest way out might be to use something like cx_Freeze or py2exe to make your application into a single executable (and possibly a few dlls). That way it's a small effort do download, install and run the program. You certainly don't want to force them to download and install first Python and then wxPython before they get to your app... If there is data on a central server, you can certainly write your wxPython application so that it accesses data from your server across the web. But if all they need to do is to calculate a number, I guess they don't need a full featured GUI. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From smith-matt at tiscali.co.uk Fri Jul 16 17:32:54 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Fri Jul 16 17:28:13 2004 Subject: [Tutor] Re: Why can't I make this function work? References: Message-ID: On Thu, 15 Jul 2004 20:35:56 +0100, Matt Smith wrote: > I have written the following function as part of my guessing game program > (as discussed in another thread): > > def Get_int(): > "Function to collect an integer from the user" > type_check = 0 > while type_check == 0: > int = raw_input() > if type(int) != type(1): > print "Invalid input" > else: > type_check = 1 > return int Thanks for the help, I've re-written the funcion as below and it seams to work correctly now. def Get_int(): "Function to collect a integer from the user" type_check = 0 while type_check == 0: try: integer = int(raw_input()) type_check = 1 except: print "Invalid input, try agin. ", return integer Cheers, Matt. From smith-matt at tiscali.co.uk Fri Jul 16 17:45:56 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Fri Jul 16 17:41:17 2004 Subject: [Tutor] Re: Please critique my guessing game program. References: <20040713193653.67bb24fb@localhost> Message-ID: Hi, I've changed the program further to account for the help and suggestions I've recieved. I think this version is structured in a more logical way and should also be impossible to crash through inputing the wrong answer. Please let me know what you think and if the program could be improved in anyway. I have greatly enjoyed writing my first Python program. # A guessing game program. # By Matt Smith import random def Random100(): "Function to return a random number between 1 and 100" return random.randint(1,100) def Get_int(): "Function to collect an integer from the user" type_check = 0 while type_check == 0: try: integer = int(raw_input()) type_check = 1 except: print "Invalid input, try agin. ", return integer # Main program. # Introduce the program. print "\n*****************" print "* Guessing Game *" print "*****************\n" # Play the game. playagainflag = 1 while playagainflag == 1: print "\nI am thinking of a number between 1 and 100" number = Random100() print "What's your first guess? ", guesses = 1 guess = Get_int() while guess != number: if guess > number: print "Too high, try again. ", guess = Get_int() else: print "Too low, try again. ", guess = Get_int() guesses = guesses + 1 print "Well done, you got it in",guesses,"goes.\n" playagain = raw_input("Do you want to play again? (y/n) ") if playagain == "y" or playagain == "Y": playagainflag = 1 else: playagainflag = 0 print "Goodbye!\n" # End of program. Thanks again, Matt. From dyoo at hkn.eecs.berkeley.edu Fri Jul 16 19:03:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 16 19:03:59 2004 Subject: [Tutor] hello. I need some help pls (fwd) Message-ID: [Forwarding to python-tutor] ---------- Forwarded message ---------- Date: Thu, 15 Jul 2004 15:07:57 -0700 (PDT) From: loghin robert To: tutor-owner@python.org Subject: hello. I need some help pls >>> print 'here are the ten numbers from 0 to 9' here are the ten numbers from 0 to 9 >>> for 1 in range(10): print 1, SyntaxError: can't assign to literal Any idea?Pls...:) __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From dyoo at hkn.eecs.berkeley.edu Fri Jul 16 19:11:10 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 16 19:14:22 2004 Subject: [Tutor] Re: Program Questions In-Reply-To: Message-ID: > >This is what I saw (there are single quotes around each string > >literal): > > > > > heh. Yours looks like this to me (question marks, not quotation marks.) > Maybe those are those strange "smart quotes" that some word processors > create. What editor are you using to write the code? Are you saving as > plain text? Hi Mandy, I agree with Lee Harr; I'm seeing something wacky with those quotes too. Are you using a word processor like Wordpad or Microsoft Word? If so, that's the problem: don't use a word processor when you program in Python. Word processors use strange characters for quotation symbols, and Python won't recognize them. Instead, use a text editor, preferably one that makes Python programming more pleasant. Python comes with the IDLE text editor as part of its default install, so you may want to try that one first. Here's a slightly old (but hopefully still good) tutorial I wrote on IDLE: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ There are a list of alternative text editors on Python.org: http://www.python.org/cgi-bin/moinmoin/PythonEditors Good luck to you! From smith-matt at tiscali.co.uk Fri Jul 16 19:23:59 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Fri Jul 16 19:19:17 2004 Subject: [Tutor] Re: hello. I need some help pls (fwd) References: Message-ID: On Fri, 16 Jul 2004 10:03:56 -0700, Danny Yoo wrote: >>>> print 'here are the ten numbers from 0 to 9' > here are the ten numbers from 0 to 9 >>>> for 1 in range(10): > print 1, > > SyntaxError: can't assign to literal You need to use a valid variable name (eg. a letter or a string that starts with a letter). Try this: >>> for number in range(10): print number that should produce the desired result. Matt. From dyoo at hkn.eecs.berkeley.edu Fri Jul 16 19:21:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 16 19:21:33 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <5.2.1.1.0.20040716130642.02892ea8@www.thinkware.se> Message-ID: > Try replacing "range(max)" with "xrange(max)". > No need for a degree, just read the manual: > http://docs.python.org/lib/built-in-funcs.html Hi Dick, An alternative solution is to use a while-loop, something like: ### counter = 0 while counter < 10: print "counter is:", counter counter = counter + 1 ### Using range() on large numbers is a common gotcha, so don't worry too much about not knowing about xrange(). There are a few things that work perfectly well on small things, but break down when the problem grows much larger; range() is one of those. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Jul 16 19:28:58 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 16 19:29:01 2004 Subject: [Tutor] Re: Why can't I make this function work? In-Reply-To: Message-ID: > Thanks for the help, I've re-written the funcion as below and it seams to > work correctly now. > > def Get_int(): > "Function to collect a integer from the user" > type_check = 0 > while type_check == 0: > try: > integer = int(raw_input()) > type_check = 1 > except: > print "Invalid input, try agin. ", > return integer Hi Matt, One nitpick: When we try interrupting a program by pressing Control-C, that actually raises a "KeyboardInterrupt" exception to make the program stop. However, the loop above will disregard KeyboardInterrupts, so it'll make it difficult to interrupt that program in the middle of a Get_int(). I'd modify it just a little more so that the exception handling isn't so comprehensive: ### try: integer = int(raw_input()) type_check = 1 except ValueError: ## <--- Changed line here print "Invalid input, try agin. ", ### ValueError is the exception class that gets raised when we pass silly things to int(): ### >>> int("foobar") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): foobar ### Hope this helps! From apb_4 at hotmail.com Sat Jul 10 16:37:14 2004 From: apb_4 at hotmail.com (Adam Bark) Date: Fri Jul 16 19:30:09 2004 Subject: [Tutor] CGI Message-ID: Is it possible to create a common gateway interface in python? If it is how do i submit data to it using vbscript? Thanks. Adam _________________________________________________________________ It's fast, it's easy and it's free. Get MSN Messenger today! http://www.msn.co.uk/messenger From CMeesters at ucdavis.edu Sat Jul 10 04:36:01 2004 From: CMeesters at ucdavis.edu (Christian Meesters) Date: Fri Jul 16 19:30:19 2004 Subject: [Tutor] removing line ends from Word text files Message-ID: Hi Right now I have the problem that I want to remove the MS Word line end token from text files: When saving a text file as 'text only' line ends are displayed as '^M' in a shell (SGI IRIX (tcsh) and Mac (tcsh or bash)). I want to get rid of these elements for further processing of the file and have no idea how to access them in a Python script. Any idea how to replace the '^M' against a simple '\n'? (I already tried '\r\n' and various other combinations of characters, but apparently all aren't '^M'.) '^M' is one character. As supplementary information: I'm using MacOSX (version 10.3.4) with Python 2.3 or SGI Irix with Python 2.1.1 . Thanks a lot in advance, Christian From Puki at join2000.de Mon Jul 5 21:58:42 2004 From: Puki at join2000.de (Puki) Date: Fri Jul 16 19:31:27 2004 Subject: [Tutor] ComboBox with Tkinter Message-ID: <001401c462ca$7994d790$d101a8c0@pukispc> Hi Folks out there, I'm just starting to code in Pyhton. The first project is to build a GUI for an already existing program. Til now the little GUI of the program is only with Tkiner and without wxpython. Since two days I'm trying to figure out who to get a combobox in there without remodelling the whole stuff. At the beginning I thougt a combobox can't be that difficult, but I'm just not able to figure it out the wright way. The button wasn't a problem at all: self.Button=Button(frame7, text='Button', command=Parser).pack(side=BOTTOM) and I thought a combobox should act the same way: self.cb = Combobox(frame7, -1, choices['choice1','choice2'], value= 'combobox')??? The first problem is: There is no global name like "Combobox" and any other spelling. The second problem: I haven't figured out what arguments HAVE to be there and what CAN be there. The third problem: Can I handle this without wxPython? I hope my problem is only a big problem for me and you can give me some hints. Thanks a lot Puki -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040705/88816209/attachment.htm From SMITHB2 at WESTAT.com Tue Jul 13 20:31:29 2004 From: SMITHB2 at WESTAT.com (Barrett Smith) Date: Fri Jul 16 19:31:29 2004 Subject: [Tutor] Os.system on winXP system having trouble with spaces in directory names Message-ID: <446DDE75CFC7E1438061462F85557B0F0373A04A@remail2.westat.com> I'm having trouble with a using os.system on a windowsXP machine. Running: os.system('start C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html') Yields and error saying 'Windows cannot find C:\Documents.....' This same problem means I can't access things in the 'Program Files' directory and so forth. Any ideas of work-arounds (other than moving to non-space included directories)? Thanks, Barrett -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040713/f232ddf0/attachment.html From leomandy at hotmail.com Fri Jul 16 19:33:19 2004 From: leomandy at hotmail.com (mandy bowen) Date: Fri Jul 16 19:33:23 2004 Subject: [Tutor] Program Problems Message-ID: Thanks to all - I figured it out (with your help) - now onto figuring out the GUI for it... _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From Christian.Wyglendowski at greenville.edu Fri Jul 16 20:07:53 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Fri Jul 16 20:07:57 2004 Subject: [Tutor] Os.system on winXP system having trouble with spaces indirectory names Message-ID: Quoting your path should take care of it: os.system('start "C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html"') Christian http://www.dowski.com ________________________________ From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Barrett Smith Sent: Tuesday, July 13, 2004 1:31 PM To: 'tutor@python.org' Subject: [Tutor] Os.system on winXP system having trouble with spaces indirectory names I'm having trouble with a using os.system on a windowsXP machine. Running: os.system('start C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html') Yields and error saying 'Windows cannot find C:\Documents.....' This same problem means I can't access things in the 'Program Files' directory and so forth. Any ideas of work-arounds (other than moving to non-space included directories)? Thanks, Barrett From m at mongers.org Fri Jul 16 20:36:22 2004 From: m at mongers.org (Morten Liebach) Date: Fri Jul 16 20:43:22 2004 Subject: [Tutor] Os.system on winXP system having trouble with spaces in directory names In-Reply-To: <446DDE75CFC7E1438061462F85557B0F0373A04A@remail2.westat.com> References: <446DDE75CFC7E1438061462F85557B0F0373A04A@remail2.westat.com> Message-ID: <20040716183644.GB22028@mongers.org> On 2004-07-13 14:31:29 -0400, Barrett Smith wrote: > I'm having trouble with a using os.system on a windowsXP machine. > > Running: > os.system('start C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html') Try quoting: os.system('start "C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html"') Hope this helps Morten -- http://m.mongers.org/ -- http://gallery.zentience.org/ __END__ From dyoo at hkn.eecs.berkeley.edu Fri Jul 16 20:55:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 16 20:55:34 2004 Subject: [Tutor] Os.system on winXP system having trouble with spaces indirectory names In-Reply-To: Message-ID: On Fri, 16 Jul 2004, Christian Wyglendowski wrote: > Quoting your path should take care of it: > > os.system('start "C:\\Documents and > Settings\\Smith_B2\\Desktop\\page.html"') Hi Barrett, Just an an aside: if you're specifically trying to open up a web page from Python, you may want to look at the platform-independent 'webbrowser' module: http://www.python.org/doc/lib/module-webbrowser.html 'webbrowser' allows you to avoid doing using the Windows-specific 'start' command; the example above could probably be done using a 'file:///' URI. Good luck! From pythonTutor at venix.com Fri Jul 16 21:42:42 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Jul 16 21:42:50 2004 Subject: [Tutor] Program Questions In-Reply-To: <20040716012459.84481.qmail@web50304.mail.yahoo.com> References: <20040716012459.84481.qmail@web50304.mail.yahoo.com> Message-ID: <1090006962.8808.85.camel@laptop.venix.com> (I failed to send this to the list earlier) I saved the original email as a file so that I could examine it directly. The quotes in the original email are 0x91 and 0x92 characters and apparently came from a word processing program. My email program (evolution) simply dropped them. They are in the latin-1 control character range (0x80 - 0x9f) and are not encodings of displayable characters. Presumably they originated from a Windows Cp1252 encoding. The tabs and spaces are inconsistent. I assume the tab stops were set to half inch or something like that within a word processing program. The bottom line is that programs should be edited with a program editor rather than a word processor. On Windows, notepad will work in a pinch, but idle or pythonwin are MUCH better free options. I suppose this is a drawback with Python if you are using the wrong tools to edit your code. With most languages the blocks are marked with clearly visible characters. On Thu, 2004-07-15 at 21:24, Adelein and Jeremy wrote: > --- Lloyd Kvam wrote: > > print "\n" > > print "TRANSACTION COMPLETED" > > > > You need quotes around string literals, pieces of text that were > > never assigned a name. > > > > She did have quotes. > This is what you apparently saw: > > > > def MenuOption(self, option, Account): > > > if option == 1: > > > print \n > > > Account.deposit(input(Deposit amount: $)) > > > print \n > > > print TRANSACTION COMPLETED > > > print \n > > > elif option == 2: > > > print \n > > > Account.withdraw(input(Withdraw amount: $)) > > > print \n > > > print TRANSACTION COMPLETED > > > print \n > > > elif option == 3: > > > print \n > > > Account.trans() > > > print \n > > > print QUERY COMPLETED > > > print \n > > This is what I saw (there are single quotes around each string > literal): > > def MenuOption(self, option, Account): > if option == 1: > print ?\n? > Account.deposit(input(?Deposit amount: $?)) > print ?\n? > print ?TRANSACTION COMPLETED? > print ?\n? > elif option == 2: > print ?\n? > Account.withdraw(input(?Withdraw amount: $?)) > print ?\n? > print ?TRANSACTION COMPLETED? > print ?\n? > elif option == 3: > print ?\n? > Account.trans() > print ?\n? > print ?QUERY COMPLETED? > print ?\n? > > > I suspect the elif problems come from using a mix of tabs and > > spaces in > > lining things up. Python uses 8 spaces per tab, but your editor > > could > > be different. If your editor was using tab stops of four spaces, > > you > > could mix tabs and spaces in a way that looked reasonable in your > > editor, but looks unreasonable to the Python compiler. > > If indeed that is the problem, then this is also the problem with the > print statement. I see no other error - could be missing something > though. > > HTH > Jeremy > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com -- 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 Fri Jul 16 14:08:36 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 16 22:31:02 2004 Subject: [Tutor] Program Problems In-Reply-To: Message-ID: <5.2.1.1.0.20040716134808.02939580@www.thinkware.se> At 02:40 2004-07-16 +0000, mandy bowen wrote: >If you see a problem, can you tell me? > >http://rafb.net/paste/results/88yf5V76.html > >I cannot figure out the errors. The syntax error on the print statement at if option == 1: Account.deposit(input("Deposit amount:$") print "TRANSACTION COMPLETED" is because you lack a ")" on the previous line. A logical line in Python extends through several physical lines in Python while you are inside {}, [] or (), so that you can write things like: def func(parameter1, parameter2, parameter3, parameter4, parameter5, parameter6, parameter7, parameter8, parameter9, parameter10, parameter11, parameter12): This means that *your* code is interpreted as if option == 1: Account.deposit(input("Deposit amount:$") print "TRANSACTION COMPLETED" [...rest of program] Of course, you can't have a print statement inside the method call to Account.deposit(). It's very common that errors found by interpreters and compilers are actually caused by something on the line above. Python can't start complaining about the line where you forgot the ), since it's correct to write your code like that. A "smarter" compiler could have see that there aren't matching ) in the rest of the file, and given a proper diagnostic message for that, but the current approach of going through the code linearly and stopping at the first encountered error, has some advantages from a debugging point of view, and it's probably much easier to maintain the code and to keep the performance up with this simple approach. Of course, the error message could hint about the possibility of this problem, but this is such a common thing that most programmers (in all languages I've coded in) will check for a thing like that on reflex when they see an error message like that. The fact that it complained about something else when you removed the print statements must in hindsight be seen as a hint that your problem was actually somewhat earlier in the code, but I've certainly been confused about that kind of error myself in some long forgotten past. (Probably while coding Pascal.) > Or this list. Are you saying that you can't figure out the list or that the list can't figure out the errors? ;) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Fri Jul 16 22:43:02 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 16 22:39:11 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <6.1.2.0.2.20040716075503.029b5e68@rcblue.com> References: <5.2.1.1.0.20040716130642.02892ea8@www.thinkware.se> <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> <5.2.1.1.0.20040716130642.02892ea8@www.thinkware.se> Message-ID: <5.2.1.1.0.20040716223617.02909ca8@www.thinkware.se> At 08:01 2004-07-16 -0700, Dick Moores wrote: >Now I'm wondering about a reason to use range(x) instead of xrange(x). >Could you give me an example? How can the list range(x) builds be used? It's a normal Python list, right? Sometimes you *do* want lists, right? For instance, you can reverse a list, you can't reverse an xrange object. (On the other hand, you can generate a reversed xrange object from the start, such as with "x = xrange(max-1, -1, -1)" but I think you get the point. If you play around and experiment interactively with lists generated from range() and xrange objects, you'll notice the differences. I assume that range() predates xrange() in the development of Python. If that famous time machine really existed, I assume range would work like xrange does, and if you really wanted a list, you'd have to do "l=list(range(5))" or whatever. Maybe that will happen in the mythical Python 3 version. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From c-ng at northwestern.edu Fri Jul 16 22:43:45 2004 From: c-ng at northwestern.edu (Carla A. Ng) Date: Fri Jul 16 22:43:55 2004 Subject: [Tutor] when 1 is not equal to 1...?? Message-ID: <200407162043.i6GKhq7l004573@hecky.it.northwestern.edu> I've put in an error catch in a program to alert me when the equations I'm trying to solve have an error. Basically, if the sum of contributions to something does not equal 1, it should print out an error message (I don't plan on keeping this in my code, since it's bulky and outputs a bunch of stuff to the screen, but I wanted to make sure everything was working correctly). But I'm getting an error message when it *does* equal 1. Here's the code: diet=resize(base, (max,1)) for i in range(max): for j in range(max): diet[i,0]+=web[i,j] for i in range(max): if diet[i,0]<1.0 and i+1 not in Basal: print "wij for ", i+1, "has an error!" print diet Just to double-check that my check was working, I printed "diet" at the end. Then when I run it, I get: wij for 1 has an error! wij for 2 has an error! wij for 3 has an error! wij for 4 has an error! wij for 5 has an error! wij for 6 has an error! wij for 7 has an error! wij for 12 has an error! wij for 13 has an error! wij for 14 has an error! wij for 15 has an error! wij for 21 has an error! wij for 22 has an error! wij for 27 has an error! wij for 28 has an error! wij for 43 has an error! wij for 54 has an error! wij for 57 has an error! wij for 58 has an error! wij for 61 has an error! wij for 63 has an error! wij for 79 has an error! wij for 83 has an error! [[ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 0.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] (I didn't print out the whole thing, just enough to show it's not working). Obviously, since diet[0,0]=1, I should not get the error message: wij for 1 has an error! Any ideas out there? I thought it might be a float/integer problem, but everything is in floats, so I'm stumped. Thanks! Carla A. Ng =================================== Northwestern University Department of Chemical and Biological Engineering 2145 North Sheridan Road Evanston, IL 60208 Phone: (847)467-4980 Fax: (847)491-4011 =================================== "When one tugs at a single thing in nature, he finds it attached to the rest of the world." -- John Muir From c-ng at northwestern.edu Fri Jul 16 22:43:51 2004 From: c-ng at northwestern.edu (Carla A. Ng) Date: Fri Jul 16 22:44:05 2004 Subject: [Tutor] when 1 is not equal to 1...?? Message-ID: <200407162044.i6GKi2Ev004737@hecky.it.northwestern.edu> I've put in an error catch in a program to alert me when the equations I'm trying to solve have an error. Basically, if the sum of contributions to something does not equal 1, it should print out an error message (I don't plan on keeping this in my code, since it's bulky and outputs a bunch of stuff to the screen, but I wanted to make sure everything was working correctly). But I'm getting an error message when it *does* equal 1. Here's the code: diet=resize(base, (max,1)) for i in range(max): for j in range(max): diet[i,0]+=web[i,j] for i in range(max): if diet[i,0]<1.0 and i+1 not in Basal: print "wij for ", i+1, "has an error!" print diet Just to double-check that my check was working, I printed "diet" at the end. Then when I run it, I get: wij for 1 has an error! wij for 2 has an error! wij for 3 has an error! wij for 4 has an error! wij for 5 has an error! wij for 6 has an error! wij for 7 has an error! wij for 12 has an error! wij for 13 has an error! wij for 14 has an error! wij for 15 has an error! wij for 21 has an error! wij for 22 has an error! wij for 27 has an error! wij for 28 has an error! wij for 43 has an error! wij for 54 has an error! wij for 57 has an error! wij for 58 has an error! wij for 61 has an error! wij for 63 has an error! wij for 79 has an error! wij for 83 has an error! [[ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 0.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] [ 1.] (I didn't print out the whole thing, just enough to show it's not working). Obviously, since diet[0,0]=1, I should not get the error message: wij for 1 has an error! Any ideas out there? I thought it might be a float/integer problem, but everything is in floats, so I'm stumped. Thanks! Carla A. Ng =================================== Northwestern University Department of Chemical and Biological Engineering 2145 North Sheridan Road Evanston, IL 60208 Phone: (847)467-4980 Fax: (847)491-4011 =================================== "When one tugs at a single thing in nature, he finds it attached to the rest of the world." -- John Muir From magnus at thinkware.se Fri Jul 16 22:59:14 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 16 22:55:32 2004 Subject: [Tutor] Re: Please critique my guessing game program. In-Reply-To: References: <20040713193653.67bb24fb@localhost> Message-ID: <5.2.1.1.0.20040716224843.02916e58@www.thinkware.se> At 16:45 2004-07-16 +0100, Matt Smith wrote: >Hi, >I've changed the program further to account for the help and suggestions >I've recieved. I think this version is structured in a more logical way >and should also be impossible to crash through inputing the wrong answer. >Please let me know what you think and if the program could be improved in >anyway. It seems redundant to use both "playagain" and "playagain" >I have greatly enjoyed writing my first Python program. I hope you will enjoy writing a lot more programs soon! >playagainflag = 1 >while playagainflag == 1: [snip] > playagain = raw_input("Do you want to play again? (y/n) ") > if playagain == "y" or playagain == "Y": > playagainflag = 1 > else: > playagainflag = 0 I'd just do... playagain = 'y' while playagain.lower() == 'y': [snip] playagain = raw_input("Do you want to play again? (y/n) ") ...and skip all the use of that flag variable. Another solution which is seen fairly often in Python is to do it like this: while True: [snip] if raw_input("Do you want to play again? (y/n) ").lower() != 'y': break It might possibly be prettier to make that into... while True: [snip] if stop_playing(): break ...and define stop_playing as a separate function with the raw_input or whatever. But that really only makes sense if the rest of the actual user interaction is removed from the logic as well. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From dyoo at hkn.eecs.berkeley.edu Fri Jul 16 23:00:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 16 23:00:43 2004 Subject: [Tutor] when 1 is not equal to 1...?? In-Reply-To: <200407162043.i6GKhq7l004573@hecky.it.northwestern.edu> Message-ID: On Fri, 16 Jul 2004, Carla A. Ng wrote: > I've put in an error catch in a program to alert me when the equations > I'm trying to solve have an error. > > Basically, if the sum of contributions to something does not equal 1, it > should print out an error message (I don't plan on keeping this in my > code, since it's bulky and outputs a bunch of stuff to the screen, but I > wanted to make sure everything was working correctly). But I'm getting > an error message when it *does* equal 1. Hi Carla, You may be running into floating point representation errors: http://www.python.org/doc/tut/node15.html http://www.lahey.com/float.htm It's in the nature of floating-point that it's inexact. Whenever we're doing some kind of numerical method with floating point numbers, instead of comparing floating point numbers for exact equality, we may need to compare with some kind of "tolerance" in mind. (Trivia: in fact, some programming languages just won't allow an the equality-check between floating point numbers; Standard ML is one example of a language that disallows comparing floats for equality.) Anyway, I'd recommend using a small routine to check for equality within a tolerable epsilon: ### def closeEnough(a, b, tolerance=0.0001): """Returns true if 'a' and 'b' are close enough to each other.""" return abs(a-b) < tolerance ### Hope this helps! From missive at hotmail.com Fri Jul 16 23:40:18 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Jul 16 23:40:22 2004 Subject: [Tutor] Re: removing line ends from Word text files Message-ID: >Right now I have the problem that I want to remove the MS Word line end >token from text files: When saving a text file as 'text only' line ends >are displayed as '^M' in a shell (SGI IRIX (tcsh) and Mac (tcsh or >bash)). I want to get rid of these elements for further processing of >the file and have no idea how to access them in a Python script. Any >idea how to replace the '^M' against a simple '\n'? (I already tried >'\r\n' and various other combinations of characters, but apparently all >aren't '^M'.) '^M' is one character. > >As supplementary information: I'm using MacOSX (version 10.3.4) with >Python 2.3 or SGI Irix with Python 2.1.1 . > See if your systems have a script called dos2unix. That is the one that I always use when I get one of those dossy files. If you cannot find that, try searching through the lines for characters around ord(10) ord(11) ord(12) ord(13) as I am pretty sure that ^M is somewhere in there... _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From missive at hotmail.com Fri Jul 16 23:43:12 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Jul 16 23:43:16 2004 Subject: [Tutor] Re: CGI Message-ID: >Is it possible to create a common gateway interface in python? http://python.org/doc/current/lib/module-cgi.html (plus about 2 dozen other ways that don't involve "cgi" directly) >If it is how >do i submit data to it using vbscript? What is vbscript? _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From chris.irish at libertydistribution.com Sat Jul 17 01:35:09 2004 From: chris.irish at libertydistribution.com (Chris Irish) Date: Sat Jul 17 01:35:20 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> References: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> Message-ID: <40F8662D.7060401@libertydistribution.com> Dick Moores wrote: > I was just fooling around writing a script (below) that would show how > fast my computer can count. I was pleased with the speed, but dismayed > that counting to a mere 15 or 20 million reduced available memory from > about 300 to close to zero, forcing a reboot; and sometimes upon > rebooting I would find some important Win XP settings changed. Do I > have to get a CS degree to understand what's going on? Or can someone > point me to an explanation? > > Some results: > 0 to 9999999 in 7.641 seconds! > 0 to 1000000 in 0.766 seconds! > 0 to 100000 in 0.078 seconds! > 0 to 50000 in 0.031 seconds! > 0 to 10000 in 0.000 seconds! > On my Powerbook G4 @ 1Ghz with 1 GB SDRAM it took me 228.033 seconds to count to 50 million.......Cool Does anyone have a 2.5 Ghz or faster P4 that can run Dick's program? I'm curious to just how much faster those newer processors really are from Intel :) Thanks Chris From marvboyes at att.net Sat Jul 17 01:50:51 2004 From: marvboyes at att.net (Marv Boyes) Date: Sat Jul 17 01:51:09 2004 Subject: [Tutor] Tkinter: checking a Text widget for contents/changes Message-ID: <40F869DB.4070800@att.net> Hello, everyone. I'm hoping I can get an answer to this without having to burden all of you with a lengthy code-paste. :) I'm working on a simple text-editing application, and would like to include a function to ask the user to save changes before quitting. Can anyone describe a method for checking to see if anything has been entered into a Text widget's buffer (or, ideally, to check for changes since the last save)? I'm pretty sure I already have all the other pieces I need to make it work. Any guidance would be greatly appreciated; thanks very much 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 nick at javacat.f2s.com Sat Jul 17 02:02:35 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sat Jul 17 02:01:25 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <40F8662D.7060401@libertydistribution.com> Message-ID: Hi Chris, My setup is Athlon 3200+ Barton with 1GB RAM, my bios recognises this as approx 2.2Ghz. Also my motherboard runs at 400Mhz FSB. using range(50000000): 18.281 seconds using xrange(50000000): 13.516 seconds You sure you didnt type in 500000000 ;) So xrange is definitely quicker. Is it better to use xrange all the time in place of range then ? Regards Nick. -----Original Message----- From: tutor-bounces+nick=javacat.f2s.com@python.org [mailto:tutor-bounces+nick=javacat.f2s.com@python.org]On Behalf Of Chris Irish Sent: 17 July 2004 00:35 To: Dick Moores Cc: tutor@python.org Subject: Re: [Tutor] Why does counting to 20 million stress my computer? Dick Moores wrote: > I was just fooling around writing a script (below) that would show how > fast my computer can count. I was pleased with the speed, but dismayed > that counting to a mere 15 or 20 million reduced available memory from > about 300 to close to zero, forcing a reboot; and sometimes upon > rebooting I would find some important Win XP settings changed. Do I > have to get a CS degree to understand what's going on? Or can someone > point me to an explanation? > > Some results: > 0 to 9999999 in 7.641 seconds! > 0 to 1000000 in 0.766 seconds! > 0 to 100000 in 0.078 seconds! > 0 to 50000 in 0.031 seconds! > 0 to 10000 in 0.000 seconds! > On my Powerbook G4 @ 1Ghz with 1 GB SDRAM it took me 228.033 seconds to count to 50 million.......Cool Does anyone have a 2.5 Ghz or faster P4 that can run Dick's program? I'm curious to just how much faster those newer processors really are from Intel :) Thanks Chris _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From klappnase at freenet.de Sat Jul 17 02:50:31 2004 From: klappnase at freenet.de (Michael Lange) Date: Sat Jul 17 02:53:20 2004 Subject: [Tutor] ComboBox with Tkinter In-Reply-To: <001401c462ca$7994d790$d101a8c0@pukispc> References: <001401c462ca$7994d790$d101a8c0@pukispc> Message-ID: <20040717025031.55a8a1c8.klappnase@freenet.de> On Mon, 5 Jul 2004 21:58:42 +0200 "Puki" wrote: Hi Puki, > > and I thought a combobox should act the same way: > self.cb = Combobox(frame7, -1, choices['choice1','choice2'], value= > 'combobox')??? > > unfortunately there is no combobox widget in the standard Tkinter module; there are two extensions for Tkinter that have comboboxes (and many other extra widgets) for Tkinter: Pmw () is completely written in Python and therefore it is no problem to install it on any system with a running Python/Tkinter and it's very well documented. Tix () is (in my opinion) a little nicer than Pmw and more powerful but it was written for tcl/tk in the first place, so it must be compiled first and may therefore be problematic to install at least on windows (on linux it should be already included in the distribution). Tix doesn't also come with such a nice manual as Pmw, so maybe Pmw might be the better choice for a start. If you need some documentation for the standard Tkinter module you can start with Frederic Lundh's excellent "Introduction to Tkinter" () I hope this helps Michael From missive at hotmail.com Sat Jul 17 03:37:49 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Jul 17 03:37:53 2004 Subject: [Tutor] Re: removing line ends from Word text files Message-ID: >>See if your systems have a script called dos2unix. That is the one >>that I always use when I get one of those dossy files. >> >>If you cannot find that, try searching through the lines for characters >>around ord(10) ord(11) ord(12) ord(13) as I am pretty sure that ^M >>is somewhere in there... >Do you mean chr(10-12)? Ord() takes in a character and outputs an integer. >Chr() does the opposite. > wups. yep. sorry 'bout that. Guess I probably meant something like ord(c)==10 orc(c)==11 ... _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From orbitz at ezabel.com Sat Jul 17 03:42:12 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Jul 17 03:42:31 2004 Subject: [Tutor] Re: CGI In-Reply-To: References: Message-ID: <40F883F4.5080400@ezabel.com> Using CGI is generally a waste of time. I'd suggest lokign into twisted at twistedmatrix.com aswell as nevow which can be found at www.divmod.org (maybe .com) Lee Harr wrote: >> Is it possible to create a common gateway interface in python? > > > http://python.org/doc/current/lib/module-cgi.html > (plus about 2 dozen other ways that don't involve "cgi" directly) > > >> If it is how >> do i submit data to it using vbscript? > > > What is vbscript? > > _________________________________________________________________ > MSN 8 with e-mail virus protection service: 2 months FREE* > http://join.msn.com/?page=features/virus > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cspears2002 at yahoo.com Sat Jul 17 04:12:14 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Sat Jul 17 04:12:17 2004 Subject: [Tutor] taking Python to next level Message-ID: <20040717021214.50367.qmail@web51605.mail.yahoo.com> I completed an online course a few months ago that was a pretty good general introduction to Python. I want to take my Python programming to the next level and start tackling more advanced programming topics. The book used for the online class was "The Quick Python Book" by Harms and McDonald. I downloaded "Dive Into Python" and might starting reading that. Any suggestions? ===== "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter From orbitz at ezabel.com Sat Jul 17 04:54:11 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Jul 17 04:54:20 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <20040717021214.50367.qmail@web51605.mail.yahoo.com> References: <20040717021214.50367.qmail@web51605.mail.yahoo.com> Message-ID: <40F894D3.40508@ezabel.com> Dive into python is good. Python is also distinct from other languages in that reading other peoples code is actually helpful, usually. I read Quotient source and twisted source when I need to look at possible ways to implement specific things. Christopher Spears wrote: >I completed an online course a few months ago that was >a pretty good general introduction to Python. I want >to take my Python programming to the next level and >start tackling more advanced programming topics. The >book used for the online class was "The Quick Python >Book" by Harms and McDonald. I downloaded "Dive Into >Python" and might starting reading that. Any suggestions? > >===== >"I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." >-David Bowie > >"Who dares wins" >-British military motto > >"The freak is the norm." - "The Infernal Desire Machines of Dr. Hoffman" by Angela Carter >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From rdm at rcblue.com Sat Jul 17 05:17:50 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 17 05:17:54 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: References: <5.2.1.1.0.20040716130642.02892ea8@www.thinkware.se> Message-ID: <6.1.2.0.2.20040716195938.0569d788@rcblue.com> Danny Yoo wrote at 10:21 7/16/2004: >An alternative solution is to use a while-loop, something like: > >### >counter = 0 >while counter < 10: > print "counter is:", counter > counter = counter + 1 >### > > >Using range() on large numbers is a common gotcha, so don't worry too much >about not knowing about xrange(). There are a few things that work >perfectly well on small things, but break down when the problem grows much >larger; range() is one of those. Thanks, Danny. I found an egregious error in the spin.py I posted earlier. It had k being augmented inside the range() loop. I took this line out, used xrange() instead of range(), and for a speed comparison, added the loop you suggested as another way. Here are some results: integer: 1000000 (1,000,000) Counting.. 0 to 1000000 in 0.141 seconds! And now counting using a different loop.. 0 to 1000000 in 0.406 seconds! integer: 10000000 (10,000,000) Counting.. 0 to 10000000 in 1.500 seconds! And now counting using a different loop.. 0 to 10000000 in 4.016 seconds! integer: 50000000 (50,000,000) Counting.. 0 to 50000000 in 7.188 seconds! And now counting using a different loop.. 0 to 50000000 in 19.110 seconds! integer: 100000000 (100,000,000) Counting.. 0 to 100000000 in 15.078 seconds! And now counting using a different loop.. 0 to 100000000 in 40.204 seconds! integer: 1000000000 (1,000,000,000) Counting.. 0 to 1000000000 in 148.859 seconds! And now counting using a different loop.. 0 to 1000000000 in 397.484 seconds! Here's some info on my Dell desktop (thanks to Belarc Advisor): 2.80 gigahertz Intel Pentium 4 8 kilobyte primary memory cache 512 kilobyte secondary memory cache Bus Clock: 533 megahertz 512 Megabytes Installed Memory ======================================= #spin2.py import time print """ Enter an integer to count to from zero. To quit, enter x or q. """ while True: # for exiting via ^C or ^D try: max = raw_input("integer: ") except (TypeError, EOFError): print "Bye." break if len(max) == 0: print "Hey, don't just hit Enter, type an integer first!" continue if max in ["q", "x"]: print "Bye." break try: max = int(max) + 1 except: print "That's not an integer!" continue print "Counting.." tStart = time.time() for k in xrange(max): pass tEnd = time.time() print "0 to %d in %.3f seconds!" % (k, (tEnd - tStart)) print "And now counting using a different loop.." c = 0 tStart = time.time() while c < max -1 : c += 1 tEnd = time.time() print "0 to %d in %.3f seconds!" % (c, (tEnd - tStart)) ================================ From rdm at rcblue.com Sat Jul 17 05:34:55 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 17 05:35:00 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <40F894D3.40508@ezabel.com> References: <20040717021214.50367.qmail@web51605.mail.yahoo.com> <40F894D3.40508@ezabel.com> Message-ID: <6.1.2.0.2.20040716203333.05005608@rcblue.com> orbitz wrote at 19:54 7/16/2004: >Dive into python is good. Python is also distinct from other languages >in that reading other peoples code is actually helpful, usually. I read >Quotient source and twisted source when I need to look at possible ways >to implement specific things. I'm eager to do this. Please post the URLs for these. Thanks, Dick Moores From rdm at rcblue.com Sat Jul 17 05:50:45 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 17 05:50:48 2004 Subject: [Tutor] ComboBox with Tkinter In-Reply-To: <20040717025031.55a8a1c8.klappnase@freenet.de> References: <001401c462ca$7994d790$d101a8c0@pukispc> <20040717025031.55a8a1c8.klappnase@freenet.de> Message-ID: <6.1.2.0.2.20040716203945.04b95100@rcblue.com> Michael Lange wrote at 17:50 7/16/2004: >If you need some documentation for the standard Tkinter module you can >start with Frederic Lundh's >excellent "Introduction to Tkinter" >() "last update: Dec 10, 1999" No problem? For example, I just ran his hello2.py. The Hello button works, but the Quit button doesn't quit. Or maybe I don't understand even enough to run these things. I have Python 2.3.4. =================================== # File: hello2.py # from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() ========================================= Dick Moores From bill.mill at gmail.com Sat Jul 17 05:56:13 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sat Jul 17 05:56:16 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <6.1.2.0.2.20040716203333.05005608@rcblue.com> References: <20040717021214.50367.qmail@web51605.mail.yahoo.com> <40F894D3.40508@ezabel.com> <6.1.2.0.2.20040716203333.05005608@rcblue.com> Message-ID: <797fe3d4040716205657d34577@mail.gmail.com> google is your friend. quotient: http://www.divmod.org/Home/Projects/Quotient/ twisted: http://www.twistedmatrix.com/ Peace Bill Mill On Fri, 16 Jul 2004 20:34:55 -0700, Dick Moores wrote: > orbitz wrote at 19:54 7/16/2004: > >Dive into python is good. Python is also distinct from other languages > >in that reading other peoples code is actually helpful, usually. I read > >Quotient source and twisted source when I need to look at possible ways > >to implement specific things. > > I'm eager to do this. Please post the URLs for these. > > Thanks, > > Dick Moores > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Sat Jul 17 09:01:42 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 17 09:01:47 2004 Subject: [Tutor] Want to use msvcrt.getch() but can't import msvcrt Message-ID: <6.1.2.0.2.20040716234123.04656640@rcblue.com> A week ago or so I asked how I might enable pausing my timer.py. Alan Gauld suggested looking at the mscvrt module (which is available for Windows) and mscvrt.getch(). He also referred me to a page of his tutorial, This seems to be just what I'm looking for, but when I import mscvrt I get "ImportError: No module named mscvrt". So I can't even run the scripts on his page. For your instructing convenience here's a bare-bones version of my timer: ============================= #timer_simple.py import time #import mscvrt # gets "ImportError: No module named mscvrt" secondsToTime = int(raw_input("Seconds: ")) timeStart = time.time() timeNow = 0 while True: time.sleep(.25) timeNow = time.time() secondsPassed = timeNow - timeStart secondsLeft = secondsToTime - secondsPassed if secondsPassed >= secondsToTime: break print "TIME'S UP! %d seconds have passed" % secondsToTime print "Actual time is %f" % (timeNow - timeStart) ================================== Alan suggested the time.sleep(.25) line to slow the loop down so I can do something else with my computer while using the timer. He said to create a "guard condition" by making the timeNow = time.time() line into an if statement. If was able to import mscvrt and use mscvrt.getch() I suppose I could figure this out by experimenting, but I can't even do that. I'd also like to build in a way to stop the time in mid-timing, without resort to ^C or ^D. I suppose getch() is the thing to use here also. BTW I'm using Python 2.3.4 on Windows XP. Do I need to download the mscvrt from somewhere? Help, please? Thanks, tutors. Dick Moores From python at bernardlebel.com Sat Jul 17 10:45:13 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Jul 17 09:43:34 2004 Subject: [Tutor] Re: CGI References: Message-ID: <001201c46bda$62595240$0095fea9@atyss> > What is vbscript? It's Microsoft's Visual Basic, scripting edition. It is activeX enabled. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/vbstutor.asp Cheers Bernard From alipolatel at yahoo.com Sat Jul 17 12:08:06 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Jul 17 12:08:09 2004 Subject: [Tutor] Problem with exe file Message-ID: <20040717100806.7935.qmail@web61009.mail.yahoo.com> Dear Friends, I wrote a simple programme with python then have changed it into an exe file with py2exe. but it doesn't work in computers where python is not installed. What should I do to make it work independently? Regards --------------------------------- Do you Yahoo!? Vote for the stars of Yahoo!'s next ad campaign! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040717/5c908d4b/attachment.htm From magnus at thinkware.se Sat Jul 17 13:27:52 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Jul 17 13:23:51 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <20040717021214.50367.qmail@web51605.mail.yahoo.com> Message-ID: <5.2.1.1.0.20040717132353.029098e0@www.thinkware.se> At 19:12 2004-07-16 -0700, Christopher Spears wrote: >I completed an online course a few months ago that was >a pretty good general introduction to Python. I want >to take my Python programming to the next level and >start tackling more advanced programming topics. The >book used for the online class was "The Quick Python >Book" by Harms and McDonald. I downloaded "Dive Into >Python" and might starting reading that. Any suggestions? A few good paper books are "Python in a Nutshell" and "Python Cookbook". Depending on where you are heading, there are other books such as "Python Web Programming" or "Text Processing in Python" you might want to read. Text Processing in Python can be found on-line at http://gnosis.cx/TPiP/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From Janssen at rz.uni-frankfurt.de Sat Jul 17 15:55:50 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat Jul 17 15:55:57 2004 Subject: [Tutor] removing line ends from Word text files In-Reply-To: References: Message-ID: On Fri, 9 Jul 2004, Christian Meesters wrote: > Right now I have the problem that I want to remove the MS Word line end > token from text files: When saving a text file as 'text only' line ends > are displayed as '^M' in a shell (SGI IRIX (tcsh) and Mac (tcsh or > bash)). I want to get rid of these elements for further processing of > the file and have no idea how to access them in a Python script. Any > idea how to replace the '^M' against a simple '\n'? (I already tried > '\r\n' and various other combinations of characters, but apparently all > aren't '^M'.) '^M' is one character. You can allways ask Python when you want to know how it will represent this character: Read one line with "readline" and print its repr-string: fo = open("filename") line = fo.readline() print repr(line) repr gives you an alternative string representation of any objects. repr used on strings doesn't interpret backslash sequences like \n or \r. As you are on MAC, I would guess your newline character is a simple "\r". you can also ask Python for the caracter's ordinal print ord(line[-2]) # just in case one newline consists of two chars print ord(line[-1]) It's probably best to do such investigations with an interactive Python session. But now since I've realized that readline is Unix-only, I don't think interactive mode is that much fun on MAC/Win: without readline you can't repeat your commands (without having to type them again and again). You can't use the cursor keys. Perhaps Idle offers elaborate line editing even on those systems. regards Michael From pythonTutor at venix.com Sat Jul 17 17:05:48 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Jul 17 17:05:53 2004 Subject: [Tutor] Re: CGI In-Reply-To: <40F883F4.5080400@ezabel.com> References: <40F883F4.5080400@ezabel.com> Message-ID: <1090076748.2142.9.camel@laptop.venix.com> On Fri, 2004-07-16 at 21:42, orbitz wrote: > Using CGI is generally a waste of time. I think that's a little extreme. CGI is a standard that is available from any hosting service. Also, CGI is adequate for many kinds of interactions. Twisted is terrific at what it does, but can be overkill for some situations. > I'd suggest lokign into twisted > at twistedmatrix.com aswell as nevow which can be found at > www.divmod.org (maybe .com) > > > Lee Harr wrote: > > >> Is it possible to create a common gateway interface in python? > > > > > > http://python.org/doc/current/lib/module-cgi.html > > (plus about 2 dozen other ways that don't involve "cgi" directly) > > > > > >> If it is how > >> do i submit data to it using vbscript? > > > > > > What is vbscript? > > > > _________________________________________________________________ > > MSN 8 with e-mail virus protection service: 2 months FREE* > > http://join.msn.com/?page=features/virus > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > 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 klappnase at freenet.de Sat Jul 17 17:18:47 2004 From: klappnase at freenet.de (Michael Lange) Date: Sat Jul 17 17:21:38 2004 Subject: [Tutor] ComboBox with Tkinter In-Reply-To: <6.1.2.0.2.20040716203945.04b95100@rcblue.com> References: <001401c462ca$7994d790$d101a8c0@pukispc> <20040717025031.55a8a1c8.klappnase@freenet.de> <6.1.2.0.2.20040716203945.04b95100@rcblue.com> Message-ID: <20040717171847.63174d44.klappnase@freenet.de> On Fri, 16 Jul 2004 20:50:45 -0700 Dick Moores wrote: > "last update: Dec 10, 1999" > > No problem? > I know, it's a little outdated, but for the most part it's still o.k. The parts that have changed since 1999 mostly affect a couple of new widgets in the standard library (LabelFrame, PanedWidget, OptionMenu...) and some new options that were added (like the "compound" option for labels and buttons) but everything (or at least almost everything) from this book should still work. Frederic Lundh is currently working on an updated version of this document: but it's not yet as complete as the old version. > For example, I just ran his hello2.py. The Hello button works, but the > Quit button doesn't quit. Or maybe I don't understand even enough to run > these things. I have Python 2.3.4. > > =================================== > # File: > hello2.py > # > > from Tkinter import * > > class App: > > def __init__(self, master): > > frame = Frame(master) > frame.pack() > > self.button = Button(frame, text="QUIT", fg="red", > command=frame.quit) > self.button.pack(side=LEFT) > > self.hi_there = Button(frame, text="Hello", command=self.say_hi) > self.hi_there.pack(side=LEFT) > > def say_hi(self): > print "hi there, everyone!" > > root = Tk() > > app = App(root) > > root.mainloop() > ========================================= > This works fine for me; maybe you tried to run it from within IDLE? It's a special IDLE issue that using the quit() method does not work; quit() exits Tk's mainloop, and the problem is that IDLE runs inside the mainloop itself. Best regards Michael From david at graniteweb.com Sat Jul 17 18:54:33 2004 From: david at graniteweb.com (David Rock) Date: Sat Jul 17 18:54:37 2004 Subject: [Tutor] removing line ends from Word text files In-Reply-To: References: Message-ID: <20040717165433.GA7187@wdfs.attbi.com> * Michael Janssen [2004-07-17 15:55]: > On Fri, 9 Jul 2004, Christian Meesters wrote: > > > Right now I have the problem that I want to remove the MS Word line end > > token from text files: When saving a text file as 'text only' line ends > > are displayed as '^M' in a shell (SGI IRIX (tcsh) and Mac (tcsh or > > bash)). I want to get rid of these elements for further processing of > > the file and have no idea how to access them in a Python script. Any > > idea how to replace the '^M' against a simple '\n'? (I already tried > > '\r\n' and various other combinations of characters, but apparently all > > aren't '^M'.) '^M' is one character. > > You can allways ask Python when you want to know how it will represent > this character: Read one line with "readline" and print its repr-string: > > fo = open("filename") > line = fo.readline() > print repr(line) > > repr gives you an alternative string representation of any objects. repr > used on strings doesn't interpret backslash sequences like \n or \r. As > you are on MAC, I would guess your newline character is a simple "\r". > > you can also ask Python for the caracter's ordinal > print ord(line[-2]) # just in case one newline consists of two chars > print ord(line[-1]) > > It's probably best to do such investigations with an interactive Python > session. But now since I've realized that readline is Unix-only, I don't > think interactive mode is that much fun on MAC/Win: without readline you > can't repeat your commands (without having to type them again and again). > You can't use the cursor keys. Perhaps Idle offers elaborate line editing > even on those systems. OK, a couple things... readline is NOT a Unix-only thing. I just tried it on my XP box and it's fine. open is also an older way of doing things with opening files, as of 2.2, file is probably what you want. http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-25 and for the sake of completeness, here is the info about built-in file objects: http://www.python.org/doc/current/lib/bltin-file-objects.html So this: fo = open("filename") line = fo.readline() print repr(line) becomes this: fo = file("filename") line = fo.readline() print repr(line) as for interactive Python, I have recently been introduced to ipython and it's great. It has a LOT of features that aren't in the normal shell: http://ipython.scipy.org/ And finally, ^M is decimal 13 (hex 0D), \n is 10, and \r is 13 ... hmm, I guess that means ^M == \r One thing that I have used over the years to strip newline chars off lines is this, it's not the prettiest, but you'll get the idea: if '\n' in line: line = line[:-1] if '\r' in line: line = line[:-1] basically, it's assuming (in the case of Windows) that the file ends with '\r\n', and strips them off one at a time. -- 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/20040717/7ebf04f4/attachment.pgp From tim.peters at gmail.com Sat Jul 17 19:16:48 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat Jul 17 19:16:51 2004 Subject: [Tutor] Want to use msvcrt.getch() but can't import msvcrt In-Reply-To: <6.1.2.0.2.20040716234123.04656640@rcblue.com> References: <6.1.2.0.2.20040716234123.04656640@rcblue.com> Message-ID: <1f7befae04071710164d9630e3@mail.gmail.com> [Dick Moores] > A week ago or so I asked how I might enable pausing my timer.py. Alan > Gauld suggested looking at the mscvrt module (which is available for > Windows) and mscvrt.getch(). He also referred me to a page of his > tutorial, > > This seems to be just what I'm looking for, but when I import mscvrt I get > "ImportError: No module named mscvrt" Get ready to kick yourself . >>> import mscvrt # no good Traceback (most recent call last): File "", line 1, in ? ImportError: No module named mscvrt >>> import msvcrt # good >>> The name only makes sense to hard-core Windows geeks; it's short for MicroSoft Visual C Runtime, and exposes some function specific to Microsoft's Visual C runtime libraries. From dyoo at hkn.eecs.berkeley.edu Sat Jul 17 20:36:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 17 20:36:35 2004 Subject: [Tutor] Problem with exe file In-Reply-To: <20040717100806.7935.qmail@web61009.mail.yahoo.com> Message-ID: On Sat, 17 Jul 2004, Ali Polatel wrote: > I wrote a simple programme with python then have changed it into an exe > file with py2exe. but it doesn't work in computers where python is not > installed. Hi Ali, This is strange! py2exe is supposed to create executables that can be run on a machine without Python. According to: http://py2exe.sourceforge.net/ py2exe is usually smart enough to figure out what things need to be included in the executable. Let's try duplicating the problem. Do you mind showing us the program you tried to create as an EXE, as well as the 'setup.py' file that you fed into py2exe? From dyoo at hkn.eecs.berkeley.edu Sat Jul 17 20:47:40 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 17 20:47:44 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: Message-ID: > using range(50000000): 18.281 seconds > using xrange(50000000): 13.516 seconds > > You sure you didnt type in 500000000 ;) > > So xrange is definitely quicker. Is it better to use xrange all the time > in place of range then ? Hi Nick, It depends on what we need. *grin* xrange() returns an iterable object that's wonderful if we want to go through the integers in order, one at a time. But say we wanted to do something, like grab a randomized list of numbers: ### >>> import random >>> numbers = range(52) >>> random.shuffle(numbers) >>> numbers [1, 43, 18, 48, 47, 0, 46, 36, 13, 9, 20, 27, 42, 45, 10, 26, 19, 38, 16, 35, 25, 32, 17, 22, 23, 29, 6, 41, 14, 30, 15, 40, 50, 28, 3, 49, 12, 39, 5, 11, 33, 4, 34, 37, 24, 21, 2, 7, 8, 51, 31, 44] ### In this case, range() is a good tool for this job, because it gives us a list that we can munge up with random.shuffle(). xrange() gives us just an iterable that's specialized only to do sequential counting, so it wouldn't be as appropriate here. Personally, I usually do stick with range(), and completely disregard efficiency until I really need it. Hope this helps! From Dragonfirebane at aol.com Sat Jul 17 20:58:31 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jul 17 20:58:41 2004 Subject: [Tutor] msvcrt.getch() Message-ID: <46.535f3de6.2e2ad0d7@aol.com> Hello all, I was trying to set up a 'press any key to exit' mini-program similar to the one described here: http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/tutevent.htm, but there seemse to be an issue with msvcrt.getch() on my computer (Windows XP Home, Python Version 2.3.4 final, IDLE version 1.0.3) when I ran it on IDLE. When I just type [msvcrt.getch()] at the prompt, it returns '\xff' as shown below: >>> msvcrt.getch() '\xff' This means that when I try running the script described at the above website, a space does squat, as demonstrated below: >>> Hit space to end... 255 255 255 255 255 255 255 255 255 255 ... ##until i hit Control-C Traceback (most recent call last): File "C:/Documents and Settings/Cookie/Desktop/try.py", line 32, in ? doKeyEvent(key) File "C:/Documents and Settings/Cookie/Desktop/try.py", line 9, in doKeyEvent print ord(key) File "C:\PROGRA~1\lib\idlelib\PyShell.py", line 1128, in write self.shell.write(s, self.tags) File "C:\PROGRA~1\lib\idlelib\PyShell.py", line 1117, in write raise KeyboardInterrupt KeyboardInterrupt The spaces before the '255' are points when i tried to exit using a space. A minor detail about the script at the site: it doesn't work as is, so i added a colon after the if-else lines in the first module and changed all references to 'ky' to 'key' for consistency. Any ideas as to why this doesn't work? Thanks in advance, Orri P.S.: I just had a thought that perhaps it was something with IDLE, and since it *does* work on the Python command line, i suspect that there might be an issue with IDLE's way of handling msvcrt.getch(). 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/20040717/5405b05c/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Jul 17 21:10:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 17 21:10:29 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <40F894D3.40508@ezabel.com> Message-ID: On Fri, 16 Jul 2004, orbitz wrote: > Dive into python is good. Python is also distinct from other languages > in that reading other peoples code is actually helpful, usually. I have to agree with Dive into Python: it's an excellent book that covers a lot of advanced topics like XML parsing and Unit Testing. I have to argue with the second sentence, though. (Just slightly. *grin*) I feel that reading other people's code, in any programming language, is a good thing. There's a book called 'Code Reading': http://www.spinellis.gr/codereading/ that talks about the advantages of reading and understanding code; I'd wouldn't exclude it just because they don't use Python. Good code can be written in any language. (And it's not necessarily a bad thing to read "bad" code, either: we learn more quickly from mistakes than from successes.) > >I completed an online course a few months ago that was a pretty good > >general introduction to Python. I want to take my Python programming > >to the next level and start tackling more advanced programming topics. You might want to pick out an interesting project in SourceForge and fiddle around with someone's source code: http://sourceforge.net/index.php There's a whole section dedicated to projects that use Python: http://sourceforge.net/softwaremap/trove_list.php?form_cat=178 Playing with a project, one that that excites and interests you, should help to cement your Python knowledge. Good luck! From pythonTutor at venix.com Sat Jul 17 21:25:08 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Jul 17 21:25:14 2004 Subject: [Tutor] removing line ends from Word text files In-Reply-To: <20040717165433.GA7187@wdfs.attbi.com> References: <20040717165433.GA7187@wdfs.attbi.com> Message-ID: <1090092307.2119.9.camel@laptop.venix.com> On Sat, 2004-07-17 at 12:54, David Rock wrote: > * Michael Janssen [2004-07-17 15:55]: > > On Fri, 9 Jul 2004, Christian Meesters wrote: > > > > > Right now I have the problem that I want to remove the MS Word line end > > > token from text files: When saving a text file as 'text only' line ends > > > are displayed as '^M' in a shell (SGI IRIX (tcsh) and Mac (tcsh or > > > bash)). I want to get rid of these elements for further processing of > > > the file and have no idea how to access them in a Python script. Any > > > idea how to replace the '^M' against a simple '\n'? (I already tried > > > '\r\n' and various other combinations of characters, but apparently all > > > aren't '^M'.) '^M' is one character. > > > > You can allways ask Python when you want to know how it will represent > > this character: Read one line with "readline" and print its repr-string: > > > > fo = open("filename") > > line = fo.readline() > > print repr(line) > > > > repr gives you an alternative string representation of any objects. repr > > used on strings doesn't interpret backslash sequences like \n or \r. As > > you are on MAC, I would guess your newline character is a simple "\r". > > > > you can also ask Python for the caracter's ordinal > > print ord(line[-2]) # just in case one newline consists of two chars > > print ord(line[-1]) > > > > It's probably best to do such investigations with an interactive Python > > session. But now since I've realized that readline is Unix-only, I don't > > think interactive mode is that much fun on MAC/Win: without readline you > > can't repeat your commands (without having to type them again and again). > > You can't use the cursor keys. Perhaps Idle offers elaborate line editing > > even on those systems. > > OK, a couple things... > readline is NOT a Unix-only thing. I just tried it on my XP box and it's > fine. open is also an older way of doing things with opening files, as > of 2.2, file is probably what you want. I too was shifting from open(...) to file(...), however, Guido is recommending a change to the documentation and continued use of open. http://mail.python.org/pipermail/python-dev/2004-July/045931.html > > http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-25 > > and for the sake of completeness, here is the info about built-in file > objects: > http://www.python.org/doc/current/lib/bltin-file-objects.html > > So this: > fo = open("filename") > line = fo.readline() > print repr(line) > > becomes this: > fo = file("filename") > line = fo.readline() > print repr(line) > > as for interactive Python, I have recently been introduced to ipython > and it's great. It has a LOT of features that aren't in the normal > shell: > http://ipython.scipy.org/ > > And finally, ^M is decimal 13 (hex 0D), \n is 10, and \r is 13 ... > hmm, I guess that means ^M == \r > > One thing that I have used over the years to strip newline chars off > lines is this, it's not the prettiest, but you'll get the idea: > > if '\n' in line: > line = line[:-1] > if '\r' in line: > line = line[:-1] I think for c in "\r\n": if line.endswith(c): > > basically, it's assuming (in the case of Windows) that the file ends > with '\r\n', and strips them off one at a time. -- 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 Sat Jul 17 21:40:55 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Jul 17 21:41:01 2004 Subject: [Tutor] removing line ends from Word text files (continued) In-Reply-To: <20040717165433.GA7187@wdfs.attbi.com> References: <20040717165433.GA7187@wdfs.attbi.com> Message-ID: <1090093255.2119.26.camel@laptop.venix.com> (Continuing - the earlier post was an accident) On Sat, 2004-07-17 at 12:54, David Rock wrote: > * Michael Janssen [2004-07-17 15:55]: > > On Fri, 9 Jul 2004, Christian Meesters wrote: > > > > > Right now I have the problem that I want to remove the MS Word line end > > > token from text files: When saving a text file as 'text only' line ends > > > are displayed as '^M' in a shell (SGI IRIX (tcsh) and Mac (tcsh or > > > bash)). I want to get rid of these elements for further processing of > > > the file and have no idea how to access them in a Python script. Any (snipped) > > > > You can allways ask Python when you want to know how it will represent > > this character: Read one line with "readline" and print its repr-string: > > > > fo = open("filename") > > line = fo.readline() > > print repr(line) > > > > repr gives you an alternative string representation of any objects. repr > > used on strings doesn't interpret backslash sequences like \n or \r. As > > you are on MAC, I would guess your newline character is a simple "\r". > > > > you can also ask Python for the caracter's ordinal > > print ord(line[-2]) # just in case one newline consists of two chars > > print ord(line[-1]) > > > > It's probably best to do such investigations with an interactive Python > > session. But now since I've realized that readline is Unix-only, I don't > > think interactive mode is that much fun on MAC/Win: without readline you > > can't repeat your commands (without having to type them again and again). > > You can't use the cursor keys. Perhaps Idle offers elaborate line editing > > even on those systems. > > OK, a couple things... > readline is NOT a Unix-only thing. I just tried it on my XP box and it's > fine. open is also an older way of doing things with opening files, as > of 2.2, file is probably what you want. I too was shifting from open(...) to file(...), however, Guido is recommending a change to the documentation and continued use of open. http://mail.python.org/pipermail/python-dev/2004-July/045931.html > > http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-25 > > and for the sake of completeness, here is the info about built-in file > objects: > http://www.python.org/doc/current/lib/bltin-file-objects.html > (snipped) > > as for interactive Python, I have recently been introduced to ipython > and it's great. It has a LOT of features that aren't in the normal > shell: > http://ipython.scipy.org/ > > And finally, ^M is decimal 13 (hex 0D), \n is 10, and \r is 13 ... > hmm, I guess that means ^M == \r > > One thing that I have used over the years to strip newline chars off > lines is this, it's not the prettiest, but you'll get the idea: > > if '\n' in line: > line = line[:-1] > if '\r' in line: > line = line[:-1] I think while line[-1] in "\n\r": line = line[:-1] is much less risky depending upon the source of the file. Most of the time line = line.strip() # rstrip would do only trailing white space will do what you want. However, it strips ALL leading and trailing white space characters, not just the \r and \n at the end of the line. > > basically, it's assuming (in the case of Windows) that the file ends > with '\r\n', and strips them off one at a time. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From Dragonfirebane at aol.com Sat Jul 17 22:22:45 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Sat Jul 17 22:22:55 2004 Subject: [Tutor] alphabetizing a file by lines Message-ID: <1a1.26f90d2d.2e2ae495@aol.com> Hello all, I'm trying to write a program that alphabetizes a file by the first letter on each line. I'm having some problems because as soon as the program finds a letter, it looks for the next letter, ignoring subsequent appearances of that letter. I can think of a couple ways to fix this but none of them seem to work. The first of these would be to add a special character to lines that have already been alphabetized, but file.write() writes to the end of a file and i would need to write the character at the current position in the file. This might be circumvented by creating a file for each line that is alphabetized, but that seems a bit extreme . . . The code is below. Any suggestions would be appreciated. Future concerns will be alphabetizing past the first letter. ############## def linum(): global i linu = open("%s%s" % (fn, ext), "r") i = 0 for line in linu.readlines(): i += 1 linu.close() def alph(): alp = open("alphebatized%s%s" % (fn, ext), "w") pal = open("prealp%s%s" % (fn, ext), "w") ## eventually for writing "\xfe" after a line that has been alphabetized read = open("%s%s" % (fn, ext), "r") ## same reason for this line until read.close() for line in read.read(): pal.write(line) pal.close() read.close() print i for do in range(i): falp(alp) alp.close() def falp(alp): global a read = open("prealp%s%s" % (fn, ext), "r") for line in read.readlines(): try: alpn = re.compile("%s(?!\xfe)" % alpha[a], re.IGNORECASE) falpn = alpn.match(line) if falpn: print line alp.write(line) a += 1 break except IndexError: pass import re import string i = 0 a = 0 alpha = ' '.join(string.ascii_letters[:26]).split() fn = raw_input("Please enter name of file you wish to prioritize: ") ext = raw_input("Please enter extension of file you wish to prioritize: ") linum() alph() ################ Here is random.txt, the file being alphabetized: K cx c cd e X y v l f w Q z h r i T s p d m n a o j u b G 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/20040717/00ccd201/attachment.htm From orbitz at ezabel.com Sat Jul 17 22:33:08 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Jul 17 22:33:23 2004 Subject: [Tutor] alphabetizing a file by lines In-Reply-To: <1a1.26f90d2d.2e2ae495@aol.com> References: <1a1.26f90d2d.2e2ae495@aol.com> Message-ID: <40F98D04.80105@ezabel.com> lines = open(file).readlines() lines.sort() print lines Dragonfirebane@aol.com wrote: > Hello all, > > I'm trying to write a program that alphabetizes a file by the first > letter on each line. I'm having some problems because as soon as the > program finds a letter, it looks for the next letter, ignoring > subsequent appearances of that letter. I can think of a couple ways to > fix this but none of them seem to work. The first of these would be to > add a special character to lines that have already been alphabetized, > but file.write() writes to the end of a file and i would need to write > the character at the current position in the file. This might be > circumvented by creating a file for each line that is alphabetized, > but that seems a bit extreme . . . The code is below. Any suggestions > would be appreciated. Future concerns will be alphabetizing past the > first letter. > > ############## > def linum(): > global i > linu = open("%s%s" % (fn, ext), "r") > i = 0 > for line in linu.readlines(): > i += 1 > linu.close() > def alph(): > alp = open("alphebatized%s%s" % (fn, ext), "w") > pal = open("prealp%s%s" % (fn, ext), "w") ## eventually for > writing "\xfe" after a line that has been alphabetized > read = open("%s%s" % (fn, ext), "r") ## same reason > for this line until read.close() > for line in read.read(): > pal.write(line) > pal.close() > read.close() > print i > for do in range(i): > falp(alp) > alp.close() > def falp(alp): > global a > read = open("prealp%s%s" % (fn, ext), "r") > for line in read.readlines(): > try: > alpn = re.compile("%s(?!\xfe)" % alpha[a], re.IGNORECASE) > falpn = alpn.match(line) > if falpn: > print line > alp.write(line) > a += 1 > break > except IndexError: > pass > import re > import string > i = 0 > a = 0 > alpha = ' '.join(string.ascii_letters[:26]).split() > fn = raw_input("Please enter name of file you wish to prioritize: ") > ext = raw_input("Please enter extension of file you wish to prioritize: ") > linum() > alph() > ################ > > Here is random.txt, the file being alphabetized: > > K > cx > c > cd > e > X > y > v > l > f > w > Q > z > h > r > i > T > s > p > d > m > n > a > o > j > u > b > G > > Thanks in advance, > Orri > > Email: dragonfirebane@aol.com > AIM: singingxduck > Programming Python for the fun of it. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From bvande at po-box.mcgill.ca Sat Jul 17 23:28:22 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 17 23:28:50 2004 Subject: [Tutor] alphabetizing a file by lines In-Reply-To: <40F98D04.80105@ezabel.com> References: <1a1.26f90d2d.2e2ae495@aol.com> <40F98D04.80105@ezabel.com> Message-ID: <40F999F6.3020306@po-box.mcgill.ca> orbitz said unto the world upon 17/07/2004 16:33: > lines = open(file).readlines() > lines.sort() > print lines > > > Dragonfirebane@aol.com wrote: > >> Hello all, >> >> I'm trying to write a program that alphabetizes a file by the first >> letter on each line. I'm having some problems because as soon as the >> program finds a letter, it looks for the next letter, ignoring >> subsequent appearances of that letter. I can think of a couple ways to >> fix this but none of them seem to work. The first of these would be to >> add a special character to lines that have already been alphabetized, >> but file.write() writes to the end of a file and i would need to write >> the character at the current position in the file. This might be >> circumvented by creating a file for each line that is alphabetized, >> but that seems a bit extreme . . . The code is below. Any suggestions >> would be appreciated. Future concerns will be alphabetizing past the >> first letter. >> >> ############## >> def linum(): >> global i >> linu = open("%s%s" % (fn, ext), "r") >> i = 0 >> for line in linu.readlines(): >> i += 1 >> linu.close() >> def alph(): >> alp = open("alphebatized%s%s" % (fn, ext), "w") >> pal = open("prealp%s%s" % (fn, ext), "w") ## eventually for >> writing "\xfe" after a line that has been alphabetized >> read = open("%s%s" % (fn, ext), "r") ## same reason >> for this line until read.close() >> for line in read.read(): >> pal.write(line) >> pal.close() >> read.close() >> print i >> for do in range(i): >> falp(alp) >> alp.close() >> def falp(alp): >> global a >> read = open("prealp%s%s" % (fn, ext), "r") >> for line in read.readlines(): >> try: >> alpn = re.compile("%s(?!\xfe)" % alpha[a], re.IGNORECASE) >> falpn = alpn.match(line) >> if falpn: >> print line >> alp.write(line) >> a += 1 >> break >> except IndexError: >> pass >> import re >> import string >> i = 0 >> a = 0 >> alpha = ' '.join(string.ascii_letters[:26]).split() >> fn = raw_input("Please enter name of file you wish to prioritize: ") >> ext = raw_input("Please enter extension of file you wish to >> prioritize: ") >> linum() >> alph() >> ################ >> >> Here is random.txt, the file being alphabetized: >> >> K >> cx >> c >> cd >> e >> X >> y >> v >> l >> f >> w >> Q >> z >> h >> r >> i >> T >> s >> p >> d >> m >> n >> a >> o >> j >> u >> b >> G >> >> Thanks in advance, >> Orri >> >> Email: dragonfirebane@aol.com >> AIM: singingxduck >> Programming Python for the fun of it. Hi Orri and all, the advice at the top is good. The only thing I would add is that this will sort your lines by their entire contents and will perform a case sensitive sort. It seemed from your problem description that you wanted only the first letter taken into account regardless of case so that the lines: abc ABC azz acd would not be rearranged. Both the case-insensitivity and the consideration of just the first letter can easily be obtained by writing a custom compare function to pass in with the sort method call. The case insensitivity part can be accomplished like so: def alphabetical_sort(first, second): return cmp(first.lower(), second.lower()) (You could easily extend this to look at just the leading n-characters of the two strings being compared.) You'd use it like so: lines = open(file).readlines() lines.sort(alphabetical_sort) print lines Best, Brian vdB From pythonTutor at venix.com Sun Jul 18 01:13:56 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sun Jul 18 01:14:07 2004 Subject: [Tutor] alphabetizing a file by lines In-Reply-To: <1a1.26f90d2d.2e2ae495@aol.com> References: <1a1.26f90d2d.2e2ae495@aol.com> Message-ID: <1090106030.2119.42.camel@laptop.venix.com> You've gotten two suggestions for how to do this using Python's sorting abilities. I'm going to assume you are really just trying to do an exercise where you code more of the details. I think it would help if you started with a clearer statement of how you are accomplishing your task. After looking through the code I think this describes what you are trying to do: For each letter of the alphabet: For each line of the input file: if the line starts with this letter: write the line to the output file It should not be too hard to flesh those statements out into Python code. I think this kind of approach will help with organizing your code and untangling your loop logic. If these statements do not fit your intent, write your own statements and then write the program around them. On Sat, 2004-07-17 at 16:22, Dragonfirebane@aol.com wrote: > Hello all, > > I'm trying to write a program that alphabetizes a file by the first > letter on each line. I'm having some problems because as soon as the > program finds a letter, it looks for the next letter, ignoring > subsequent appearances of that letter. I can think of a couple ways to > fix this but none of them seem to work. The first of these would be to > add a special character to lines that have already been alphabetized, > but file.write() writes to the end of a file and i would need to write > the character at the current position in the file. This might be > circumvented by creating a file for each line that is alphabetized, > but that seems a bit extreme . . . The code is below. Any suggestions > would be appreciated. Future concerns will be alphabetizing past the > first letter. > > ############## > def linum(): > global i > linu = open("%s%s" % (fn, ext), "r") > i = 0 > for line in linu.readlines(): > i += 1 > linu.close() > def alph(): > alp = open("alphebatized%s%s" % (fn, ext), "w") > pal = open("prealp%s%s" % (fn, ext), "w") ## eventually for > writing "\xfe" after a line that has been alphabetized > read = open("%s%s" % (fn, ext), "r") ## same reason > for this line until read.close() > for line in read.read(): > pal.write(line) > pal.close() > read.close() > print i > for do in range(i): > falp(alp) > alp.close() > def falp(alp): > global a > read = open("prealp%s%s" % (fn, ext), "r") > for line in read.readlines(): > try: > alpn = re.compile("%s(?!\xfe)" % alpha[a], re.IGNORECASE) > falpn = alpn.match(line) > if falpn: > print line > alp.write(line) > a += 1 > break > except IndexError: > pass > import re > import string > i = 0 > a = 0 > alpha = ' '.join(string.ascii_letters[:26]).split() > fn = raw_input("Please enter name of file you wish to prioritize: ") > ext = raw_input("Please enter extension of file you wish to > prioritize: ") > linum() > alph() > ################ > > Here is random.txt, the file being alphabetized: > > K > cx > c > cd > e > X > y > v > l > f > w > Q > z > h > r > i > T > s > p > d > m > n > a > o > j > u > b > G > > > Thanks in advance, > Orri > > Email: dragonfirebane@aol.com > AIM: singingxduck > Programming Python for the fun of it. > > ______________________________________________________________________ > > _______________________________________________ > 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 Sun Jul 18 01:36:58 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 01:32:57 2004 Subject: [Tutor] alphabetizing a file by lines In-Reply-To: <40F999F6.3020306@po-box.mcgill.ca> References: <40F98D04.80105@ezabel.com> <1a1.26f90d2d.2e2ae495@aol.com> <40F98D04.80105@ezabel.com> Message-ID: <5.2.1.1.0.20040718010424.028e2830@www.thinkware.se> At 17:28 2004-07-17 -0400, Brian van den Broek wrote: >the advice at the top is good. The only thing I would add is that this >will sort your lines by their entire contents and will perform a case >sensitive sort. Another problem is that is has to read the whole file into memory at once. >It seemed from your problem description that you wanted only the first >letter taken into account regardless of case so that the lines: > >abc >ABC >azz >acd > >would not be rearranged. This is really good if the file is so large that you don't want to read it into memory at once. >Both the case-insensitivity and the consideration of just the first letter >can easily be obtained by writing a custom compare function to pass in >with the sort method call. > >The case insensitivity part can be accomplished like so: > >def alphabetical_sort(first, second): > return cmp(first.lower(), second.lower()) > >(You could easily extend this to look at just the leading n-characters of >the two strings being compared.) > >You'd use it like so: > >lines = open(file).readlines() >lines.sort(alphabetical_sort) >print lines the problem with this is that it's slow for big lists, since you have to call a Python function over and over from inside the sort function. The common approach is to do something like this. sort_list = [] for line in open(file): sort_list.append((line[0].lower(), line)) sort_list.sort() for first_char, line in sort_list: print line In the coming Python 2.4, there will be more features added to the sort method which will make this simpler. Here we still have a problem with large files, but if we only need to sort on the first character, that's easy to overcome. Just do something like this (untested) to store lines for each starting letter in a separate file and cat the files together in the end: files = {} def store(line): name = line[0].lower() if not name in files: f = open(name, 'w+') files[name] = f files[name].write(line+'\n') for line in open(file): line = line.rstrip() if line: store(line) file_names = files.keys() file_names.sort() big_file = open('big_file.txt', 'w') for file_name in file_names: files[file_name].seek(0) chunk = files[file_name].read() big_file.write(chunk) big_file.close() This approach never reads need to use up more memory than required for all lines starting with one letter. For a more memory conservative approach, make an inner loop in the last loop, and read one line at a time, or a few lines using something like files[file_name].readlines(100). If I recall correctly, Bentley's "Programming Pearls" has a chapter on something like this. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From ppareek at ualberta.ca Sun Jul 18 01:51:40 2004 From: ppareek at ualberta.ca (ppareek) Date: Sun Jul 18 01:42:44 2004 Subject: [Tutor] text processing by reading in a character at a time Message-ID: <40FA520D@webmail.ualberta.ca> Hi, I was wondering if anyone new an efficient way of reading in a character at a time from a file(I want to directly process a character from the file and not by reading in lines because I want to be able to access the postion of the character in the file) Thanks for the help, P From magnus at thinkware.se Sun Jul 18 02:05:55 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 02:01:53 2004 Subject: [Tutor] text processing by reading in a character at a time In-Reply-To: <40FA520D@webmail.ualberta.ca> Message-ID: <5.2.1.1.0.20040718014955.02927b18@www.thinkware.se> At 17:51 2004-07-17 -0600, ppareek wrote: >Hi, >I was wondering if anyone new an efficient way of reading in a character at a >time from a file(I want to directly process a character from the file and not >by reading in lines because I want to be able to access the postion of the >character in the file) It typically isn't efficient to read files one character at a time, but the simple way to do it is with "f.read(1)" (if f is your file object). It isn't exactly rocket science to access the position in the file even if you read more characters at a time. What are you trying to do? Do you understand how f.seek() and f.tell() works? For instance, if you want to modify a file, you can open it in 'rb+' mode, read it all into a string s, and do something like this to replace a certain character with another: f = open(file_name, 'rb+') s = f.read() for pos, char in enumerate(s): if char == myTarget: f.seek(pos) f.write(myValue) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sun Jul 18 02:48:08 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 02:44:17 2004 Subject: [Tutor] Want to use msvcrt.getch() but can't import msvcrt In-Reply-To: <1f7befae04071710164d9630e3@mail.gmail.com> References: <6.1.2.0.2.20040716234123.04656640@rcblue.com> <6.1.2.0.2.20040716234123.04656640@rcblue.com> Message-ID: <5.2.1.1.0.20040718024412.028bad88@www.thinkware.se> At 13:16 2004-07-17 -0400, Tim Peters wrote: >The name only makes sense to hard-core Windows geeks; it's short for >MicroSoft Visual C Runtime, and exposes some function specific to >Microsoft's Visual C runtime libraries. Apart from the fact that the abbreviation msvcrt isn't very readable, I think there are some key sequences that are easy to reverse on a qwerty keyboard, and turning 'vc' to 'cv' is one. The index finger is to short, so it looses the race so to say... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sun Jul 18 03:00:15 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 02:56:39 2004 Subject: [Tutor] taking Python to next level In-Reply-To: References: <40F894D3.40508@ezabel.com> Message-ID: <5.2.1.1.0.20040718024924.02920d88@www.thinkware.se> At 12:10 2004-07-17 -0700, Danny Yoo wrote: >On Fri, 16 Jul 2004, orbitz wrote: > > Dive into python is good. Python is also distinct from other languages > > in that reading other peoples code is actually helpful, usually. > >I have to argue with the second sentence, though. (Just slightly. >*grin*) I feel that reading other people's code, in any programming >language, is a good thing. There's a book called 'Code Reading': > > http://www.spinellis.gr/codereading/ > >that talks about the advantages of reading and understanding code; I'd >wouldn't exclude it just because they don't use Python. Good code can be >written in any language. Sure, but I agree with orbitz that it's more common that Python code you stumble over is "a good read" than code written in most other languages. This is probably both a consquence of Python itself and of the kind of programmers that the language attracts. It works both ways. Python is know for its readability and clarity. People who value readability and clarity in code are more likely to use Python than people who don't value these aspects highly. >(And it's not necessarily a bad thing to read "bad" code, either: we learn >more quickly from mistakes than from successes.) I'm not so sure about that. First of all, for a beginner who reads someone elses code, it's not so easy to know whether something is bad or good. Secondly, there are an infinite number of ways to write a program. Learning one way *not* to write doesn't seem very helpful. It's probably easy to spot problems in code if you know how to do things right, and it might be a pedagogical thing to do to demonstrate problems and failures, but I don't think it should be more than some "seasoning" on the meal of good idioms and techniques... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From david at graniteweb.com Sun Jul 18 03:12:50 2004 From: david at graniteweb.com (David Rock) Date: Sun Jul 18 03:12:52 2004 Subject: [Tutor] removing line ends from Word text files In-Reply-To: <1090092307.2119.9.camel@laptop.venix.com> References: <20040717165433.GA7187@wdfs.attbi.com> <1090092307.2119.9.camel@laptop.venix.com> Message-ID: <20040718011250.GA8481@wdfs.attbi.com> * Lloyd Kvam [2004-07-17 15:25]: > > I too was shifting from open(...) to file(...), however, Guido is > recommending a change to the documentation and continued use of open. > http://mail.python.org/pipermail/python-dev/2004-July/045931.html Interesting... thanks for the information. -- 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/20040717/c50438ed/attachment.pgp From bvande at po-box.mcgill.ca Sun Jul 18 04:43:16 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 18 04:49:33 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <5.2.1.1.0.20040718024924.02920d88@www.thinkware.se> References: <40F894D3.40508@ezabel.com> <5.2.1.1.0.20040718024924.02920d88@www.thinkware.se> Message-ID: <40F9E3C4.80203@po-box.mcgill.ca> Magnus Lyck? said unto the world upon 17/07/2004 21:00: > At 12:10 2004-07-17 -0700, Danny Yoo wrote: > >> On Fri, 16 Jul 2004, orbitz wrote: >> > Dive into python is good. Python is also distinct from other languages >> > in that reading other peoples code is actually helpful, usually. >> >> I have to argue with the second sentence, though. (Just slightly. >> *grin*) I feel that reading other people's code, in any programming >> language, is a good thing. There's a book called 'Code Reading': >> >> http://www.spinellis.gr/codereading/ >> >> that talks about the advantages of reading and understanding code; I'd >> wouldn't exclude it just because they don't use Python. Good code can be >> written in any language. > > >> (And it's not necessarily a bad thing to read "bad" code, either: we >> learn >> more quickly from mistakes than from successes.) > > > I'm not so sure about that. > > First of all, for a beginner who reads someone elses > code, it's not so easy to know whether something is > bad or good. Secondly, there are an infinite number of > ways to write a program. Learning one way *not* to write > doesn't seem very helpful. > > It's probably easy to spot problems in code if you know > how to do things right, and it might be a pedagogical > thing to do to demonstrate problems and failures, but I > don't think it should be more than some "seasoning" on > the meal of good idioms and techniques... > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language Hi all, first off, thanks to Danny for the book reference. I skimmed through some of it on Safari this afternoon and it looks worth close study. Magnus's point about beginners not being well-placed to distinguish the good from the bad has been a bit of a worry for me. I've been reading things in the Cookbook (dead-tree and on-line) but think the time has come where sitting down for serious study of a medium-sized chunk of code would do me some real good. Any recommendations for projects which provide good models? (I get that it would be best to read code in an application area that interests me, but I also think my request to be harder to accommodate if I pile on conditions ;-) Thanks, Brian vdB From dyoo at hkn.eecs.berkeley.edu Sun Jul 18 09:44:16 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jul 18 09:44:19 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <40F9E3C4.80203@po-box.mcgill.ca> Message-ID: > >> (And it's not necessarily a bad thing to read "bad" code, either: we > >> learn more quickly from mistakes than from successes.) > > > > I'm not so sure about that. > > > > First of all, for a beginner who reads someone elses code, it's not so > > easy to know whether something is bad or good. Hi Magnus, Very true; reading code without some accurate sense of the goodness or badness of it isn't helpful at all; it might even hurt. I was assuming that any such code wouldn't be read alone, but would be rigorously critiqued in a supervised forum like Python-Tutor. *grin* > > Secondly, there are an infinite number of ways to write a program. > > Learning one way *not* to write doesn't seem very helpful. There may be infinite surface variation, but I think that the common mistakes can be broken down into a few classes, like overusing globals, or writing really long functions. That is, I think there's a common set of "smells" that I think are indicators of code that needs a rewrite. http://c2.com/cgi/wiki?CodeSmell For example, code like this: ### """Reads out a number's digits.""" number = raw_input("type a number: ") for digit in phone_number: if digit == '0': print "zero" if digit == '1': print "one" if digit == '2': print "two" if digit == '3': print "three" if digit == '4': print "four" if digit == '5': print "five" if digit == '6': print "six" if digit == '7': print "seven" if digit == '8': print "eight" if digit == '9': print "nine" ### is functional, but it's also, frankly, ugly, because it's much too long, and there's so much repetition in there. Beginners might not have the experience to know how to fix this, but they should at least try to develop a sense of the "smell" of a code snippet, so that they can ask others about how to improve it. I think it's worthwhile to show nonoptimal code, as long as we also show why it needs work, and how to fix it. The carrot and the stick approach, I guess. *grin* I'd better follow my own advice. Here's one way to rewrite that snippet above: ### """Reads out a number's digits.""" number = raw_input("type a number: ") lookup_table = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] for digit in phone_number: print lookup_table[int(digit)] ### > Any recommendations for projects which provide good models? (I get that > it would be best to read code in an application area that interests me, > but I also think my request to be harder to accommodate if I pile on > conditions ;-) Orbitz mentioned the Quotient project, which I'm not familiar with at all. It sounds interesting, though! http://www.divmod.org/Home/Projects/Quotient/ The 'Twisted' network framework itself is getting some really high praise from folks here; it might be interesting to look into that. I dunno; do you have a particular application area that interests you? (Personally, I'm planning to look into Chandler: http://www.osafoundation.org/ but that's partially because I'm always losing track of information; a PIM would probably help me. *grin*) From bvande at po-box.mcgill.ca Sun Jul 18 10:10:20 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 18 10:31:33 2004 Subject: [Tutor] taking Python to next level In-Reply-To: References: Message-ID: <40FA306C.7000308@po-box.mcgill.ca> Danny Yoo said unto the world upon 18/07/2004 03:44: >>Any recommendations for projects which provide good models? (I get that >>it would be best to read code in an application area that interests me, >>but I also think my request to be harder to accommodate if I pile on >>conditions ;-) > > > Orbitz mentioned the Quotient project, which I'm not familiar with at all. > It sounds interesting, though! > > http://www.divmod.org/Home/Projects/Quotient/ > > The 'Twisted' network framework itself is getting some really high praise > from folks here; it might be interesting to look into that. I dunno; do > you have a particular application area that interests you? > > > (Personally, I'm planning to look into Chandler: > > http://www.osafoundation.org/ > > but that's partially because I'm always losing track of information; a PIM > would probably help me. *grin*) Hi all, thanks for the suggestions, Danny. Chandler interest me a lot -- the personal itch I'd like to program a scratch for is PIM-related. (I've made a start, but I'm quite a while from feeling I've anything to speak of.) But Chandler seems to gigantic for a first real 'code read'. Also, when I downloaded 0.2, it seemed like a lot of MB little (obvious to the user) functionality. Something closer to a working product seems a better idea. FWIW I've seen (in the sense of 'read the web page') a couple of other Python PIM's: http://storm-pim.sourceforge.net/ http://www.muth.org/Robert/Winzig/ Thanks again, Brian vdB From magnus at thinkware.se Sun Jul 18 11:21:14 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 11:17:12 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <40F9E3C4.80203@po-box.mcgill.ca> References: <5.2.1.1.0.20040718024924.02920d88@www.thinkware.se> <40F894D3.40508@ezabel.com> <5.2.1.1.0.20040718024924.02920d88@www.thinkware.se> Message-ID: <5.2.1.1.0.20040718110621.0291dc60@www.thinkware.se> At 22:43 2004-07-17 -0400, Brian van den Broek wrote: >Any recommendations for projects which provide good models? (I get that it >would be best to read code in an application area that interests me, but I >also think my request to be harder to accommodate if I pile on conditions ;-) The obvious candidate for Python code should be Python itself. Most of the library modules are written in Python, and they have been looked at by core Python developers. No need for any separate downloads there... Maybe you should look at file like Tools/Scripts/reindent.py or Lib/idlelib/* etc. Don't expect any code to be read as gospel though. The problem with the standard Python library is that a lot of the code is rather old, and doesn't take advantage of the more recent features in Python. With any Python library, you are likely to see idioms used that might meet some controversy among developers. For instance, if I recall correctly, it's common in Twisted that methods return 'self', so that you can replace code such as: some_object.method1(param1) some_object.method2(param2) some_object.method3(param3) some_object.method4(param4) with some_object.method1(param1).method2(param2).method3(param3).method4(param4) I'm not at all sure this is good coding practice. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sun Jul 18 12:42:43 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 12:38:42 2004 Subject: [Tutor] text processing by reading in a character at a time In-Reply-To: <40FB0E44@webmail.ualberta.ca> Message-ID: <5.2.1.1.0.20040718112304.02927988@www.thinkware.se> I'm bouncing this back to the list. Hope you don't mind. At 02:41 2004-07-18 -0600, ppareek wrote: >Thanks Magnus. >You are right, i am worried about the efficiency of the program. One big advantage with Python is that it's quick and easy to try out different approaches and technical solutions. >Basically my programme has to work similar to the online discussion systems. >It reads in the user's comments once the user submits them and adds them >after >finding the last comment on the html page. That is the reason that I want to >process the file one character at a time and find the last comment on the >page. >this is the place where i append the new comment. Do I understand that you have a file which looks something like this: [head] [comment1] [comment2] [comment3] ... [commentn] [tail] Your plan was to scan through that file, and insert [commentn+1] between [commentn] and [tail], right? I wouldn't have done that. >I do understand that this would be very inefficient give that this is server >side scripting, but this is my only plan for now I have several other approches in mind. One simple solution is to keep your original data in two files, one contaning: [head] [comment1] [comment2] [comment3] ... [commentn] and a separate with: [tail] It's trivial to append [commentn+1] to the end of the first file, make a copy of that, add [tail] to the copy, remove your old public HTML file, and rename the new file with all the data you need to the name of the file you serve. Another approach is to have a template such as templ = """[snip...] %s [snip some more]""" keep the comments in way so that they can be retrieved into a python list and do something like html = templ % "

".join(comment_list) I don't know how big your file is supposed to be, but huge HTML files aren't very meaningful anyway... Maybe you even want something like html = templ % "

".join(comment_list[-50:]) to get the last 50 comments. Perhaps you want to do... html = templ % "

".join(comment_list[start:stop+1]) ...and have parameters passed into your script to get a particular slice of comments from the whole list. Of course, if you have a huge amount of comments, you'd store them in a database and do the selection of rows when you fetch them from the database. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sun Jul 18 12:45:56 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 12:42:05 2004 Subject: [Tutor] Problem with exe file In-Reply-To: <20040717100806.7935.qmail@web61009.mail.yahoo.com> Message-ID: <5.2.1.1.0.20040718124427.02926098@www.thinkware.se> At 03:08 2004-07-17 -0700, Ali Polatel wrote: >Dear Friends, >I wrote a simple programme with python then have changed it into an exe >file with py2exe. >but it doesn't work in computers where python is not installed. >What should I do to make it work independently? It's a while since I used it, but if you got some DLLs etc in the directory where the exe-file got created, you need to deploy them as well. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sun Jul 18 12:59:53 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 18 12:56:02 2004 Subject: [Tutor] ComboBox with Tkinter In-Reply-To: <20040717025031.55a8a1c8.klappnase@freenet.de> References: <001401c462ca$7994d790$d101a8c0@pukispc> <001401c462ca$7994d790$d101a8c0@pukispc> Message-ID: <5.2.1.1.0.20040718125247.029291f0@www.thinkware.se> At 02:50 2004-07-17 +0200, Michael Lange wrote: >unfortunately there is no combobox widget in the standard Tkinter module; >there are two extensions >for Tkinter that have comboboxes (and many other extra widgets) for Tkinter: Since Tkinter is such a crippled GUI toolkit on its own, I've come to the conclusion that it's better to skip it entirely and use something more complete instead. May I suggest wxPython? http://www.wxpython.org/ As Guido put it: wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From orbitz at ezabel.com Sun Jul 18 22:25:35 2004 From: orbitz at ezabel.com (orbitz) Date: Sun Jul 18 22:25:57 2004 Subject: [Tutor] alphabetizing a file by lines In-Reply-To: <1a1.26f90d2d.2e2ae495@aol.com> References: <1a1.26f90d2d.2e2ae495@aol.com> Message-ID: <40FADCBF.2020606@ezabel.com> Dragonfirebane seems to want to write his code in the way he has given under the guise of learning. I'm not sure if others would agree or disagree with me here, but I think doing such a thing is probably counter productive with python. I'd like to hear others suggestions but here are my thoughts. In python, we should generally try to avoid duplicating as much code as possible. This means making use of the standard library and 3rd party libraries where we can. In dragonfirebane's situation he most likely wants to learn about sorting. which is fine, however I think he'd have more success if he took a simple case of say, implementing a high school level sorting algorithm on a simple list to get the idea of how sorting is done, but for something like this just using what python offers. IMO, using large relatively complex programs to learn about relatively simplistic problems is counter productive because you spend too much time in silly details of implementation rather than focusing on what you are trying to learn. Dragonfirebane@aol.com wrote: > Hello all, > > I'm trying to write a program that alphabetizes a file by the first > letter on each line. I'm having some problems because as soon as the > program finds a letter, it looks for the next letter, ignoring > subsequent appearances of that letter. I can think of a couple ways to > fix this but none of them seem to work. The first of these would be to > add a special character to lines that have already been alphabetized, > but file.write() writes to the end of a file and i would need to write > the character at the current position in the file. This might be > circumvented by creating a file for each line that is alphabetized, > but that seems a bit extreme . . . The code is below. Any suggestions > would be appreciated. Future concerns will be alphabetizing past the > first letter. > > ############## > def linum(): > global i > linu = open("%s%s" % (fn, ext), "r") > i = 0 > for line in linu.readlines(): > i += 1 > linu.close() > def alph(): > alp = open("alphebatized%s%s" % (fn, ext), "w") > pal = open("prealp%s%s" % (fn, ext), "w") ## eventually for > writing "\xfe" after a line that has been alphabetized > read = open("%s%s" % (fn, ext), "r") ## same reason > for this line until read.close() > for line in read.read(): > pal.write(line) > pal.close() > read.close() > print i > for do in range(i): > falp(alp) > alp.close() > def falp(alp): > global a > read = open("prealp%s%s" % (fn, ext), "r") > for line in read.readlines(): > try: > alpn = re.compile("%s(?!\xfe)" % alpha[a], re.IGNORECASE) > falpn = alpn.match(line) > if falpn: > print line > alp.write(line) > a += 1 > break > except IndexError: > pass > import re > import string > i = 0 > a = 0 > alpha = ' '.join(string.ascii_letters[:26]).split() > fn = raw_input("Please enter name of file you wish to prioritize: ") > ext = raw_input("Please enter extension of file you wish to prioritize: ") > linum() > alph() > ################ > > Here is random.txt, the file being alphabetized: > > K > cx > c > cd > e > X > y > v > l > f > w > Q > z > h > r > i > T > s > p > d > m > n > a > o > j > u > b > G > > Thanks in advance, > Orri > > Email: dragonfirebane@aol.com > AIM: singingxduck > Programming Python for the fun of it. > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From bvande at po-box.mcgill.ca Sun Jul 18 23:37:43 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 18 23:38:09 2004 Subject: [Tutor] alphabetizing a file by lines In-Reply-To: <40FADCBF.2020606@ezabel.com> References: <1a1.26f90d2d.2e2ae495@aol.com> <40FADCBF.2020606@ezabel.com> Message-ID: <40FAEDA7.60800@po-box.mcgill.ca> orbitz said unto the world upon 18/07/2004 16:25: > Dragonfirebane seems to want to write his code in the way he has given > under the guise of learning. I'm not sure if others would agree or > disagree with me here, but I think doing such a thing is probably > counter productive with python. > I'd like to hear others suggestions but here are my thoughts. > In python, we should generally try to avoid duplicating as much code as > possible. This means making use of the standard library and 3rd party > libraries where we can. In dragonfirebane's situation he most likely > wants to learn about sorting. which is fine, however I think he'd have > more success if he took a simple case of say, implementing a high school > level sorting algorithm on a simple list to get the idea of how sorting > is done, but for something like this just using what python offers. > IMO, using large relatively complex programs to learn about relatively > simplistic problems is counter productive because you spend too much > time in silly details of implementation rather than focusing on what you > are trying to learn. > > > Dragonfirebane@aol.com wrote: > >> Hello all, >> >> I'm trying to write a program that alphabetizes a file by the first >> letter on each line. I'm having some problems because as soon as the >> program finds a letter, it looks for the next letter, ignoring >> subsequent appearances of that letter. I can think of a couple ways to >> fix this but none of them seem to work. The first of these would be to >> add a special character to lines that have already been alphabetized, >> but file.write() writes to the end of a file and i would need to write >> the character at the current position in the file. This might be >> circumvented by creating a file for each line that is alphabetized, >> but that seems a bit extreme . . . The code is below. Any suggestions >> would be appreciated. Future concerns will be alphabetizing past the >> first letter. >> >> ############## >> def linum(): >> Thanks in advance, >> Orri >> >> Email: dragonfirebane@aol.com >> AIM: singingxduck >> Programming Python for the fun of it. >> ------------------------------------------------------------------------ Hi all, as I'm still learning, I doubt that it was my thoughts on this that orbitz was seeking :-) But I spent a bit of time re-implementing a few library functions just to learn how to do it (I did my own cmp() and sort() for instance). I thought I learned something useful from the effort. I wouldn't use them again -- in fact, once they worked, I trashed them. (They'd served their learning purpose.) But for learning, the duplication of some of the built-in and lib functions seems almost inevitable to me. Learners want to try central, basic, and fairly small tasks at first. Central and basic tasks seem those likely to have an implementation in Python already ;-) (I absolutely agree that once past learning, it would be daft not to rely on the lib when what was there did what you want.) What I find odd about dragonfirebane's approach though is the use of regular expressions to accomplish the sorting task. I felt like I was learning by taking something central and re-doing it in basic building blocks. By using r.e. I feel like dfb is re-doing the central and fairly simple in terms of the considerably more complex and I at least have doubts about the learning value of that approach. (But what do I know ;-) Best to all, Brian vdB From orbitz at ezabel.com Mon Jul 19 08:44:31 2004 From: orbitz at ezabel.com (orbitz) Date: Mon Jul 19 08:45:03 2004 Subject: [Tutor] alphabetizing a file by lines In-Reply-To: <40FAEDA7.60800@po-box.mcgill.ca> References: <1a1.26f90d2d.2e2ae495@aol.com> <40FADCBF.2020606@ezabel.com> <40FAEDA7.60800@po-box.mcgill.ca> Message-ID: <40FB6DCF.1060907@ezabel.com> I didn't mean to imply learning how things are implemented is bad, but rather learn on a simple test case so you understand the basic concept, such as just sorting elements in a list rather than sorting them based on very specific needs. That way you learn the basics of sorting, but then can just use builtins to accomplish a more difficult task. Brian van den Broek wrote: > orbitz said unto the world upon 18/07/2004 16:25: > >> Dragonfirebane seems to want to write his code in the way he has >> given under the guise of learning. I'm not sure if others would agree >> or disagree with me here, but I think doing such a thing is probably >> counter productive with python. >> I'd like to hear others suggestions but here are my thoughts. >> In python, we should generally try to avoid duplicating as much code >> as possible. This means making use of the standard library and 3rd >> party libraries where we can. In dragonfirebane's situation he most >> likely wants to learn about sorting. which is fine, however I think >> he'd have more success if he took a simple case of say, implementing >> a high school level sorting algorithm on a simple list to get the >> idea of how sorting is done, but for something like this just using >> what python offers. IMO, using large relatively complex programs to >> learn about relatively simplistic problems is counter productive >> because you spend too much time in silly details of implementation >> rather than focusing on what you are trying to learn. >> >> >> Dragonfirebane@aol.com wrote: >> >>> Hello all, >>> >>> I'm trying to write a program that alphabetizes a file by the first >>> letter on each line. I'm having some problems because as soon as the >>> program finds a letter, it looks for the next letter, ignoring >>> subsequent appearances of that letter. I can think of a couple ways >>> to fix this but none of them seem to work. The first of these would >>> be to add a special character to lines that have already been >>> alphabetized, but file.write() writes to the end of a file and i >>> would need to write the character at the current position in the >>> file. This might be circumvented by creating a file for each line >>> that is alphabetized, but that seems a bit extreme . . . The code is >>> below. Any suggestions would be appreciated. Future concerns will be >>> alphabetizing past the first letter. >>> >>> ############## >>> def linum(): >> > > > >>> Thanks in advance, >>> Orri >>> >>> Email: dragonfirebane@aol.com >>> AIM: singingxduck >>> Programming Python for the fun of it. >>> ------------------------------------------------------------------------ >>> >> > > Hi all, > > as I'm still learning, I doubt that it was my thoughts on this that > orbitz was seeking :-) > > But I spent a bit of time re-implementing a few library functions just > to learn how to do it (I did my own cmp() and sort() for instance). I > thought I learned something useful from the effort. > > I wouldn't use them again -- in fact, once they worked, I trashed > them. (They'd served their learning purpose.) But for learning, the > duplication of some of the built-in and lib functions seems almost > inevitable to me. Learners want to try central, basic, and fairly > small tasks at first. Central and basic tasks seem those likely to > have an implementation in Python already ;-) > > (I absolutely agree that once past learning, it would be daft not to > rely on the lib when what was there did what you want.) > > What I find odd about dragonfirebane's approach though is the use of > regular expressions to accomplish the sorting task. I felt like I was > learning by taking something central and re-doing it in basic building > blocks. By using r.e. I feel like dfb is re-doing the central and > fairly simple in terms of the considerably more complex and I at least > have doubts about the learning value of that approach. (But what do I > know ;-) > > Best to all, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From smith-matt at tiscali.co.uk Mon Jul 19 14:21:57 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Mon Jul 19 14:17:07 2004 Subject: [Tutor] problem writing random_word function Message-ID: Hi, I'm attempting to write a function that returns a random word of a specified length for use in a hangman game. The source of the words is a text file with each word on a new line. I got the function working printing all of the words of the desired length. I now want to make a list of all the words of the correct length then pick a random item from the list. Here is the function and traceback: def random_word(word_length): """Returns a random word of length word_length""" import random f = open("hangman_words.txt","r") while 1: n = 0 text = f.readline() text = text[0:len(text)-2] if len(text) == word_length: word_list[n] = text n = n+1 f.close() return word_list[random.randint(0,n)] Traceback (most recent call last): File "/home/matt/hangman.py", line 15, in -toplevel- print random_word(5) File "/home/matt/hangman.py", line 9, in random_word word_list[n] = text NameError: global name 'word_list' is not defined Hope you can help, Matt. From pythonTutor at venix.com Mon Jul 19 17:13:11 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Jul 19 17:13:23 2004 Subject: [Tutor] problem writing random_word function In-Reply-To: References: Message-ID: <1090249991.2141.44.camel@laptop.venix.com> You never initialized word_list. See below. You are better off simply appending to word_list rather than maintaining your own counter. len(word_list) will tell you how many entries are present when you go to choose a random word. Also, text.strip() will discard the line mark and is portable across operating systems. Stripping the last two characters assumes that you are running with an OS that uses two character line marks. On Mon, 2004-07-19 at 08:21, Matt Smith wrote: > Hi, > I'm attempting to write a function that returns a random word of a > specified length for use in a hangman game. The source of the words is a > text file with each word on a new line. I got the function working > printing all of the words of the desired length. I now want to make a > list of all the words of the correct length then pick a random item from > the list. Here is the function and traceback: > > def random_word(word_length): > """Returns a random word of length word_length""" > import random > f = open("hangman_words.txt","r") word_list = [] > while 1: > n = 0 > text = f.readline() > text = text[0:len(text)-2] > if len(text) == word_length: > word_list[n] = text > n = n+1 > f.close() > return word_list[random.randint(0,n)] > > Traceback (most recent call last): > File "/home/matt/hangman.py", line 15, in -toplevel- > print random_word(5) > File "/home/matt/hangman.py", line 9, in random_word > word_list[n] = text > NameError: global name 'word_list' is not defined > > Hope you can help, > Matt. > > _______________________________________________ > 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 rdm at rcblue.com Mon Jul 19 17:19:38 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Jul 19 17:20:30 2004 Subject: [Tutor] Please critique my Fraq.py Message-ID: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> Tutors, This may seem like a silly script to write. But it's just an exercise I set for myself. And it does compute that amazingly close approximation to PI, 355/113: ============================ Maximum denominator: 200 For pi, 355/113 is closest fraction up to maximum denominator of 200 Error is 8.4913678767406e-006 percent =========================== You'll notice that I've had to use this if statement twice in order to enable user to close the program: if choice in ["x", "q"]: break And also twice: if maximumDenom in ["x", "q"]: break And this: if minimumError in ["x", "q"]: break Is there a better way to do this? How about my variable and constant names? And all the while loops are "while True:". This OK? Should the script be a lot more modular? Thanks, tutors. Dick Moores ============================= # Frac.py print """ Enter a decimal number and Frac will calculate a fraction for use as an approximation to the number. You can choose to set a maximum denominator for the fraction, or to set a minimum error for the fraction to satisfy. Enter e or E for the mathematical constant 2.7182818284590451, and pi or PI for the mathematical constant 3.1415926535897931. You may exit the program at any prompt by entering x or q. """ import random, time defaultMinimumError = 0.01 defaultMaximumDenom = 100 def exit(): print "Thank you for using Frac. Frac will now close" time.sleep(1.1) # to provide the user with enough time to read the message while True: print "If no decimal entered, a random decimal " \ "between 0.1 and 1.0 will be chosen." # for exiting via ^C or ^D try: string = raw_input("Decimal: ") except (TypeError, EOFError): break if string in ["x", "q"]: break if string in ["pi", "PI"]: decimal = 3.1415926535897931 elif string in ["E", "e"]: decimal = 2.7182818284590451 elif string == "": while True: decimal = random.random() # permit only 0.1 <= decimal < 1.0 if decimal >= .1: break string = str(decimal) print decimal, "was picked at random for you.\n" else: try: decimal = float(string) except: print "That's not a decimal number! Try again." continue while True: choice = raw_input("Minimum error (e) or maximum denominator (d)? ") if choice in ["x", "q"]: break elif not (choice in ["e", "d"]): print "Enter d or e" continue else: break if choice in ["x", "q"]: break if choice == "d": while True: print "If no maximum denominator entered, the default is 100" maximumDenom = raw_input("Maximum denominator: ") if maximumDenom in ["x", "q"]: break elif maximumDenom == "": maximumDenom = defaultMaximumDenom print "Maximum denominator is %g by default" % maximumDenom else: try: maximumDenom = int(maximumDenom) except: print "That's not an integer! Try again." continue break if maximumDenom in ["x", "q"]: break leastError = 1 for denom in xrange(1, maximumDenom + 1): num = round(decimal * denom) error = abs((num / denom - decimal) / decimal) if error < leastError: leastError = error bestDenom = denom bestNum = num if leastError == 0: # should I have this if statement? break print "For %s, %d/%d is closest fraction" % (string, int(bestNum), bestDenom) print " up to maximum denominator of %d" % maximumDenom print "Error is %.13e percent" % (leastError * 100) print "\n" elif choice == "e": while True: print "If no minimum error entered, the default is %g percent" % defaultMinimumError minimumError = raw_input("Minimum error in percent: ") if minimumError in ["x", "q"]: break elif minimumError == "": minimumError = defaultMinimumError print "Minimum error is %g by default" % defaultMinimumError else: try: minimumError = float(minimumError) except: print "That's not a decimal number!" continue break if minimumError in ["x", "q"]: break denom = 0 while True: denom += 1 num = round(decimal * denom) error = abs((num / denom - decimal) / decimal) * 100 if error <= minimumError: break print "%d/%d is fraction with smallest denominator with error <= %.13g percent" % (num, denom, minimumError) print "Actual error is %.13e percent" % error print "\n" exit() ==========End of Frac.py=============== From smith-matt at tiscali.co.uk Mon Jul 19 18:40:44 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Mon Jul 19 18:35:51 2004 Subject: [Tutor] Re: problem writing random_word function References: <1090249991.2141.44.camel@laptop.venix.com> Message-ID: On Mon, 19 Jul 2004 11:13:11 -0400, Lloyd Kvam wrote: > You never initialized word_list. See below. > > You are better off simply appending to word_list rather than maintaining > your own counter. len(word_list) will tell you how many entries are > present when you go to choose a random word. Also, text.strip() will > discard the line mark and is portable across operating systems. > Stripping the last two characters assumes that you are running with an > OS that uses two character line marks. Thanks Lloyd, I've rewritten the function as below and everything seems to work correctly. def random_word(word_length): """Returns a random word of length word_length""" import random f = open("hangman_words.txt","r") word_list = [] while 1: word = f.readline() word = word.strip() if word == "": break elif len(word) == word_length: word_list = word_list + [word] f.close() return word_list[random.randint(0,(len(word_list)-1))] Cheers, Matt. From dyoo at hkn.eecs.berkeley.edu Mon Jul 19 19:59:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 19 19:59:41 2004 Subject: [Tutor] Re: problem writing random_word function In-Reply-To: Message-ID: > I've rewritten the function as below and everything seems to work > correctly. > > def random_word(word_length): > """Returns a random word of length word_length""" > import random > f = open("hangman_words.txt","r") > word_list = [] > while 1: > word = f.readline() > word = word.strip() > if word == "": > break > elif len(word) == word_length: > word_list = word_list + [word] > f.close() > return word_list[random.randint(0,(len(word_list)-1))] Hi Matt, Looks ok! Here are some suggestions to make the code more "Pythonic" (whatever that means... *grin*). There's a slightly more idiomatic way of writing that loop --- instead of using a 'while' loop, we're allowed to use a 'for' loop across a file: for word in file: word = word.strip() ... This works because files are 'iterable' in the same way that lists or sequences are iterable. Using the 'for' construct will cut down on a few lines, and also remove the need for the an explicit 'break' statement to stop the loop. Using the 'for' loop approach also ends up being less bug prone. In the original code, if there were an empty line in the middle of the 'hangman_words.txt' file, then the loop would break prematurely. Rewriting the loop as: while 1: word = f.readline() if word == "": break ... that is, pushing the 'if word == "": ...' test up a bit, will also fix that potential problem. Also, as you're scanning for new candidate words for selection, you may want to use the 'append()' method to add new words into the 'word_list'. What you have right now: word_list = word_list + [word] constructs a whole new word_list out of the original word_list. It's a little less expensive to do an 'append': word_list.append(word) More importantly, though, is that Python programmers will probably recognize the 'append' idiom for adding new elements onto a list, as opposed to using the '+' approach. Finally, there's a function in the 'random' module that knows how to choose a random element off a list, so the last expression: > return word_list[random.randint(0,(len(word_list)-1))] can be slightly simplified. See: http://www.python.org/doc/lib/module-random.html#l2h-1149 From glingl at aon.at Mon Jul 19 20:08:30 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Jul 19 20:07:55 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> Message-ID: <40FC0E1E.8090400@aon.at> Dick Moores schrieb: > Tutors, > > This may seem like a silly script to write. But it's just an exercise > I set for myself. And it does compute that amazingly close > approximation to PI, 355/113: > I won't criticize your script, I just (for fun) checked your result in a quick and dirty manner, and indeed: >>> from math import pi >>> min([(abs(float(p)/q-pi)*100/pi,p,q) for q in range(2,200) for p in range(3*q, int(3.2*q))]) (8.4913678767406097e-006, 355, 113) the next fraction which approximates pi better seems to be >>> min([(abs(float(p)/q-pi)*100/pi,p,q) for q in range(2,16717) for p in range(int(3.14*q), int(3.15*q))]) (8.4738311605107342e-006, 52163, 16604) >>> Regards, Gregor From sigurd at 12move.de Mon Jul 19 20:11:16 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer=29?=) Date: Mon Jul 19 20:16:27 2004 Subject: [Tutor] Re: problem writing random_word function In-Reply-To: (Matt Smith's message of "Mon, 19 Jul 2004 17:40:44 +0100") References: <1090249991.2141.44.camel@laptop.venix.com> Message-ID: On 19 Jul 2004, Matt Smith <- smith-matt@tiscali.co.uk wrote: > Thanks Lloyd, > I've rewritten the function as below and everything seems to work > correctly. > def random_word(word_length): > """Returns a random word of length word_length""" > import random > f = open("hangman_words.txt","r") > word_list = [] > while 1: > word = f.readline() > word = word.strip() > if word == "": > break > elif len(word) == word_length: > word_list = word_list + [word] > f.close() > return word_list[random.randint(0,(len(word_list)-1))] That function works but you could improve it a bit. First: don't import modules in functions. That may lead to dead locks. Second: you could write the above shorter and more pythonlike without the wile loop. Third: You mustn't forget that there may be no mathing word in your file. Fourth: don't hardwire the name of the file. import random def random_word (length, data="hangman_words.txt"): f = file(data) wordlist = [word for word in f if len(word.strip()) == length] f.close() if len(wordlist) > 0: return wordlist[random.randrange(0, len(wordlist))].strip() Karl -- Please do *not* send copies of replies to me. I read the list From s.varun at gmail.com Mon Jul 19 20:32:18 2004 From: s.varun at gmail.com (Nithya Soundararajan) Date: Mon Jul 19 20:32:22 2004 Subject: [Tutor] Re: problem writing random_word function In-Reply-To: References: <1090249991.2141.44.camel@laptop.venix.com> Message-ID: <32b5ee76040719113272dafac8@mail.gmail.com> Hi, a better way for loading the file could be to convert it to pickle form and then use it.(May be helpful only if you wanna load it with two lines. ;-) ). import pickle f=open(yourfile,"r") word_list=pickle.dump(f) (this will work only if you hv already converted the hangman_words.txt to pickle format, it will be easier for you and your code will look more geekier. Pour your comments -Varun On Mon, 19 Jul 2004 20:11:16 +0200, Karl Pfl?sterer) wrote: > On 19 Jul 2004, Matt Smith <- smith-matt@tiscali.co.uk wrote: > > > Thanks Lloyd, > > I've rewritten the function as below and everything seems to work > > correctly. > > > def random_word(word_length): > > """Returns a random word of length word_length""" > > import random > > f = open("hangman_words.txt","r") > > word_list = [] > > while 1: > > word = f.readline() > > word = word.strip() > > if word == "": > > break > > elif len(word) == word_length: > > word_list = word_list + [word] > > f.close() > > return word_list[random.randint(0,(len(word_list)-1))] > > That function works but you could improve it a bit. > First: don't import modules in functions. That may lead to dead locks. > > Second: you could write the above shorter and more pythonlike without > the wile loop. > > Third: You mustn't forget that there may be no mathing word in your > file. > > Fourth: don't hardwire the name of the file. > > import random > def random_word (length, data="hangman_words.txt"): > f = file(data) > wordlist = [word for word in f if len(word.strip()) == length] > f.close() > if len(wordlist) > 0: > return wordlist[random.randrange(0, len(wordlist))].strip() > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From glingl at aon.at Mon Jul 19 20:43:38 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon Jul 19 20:43:02 2004 Subject: [Tutor] Re: problem writing random_word function In-Reply-To: References: <1090249991.2141.44.camel@laptop.venix.com> Message-ID: <40FC165A.6080408@aon.at> Karl Pfl?sterer schrieb: >That function works but you could improve it a bit. >First: don't import modules in functions. That may lead to dead locks. > > > How that? Could you please explain this. Gregor From alan.gauld at blueyonder.co.uk Mon Jul 19 21:34:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jul 19 21:34:08 2004 Subject: [Tutor] (no subject) [case studies in Python] References: Message-ID: <006a01c46dc7$5d1b5b90$6401a8c0@xp> > In that case, you may want to look at Alan Gauld's "Learning to Program": > > http://www.freenetpages.co.uk/hp/alan.gauld/ That's the original URL, the new one adds "tutor2" at the end. http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 This will soon become the default but not quite yet... > His tutorial uses several programming languages, including VBScript and > Javascript, to better illustrate the ideas of programming. Only the new version compares the OOP features. Alan G. Back from vacation! :-) From alan.gauld at blueyonder.co.uk Mon Jul 19 23:47:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jul 19 23:47:48 2004 Subject: [Tutor] Why can't I make this function work? References: Message-ID: <009c01c46dda$0a876500$6401a8c0@xp> > def Get_int(): > "Function to collect an integer from the user" > type_check = 0 > while type_check == 0: > int = raw_input() > if type(int) != type(1): > print "Invalid input" > else: > type_check = 1 > return int Its usually a bad idea to use a Python builtin name as a variable. int is the function for converting to an integer. Thisis particularly unfortunate here because you need it to convert your raw_input string to an integer! - Thats why the type test keeps failing.... However a more Pythonic way to do this is probably via an exception: def getInt(): while True: try: num = int(raw_input()) except TypeError: continue return num That will of course work for floats (which will be converted to ints, so it might not be exactly what you want. But a simple test before the conversion would fix that. def getInt(): while True: try: num = raw_input() if '.' in num: continue else num = int(num) except TypeError: continue return num HTH, Alan G. From alan.gauld at blueyonder.co.uk Mon Jul 19 23:58:19 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jul 19 23:58:17 2004 Subject: [Tutor] web applications?? References: <20040715210916.59871.qmail@web60101.mail.yahoo.com> Message-ID: <00a801c46ddb$80d78590$6401a8c0@xp> > Is it possible to just execute my wxpython application from our server? Unfortunately not, wxPthon is a "fat client" llibrary, that is it runs on the PC not in a browser. You will need to reimplement the application as a web app using Web(HTML) forms and CGI or some other web type technology. If you have many thousands of users hitting the site at once consider something like Zope but if its only a few dozen cgi will be fine. > do I need to write the application in some sort of web-python variation. Any CGI type application will work. Or if it's not too complex (a single form say) then you could implement it as JavaScript and let it run on the client browser. Your biggest headache may actually be designing the HTML forms although many GUI web page designers can handle forms - FirstPage, HoTMetaL and others can do that for you. HTH, Alan G. From alan.gauld at blueyonder.co.uk Tue Jul 20 00:03:29 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 00:03:26 2004 Subject: [Tutor] Program Questions References: Message-ID: <00af01c46ddc$39989470$6401a8c0@xp> In my mail tool they were the only bits that had any indentation at all! It would be useful if you can find a way to send plain text since Python indentation is critical, not to mention easier to read! BTW Instead of print '\n' print 'foo' print '\n' its easier to do: print '\nfoo\n' or even print ''' foo ''' personally I'd go for the first option. Where you need to substitute a function call use a format string: print "\n%s\n" % acct.foo() It keeps it shorter and easier to read. As to the error, again it helps if you post the actual error report. 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 Jul 20 00:13:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 00:13:32 2004 Subject: [Tutor] Program Problems References: Message-ID: <00b801c46ddd$a2a0be60$6401a8c0@xp> > If you see a problem, can you tell me? > > http://rafb.net/paste/results/88yf5V76.html > > I cannot figure out the errors. Or this list. That's better, def MenuOption(self, option, Account): if option == 1: Account.deposit(input("Deposit amount:$") <--- mismatched parens! print "TRANSACTION COMPLETED" The error I got was: exit() File "", line 15 print "TRANSACTION COMPLETED" ^ SyntaxError: invalid syntax Which showed that it was in the class definition and which elif statement to look at. Then I noticed the missing paren. The other wee point is that input() is not recommended because Python literally evaluates the user input which could be a malicious python command! Better to use raw_input and convert to an int or float. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From linux-user at softhome.net Mon Jul 19 14:14:20 2004 From: linux-user at softhome.net (Conrad) Date: Tue Jul 20 02:11:09 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <20040719183222.ABEA11E4008@bag.python.org> References: <20040719183222.ABEA11E4008@bag.python.org> Message-ID: <1090239259.18450.1.camel@radiol> You should make it a lot more modular, assign a function for each task, then you can reuse your code. Best of Luck Conrad From Dragonfirebane at aol.com Tue Jul 20 02:23:41 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jul 20 02:23:54 2004 Subject: [Tutor] alphabetizing a file by lines Message-ID: <7A6F4232.562DF86B.34E997B7@aol.com> In a message dated 7/18/2004 1:02:33 PM Eastern Daylight Time, orbitz writes: >What sorting algorithm have you implemetned? selection sort? insertion >sort? quicksort? Well, I was kind of writing my own; one that looks at the first letter of each line and if it begins with 'a' writes it to an 'alphabetizedfilename' file first and if there are no a's it skips to the next letter, etc. However, I need to work on how it handles multiple entries with the same starting letter. (I'm not at my house until friday so I won't be able to directly send the code.) -- "n thats the way the cookie crumbles" America's Favorite Cookie From rdm at rcblue.com Tue Jul 20 13:25:30 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Jul 20 13:32:02 2004 Subject: [Tutor] dangers of input() In-Reply-To: <00b801c46ddd$a2a0be60$6401a8c0@xp> References: <00b801c46ddd$a2a0be60$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040720041715.02452b48@rcblue.com> Alan Gauld wrote at 15:13 7/19/2004: >The other wee point is that input() is not recommended because Python >literally evaluates the user input which could be a malicious python >command! Better to use raw_input and convert to an int or float. The above is from another thread. I was thinking of using input() instead of raw_input in my Frac.py (posted yesterday). This would enable the user to enter things such as "4**-3". Am I correct in assuming that this would be impossible to do without using input()? If so, I may go ahead with input()--I'm the only user, after all. Dick Moores From agunnerson at gmail.com Tue Jul 20 18:22:53 2004 From: agunnerson at gmail.com (Andy) Date: Tue Jul 20 18:22:59 2004 Subject: [Tutor] simple question about lists Message-ID: <26e9728704072009224ffe6722@mail.gmail.com> Hello all, I'm getting ready to teach myself python. I'm going to convert an old tic tac toe game I wrote in C to get my feet wet. One question though, in C I could set up a multi dimensional array by doing char board[3][3] I can't do multi dimensional lists in python can I? Am I right in thinking that I would need to either use a one dimensional list or get something like numeric to do this? Thanks in advance. -Andy From pythonTutor at venix.com Tue Jul 20 18:49:51 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Jul 20 18:49:59 2004 Subject: [Tutor] simple question about lists In-Reply-To: <26e9728704072009224ffe6722@mail.gmail.com> References: <26e9728704072009224ffe6722@mail.gmail.com> Message-ID: <1090342191.2122.33.camel@laptop.venix.com> You should have no difficulty with multi dimensional lists. board = [ [1,2,3],[4,5,6],[7,8,9] ] board[1][1] should reference the 5 I expect numeric would be overkill for this. On Tue, 2004-07-20 at 12:22, Andy wrote: > Hello all, I'm getting ready to teach myself python. I'm going to > convert an old tic tac toe game I wrote in C to get my feet wet. One > question though, in C I could set up a multi dimensional array by > doing > > char board[3][3] > > I can't do multi dimensional lists in python can I? Am I right in > thinking that I would need to either use a one dimensional list or get > something like numeric to do this? Thanks in advance. > > -Andy > _______________________________________________ > 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 orbitz at ezabel.com Tue Jul 20 18:53:49 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Jul 20 18:54:22 2004 Subject: [Tutor] simple question about lists In-Reply-To: <26e9728704072009224ffe6722@mail.gmail.com> References: <26e9728704072009224ffe6722@mail.gmail.com> Message-ID: <40FD4E1D.9040601@ezabel.com> A list can contain any other type, including lists. Andy wrote: >Hello all, I'm getting ready to teach myself python. I'm going to >convert an old tic tac toe game I wrote in C to get my feet wet. One >question though, in C I could set up a multi dimensional array by >doing > >char board[3][3] > >I can't do multi dimensional lists in python can I? Am I right in >thinking that I would need to either use a one dimensional list or get >something like numeric to do this? Thanks in advance. > >-Andy >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From eric at zomething.com Sat Jul 17 22:04:47 2004 From: eric at zomething.com (Eric @ Zomething) Date: Tue Jul 20 19:26:47 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? Message-ID: <20040717120447.715219416.eric@zomething.com> Danny Yoo wrote: > In this case, range() is a good tool for this job, because it gives us a > list that we can munge up with random.shuffle(). xrange() gives us just > an iterable that's specialized only to do sequential counting, so it > wouldn't be as appropriate here. Can anyone suggest how I might make the following a bit more efficient in terms of RAM usage (without having to do any additional file operations)? maxNumber=672,000 maxSample=20,000 nixList=completedNumbers # a list constructed from pickled data on file for x in random.Random().sample(xrange(maxNumber),maxSample): if (str(x) not in nixList): # do a bunch of processing # pickle numbers successfully processed for later reference in nixList """Thanks!""" Eric Pederson http://www.songzilla.blogspot.com :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: e-mail me at: do@something.com except, increment the "d" and "o" by one letter and spell something with a "z" :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: From "allyn." at tardigrade.net Sun Jul 18 06:46:03 2004 From: "allyn." at tardigrade.net (Allyn Weaks) Date: Tue Jul 20 19:26:49 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <5.2.1.1.0.20040718024924.02920d88@www.thinkware.se> References: <40F894D3.40508@ezabel.com> <5.2.1.1.0.20040718024924.02920d88@www.thinkware.se> Message-ID: On 18/7/2004, Magnus Lyck? wrote: >At 12:10 2004-07-17 -0700, Danny Yoo wrote: >>we learn >>more quickly from mistakes than from successes.) > >I'm not so sure about that. >Secondly, there are an infinite number of >ways to write a program. Learning one way *not* to write >doesn't seem very helpful. Indeed. Mistakes can (though don't always) convey information about what to avoid, but they say nothing about what to actively do. Learning primarily by mistakes is a losing battle. Building up a succession of successes is what takes you directly to the meat of things. There's a lot of hard evidence that all animals, even invertebrates such as bees, learn mostly from success--it's hardwired even deeper than the brain stem. But as with just about everything, it's best that the success not be random. There are now pretty well understood ways to streamline the process for many subjects/tasks, but making things better for the student can be more labor intensive on the teacher's end--since students vary, the exact path to teach them most effectively does too... Mark Plonsky's points to some good basic references about learning theory. The somewhat extreme application to human teaching tries to set things up so that the student never makes a mistake; it's alleged to be very effective for things like hand writing and basic arithmetic so far. IIRC it's called 'perfect learning' or 'perfect teaching', but it's hard to google for because both phrases are randomly common. -- Allyn Weaks allyn@tardigrade.net Seattle, WA Sunset zone 5 Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/ "To announce that there must be no criticism of the president, or that we are to stand by the president, right or wrong, is not only unpatriotic and servile, but is morally treasonable to the American public." -- Theodore Roosevelt From ppareek1784 at rediffmail.com Fri Jul 16 19:35:42 2004 From: ppareek1784 at rediffmail.com (priyanka pareek) Date: Tue Jul 20 19:27:12 2004 Subject: [Tutor] algorithm? Message-ID: <20040716173542.5597.qmail@webmail29.rediffmail.com> I am working on a web site development project and need to create a script that would add comments to the page that anyone can fill out.(something like a discussion board) Since I am want to develop this script from scratch using python , I was wondering if anyone has any good ideas as to how to go about with the same. Basically the user would fill out his/her comments in a form and they would have to be appended to the page at a specific place. Any suggestions -prachi From SMITHB2 at WESTAT.com Fri Jul 16 20:18:44 2004 From: SMITHB2 at WESTAT.com (Barrett Smith) Date: Tue Jul 20 19:27:27 2004 Subject: [Tutor] Os.system on winXP system having trouble with spaces indirectory names Message-ID: <446DDE75CFC7E1438061462F85557B0F0373A061@remail2.westat.com> Thanks, Christian. For some reason, though, quoting the path just opened a command line dialog box, not the requested page. What did work was using os.chdir to change to the Desktop then just issuing os.system('start page.html'). Barrett -----Original Message----- From: Christian Wyglendowski [mailto:Christian.Wyglendowski@greenville.edu] Sent: Friday, July 16, 2004 2:08 PM To: Barrett Smith; tutor@python.org Subject: RE: [Tutor] Os.system on winXP system having trouble with spaces indirectory names Quoting your path should take care of it: os.system('start "C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html"') Christian http://www.dowski.com ________________________________ From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Barrett Smith Sent: Tuesday, July 13, 2004 1:31 PM To: 'tutor@python.org' Subject: [Tutor] Os.system on winXP system having trouble with spaces indirectory names I'm having trouble with a using os.system on a windowsXP machine. Running: os.system('start C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html') Yields and error saying 'Windows cannot find C:\Documents.....' This same problem means I can't access things in the 'Program Files' directory and so forth. Any ideas of work-arounds (other than moving to non-space included directories)? Thanks, Barrett From alan.gauld at blueyonder.co.uk Tue Jul 20 19:53:04 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 19:52:48 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? References: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> Message-ID: <00dc01c46e82$683a1fa0$6401a8c0@xp> > for k in range(max): This line creates a list of max numbers. Each number takes up several bytes of RAM(4+?). So 20 million numbers is over 80MB RAM being used. You probably should investigate generators for this kind of thing, or at least use xrange() instread of range() Alan G. From alan.gauld at blueyonder.co.uk Tue Jul 20 19:55:33 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 19:55:22 2004 Subject: [Tutor] hello. I need some help pls (fwd) References: Message-ID: <00e901c46e82$c0e5b560$6401a8c0@xp> > >>> print 'here are the ten numbers from 0 to 9' > here are the ten numbers from 0 to 9 > >>> for 1 in range(10): > print 1, > SyntaxError: can't assign to literal > > Any idea?Pls...:) Looks like you typed a 1(one) instead of an l(ell) One reason I try to avoid l as a variable name! :-) Alan G From alipolatel at yahoo.com Tue Jul 20 19:55:46 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Tue Jul 20 19:55:49 2004 Subject: Fwd: Re: [Tutor] Problem with exe file Message-ID: <20040720175546.22015.qmail@web61009.mail.yahoo.com> Does anyone know which dlls exactly? Regards Magnus Lyckå wrote: Date: Sun, 18 Jul 2004 12:45:56 +0200 To: polatel@chess-live.com,tutor@python.org From: Magnus Lyckå Subject: Re: [Tutor] Problem with exe file At 03:08 2004-07-17 -0700, Ali Polatel wrote: >Dear Friends, >I wrote a simple programme with python then have changed it into an exe >file with py2exe. >but it doesn't work in computers where python is not installed. >What should I do to make it work independently? It's a while since I used it, but if you got some DLLs etc in the directory where the exe-file got created, you need to deploy them as well. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language --------------------------------- Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040720/ab683466/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Tue Jul 20 20:05:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 20 20:05:58 2004 Subject: [Tutor] dangers of input() In-Reply-To: <6.1.2.0.2.20040720041715.02452b48@rcblue.com> Message-ID: On Tue, 20 Jul 2004, Dick Moores wrote: > I was thinking of using input() instead of raw_input in my Frac.py > (posted yesterday). This would enable the user to enter things such as > "4**-3". Am I correct in assuming that this would be impossible to do > without using input()? If so, I may go ahead with input()--I'm the only > user, after all. Hi Dick, Yup, that's right: ### >>> value = input("enter an expression: ") enter an expression: 2**3 + 4**2 + 3**1 >>> value 27 >>> >>> >>> value = raw_input("enter an expression: ") enter an expression: 2**3 + 4**2 + 3**1 >>> value '2**3 + 4**2 + 3**1' ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue Jul 20 20:16:39 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 20 20:16:43 2004 Subject: [Tutor] simple question about lists In-Reply-To: <26e9728704072009224ffe6722@mail.gmail.com> Message-ID: On Tue, 20 Jul 2004, Andy wrote: > Hello all, I'm getting ready to teach myself python. I'm going to > convert an old tic tac toe game I wrote in C to get my feet wet. One > question though, in C I could set up a multi dimensional array by doing > > char board[3][3] > > I can't do multi dimensional lists in python can I? Am I right in > thinking that I would need to either use a one dimensional list or get > something like numeric to do this? Thanks in advance. Hi Andy, Yes, multidimensional lists are possible. The initialization is a little funny, though. Let me write the C equivlent first, and then a close Python translation to it. In C, we might do something like this: ### /*** Returns a 3x3 array of characters **/ char** mallocEmptyBoard() { int i; int j; char** board = malloc(sizeof(char*) * 3); for(i = 0; i < 3; i++) { board[i] = malloc(sizeof(char) * 3); for(j = 0; j < 3; j++) { board[i][j] = '.'; } } return board; } ### In Python, we'd have similar code, but with a little less typing: ### def getEmptyBoard(): board = [None] * 3 for i in range(3): board[i] = ['.', '.', '.'] return board ### Does this make sense? There's an entry in the Python FAQ that talks about this a little more: http://python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list Good luck! From israel at uandmedance.com Tue Jul 20 20:44:50 2004 From: israel at uandmedance.com (israel@uandmedance.com) Date: Tue Jul 20 20:43:49 2004 Subject: [Tutor] Cross version site-packages equivalent? Message-ID: hello there. I've been wondering if there is a recommended way of storing/installing modules in a site-packages equivalent that isn't tied to any one particular version of python. Is there? I've tried to keep all of my own stuff in various directories throughout my hard drive and have been using .pth files as of late to let python know they are there, but when I get large packages like wxpython, they usually want to get stuffed into whichever version/lib/site-packages that they were intended for. How do you folks manage upgrading python or having multiple versions? ~Israel~ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 640 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040720/57e87fe7/attachment.bin From scombs at ivytech.edu Tue Jul 20 21:22:09 2004 From: scombs at ivytech.edu (Steven Combs) Date: Tue Jul 20 21:27:13 2004 Subject: [Tutor] Hmm...I should be able to figure this out...but... Message-ID: <181B5DE8-DA82-11D8-8092-000D935360E0@ivytech.edu> I am using the following code to simply take user input and return the results backwards. --------------------------------------------------------------- # Initialize Variables string = "" stringlength = 0 # Begin Program string = raw_input("Enter a string and I will display it backwards.\n") stringlength = len(string) for i in range (stringlength, 0, -1): print string [i - 1], print "\n" raw_input("\nPress the enter key to exit") --------------------------------------------------------------- It works, but it places a space in between the characters displayed. For instance, if the string entered is: Test the results are displayed t s e T I tried using "\b" to backspace after each character is displayed, but this didn't work. I'm embarrassed to admit that I am trying to give this as an assignment for a basic computer programming course I teach (I'm stilling trying to learn the finer points of Python myself). I know I could use other commands, but I have to limit the command set for the students at this stage in their programming section (we have yet to discuss mutability and immutability) Any suggestion for an easy fix? Steven From bill.mill at gmail.com Tue Jul 20 22:20:24 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Jul 20 22:20:28 2004 Subject: [Tutor] simple question about lists In-Reply-To: References: Message-ID: <797fe3d40407201320dd91dfc@mail.gmail.com> Or, if you want to use list comprehensions to be in with the "cool programmers", you could do: def getEmptyBoard(): return [['.'] * 3 for i in range(3)] Peace, Bill Mill On Tue, 20 Jul 2004 11:16:39 -0700 (PDT), Danny Yoo wrote: > > > On Tue, 20 Jul 2004, Andy wrote: > > > Hello all, I'm getting ready to teach myself python. I'm going to > > convert an old tic tac toe game I wrote in C to get my feet wet. One > > question though, in C I could set up a multi dimensional array by doing > > > > char board[3][3] > > > > I can't do multi dimensional lists in python can I? Am I right in > > thinking that I would need to either use a one dimensional list or get > > something like numeric to do this? Thanks in advance. > > > Hi Andy, > > Yes, multidimensional lists are possible. The initialization is a little > funny, though. Let me write the C equivlent first, and then a close > Python translation to it. > > In C, we might do something like this: > > ### > /*** Returns a 3x3 array of characters **/ > char** mallocEmptyBoard() { > int i; > int j; > char** board = malloc(sizeof(char*) * 3); > for(i = 0; i < 3; i++) { > board[i] = malloc(sizeof(char) * 3); > for(j = 0; j < 3; j++) { > board[i][j] = '.'; > } > } > return board; > } > ### > > In Python, we'd have similar code, but with a little less typing: > > ### > def getEmptyBoard(): > board = [None] * 3 > for i in range(3): > board[i] = ['.', '.', '.'] > return board > ### > > Does this make sense? > > There's an entry in the Python FAQ that talks about this a little more: > > http://python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list > > Good luck! > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Tue Jul 20 22:43:40 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Jul 20 22:40:32 2004 Subject: [Tutor] dangers of input() In-Reply-To: <6.1.2.0.2.20040720041715.02452b48@rcblue.com> References: <00b801c46ddd$a2a0be60$6401a8c0@xp> <6.1.2.0.2.20040720041715.02452b48@rcblue.com> Message-ID: <40FD83FC.60002@ccvcorp.com> Dick Moores wrote: > I was thinking of using input() instead of raw_input in my Frac.py > (posted yesterday). This would enable the user to enter things such as > "4**-3". Am I correct in assuming that this would be impossible to do > without using input()? If so, I may go ahead with input()--I'm the only > user, after all. Well, it's not impossible to do it without input() -- input() itself is equivalent to eval(raw_input()). You can use this equivalence to limit things a bit, by providing some dictionaries to eval() to use in place of globals() and locals(), which will provide some degree of safety. You could also, if you were really ambitious, parse the input string yourself and thus have complete control over what operations were allowed and not allowed. This is rather overkill for the project at hand, though. ;) But, given that you're the only user and you presumably have some idea of the consequences of your actions (and nobody to blame but yourself if something *does* go wrong ;) ), then using input() is a reasonable solution. Jeff Shannon Technician/Programmer Credit International From bgailer at alum.rpi.edu Tue Jul 20 22:42:44 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Jul 20 22:41:29 2004 Subject: [Tutor] Hmm...I should be able to figure this out...but... In-Reply-To: <181B5DE8-DA82-11D8-8092-000D935360E0@ivytech.edu> References: <181B5DE8-DA82-11D8-8092-000D935360E0@ivytech.edu> Message-ID: <6.1.0.6.0.20040720143936.040344e0@mail.mric.net> At 01:22 PM 7/20/2004, Steven Combs wrote: >I am using the following code to simply take user input and return the >results backwards. > >--------------------------------------------------------------- ># Initialize Variables >string = "" >stringlength = 0 > ># Begin Program > >string = raw_input("Enter a string and I will display it backwards.\n") >stringlength = len(string) > >for i in range (stringlength, 0, -1): > print string [i - 1], > >print "\n" > >raw_input("\nPress the enter key to exit") > >--------------------------------------------------------------- > >It works, but it places a space in between the characters displayed. >For instance, if the string entered is: > >Test > >the results are displayed > >t s e T print puts a space after each ,. The easiest way to do what you want is to collect the letters in a string and print the string: output = '' for i in range (stringlength, 0, -1): output += i print output There are numerous other ways to do this, including reverse(), slicing, stdout,write(), et al. >I tried using "\b" to backspace after each character is displayed, but >this didn't work. I'm embarrassed to admit that I am trying to give this >as an assignment for a basic computer programming course I teach (I'm >stilling trying to learn the finer points of Python myself). I know I >could use other commands, but I have to limit the command set for the >students at this stage in their programming section (we have yet to >discuss mutability and immutability) Any suggestion for an easy fix? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From Dragonfirebane at aol.com Tue Jul 20 22:54:23 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Tue Jul 20 22:54:32 2004 Subject: [Tutor] Hmm...I should be able to figure this out...but... Message-ID: <5ECBE077.056B59CC.34E997B7@aol.com> ># Initialize Variables >string = "" >stringlength = 0 > ># Begin Program > >string = raw_input("Enter a string and I will display it backwards.\n") >stringlength = len(string) > >for i in range (stringlength, 0, -1): > print string [i - 1], > >print "\n" > >raw_input("\nPress the enter key to exit") try (untested): # Initialize Variables string = "" stringlength = 0 rstring = [] # Begin Program string = raw_input("Enter a string and I will display it backwards.\n") stringlength = len(string) for i in range (stringlength, 0, -1): rstring.append(string[i - 1]) print ''.join(rstring), print "\n" raw_input("\nPress the enter key to exit") -- "n thats the way the cookie crumbles" America's Favorite Cookie From alan.gauld at blueyonder.co.uk Tue Jul 20 23:19:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:19:27 2004 Subject: [Tutor] CGI References: Message-ID: <010b01c46e9f$4851c3b0$6401a8c0@xp> > Is it possible to create a common gateway interface in python? Yes, using the cgi module! :-) > If it is how do i submit data to it using vbscript? Exactly like any other CGI program - its a *Common* gateway interface, that is, it is the same regardless of language. So you just send an http GET or POST message from VBScript and Python will pick it up and extract the values into the field storage in the cgi module. The cgi documentation gives some simple examples. HTH, Alan G. From alan.gauld at blueyonder.co.uk Tue Jul 20 23:30:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:29:55 2004 Subject: [Tutor] ComboBox with Tkinter References: <001401c462ca$7994d790$d101a8c0@pukispc> Message-ID: <014301c46ea0$be5ec0c0$6401a8c0@xp> > and I thought a combobox should act the same way: > self.cb = Combobox(frame7, -1, choices['choice1','choice2'], value= > 'combobox')??? Tkinter has no combo box widget, you need to get PMW for that. A Google search should find it, and frankly I don't know why they don't just add PMW to the standard library. It is pretty much essential for serious Tkinter programming. > I haven't figured out what arguments HAVE to be there and what CAN be > there. Using the Tkinter tutorial and reference guide helps a lot. http://starship.python.net/lib.html > Can I handle this without wxPython? Yes using PMW (or building it from scratch which is what PMW does for you!) Alan G. From alan.gauld at blueyonder.co.uk Tue Jul 20 23:31:45 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:31:25 2004 Subject: [Tutor] Os.system on winXP system having trouble with spaces indirectory names References: <446DDE75CFC7E1438061462F85557B0F0373A04A@remail2.westat.com> Message-ID: <014b01c46ea0$f50143a0$6401a8c0@xp> > I'm having trouble with a using os.system on a windowsXP machine. > > Running: > os.system('start C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html') Put nested strings: os.system('start "C:\\Documents and Settings\\Smith_B2\\Desktop\\page.html"') or escape the spaces: os.system('start C:\\Documents\ and\ Settings\\Smith_B2\\Desktop\\page.html') Alan G From alan.gauld at blueyonder.co.uk Tue Jul 20 23:39:33 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:39:13 2004 Subject: [Tutor] Tkinter: checking a Text widget for contents/changes References: <40F869DB.4070800@att.net> Message-ID: <016c01c46ea2$0bd19b60$6401a8c0@xp> > I'm working on a simple text-editing application, and would like to > include a function to ask the user to save changes before quitting. Can > anyone describe a method for checking to see if anything has been > entered into a Text widget's buffer The classic way of doing this is to have a "dirty" flag. You set it to FAlse at startup and after a save. On any changes(text entry via keyboard or pasting etc) set the flag to True. At exit or Save you can check if dirty: self.SaveFile() This means you have to bind an event handler to all the input events plus the load and save events handlers. Not pretty but thats how its done in all the text editors I've worked on (that'd be precisely two! :-) Alan G From missive at hotmail.com Tue Jul 20 23:41:09 2004 From: missive at hotmail.com (Lee Harr) Date: Tue Jul 20 23:41:12 2004 Subject: [Tutor] Re: algorithm? Message-ID: >I am working on a web site development project and need to create >a script that would add >comments to the page that anyone can fill out.(something like a >discussion board) >Since I am want to develop this script from scratch using python , >I was wondering if anyone >has any good ideas as to how to go about with the same. >Basically the user would fill out his/her comments in a form and >they would have to be >appended to the page at a specific place. > Have you ever created a web application before? If not, I would suggest the first thing you want to do is set up some kind of server (might be a SimpleHTTPServer from the python base system, or you might want to use twisted from http://www.twistedmatrix.com/) and see if you can 1. display a page 2. display a form 3. get form data returned from the form 4. return another page 5. display form data returned from the form Once you can do those things you will be well on your way to creating your script. Other than that ... you will need to be much more specific with your questions in order for us to help (and include the code that you are using so that we can see what it is exactly that you are trying to do ...) _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From alan.gauld at blueyonder.co.uk Tue Jul 20 23:41:38 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:41:19 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? References: Message-ID: <017101c46ea2$56996fb0$6401a8c0@xp> > So xrange is definitely quicker. Is it better to use xrange all the time in > place of range then ? I haven't checked but my guess is that for small values range will be faster because it holds all the values in RAM and indexing will be faster than calculation. But if in doubt try it out... And tell us the result! Alan G. From alan.gauld at blueyonder.co.uk Tue Jul 20 23:44:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:43:49 2004 Subject: [Tutor] Want to use msvcrt.getch() but can't import msvcrt References: <6.1.2.0.2.20040716234123.04656640@rcblue.com> Message-ID: <018401c46ea2$b07c9b10$6401a8c0@xp> That should be msvcrt MicroSoft Visual C RunTime Its obvious really... :-) And I just checked, I got it right on the webn page :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ ----- Original Message ----- From: "Dick Moores" To: Sent: Saturday, July 17, 2004 8:01 AM Subject: [Tutor] Want to use msvcrt.getch() but can't import msvcrt > A week ago or so I asked how I might enable pausing my timer.py. Alan > Gauld suggested looking at the mscvrt module (which is available for > Windows) and mscvrt.getch(). He also referred me to a page of his > tutorial, > > This seems to be just what I'm looking for, but when I import mscvrt I get > "ImportError: No module named mscvrt". > > So I can't even run the scripts on his page. > > For your instructing convenience here's a bare-bones version of my timer: > > ============================= > #timer_simple.py > import time > #import mscvrt # gets "ImportError: No module named mscvrt" > > secondsToTime = int(raw_input("Seconds: ")) > timeStart = time.time() > timeNow = 0 > while True: > time.sleep(.25) > timeNow = time.time() > secondsPassed = timeNow - timeStart > secondsLeft = secondsToTime - secondsPassed > if secondsPassed >= secondsToTime: > break > > print "TIME'S UP! %d seconds have passed" % secondsToTime > print "Actual time is %f" % (timeNow - timeStart) > ================================== > > Alan suggested the time.sleep(.25) line to slow the loop down so I can do > something else with my computer while using the timer. He said to create > a "guard condition" by making the timeNow = time.time() line into an if > statement. If was able to import mscvrt and use mscvrt.getch() I suppose > I could figure this out by experimenting, but I can't even do that. > > I'd also like to build in a way to stop the time in mid-timing, without > resort to ^C or ^D. I suppose getch() is the thing to use here also. > > BTW I'm using Python 2.3.4 on Windows XP. > > Do I need to download the mscvrt from somewhere? > > Help, please? > > Thanks, tutors. > > Dick Moores > > > From alan.gauld at blueyonder.co.uk Tue Jul 20 23:46:15 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:45:55 2004 Subject: [Tutor] Re: CGI References: <001201c46bda$62595240$0095fea9@atyss> Message-ID: <018e01c46ea2$fb7ff1c0$6401a8c0@xp> > > What is vbscript? > > > It's Microsoft's Visual Basic, scripting edition. It is activeX enabled. > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/vbstutor.asp And only works on Internet Explorer on PCs running Windows. No good for Mac users of IE or users of any other browser. That's why most client side scripting is done in JavaScript - it works on almost any platform (unless it uses Active X in which case it is as broken as VBScript...) Alan G From alan.gauld at blueyonder.co.uk Tue Jul 20 23:50:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:50:16 2004 Subject: [Tutor] msvcrt.getch() References: <46.535f3de6.2e2ad0d7@aol.com> Message-ID: <01a401c46ea3$96d395f0$6401a8c0@xp> > >>> msvcrt.getch() > '\xff' > > This means that when I try running the script described at the above website, > a space does squat, as demonstrated below: > > >>> Thats because getch reads whats in the input immediately, it doesn't wait until you type something. So you have to put it inside a loop: while True: inp = msvcrt.getch() if inp: break Alan G. From alan.gauld at blueyonder.co.uk Tue Jul 20 23:57:59 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 20 23:57:39 2004 Subject: [Tutor] dangers of input() References: <00b801c46ddd$a2a0be60$6401a8c0@xp> <6.1.2.0.2.20040720041715.02452b48@rcblue.com> Message-ID: <020301c46ea4$9f2d8930$6401a8c0@xp> > I was thinking of using input() instead of raw_input in my Frac.py > (posted yesterday). This would enable the user to enter things such as > "4**-3". Am I correct in assuming that this would be impossible to do > without using input()? No, you could use eval() instead. eval() has the advantage of allowing you to sanity check the string before executing it. input allows a user to type import os; os.system('del *.*') > If so, I may go ahead with input()--I'm the only user, after all. If you will always be the sole user input is fine, I use it all the time for my own use, but be aware that own-use can often become shared use... Alan G. From alan.gauld at blueyonder.co.uk Wed Jul 21 00:01:56 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 21 00:01:36 2004 Subject: [Tutor] simple question about lists References: <26e9728704072009224ffe6722@mail.gmail.com> Message-ID: <020801c46ea5$2c64a8b0$6401a8c0@xp> > char board[3][3] > > I can't do multi dimensional lists in python can I? Am I right in > thinking that I would need to either use a one dimensional list or get > something like numeric to do this? Thanks in advance. You can do multi dimensional lists in Python, but there are a few gottchas to watch out for because Python holds everything as references (pointers to an old C hand) so you can wind up referencing the same object from multiple places if you aren't careful. The documentation warns of this. But otherwise row1 = [1,2,3] row2 = [4,5,6] matrix = [row1,row2] print matrix[0][1] # prints 2 You can also initialise in one step: m2 = [ [1,2,3], [4,5,6] ] HTH, Alan G. From alan.gauld at blueyonder.co.uk Wed Jul 21 00:04:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 21 00:03:48 2004 Subject: [Tutor] algorithm? References: <20040716173542.5597.qmail@webmail29.rediffmail.com> Message-ID: <021501c46ea5$7aeda3b0$6401a8c0@xp> Search the archives for the recent wiki project that unfolded here.... You should find several threads discussing how to do this. Alan G. ----- Original Message ----- From: "priyanka pareek" To: Sent: Friday, July 16, 2004 6:35 PM Subject: [Tutor] algorithm? > I am working on a web site development project and need to create > a script that would add > comments to the page that anyone can fill out.(something like a > discussion board) > Since I am want to develop this script from scratch using python , > I was wondering if anyone > has any good ideas as to how to go about with the same. > Basically the user would fill out his/her comments in a form and > they would have to be > appended to the page at a specific place. > > > Any suggestions > -prachi > > From rdm at rcblue.com Wed Jul 21 06:51:04 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jul 21 06:51:06 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <00dc01c46e82$683a1fa0$6401a8c0@xp> References: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> <00dc01c46e82$683a1fa0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040720214106.02120d58@rcblue.com> Alan Gauld wrote at 10:53 7/20/2004: > > for k in range(max): > >This line creates a list of max numbers. Each number takes up >several bytes of RAM(4+?). So 20 million numbers is over >80MB RAM being used. > >You probably should investigate generators for this kind of >thing, or at least use xrange() instread of range() > >Alan G. Yes, I went with xrange(). But you've got me curious. I looked up generators in _Learning Python_, 2nd ed. Not sure I understand them, but would you expect using a generator to be a faster way to count than using xrange()? Could you give me an example that would fit my spin3.py below? Thank you, Dick Moores ========================================== #spin3.py import time print """ Enter a positive integer n to count to n millions from zero. The counting will be done in two separate ways, and both will be timed. To quit, enter x or q at the prompt. """ while True: # for exiting via ^C or ^D try: max = raw_input("positive integer: ") except (TypeError, EOFError): print "Bye." break if len(max) == 0: print "Hey, don't just hit Enter, type an integer first!" continue if max in ["q", "x"]: print "Bye." break try: max = int(max) * 1000000 + 1 except: print "That's not an integer!" continue if max <= 0: print "That's not a positive integer!" continue print "Counting.." tStart = time.time() for k in xrange(max): pass tEnd = time.time() print "0 to %d in %.3f seconds!" % (k, (tEnd - tStart)) print "And now counting using a different loop.." c = 0 tStart = time.time() while c < max -1 : c += 1 tEnd = time.time() print "0 to %d in %.3f seconds!" % (c, (tEnd - tStart)) ====================================== -------------- next part -------------- #spin3.py import time print """ Enter a positive integer n to count to n millions from zero. The counting will be done in two separate ways, and both will be timed. To quit, enter x or q at the prompt. """ while True: # for exiting via ^C or ^D try: max = raw_input("positive integer: ") except (TypeError, EOFError): print "Bye." break if len(max) == 0: print "Hey, don't just hit Enter, type an integer first!" continue if max in ["q", "x"]: print "Bye." break try: max = int(max) * 1000000 + 1 except: print "That's not an integer!" continue if max <= 0: print "That's not a positive integer!" continue print "Counting.." tStart = time.time() for k in xrange(max): pass tEnd = time.time() print "0 to %d in %.3f seconds!" % (k, (tEnd - tStart)) print "And now counting using a different loop.." c = 0 tStart = time.time() while c < max -1 : c += 1 tEnd = time.time() print "0 to %d in %.3f seconds!" % (c, (tEnd - tStart)) From rdm at rcblue.com Wed Jul 21 07:26:19 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jul 21 07:26:22 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? In-Reply-To: <017101c46ea2$56996fb0$6401a8c0@xp> References: <017101c46ea2$56996fb0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040720221534.05aca268@rcblue.com> Alan Gauld wrote at 14:41 7/20/2004: > > So xrange is definitely quicker. Is it better to use xrange all the >time in > > place of range then ? > >I haven't checked but my guess is that for small values range will be >faster >because it holds all the values in RAM and indexing will be faster >than >calculation. > >But if in doubt try it out... >And tell us the result! > >Alan G. Not sure if 1,000,000 and 10,000,000 are small values, but here's what I get: positive integer: 1 (that's 1,000,000) Counting using xrange().. 0 to 1000000 in 0.156 seconds! positive integer: 10 Counting using xrange().. 0 to 10000000 in 1.485 seconds! positive integer: 1 Counting using range().. 0 to 1000000 in 0.172 seconds! positive integer: 10 Counting using range().. 0 to 10000000 in 1.766 seconds! So xrange() has the edge. I used this code, and switched from xrange() to range(): ============================== import time while True: # for exiting via ^C or ^D try: max = raw_input("positive integer: ") except (TypeError, EOFError): print "Bye." break if len(max) == 0: print "Hey, don't just hit Enter, type an integer first!" continue if max in ["q", "x"]: print "Bye." break try: max = int(max) * 1000000 + 1 except: print "That's not an integer!" continue if max <= 0: print "That's not a positive integer!" continue print "Counting using range().." tStart = time.time() for k in range(max): pass tEnd = time.time() print "0 to %d in %.3f seconds!" % (k, (tEnd - tStart)) ================================== Dick Moores From rdm at rcblue.com Wed Jul 21 12:52:09 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jul 21 12:52:14 2004 Subject: [Tutor] Hmm...I should be able to figure this out...but... Message-ID: <6.1.2.0.2.20040721035151.020d2fb0@rcblue.com> Dragonfirebane@aol.com wrote at 13:54 7/20/2004: >try (untested): > ># Initialize Variables >string = "" >stringlength = 0 >rstring = [] > ># Begin Program > >string = raw_input("Enter a string and I will display it backwards.\n") >stringlength = len(string) > >for i in range (stringlength, 0, -1): > rstring.append(string[i - 1]) > print ''.join(rstring), > >print "\n" > >raw_input("\nPress the enter key to exit") This works fine if the loop and print are: for i in range (stringlength, 0, -1): rstring.append(string[i - 1]) print ''.join(rstring) Sorry for what is surely a dumb question, but what is the ". in print ''.join(rstring). Can't find this anywhere in the Python docs. Thanks, Dick Moores From Francis.Moore at shaws.co.uk Wed Jul 21 13:19:37 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Wed Jul 21 13:20:56 2004 Subject: [Tutor] Hmm...I should be able to figure this out...but... Message-ID: <6081EBC21D52F744B484088BBBE665C32EEB62@sbserver.shaws.local> From: Dick Moores [mailto:rdm@rcblue.com] > print ''.join(rstring) > Sorry for what is surely a dumb question, but > what is the ". in print ''.join(rstring). > Can't find this anywhere in the Python docs. This is a Pythonic way of calling the string method join() to concatenate all the elements of the sequence 'rstring'. The call uses an empty string ('') as an intermediate/temporary object to hold the result. 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 kalle at lysator.liu.se Wed Jul 21 13:49:10 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Wed Jul 21 13:45:06 2004 Subject: [Tutor] Hmm...I should be able to figure this out...but... In-Reply-To: <6.1.2.0.2.20040721035151.020d2fb0@rcblue.com> References: <6.1.2.0.2.20040721035151.020d2fb0@rcblue.com> Message-ID: <20040721114910.GG17540@i92.ryd.student.liu.se> [Dick Moores] > Sorry for what is surely a dumb question, but what is the ". in > print ''.join(rstring). Can't find this anywhere in the Python docs. '' is a string object (the empty string). ''.join is the method join of the string object. ''.join(rstring) is the join method of the string object called with rstring as an argument. There's more about string methods in the documentation: http://python.org/doc/lib/string-methods.html Peace, Kalle -- http://juckapan.org/~kalle/ http://laxmasteriet.se/04-05/ From rdm at rcblue.com Wed Jul 21 14:14:29 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Jul 21 14:14:30 2004 Subject: [Tutor] Hmm...I should be able to figure this out...but... In-Reply-To: <20040721114910.GG17540@i92.ryd.student.liu.se> References: <6.1.2.0.2.20040721035151.020d2fb0@rcblue.com> <20040721114910.GG17540@i92.ryd.student.liu.se> Message-ID: <6.1.2.0.2.20040721051022.023d8e48@rcblue.com> My thanks to Francis Moore and Kalle Svensson for their fast and understandable replies. My problem was, in part, not seeing '' as an empty string. "" I might have recognized.. Dick Moores From STEVEN.M.FAULCONER at saic.com Wed Jul 21 15:24:17 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Wed Jul 21 15:31:02 2004 Subject: [Tutor] Tkinter / Variable passing Message-ID: <207DA77D2384D411A48B0008C7095D81C1DE66@us-melbourne.mail.saic.com> Hello everyone, Been working on a Tkinter/PMW application that acts as a graphical front end to several command-line programs. The gist of the program is this: User starts program, instantiates MainApp class. User selects a project and a 'database' (a term for a flat file, binary database used by our software, not an SQL-type database), and clicks the select button. This instantiates the CheckerApp class that gives the user the option to run the various command-line programs or view their reports. When the user clicks a button to run a checker, it instantiates the CheckerWindow class that essentially redirects the output of the command line program and displays it in a Tkinter window. The user then clicks accept/cancel to accept the software run or not accept. This is where the issue lies. How can I tell the CheckerApp instance what the user selected in the CheckerWindow instance? I've tried different types of variables (global and non). I've even added a function to the CheckerApp that I attempt to call from the CheckerWindow, which fails with an "AttributeError" Toplevel instance has no attribute 'CheckerAccept'". Anyone have any thoughts or ideas? Constructive criticism on the script would be greatly appreciated. I'm fairly new to Python and VERY new to Tkinter/GUI programming, so any suggestions would be wonderful. Something I would like to do eventually is have the 'checkers' defined in a list/dictionary, and build the GUI elements from the contents of that list/dictionary. I just haven't gotten that far yet. Also, the program isn't finished, and if you don't have the software we use installed, it won't work as is. Thanks in advance for any information you can send. Steven -------------- next part -------------- A non-text attachment was scrubbed... Name: main.py Type: application/octet-stream Size: 22100 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040721/6721a8be/main-0001.obj From STEVEN.M.FAULCONER at saic.com Wed Jul 21 15:38:47 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Wed Jul 21 15:45:24 2004 Subject: [Tutor] Tkinter / Variable passing Message-ID: <207DA77D2384D411A48B0008C7095D81C1DE6A@us-melbourne.mail.saic.com> I hit send a little too soon. Specifics: ActiveState Python 2.3.2 Pmw 1.2 Windows 2000 SP 4 Thanks. -----Original Message----- From: tutor-bounces+steven.m.faulconer=saic.com@python.org [mailto:tutor-bounces+steven.m.faulconer=saic.com@python.org] On Behalf Of Faulconer, Steven M. Sent: Wednesday, July 21, 2004 9:24 AM To: 'tutor@python.org' Subject: [Tutor] Tkinter / Variable passing Hello everyone, Been working on a Tkinter/PMW application that acts as a graphical front end to several command-line programs. The gist of the program is this: User starts program, instantiates MainApp class. User selects a project and a 'database' (a term for a flat file, binary database used by our software, not an SQL-type database), and clicks the select button. This instantiates the CheckerApp class that gives the user the option to run the various command-line programs or view their reports. When the user clicks a button to run a checker, it instantiates the CheckerWindow class that essentially redirects the output of the command line program and displays it in a Tkinter window. The user then clicks accept/cancel to accept the software run or not accept. This is where the issue lies. How can I tell the CheckerApp instance what the user selected in the CheckerWindow instance? I've tried different types of variables (global and non). I've even added a function to the CheckerApp that I attempt to call from the CheckerWindow, which fails with an "AttributeError" Toplevel instance has no attribute 'CheckerAccept'". Anyone have any thoughts or ideas? Constructive criticism on the script would be greatly appreciated. I'm fairly new to Python and VERY new to Tkinter/GUI programming, so any suggestions would be wonderful. Something I would like to do eventually is have the 'checkers' defined in a list/dictionary, and build the GUI elements from the contents of that list/dictionary. I just haven't gotten that far yet. Also, the program isn't finished, and if you don't have the software we use installed, it won't work as is. Thanks in advance for any information you can send. Steven From heslot at lpa.ens.fr Wed Jul 21 15:46:19 2004 From: heslot at lpa.ens.fr (Heslot Francois) Date: Wed Jul 21 15:46:07 2004 Subject: [Tutor] how to simply run a .py file Message-ID: <6.1.1.1.0.20040721153745.030502b0@pop.lpa.ens.fr> Hello, I am a complete beginner. I simply would like to run a .py program that I downloaded I do not find how to do it ! (the program in question takes an Endnote bibliographic file, and converts it to a format suitable for LatexBibtex (which is a pain in the ass to type when the number of references is high)) I have installed Python, and I have the .py file now what ? Francois From vk33 at mail.ru Wed Jul 21 15:52:43 2004 From: vk33 at mail.ru (Dmitriy D.) Date: Wed Jul 21 15:52:46 2004 Subject: [Tutor] how to simply run a .py file In-Reply-To: <6.1.1.1.0.20040721153745.030502b0@pop.lpa.ens.fr> Message-ID: If you have installed Python on Windows it should have set up the file associations during the installation. So you can just double-click your script. If the file association is not set up, you can launch your script by launching python interpreter with your script as an argument: C:\Python\python myscript.py Good luck! ----------------------------- Don't limit your challenges, Challenge your limits! From Francis.Moore at shaws.co.uk Wed Jul 21 16:00:30 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Wed Jul 21 16:01:40 2004 Subject: [Tutor] how to simply run a .py file Message-ID: <6081EBC21D52F744B484088BBBE665C32EEB66@sbserver.shaws.local> From: Heslot Francois [mailto:heslot@lpa.ens.fr] > I simply would like to run a .py program that I downloaded Imagine that your Python installation directory is C:\Python24. And your .py file resides in C:\Temp and is called Test.py. Go to the command line on your OS. At the command prompt type $ C:\Python24\Python.exe C:\Temp\Test.py This is the longhand way of doing it. A shorter way is to add Python to your environment path. Then you can shorten the command to: $ Python C:\Temp\Test.py An even shorter way is to set default to C:\Temp. Then the command becomes: $ Python Test.py 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 lbblair at adaptisinc.com Wed Jul 21 17:15:50 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Wed Jul 21 17:19:04 2004 Subject: [Tutor] how popen works? Message-ID: I am new to Python and have inherited some difficult code. I am expanding the functionallity because I can read and figure out what is already there. I just don't have enough background with Python to know how and why some things work the way they to. My script is shutting down an Oracle database, updating snapshots on an EMC san, and then restarting the Oracle database. To restart the database I call, via popen, a SQLPlus script, this script takes about 90 seconds to execute. I thought that Python at the popoen line would wait until the SQLPlus script was finished and then continue with the next line of code. I want to do some error trapping AFTER the database us running. Python however sends the SQLPlus script and then continues executing the rest of the program. Am I not understanding what popen does or is there a parameter I need to send to it to pause until it is finished, or is there a better way of "shelling" out to the OS and exeuting commands. Here are examples of what I have tried. Both commands work the same - send the command to the OS and comes right back and finishes running the script. We have Win2000 as an OS 1. in this I create a cmd window and with the /c tell it to close after sqlplus is finished syncCommand = 'cmd /c sqlplus /nolog @%s' %(local_ccf) pipeFile = os.popen("%s" %str(syncCommand)) 2. in this I directly call sqlplus syncCommand = 'sqlplus /nolog @%s' %(local_ccf) pipeFile = os.popen("%s" %str(syncCommand)) Thanks for any insight to this Larry __________________________________ 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 bgailer at alum.rpi.edu Wed Jul 21 20:57:46 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Jul 21 20:57:13 2004 Subject: {Spam?} [Tutor] how popen works? In-Reply-To: References: Message-ID: <6.1.0.6.0.20040721124851.0270d408@mail.mric.net> At 09:15 AM 7/21/2004, Larry Blair wrote: >I am new to Python and have inherited some difficult code. I am expanding >the functionallity because I can read and figure out what is already there. >I just don't have enough background with Python to know how and why some >things work the way they to. > >My script is shutting down an Oracle database, updating snapshots on an EMC >san, and then restarting the Oracle database. > >To restart the database I call, via popen, a SQLPlus script, this script >takes about 90 seconds to execute. I thought that Python at the popoen line >would wait until the SQLPlus script was finished and then continue with the >next line of code. I want to do some error trapping AFTER the database us >running. Python however sends the SQLPlus script and then continues >executing the rest of the program. > >Am I not understanding what popen does or is there a parameter I need to >send to it to pause until it is finished, or is there a better way of >"shelling" out to the OS and exeuting commands. > >Here are examples of what I have tried. Both commands work the same - send >the command to the OS and comes right back and finishes running the script. "The return value [of popen] is an open file object connected to the pipe, which can be read." So, after: pipeFile = os.popen("%s" %str(syncCommand)) put: x = pipeFile.readline() # this should wait until the process returns output or terminates. If there are several lines of output, use readlines() or process readline in a loop. status = pipeFile.close() # to get the exit status. >We have Win2000 as an OS > >1. > >in this I create a cmd window and with the /c tell it to close after sqlplus >is finished > > syncCommand = 'cmd /c sqlplus /nolog @%s' %(local_ccf) > pipeFile = os.popen("%s" %str(syncCommand)) > > >2. > >in this I directly call sqlplus > > syncCommand = 'sqlplus /nolog @%s' %(local_ccf) > pipeFile = os.popen("%s" %str(syncCommand)) > >Thanks for any insight to this >Larry > > > > > >__________________________________ >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. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From klappnase at freenet.de Wed Jul 21 22:28:46 2004 From: klappnase at freenet.de (Michael Lange) Date: Wed Jul 21 22:26:27 2004 Subject: [Tutor] Tkinter / Variable passing In-Reply-To: <207DA77D2384D411A48B0008C7095D81C1DE66@us-melbourne.mail.saic.com> References: <207DA77D2384D411A48B0008C7095D81C1DE66@us-melbourne.mail.saic.com> Message-ID: <20040721222846.69838ef1.klappnase@freenet.de> On Wed, 21 Jul 2004 06:24:17 -0700 "Faulconer, Steven M." wrote: > > This is where the issue lies. How can I tell the CheckerApp instance what > the user selected in the CheckerWindow instance? I've tried different types > of variables (global and non). I've even added a function to the CheckerApp > that I attempt to call from the CheckerWindow, which fails with an > "AttributeError" Toplevel instance has no attribute 'CheckerAccept'". > In line 252 of your script you create your CheckerWindow instance: > CheckerWindow( self.newroot, 'Feature Count', command ) where self.newroot is an instance of Tkinter.Toplevel . Your method "CheckerAccept()" is a method of the CheckerApp class. So when you call > self.myparent.CheckerAccept() and self.myparent is a Tkinter.Toplevel python is right to complain. There are two possibilities to fix this: 1. make your CheckerApp instance an attribute of the CheckerWindow class, like this: class CheckerWindow: def __init__( self, parent, checkerApp, checker, command ): self.checkerApp = checkerApp and pass "self" as argument for checkerApp when you create the CheckerWindow from within the CheckerApp: > CheckerWindow( self.newroot, self, 'Feature Count', command ) Then you could call > self.checkerApp.CheckerAccept() 2. make your CheckerApp class a subclass of Tkinter.Toplevel class CheckerApp(Tkinter.Toplevel): def __init__( self, parent, project, database, dbpath ): Tkinter.Toplevel.__init__(self, parent) # Window Initialization routines self.PROJECT = project self.DATABASE = database self.DBPATH = dbpath self.resizable( width = False, height = False ) self.option_add( "*Font", "Arial 12" ) self.title( "SAIC Checker Front End" ) self.focus_set() self.Status = 0 and then pass "self" as parent to the CheckerWindow: > CheckerWindow( self, 'Feature Count', command ) I hope this helps Michael From tpc at csua.berkeley.edu Wed Jul 21 23:09:12 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Jul 21 23:09:19 2004 Subject: [Tutor] replacing lists with iterators Message-ID: <20040721132419.P40217-100000@localhost.name> hi everybody, I wrote a program consisting of three scripts to automate encoding of WAVs to MP3s, and while putting in the finishing touches I realized I was using some constructs that many experienced Python programmers would frown upon. For instance, in one function that takes two lists as arguments I used map to iterate through both lists at the same time to set up a source and target for an os.system command. I've been reading how lists, which are completed sequences, can now be replaced with iterators, which are lazy sequences, to make more efficient use of memory. I would like to know how: *) you would use a iterator to store the source and target paths *) to iterate over two iterables at the same time def getListOfFullPathsToWAVs(SOURCE_DOCUMENT_ROOT): listOfFullPathsToWAVs = [] for rootdir, subdir, files in walk(SOURCE_DOCUMENT_ROOT): for filename in files: if filename.endswith('.wav'): fullPath = join(rootdir, filename) listOfFullPathsToWAVs.append(fullPath) return listOfFullPathsToWAVs def getListOfFullPathsToTargets(listOfFullPathsToWAVs, TARGET_FILE_TYPE): listOfFullPathsToTargets = [] for fullPathToWAV in listOfFullPathsToWAVs: fullPathToWAV = fullPathToWAV.replace(SOURCE_DOCUMENT_ROOT, TARGET_DOCUMENT_ROOT) filenameTuple = splitext(basename(fullPathToWAV)) fullPath = dirname(fullPathToWAV) + sep + TARGET_FILE_TYPE + sep + filenameTuple[0] + "." + TARGET_FILE_TYPE listOfFullPathsToTargets.append(fullPath) return listOfFullPathsToTargets def executeSystemCommandToEncodeWAVsAsTargets(listOfFullPathsToWAVs, listOfFullPathsToTargets): for fullPathToWAV, fullPathToTarget in map(None, listOfFullPathsToWAVs, listOfFullPathsToTargets): fullPathTargetTuple = splitext(fullPathToTarget) if fullPathTargetTuple[1] == '.mp3': system("lame % s % s") % (fullPathToWAV, fullPathToTarget) From alan.gauld at blueyonder.co.uk Wed Jul 21 23:37:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 21 23:36:46 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? References: <017101c46ea2$56996fb0$6401a8c0@xp> <6.1.2.0.2.20040720221534.05aca268@rcblue.com> Message-ID: <004c01c46f6a$e8ae2580$6401a8c0@xp> > Not sure if 1,000,000 and 10,000,000 are small values, I was thinking more in terms of less than 1000... :-) I might get round to trying it sometime... The problem with such small numbers is finding a test thats measurable and isn't slewed by the processing inside the loop. I suspect the Python profiler might be needed to do it properly... Alan G. From alan.gauld at blueyonder.co.uk Wed Jul 21 23:38:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Jul 21 23:37:56 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? References: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com> <00dc01c46e82$683a1fa0$6401a8c0@xp> <6.1.2.0.2.20040720214106.02120d58@rcblue.com> Message-ID: <005501c46f6b$120a3860$6401a8c0@xp> > Yes, I went with xrange(). But you've got me curious. I looked up > generators in _Learning Python_, 2nd ed. Not sure I understand them, but > would you expect using a generator to be a faster way to count than using > xrange()? Could you give me an example that would fit my spin3.py below? Not necessarily faster but it would lock up the PC as you originally saw. I think I read that generators are replacing xrange (or maybe xrange is just reimplemented using generators?) Alan G From alan.gauld at blueyonder.co.uk Thu Jul 22 00:32:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 22 00:31:37 2004 Subject: [Tutor] how to simply run a .py file References: <6.1.1.1.0.20040721153745.030502b0@pop.lpa.ens.fr> Message-ID: <006901c46f72$91f2cd60$6401a8c0@xp> > I simply would like to run a .py program that I downloaded > I do not find how to do it ! > > (the program in question takes an Endnote bibliographic file, and converts > it to a format suitable for LatexBibtex (which is a pain in the ass to type > when the number of references is high)) > > I have installed Python, and I have the .py file > now what ? Since you are using Latex I'll guess you are on Linux? If so then check that the first line of the python script has a line like this: #! /bin/env python If it has then you can run the python script byy simply double clicking in your favourite file manager or from a terminal prompt by typing its name: $ foo.py It might need some command line arguments too but without knowledge of the actual script I can't say... If you are using Windows then the python file should be showing a green snake icon in Windows Explorer, in which case just double click to run it. HTH, Alan G. From alan.gauld at blueyonder.co.uk Thu Jul 22 00:38:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 22 00:37:31 2004 Subject: [Tutor] how popen works? References: Message-ID: <007201c46f73$65719040$6401a8c0@xp> > To restart the database I call, via popen, a SQLPlus script, this script > takes about 90 seconds to execute. I thought that Python at the popoen line > would wait until the SQLPlus script was finished and then continue with the > next line of code. Normally it would unless the command itself is set to run in the background. > Am I not understanding what popen does or is there a parameter I need to > send to it to pause until it is finished, or is there a better way of > "shelling" out to the OS and exeuting commands. popen() is used where you need to read the output of the command. If you just need the return code from the command then os.system() is easier to use. > in this I create a cmd window and with the /c tell it to close after sqlplus > is finished > > syncCommand = 'cmd /c sqlplus /nolog @%s' %(local_ccf) > pipeFile = os.popen("%s" %str(syncCommand)) > This would be easier with: pipefile = popen(syncCommand) The extra level of string formatting and conversion is doing nothing useful. Also to read the results of the command you will need to read the results of popen like output = pipefile.read() Dunno if that helps... Alan G From alan.gauld at blueyonder.co.uk Thu Jul 22 00:51:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 22 00:50:45 2004 Subject: [Tutor] replacing lists with iterators References: <20040721132419.P40217-100000@localhost.name> Message-ID: <007f01c46f75$3eb7b4a0$6401a8c0@xp> > programmers would frown upon. For instance, in one function that takes > two lists as arguments I used map to iterate through both lists at the > same time to set up a source and target for an os.system command. Nothing wrong with that approach although list comprehensions might be more efficient. But for your app the construction of the command lines will likely be a tiny proportion of the total process time. > been reading how lists, which are completed sequences, can now be replaced > with iterators, which are lazy sequences, to make more efficient use of > memory. I would like to know how: > *) you would use a iterator to store the source and target paths > *) to iterate over two iterables at the same time Frankly I wouldn't bother unless you have a huge number of files to convert(think thousands). Iterators are neat but they require more work than the built in lists and the built in lists are there to make life easy! > for fullPathToWAV, fullPathToTarget in map(None, listOfFullPathsToWAVs, listOfFullPathsToTargets): In this case zip() is more appropriate that map() with None IMHO: for w,t in zip(listOfWAVs, listOfTargets): Alan G. From marilyn at deliberate.com Thu Jul 22 02:31:58 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Jul 22 02:32:02 2004 Subject: [Tutor] how popen works? In-Reply-To: <007201c46f73$65719040$6401a8c0@xp> Message-ID: Alan, While we're talking about popen, I'll ask you about a trouble I'm having with it. According to the documentation, you can only tell if the command failed when you close the pipe. If it failed, it returns a tuple, otherwise it returns None. When my popen call fails, it seems to return an int at the close. And I can only figure what has gone wrong by trial and error. So my code looks like: status = pipe.close() log.it("Closed pipe to exim with status = " + str(type(status)) + str(status)) if not status: return log.it('status: ' + str(status)) if status == 32512: log.it( "popen(" + command + ''', "w") not found.''') if status == 32256: log.it("popen(" + command + ''', "w") no permissions.''') if status == 256: log.it("popen(" + command + ''', "w") no permission for ''' + EXIM_OUTPUT) And I found those numbers by experimenting. So if I ruin the permission on EXIM_OUTPUT, my log looks like: Wed Jul 21 17:27:02 2004: Closing pipe to exim Wed Jul 21 17:27:02 2004: Closed pipe to exim with status = 256 Wed Jul 21 17:27:02 2004: status: 256 Wed Jul 21 17:27:02 2004: popen(/b/home/exim/bin/exim -t -oMr skip_doorman -d+expand >& /tmp/to_exim.output, "w") no permission for /tmp/to_exim.output I wonder what I'm missing? Marilyn Davis From kyeser at earthlink.net Thu Jul 22 03:22:26 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Thu Jul 22 03:22:29 2004 Subject: [Tutor] Is there a better way to do this? Message-ID: <97AF02DA-DB7D-11D8-A37A-000393479EE8@earthlink.net> I'm trying to write a program that computes six-digit numbers, in which the left digit is always smaller than its following digit (i.e., it's always ascending). The output of the program starts with "0 1 2 3 4 5" and ends on "6 7 8 9 A B." The best I could do was to have many embedded 'for' statements: c = 1 for p0 in range(0, 7): for p1 in range(1, 12): for p2 in range(2, 12): for p3 in range(3, 12): for p4 in range(4, 12): for p5 in range(5, 12): if p0 < p1 < p2 < p3 < p4 < p5: print repr(c).rjust(3), "\t", print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) c += 1 print "...Done" This works, except that it's very slow. I need to get it up to nine-digit numbers, in which case it's significantly slower. I was wondering if there is a more efficient way to do this. I would highly appreciate it if anyone could help. Many thanks. -Kye From jb at riseup.net Thu Jul 22 03:45:15 2004 From: jb at riseup.net (jb) Date: Thu Jul 22 03:36:12 2004 Subject: [Tutor] Is there a better way to do this? In-Reply-To: <97AF02DA-DB7D-11D8-A37A-000393479EE8@earthlink.net> References: <97AF02DA-DB7D-11D8-A37A-000393479EE8@earthlink.net> Message-ID: <20040722014515.GA18331@tsoupi.fl.sakeos.net> On Wed, Jul 21, 2004 at 09:22:26PM -0400, Hee-Seng Kye wrote: > I'm trying to write a program that computes six-digit numbers, in which > the left digit is always smaller than its following digit (i.e., it's > always ascending). The output of the program starts with "0 1 2 3 4 5" > and ends on "6 7 8 9 A B." The best I could do was to have many > embedded 'for' statements: > > c = 1 > for p0 in range(0, 7): > for p1 in range(1, 12): > for p2 in range(2, 12): > for p3 in range(3, 12): > for p4 in range(4, 12): > for p5 in range(5, 12): > if p0 < p1 < p2 < p3 < p4 < p5: > print repr(c).rjust(3), "\t", > print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) > c += 1 > print "...Done" > > This works, except that it's very slow. I need to get it up to > nine-digit numbers, in which case it's significantly slower. I was > wondering if there is a more efficient way to do this. > this version is a bit quicker: c = 1 for p0 in range(0, 7): for p1 in range(p0+1, 12): for p2 in range(p1+1, 12): for p3 in range(p2+1, 12): for p4 in range(p3+1, 12): for p5 in range(p4+1, 12): print repr(c).rjust(3), "\t", print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) c += 1 print "...Done" From operate777 at adelphia.net Thu Jul 22 03:40:53 2004 From: operate777 at adelphia.net (operate777@adelphia.net) Date: Thu Jul 22 03:40:55 2004 Subject: [Tutor] how do i start Message-ID: <20040722014052.FIWQ2023.mta9.adelphia.net@mail.adelphia.net> hello, i'm just starting to program with python... Heres my question is run script same as run module? From STEVEN.M.FAULCONER at saic.com Thu Jul 22 15:52:29 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Thu Jul 22 15:59:04 2004 Subject: [Tutor] Tkinter / Variable passing Message-ID: <207DA77D2384D411A48B0008C7095D81C1DE71@us-melbourne.mail.saic.com> Michael, Thank you very much. I liked the method you used in the second option, which worked quite well. Thanks again for the response. Steven Faulconer -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Michael Lange Sent: Wednesday, July 21, 2004 4:29 PM To: tutor@python.org Subject: Re: [Tutor] Tkinter / Variable passing On Wed, 21 Jul 2004 06:24:17 -0700 "Faulconer, Steven M." wrote: > > This is where the issue lies. How can I tell the CheckerApp instance > what the user selected in the CheckerWindow instance? I've tried > different types of variables (global and non). I've even added a > function to the CheckerApp that I attempt to call from the > CheckerWindow, which fails with an "AttributeError" Toplevel instance > has no attribute 'CheckerAccept'". > In line 252 of your script you create your CheckerWindow instance: > CheckerWindow( self.newroot, 'Feature Count', command ) where self.newroot is an instance of Tkinter.Toplevel . Your method "CheckerAccept()" is a method of the CheckerApp class. So when you call > self.myparent.CheckerAccept() and self.myparent is a Tkinter.Toplevel python is right to complain. There are two possibilities to fix this: 1. make your CheckerApp instance an attribute of the CheckerWindow class, like this: class CheckerWindow: def __init__( self, parent, checkerApp, checker, command ): self.checkerApp = checkerApp and pass "self" as argument for checkerApp when you create the CheckerWindow from within the CheckerApp: > CheckerWindow( self.newroot, self, 'Feature Count', command ) Then you could call > self.checkerApp.CheckerAccept() 2. make your CheckerApp class a subclass of Tkinter.Toplevel class CheckerApp(Tkinter.Toplevel): def __init__( self, parent, project, database, dbpath ): Tkinter.Toplevel.__init__(self, parent) # Window Initialization routines self.PROJECT = project self.DATABASE = database self.DBPATH = dbpath self.resizable( width = False, height = False ) self.option_add( "*Font", "Arial 12" ) self.title( "SAIC Checker Front End" ) self.focus_set() self.Status = 0 and then pass "self" as parent to the CheckerWindow: > CheckerWindow( self, 'Feature Count', command ) I hope this helps Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From orbitz at ezabel.com Thu Jul 22 19:01:32 2004 From: orbitz at ezabel.com (orbitz) Date: Thu Jul 22 19:01:39 2004 Subject: [Tutor] how do i start In-Reply-To: <20040722014052.FIWQ2023.mta9.adelphia.net@mail.adelphia.net> References: <20040722014052.FIWQ2023.mta9.adelphia.net@mail.adelphia.net> Message-ID: <40FFF2EC.9030000@ezabel.com> You generally don't run modules, they are meant to be imported. operate777@adelphia.net wrote: >hello, i'm just starting to program with python... Heres my question is run script same as run module? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From bgailer at alum.rpi.edu Thu Jul 22 19:16:18 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Jul 22 19:15:09 2004 Subject: {Spam?} Re: [Tutor] Is there a better way to do this? In-Reply-To: <20040722014515.GA18331@tsoupi.fl.sakeos.net> References: <97AF02DA-DB7D-11D8-A37A-000393479EE8@earthlink.net> <20040722014515.GA18331@tsoupi.fl.sakeos.net> Message-ID: <6.1.0.6.0.20040722110148.02707160@mail.mric.net> At 07:45 PM 7/21/2004, jb wrote: >On Wed, Jul 21, 2004 at 09:22:26PM -0400, Hee-Seng Kye wrote: > > I'm trying to write a program that computes six-digit numbers, in which > > the left digit is always smaller than its following digit (i.e., it's > > always ascending). The output of the program starts with "0 1 2 3 4 5" > > and ends on "6 7 8 9 A B." The best I could do was to have many > > embedded 'for' statements: > > > > c = 1 > > for p0 in range(0, 7): > > for p1 in range(1, 12): > > for p2 in range(2, 12): > > for p3 in range(3, 12): > > for p4 in range(4, 12): > > for p5 in range(5, 12): > > if p0 < p1 < p2 < p3 < p4 < p5: > > print repr(c).rjust(3), "\t", > > print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) > > c += 1 > > print "...Done" > > > > This works, except that it's very slow. I need to get it up to > > nine-digit numbers, in which case it's significantly slower. I was > > wondering if there is a more efficient way to do this. > > > >this version is a bit quicker: > >c = 1 >for p0 in range(0, 7): > for p1 in range(p0+1, 12): > for p2 in range(p1+1, 12): > for p3 in range(p2+1, 12): > for p4 in range(p3+1, 12): > for p5 in range(p4+1, 12): > print repr(c).rjust(3), "\t", > print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) > c += 1 >print "...Done" When I run the loops without printing on my (I think 2 GHZ with 512 M ram) machine it takes .002 seconds. Adding the expressions used in the print statements without printing raises it to .01 seconds. Running with printing takes about 2.5 seconds. 925 numbers get created in the process. What is your mileage? What is your processor speed/RAM? How are you running the program? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From vijaykumar at linuxmail.org Thu Jul 22 20:10:51 2004 From: vijaykumar at linuxmail.org (Vijay Kumar Bagavath Singh) Date: Thu Jul 22 20:10:21 2004 Subject: [Tutor] Is there a better way to do this? Message-ID: <20040722181051.7047B23C0B@ws5-3.us4.outblaze.com> jb wrote: > > > > c = 1 > > for p0 in range(0, 7): > > for p1 in range(1, 12): > > for p2 in range(2, 12): > > for p3 in range(3, 12): > > for p4 in range(4, 12): > > for p5 in range(5, 12): > > if p0 < p1 < p2 < p3 < p4 < p5: > > print repr(c).rjust(3), "\t", > > print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) > > c += 1 > > print "...Done" > > > > This works, except that it's very slow. I need to get it up to > > nine-digit numbers, in which case it's significantly slower. I was > > wondering if there is a more efficient way to do this. > > > > this version is a bit quicker: > > c = 1 > for p0 in range(0, 7): > for p1 in range(p0+1, 12): > for p2 in range(p1+1, 12): > for p3 in range(p2+1, 12): > for p4 in range(p3+1, 12): > for p5 in range(p4+1, 12): > print repr(c).rjust(3), "\t", > print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) > c += 1 > print "...Done" > That was a really great improvement. The following code acheives a little more improvement. c = 1 r = tuple([tuple(range(i, 12)) for i in range(0, 13)]) for p0 in range(0, 7): for p1 in r[p0+1]: for p2 in r[p1+1]: for p3 in r[p2+1]: for p4 in r[p3+1]: for p5 in r[p4+1]: if p0 < p1 < p2 < p3 < p4 < p5: print repr(c).rjust(3), "\t", print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) c += 1 print "...Done" Vijay -- ______________________________________________ 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 kyeser at earthlink.net Thu Jul 22 22:22:29 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Thu Jul 22 22:22:31 2004 Subject: [Tutor] Is there a better way to do this? In-Reply-To: <20040722181051.7047B23C0B@ws5-3.us4.outblaze.com> References: <20040722181051.7047B23C0B@ws5-3.us4.outblaze.com> Message-ID: Thanks a lot everyone for suggestions. On my slow machine (667 MHz), inefficient programs run even slower, and when I expand the program to calculate 9-digit numbers, there is almost a 2-minute difference! Thanks again. Best, Kye From alan.gauld at blueyonder.co.uk Thu Jul 22 22:45:13 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 22 22:44:21 2004 Subject: [Tutor] Why does counting to 20 million stress my computer? References: <6.1.2.0.2.20040716021855.04a24ec0@rcblue.com><00dc01c46e82$683a1fa0$6401a8c0@xp><6.1.2.0.2.20040720214106.02120d58@rcblue.com> <005501c46f6b$120a3860$6401a8c0@xp> Message-ID: <001701c4702c$c9f009c0$6401a8c0@xp> > > would you expect using a generator to be a faster way to count than > > Not necessarily faster but it would lock up the PC as you originally Doh! that should of course say would NOT lock up... Alan G. From alan.gauld at blueyonder.co.uk Thu Jul 22 23:08:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 22 23:08:01 2004 Subject: [Tutor] Is there a better way to do this? References: <97AF02DA-DB7D-11D8-A37A-000393479EE8@earthlink.net> Message-ID: <002401c47030$18cee590$6401a8c0@xp> This might help: > c = 1 > for p0 in range(0, 7): > for p1 in range(p0, 12): > for p2 in range(p1, 12): > for p3 in range(p2, 12): > for p4 in range(p3, 12): > for p5 in range(p4, 12): > print repr(c).rjust(3), "\t", > print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) > c += 1 Not sure what the c increment does but I'll leave it in! > print "...Done" Ultimately you have to generate all the permutations but by eliminating the ones you already know are invalid it should speed it up a bit. Alan G. From smith-matt at tiscali.co.uk Thu Jul 22 23:19:13 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Thu Jul 22 23:14:12 2004 Subject: [Tutor] Re: Re: problem writing random_word function References: <1090249991.2141.44.camel@laptop.venix.com> <32b5ee76040719113272dafac8@mail.gmail.com> Message-ID: Thanks for all of the help, I've modified the function to hopefully take into account all of the suggestions. I know the filename is still hard coded. I'm leaving it as so until I decide how to get the file name to use (maybe an option in the program or a command line argument). Anyway, heres the function: import random def random_word(word_length): """Returns a random word of length word_length""" file = open("hangman_words.txt","r") word_list = [] for word in file: word = word.strip() if len(word) == word_length: word_list.append(word) file.close() if len(word_list) == 0: return 0 else: return random.choice(word_list) I'll post the full program for people to have a look at when I've cleaned it up a bit. Cheers, Matt. From alan.gauld at blueyonder.co.uk Thu Jul 22 23:16:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 22 23:15:34 2004 Subject: [Tutor] how do i start References: <20040722014052.FIWQ2023.mta9.adelphia.net@mail.adelphia.net> Message-ID: <002b01c47031$266e0770$6401a8c0@xp> > hello, i'm just starting to program with python... Welcome to the gang... :-) > Heres my question is run script same as run module? A module in Python is a file. So is a script. But if the file contains the magic line: if __name__ == "__main__": the behaviour will be different depending on whether you import it (acting as a module) or run it(acting as a script) But basically there is no difference in Python between a module or a script if you run it from the command prompt: C:\> python foo.py More info in my tutor in the topic on Adding Style(at the bottom) and the Case Study under "Turning it into a module" HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Jul 22 23:32:55 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 22 23:32:04 2004 Subject: [Tutor] how popen works? References: Message-ID: <004001c47033$73686140$6401a8c0@xp> > While we're talking about popen, I'll ask you about a trouble I'm > having with it. According to the documentation, you can only tell if > the command failed when you close the pipe. If it failed, it returns > a tuple, otherwise it returns None. You can usually tell by looking at the output returned by read() but the close() function returns the formal exitcode of the command - the same status value you get from os.system() The current website documentation says: ''' The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method ''' And about wait() it says: ''' return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. Availability: Unix. ''' Phew! So the exit status consists of a 16 bit int (not a tuple - thats what wait() returns) the high byte being the exit status from the process. You can extract the high byte by dividing by 256 or right shifting 8 bits using the >> operator. > And I found those numbers by experimenting. The numbers should be documented by the program that you run - so look in the EXIM docs. But the EXIM numbers will only correspond after you do the decoding described above... > I wonder what I'm missing? Hopefully that explains it a bit better? Alan G. PS You might find it easier to use popen2 or popen3 and monitor the stderr stream... Alan G. From jeff at ccvcorp.com Thu Jul 22 23:40:54 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Jul 22 23:37:58 2004 Subject: [Tutor] Is there a better way to do this? In-Reply-To: <97AF02DA-DB7D-11D8-A37A-000393479EE8@earthlink.net> References: <97AF02DA-DB7D-11D8-A37A-000393479EE8@earthlink.net> Message-ID: <41003466.6090004@ccvcorp.com> Hee-Seng Kye wrote: > I'm trying to write a program that computes six-digit numbers, in which > the left digit is always smaller than its following digit (i.e., it's > always ascending). The output of the program starts with "0 1 2 3 4 5" > and ends on "6 7 8 9 A B." The best I could do was to have many > embedded 'for' statements: > > c = 1 > for p0 in range(0, 7): > for p1 in range(1, 12): > for p2 in range(2, 12): > for p3 in range(3, 12): > for p4 in range(4, 12): > for p5 in range(5, 12): > if p0 < p1 < p2 < p3 < p4 < p5: > print repr(c).rjust(3), "\t", > print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5) > c += 1 > print "...Done" I don't have the time / spare brain cycles to write real sample code, but if I were doing something like this, I'd look closely at the possibility of using a recursion instead of multiply-nested for loops. You might be able to craft a recursive generator that would iterate over its sub-generator and then itself. I don't know whether this would be likely to run *faster*, but it would be a lot more flexible than manually writing out N levels of for-loops... def my_generator(depth, min, max): for n in range(min, max): for result in my_generator(depth-1, n, max): yield (n,) + result for results in my_generator(depth, min, max): format = " ".join(["%X"] * depth) print format % results The generator there won't actually work -- it needs to do bounds-checking on depth before entering the loop, and of course I haven't tested *any* of this -- but this may give you a starting point. Jeff Shannon Technician/Programmer Credit International From bofifin at yahoo.com.hk Thu Jul 22 23:45:41 2004 From: bofifin at yahoo.com.hk (=?iso-8859-1?q?john=20bofifin?=) Date: Fri Jul 23 01:00:39 2004 Subject: [Tutor] win32file missing from python build In-Reply-To: <20040722213203.F08AE1E400E@bag.python.org> Message-ID: <20040722214541.46318.qmail@web51801.mail.yahoo.com> I have latest build of Python windows98. I can't compile serial routines because IDE complains that win32file can't be found. It is not on my computer and I can't find it on google. Would someobody please email me the win32 files for pyhton used with the import command. --------------------------------- Do You Yahoo!? Get your free @yahoo.com.hk address at Yahoo! Mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040723/7aa5867b/attachment.htm From magnus at thinkware.se Fri Jul 23 01:49:09 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 23 01:45:12 2004 Subject: [Tutor] win32file missing from python build In-Reply-To: <20040722214541.46318.qmail@web51801.mail.yahoo.com> References: <20040722213203.F08AE1E400E@bag.python.org> Message-ID: <5.2.1.1.0.20040723014605.0292ee38@www.thinkware.se> At 05:45 2004-07-23 +0800, john bofifin wrote: >I have latest build of Python windows98. I can't compile serial routines >because IDE complains that win32file can't be found. >It is not on my computer and I can't find it on google. > >Would someobody please email me the win32 files for pyhton used with >the import command. Did you install the win32all package? From http://python.org/2.3.4/ : "Windows users should download the Windows installer, Python-2.3.4.exe, run it and follow the friendly instructions on the screen to complete the installation. Windows users may also be interested in Mark Hammond's win32all, a collection of Windows-specific extensions including COM support and Pythonwin, an IDE built using Windows components." It's at http://starship.python.net/crew/mhammond/win32/Downloads.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From linux-user at softhome.net Thu Jul 22 20:11:09 2004 From: linux-user at softhome.net (Conrad) Date: Fri Jul 23 08:08:28 2004 Subject: [Tutor] Subclassing a module's class. Message-ID: <1090519869.5439.18.camel@radiol> I'm trying to subclass a class (HelpFormatter) from a module (optparse), so that all calls will use my Helpformatter instead of optparse.HelpFormatter.Currently I'm trying it like this: import optparse class HelpFormatter(optparse.HelpFormatter): def format_option(self, option): print "Hello, World!" parser = optparse.OptionParser() print parser.print_help print_help() in optparse calls the class HelpFormatter. Can anyone explain to me why it doesnt use my HelpFormatter? Thanks for the time, Conrad From smith-matt at tiscali.co.uk Fri Jul 23 12:10:19 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Fri Jul 23 12:05:14 2004 Subject: [Tutor] Please critique my hangman.py program Message-ID: Hi, Thanks again for all of the help. This list is making learning Python much easier than it could have been. My second Python program has now reached a stage where I'd like to show it to people and get some comments. It's a fairly no-violent version of hangman as no one gets hung and it's impossible to lose. It has taught me alot about using strings, lists and files. Here's the program: # Hangman program by Matt Smith import random import string def random_word(word_length): """Returns a random word of length word_length""" file = open("hangman_words.txt","r") word_list = [] for word in file: word = word.strip() if len(word) == word_length: word_list.append(word) file.close() if len(word_list) == 0: return 0 else: return random.choice(word_list) def print_status (correct_so_far,incorrect,guesses): """Prints the current status of the game""" for i in range(len(correct_so_far)): print correct_so_far[i], print "\nIncorrect letters:", for i in range(len(incorrect)): print incorrect[i], print "\nYou have had",guesses,"guesses so far." # Game title print "\n**************" print "*Hangman Game*" print "**************\n" play_again = "y" while string.lower(play_again) == "y": # Get a word to guess while 1: try: word_length = input("What length word do you want to guess? ",) print "Thinking, please wait.." word = random_word(word_length) if word == 0: print "I don't know any words that long!" else: break except: print "That's not a proper word length!" word = string.lower(word) # Setup list to hold correct letters correct_so_far = [] for i in range(word_length): correct_so_far.append("_") # Setup some other variables incorrect = [] guesses = 0 letters_guessed = 0 # Start main game loop. print "\nI am thinking of a word",word_length,"letters long" while letters_guessed < word_length: # Print status of game on each pass. print print_status (correct_so_far,incorrect,guesses) # Get guess from user while 1: guess = raw_input("Which letter would you like to try? ") guess = string.lower(guess) if len(guess) != 1: print "You can only guess one letter at a time!" elif guess in incorrect or guess in correct_so_far: print "You've already tried that letter!" elif guess not in ["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"]: print "That's not a valid letter." else: break guesses = guesses + 1 # Evaluate guess against word letter_correct = 0 for i in range(word_length): if guess == word[i]: correct_so_far[i] = guess letter_correct=1 letters_guessed = letters_guessed + 1 if letter_correct == 0: incorrect.append(guess) # Finish the game print "\nWell done! You guessed the",word_length,"letter word",word,"in",guesses,"goes." print "You guessed",len(incorrect),"letters incorrectly." play_again = raw_input("Do you want to play again? (y/n) ",) print "Goodybye!" # End of Program Cheers, Matt. From Francis.Moore at shaws.co.uk Fri Jul 23 12:08:11 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Fri Jul 23 12:09:22 2004 Subject: [Tutor] Subclassing a module's class. Message-ID: <6081EBC21D52F744B484088BBBE665C3199F2B@sbserver.shaws.local> From: Conrad [mailto:linux-user@softhome.net] > class HelpFormatter(optparse.HelpFormatter): > def format_option(self, option): > print "Hello, World!" > parser = optparse.OptionParser() > print parser.print_help > print_help() in optparse calls the class HelpFormatter. > Can anyone explain to me why it doesnt use my HelpFormatter? Could it be because you haven't overriden print_help() in your class? The only function you've overridden is called format_option(). Try changing this function to print_help() and see if that works. 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 dswj at plasa.com Fri Jul 23 12:13:40 2004 From: dswj at plasa.com (dw) Date: Fri Jul 23 12:13:52 2004 Subject: [Tutor] ASPN Python Recipe in CHM Message-ID: Pehaba, latest updated at 23 July 2004 http://miaw.compeng.org/~dody/aspncookbook.chm dw =========================================================================================== "Gabung INSTANIA, dapatkan XENIA. Daftar di www.telkomnetinstan.com, langsung dapat akses Internet Gratis.. Dan ..ikuti "Instan Smile" berhadiah Xenia,Tour S'pore, Komputer,dll, info hub : TELKOM Jatim 0-800-1-467826 " =========================================================================================== From magnus at thinkware.se Fri Jul 23 15:35:59 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 23 15:32:02 2004 Subject: [Tutor] Subclassing a module's class. In-Reply-To: <1090519869.5439.18.camel@radiol> Message-ID: <5.2.1.1.0.20040723152145.027bebc0@www.thinkware.se> At 11:11 2004-07-22 -0700, Conrad wrote: >I'm trying to subclass a class (HelpFormatter) from a module (optparse), >so that all calls will use my Helpformatter instead of >optparse.HelpFormatter.Currently I'm trying it like this: > >import optparse > >class HelpFormatter(optparse.HelpFormatter): > def format_option(self, option): > print "Hello, World!" > >parser = optparse.OptionParser() >print parser.print_help > >print_help() in optparse calls the class HelpFormatter. Can anyone >explain to me why it doesnt use my HelpFormatter? You need to tell the OptionParser to use it! parser = optparse.OptionParser(formatter=HelpFormatter) I suggest that you call your class something less generic than just HelpFormatter though. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From kyeser at earthlink.net Fri Jul 23 16:24:19 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Fri Jul 23 16:24:21 2004 Subject: [Tutor] A bit long, but would appreciate anyone's help, if time permits! Message-ID: Hi. I have a question that requires a bit of explanation. I would highly appreciate it if anyone could read this and offer any suggestions, whenever time permits. I'm trying to write a program that 1) gives all possible rotations of an ordered list, 2) chooses the ordering that has the smallest difference from first to last element of the rotation, and 3) continues to compare the difference from first to second-to-last element, and so on, if there was a tie in step 2. The following is the output of a function I wrote. The first 6 lines are all possible rotations of [0,1,3,6,7,10], and this takes care of step 1 mentioned above. The last line provides the differences (mod 12). If the last line were denoted as r, r[0] lists the differences from first to last element of each rotation (p0 through p5), r[1] the differences from first to second-to-last element, and so on. >>> from normal import normal >>> normal([0,1,3,6,7,10]) [0, 1, 3, 6, 7, 10] #p0 [1, 3, 6, 7, 10, 0] #p1 [3, 6, 7, 10, 0, 1] #p2 [6, 7, 10, 0, 1, 3] #p3 [7, 10, 0, 1, 3, 6] #p4 [10, 0, 1, 3, 6, 7] #p5 [[10, 11, 10, 9, 11, 9], [7, 9, 9, 7, 8, 8], [6, 6, 7, 6, 6, 5], [3, 5, 4, 4, 5, 3], [1, 2, 3, 1, 3, 2]] #r Here is my question. I'm having trouble realizing step 2 (and 3, if necessary). In the above case, the smallest number in r[0] is 9, which is present in both r[0][3] and r[0][5]. This means that p3 and p5 and only p3 and p5 need to be further compared. r[1][3] is 7, and r[1][5] is 8, so the comparison ends here, and the final result I'm looking for is p3, [6,7,10,0,1,3] (the final 'n' value for 'pn' corresponds to the final 'y' value for 'r[x][y]'). How would I find the smallest values of a list r[0], take only those values (r[0][3] and r[0][5]) for further comparison (r[1][3] and r[1][5]), and finally print a p3? Thanks again for reading this. If there is anything unclear, please let me know. Best, Kye My code begins here: #normal.py def normal(s): s.sort() r = [] q = [] v = [] for x in range(0, len(s)): k = s[x:]+s[0:x] r.append(k) for y in range(0, len(s)): print r[y], '\t' d = [] for yy in range(len(s)-1, 0, -1): w = (r[y][yy]-r[y][0])%12 d.append(w) q.append(d) for z in range(0, len(s)-1): d = [] for zz in range(0, len(s)): w = q[zz][z] d.append(w) v.append(d) print '\n', v From vicki at thepenguin.org Fri Jul 23 17:21:58 2004 From: vicki at thepenguin.org (Vicki Stanfield) Date: Fri Jul 23 17:23:39 2004 Subject: [Tutor] Reading in file and processing it in a thread In-Reply-To: References: Message-ID: <20040723152158.GA8637@opus.thepenguin.org> I am doing threading for the first time in Python. I need to read in and process a file recursively if a checkbox on my gui is checked (wxPython) and stop at the end of the file if it is not. I used to have an EVT handler which called the following code (I know it ain't pretty!): ------------ def ReadInFile(self): inputfile = self.filesel.GetFilename() input = open('C:/'+inputfile, 'r') tokens="" first_iteration = wx.TRUE #While not STOP_READ, iterate through lines in file while STOP_READ != wx.TRUE or first_iteration == wx.TRUE: for line in input.readlines(): if len(line)>1: first_iteration == wx.FALSE tokens=line.split("|") self.command = tokens[0][0]+tokens[0][1] self.arguments = tokens[0].lstrip(tokens[0][0]+tokens[0][1]+" ") print self.command print self.arguments self.ProcessCommand(self.command, self.arguments) wx.GetApp().Yield() else: input.close() -------------------- Now I want to create a thread in which to run the looping so that the gui is (relatively) independent and a button on it can be used to toggle the STOP_READ flag. I think I need to yank most of the above code out and run it as a thread. I added this and can run the thread with it: #Test thread code thread2 = thread.start_new_thread(self.ThreadTest, ()) so I can make the new thread start. Do I want the open and close of the file in the new thread or should input be passed to the thread from outside? If it should be passed in, how do I convert input to a tuple? I have a lot of confusion on threads at this point, so I apoligize if this simple threading exercise should be obvious to me. The examples that I have seen via google haven't been close enough to help me. Thanks, vicki "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." -- Winston Churchill From bwinton at latte.ca Fri Jul 23 18:16:19 2004 From: bwinton at latte.ca (Blake Winton) Date: Fri Jul 23 18:16:22 2004 Subject: [Tutor] A bit long, but would appreciate anyone's help, if time permits! In-Reply-To: References: Message-ID: <410139D3.7020907@latte.ca> Hee-Seng Kye wrote: > [[10, 11, 10, 9, 11, 9], [7, 9, 9, 7, 8, 8], [6, 6, 7, 6, 6, 5], [3, 5, > 4, 4, 5, 3], [1, 2, 3, 1, 3, 2]] #r > > How would I find the smallest values of a list r[0], take only those > values (r[0][3] and r[0][5]) for further comparison (r[1][3] and > r[1][5]), and finally print a p3? Well, what do you have so far? Here, I'll help you out a little. So you want to find the smallest values of a list, huh? Well, this is one way to do it. >>> def findSmallestValues( r ): ... # We'll need somewhere to store the indices of the smallest values. ... indices = [] ... for index in range(len(r)): ... if len(indices) == 0 or r[index] < r[ indices[0] ]: ... indices = [index] ... elif r[index] == r[ indices[0] ]: ... indices.append( index ) ... return indices ... >>> findSmallestValues([10, 11, 10, 9, 11, 9]) [3, 5] >>> r = [10, 11, 10, 9, 11, 9] >>> findSmallestValues(r) [3, 5] >>> r[3], r[5] (9, 9) >>> Or, I think you can make that shorter (but much less efficient) by using list comprehensions, and the reduce function. >>> def findSmallestNumber(r): ... return [i for i in range(len(r)) if r[i] == reduce( min, r ) ] ... >>> findSmallestNumber(r) [3, 5] It would be a little more efficient like this. >>> def findSmallestNumber(r): ... s = reduce( min, r ) ... return [i for i in range(len(r)) if r[i] == s ] ... >>> findSmallestNumber(r) [3, 5] (Uh, I ran into problems trying to time the various versions of the functions, so I'll let someone else do that part of it.) Later, Blake. From bvande at po-box.mcgill.ca Fri Jul 23 18:23:41 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Jul 23 18:24:15 2004 Subject: [Tutor] A bit long, but would appreciate anyone's help, if time permits! In-Reply-To: References: Message-ID: <41013B8D.2080906@po-box.mcgill.ca> Hee-Seng Kye said unto the world upon 23/07/2004 10:24: > Hi. I have a question that requires a bit of explanation. I would > highly appreciate it if anyone could read this and offer any > suggestions, whenever time permits. > > I'm trying to write a program that 1) gives all possible rotations of an > ordered list, 2) chooses the ordering that has the smallest difference > from first to last element of the rotation, and 3) continues to compare > the difference from first to second-to-last element, and so on, if there > was a tie in step 2. > > The following is the output of a function I wrote. The first 6 lines > are all possible rotations of [0,1,3,6,7,10], and this takes care of > step 1 mentioned above. The last line provides the differences (mod > 12). If the last line were denoted as r, r[0] lists the differences > from first to last element of each rotation (p0 through p5), r[1] the > differences from first to second-to-last element, and so on. > > >>> from normal import normal > >>> normal([0,1,3,6,7,10]) > [0, 1, 3, 6, 7, 10] #p0 > [1, 3, 6, 7, 10, 0] #p1 > [3, 6, 7, 10, 0, 1] #p2 > [6, 7, 10, 0, 1, 3] #p3 > [7, 10, 0, 1, 3, 6] #p4 > [10, 0, 1, 3, 6, 7] #p5 > > [[10, 11, 10, 9, 11, 9], [7, 9, 9, 7, 8, 8], [6, 6, 7, 6, 6, 5], [3, 5, > 4, 4, 5, 3], [1, 2, 3, 1, 3, 2]] #r > > Here is my question. I'm having trouble realizing step 2 (and 3, if > necessary). In the above case, the smallest number in r[0] is 9, which > is present in both r[0][3] and r[0][5]. This means that p3 and p5 and > only p3 and p5 need to be further compared. r[1][3] is 7, and r[1][5] > is 8, so the comparison ends here, and the final result I'm looking for > is p3, [6,7,10,0,1,3] (the final 'n' value for 'pn' corresponds to the > final 'y' value for 'r[x][y]'). > > How would I find the smallest values of a list r[0], take only those > values (r[0][3] and r[0][5]) for further comparison (r[1][3] and > r[1][5]), and finally print a p3? > > Thanks again for reading this. If there is anything unclear, please let > me know. > > Best, > Kye > > My code begins here: > #normal.py > def normal(s): > s.sort() > r = [] > q = [] > v = [] > > for x in range(0, len(s)): > k = s[x:]+s[0:x] > r.append(k) > > for y in range(0, len(s)): > print r[y], '\t' > d = [] > for yy in range(len(s)-1, 0, -1): > w = (r[y][yy]-r[y][0])%12 > d.append(w) > q.append(d) > > for z in range(0, len(s)-1): > d = [] > for zz in range(0, len(s)): > w = q[zz][z] > d.append(w) > v.append(d) > print '\n', v Hi Kye, I may not have understood your problem, but given your list of lists, I took you to want the one that has the least difference between first and last element to be selected, moving in one element on each end to break ties. Why I think I may have misunderstood you is that you are doing something with arithmetic mod 12 and end up considering [6, 7, 10, 0, 1, 3] and [10, 0, 1, 3, 6, 7] (your p3 and p5 from above) as the candidate "least elements". But from the description, I would have thought it was [1, 3, 6, 7, 10, 0] (your p1) that should be "least". At any rate, for my understanding of your problem, I've written a (very lightly tested) way to do it. It takes your lists of lists as given, and then sorts them by the method I understood you to want. If it doesn't solve exactly your issue, perhaps it will serve as a start :-) The idea is to replace your generation of your list r with a use of the sort method and a custom cmp() function. Two warnings: as I said, lightly tested. I am no python expert! So my code shouldn't be seen as a model to follow. ;-) The code: Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.0.3 >>> data = [[0, 1, 3, 6, 7, 10], [1, 3, 6, 7, 10, 0], [3, 6, 7, 10, 0, 1], [6, 7, 10, 0, 1, 3], [7, 10, 0, 1, 3, 6], [10, 0, 1, 3, 6, 7] ] >>> def special_cmp(first, second): upper_bound = (len(first) - 1) / 2 level_count = 0 comparison = 0 while level_count <= upper_bound and comparison == 0: comparison = cmp(abs(first[level_count] - first[(-1 - level_count)]), abs(second[level_count] - second[(-1 - level_count)])) level_count = level_count + 1 return comparison >>> data.sort(special_cmp) >>> for d in data: print d, "Difference between first and last = %i" %(abs(d[0] - d[-1])) [1, 3, 6, 7, 10, 0] Difference between first and last = 1 [7, 10, 0, 1, 3, 6] Difference between first and last = 1 [3, 6, 7, 10, 0, 1] Difference between first and last = 2 [10, 0, 1, 3, 6, 7] Difference between first and last = 3 [6, 7, 10, 0, 1, 3] Difference between first and last = 3 [0, 1, 3, 6, 7, 10] Difference between first and last = 10 >>> I hope that helps. If you'd like more detail as to how/why this works, ask ;-) Best, Brian vdB From alan.gauld at blueyonder.co.uk Fri Jul 23 19:51:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 23 19:50:34 2004 Subject: [Tutor] Please critique my hangman.py program References: Message-ID: <002201c470dd$b59264d0$6401a8c0@xp> > def random_word(word_length): > """Returns a random word of length word_length""" > file = open("hangman_words.txt","r") > word_list = [] > for word in file: > word = word.strip() > if len(word) == word_length: > word_list.append(word) > file.close() You could replace all that with a list comprehension. Something like: word_list = [word.strip() for word in file("hangman_word.txt") if len(word) == word_lenth ] > if len(word_list) == 0: > return 0 > else: > return random.choice(word_list) if word_list: return random.choice(word_list) else: return None > > def print_status (correct_so_far,incorrect,guesses): > """Prints the current status of the game""" > for i in range(len(correct_so_far)): > print correct_so_far[i], for item in correct_so_far: print item > print "\nIncorrect letters:", > for i in range(len(incorrect)): > print incorrect[i], for ltr in incorrect: print ltr > print "\nYou have had",guesses,"guesses so far." > > # Game title > print "\n**************" > print "*Hangman Game*" > print "**************\n" > > play_again = "y" > while string.lower(play_again) == "y": while play_again.lower() == "y": OR while play_again in 'Yy': > while 1: while True: > try: > word_length = input("What length word do you want to guess? ",) No need for the comma - in fact I'm not sure what it does! I'd have expected an error since you are providing a tuple as a prompt, but input seems to accept it OK...! > print "Thinking, please wait.." > word = random_word(word_length) > if word == 0: > print "I don't know any words that long!" > else: > break > except: > print "That's not a proper word length!" > word = string.lower(word) > > # Setup list to hold correct letters > correct_so_far = [] > for i in range(word_length): > correct_so_far.append("_") correct_so_far = ['_'] * word_length But you could just use a string which is esier to print later: xcorrect_so_far = '_' * word_length > # Setup some other variables > incorrect = [] > guesses = 0 > letters_guessed = 0 guesses, letters_guessed = 0, 0 > # Start main game loop. > print "\nI am thinking of a word",word_length,"letters long" > while letters_guessed < word_length: > > # Print status of game on each pass. > print > print_status (correct_so_far,incorrect,guesses) > > # Get guess from user > while 1: > guess = raw_input("Which letter would you like to try? ") > guess = string.lower(guess) > if len(guess) != 1: > print "You can only guess one letter at a time!" > elif guess in incorrect or guess in correct_so_far: > print "You've already tried that letter!" > elif guess not in ["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"]: > print "That's not a valid letter." > else: > break > guesses = guesses + 1 > > # Evaluate guess against word > letter_correct = 0 > for i in range(word_length): > if guess == word[i]: > correct_so_far[i] = guess > letter_correct=1 > letters_guessed = letters_guessed + 1 Personally I'd use a while loop here: i,letter_correct = 0,False while i < word_length and not letter_correct: if guess == word[i]: correct_so_far[i] = guess letter_correct=True letters_guessed += 1 i += 1 Same length but I just think the test expresses the intention of the loop better. > if letter_correct == 0: > incorrect.append(guess) > > # Finish the game > print "\nWell done! You guessed the",word_length,"letter word",word,"in",guesses,"goes." > print "You guessed",len(incorrect),"letters incorrectly." > play_again = raw_input("Do you want to play again? (y/n) ",) > print "Goodybye!" > # End of Program Hope those ideas help. They are not definitively better just some alternatives. Alan G. From vicki at thepenguin.org Fri Jul 23 21:22:28 2004 From: vicki at thepenguin.org (Vicki Stanfield) Date: Fri Jul 23 21:24:09 2004 Subject: [Tutor] Reading in file and processing it in a thread In-Reply-To: <20040723152158.GA8637@opus.thepenguin.org> References: <20040723152158.GA8637@opus.thepenguin.org> Message-ID: <20040723192228.GA10386@opus.thepenguin.org> > #Test thread code > thread2 = thread.start_new_thread(self.ThreadTest, ()) Okay, I have set this up as the above code calling this: def ThreadTest(self): print "Got into ThreadTest" inputfile = self.filesel.GetFilename() input = open('C:/'+inputfile, 'r') tokens="" while STOP_READ != wx.TRUE or first_iteration == wx.TRUE: for line in input.readlines(): if len(line)>1: first_iteration == wx.FALSE tokens=line.split("|") self.command = tokens[0][0]+tokens[0][1] self.arguments = tokens[0].lstrip(tokens[0][0]+tokens[0][1]+" ") print self.command print self.arguments self.ProcessCommand(self.command, self.arguments) #wx.GetApp().Yield() else: input.close() But I get a strange error: Got into ThreadTest Unhandled exception in thread started by > Traceback (most recent call last): File "F:\wxComTool1.1.py", line 252, in ThreadTest inputfile = self.filesel.GetFilename() File "C:\Python23\Lib\site-packages\wxPython\wx.py", line 1834, in __getattr__ raise wxPyDeadObjectError( self.attrStr % self._name ) wxPython.wx.wxPyDeadObjectError: The C++ part of the wxFileDialog object has bee n deleted, attribute access no longer allowed. Can anyone explain to me what I am doing wrong? If this same code is included where the call to start_new_thread is, it works except that I am unable to get back to the gui to uncheck the checkbox. It needs to be a different thread, so what am I doing wrong? Thanks, --vicki From smith-matt at tiscali.co.uk Fri Jul 23 23:24:59 2004 From: smith-matt at tiscali.co.uk (Matt Smith) Date: Fri Jul 23 23:19:51 2004 Subject: [Tutor] Re: Please critique my hangman.py program References: Message-ID: If anyone wants to test the game the hangman_words.txt file is just a copy of a linux dictionary word list (/usr/share/dict/linux.words on my system). It is a list of words separated by newline characters. If anyone wants my hangman_words.txt file email me and I'll send you a copy. Cheers, Matt. From dyoo at hkn.eecs.berkeley.edu Sat Jul 24 00:26:36 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 24 00:26:39 2004 Subject: [Tutor] Re: Your advice, please [raw_input(), higher order functions] In-Reply-To: <6.1.2.0.2.20040721044443.0475cec0@rcblue.com> Message-ID: Hi Dick, I took a closer look at your program; there's actually a significant thing I can see that should shorten the program a bit. It has to do with the way that the code interacts with the user; in many places in your code, your program asks the user for input, and uses a fairly regular way of doing this. Let's look at a few places where this happens. I'll look at three blocks: Block 1: --- > while True: > print "If no decimal entered, a random decimal " \ > "between 0.1 and 1.0 will be chosen." > # for exiting via ^C or ^D > try: > string = raw_input("Decimal: ") > except (TypeError, EOFError): > break > if string in ["x", "q"]: > break Block 2: --- > while True: > choice = raw_input("Minimum error (e) or maximum denominator (d)? ") > if choice in ["x", "q"]: > break > elif not (choice in ["e", "d"]): > print "Enter d or e" > continue > else: > break > if choice in ["x", "q"]: > break Block 3: --- > while True: > print "If no maximum denominator entered, the default is 100" > maximumDenom = raw_input("Maximum denominator: ") > if maximumDenom in ["x", "q"]: > break > elif maximumDenom == "": > maximumDenom = defaultMaximumDenom > print "Maximum denominator is %g by default" % maximumDenom > else: > try: > maximumDenom = int(maximumDenom) > except: > print "That's not an integer! Try again." > continue > break > if maximumDenom in ["x", "q"]: > break Each of these blocks, conceptually, does something like this: ### To get user input: query the user from input if we get 'x' or 'q': let's quit the program if no answer comes at us: use a default value else if a bad answer comes at us: show an error message and ask again otherwise, use that user input as our final answer ### The following is code that implements the pseudocode above: ### def getUserInput(queryPrompt, isGoodInput, badAnswerMessage, defaultInput): """Queries the user for an input. Takes in four parameters: queryPrompt: the prompt we pass to raw_input. isGoodInput: some boolean function that tells us if the input looks good to us. badAnswerMessage: the message we print out if the input looks bad. defaultInput: the default value we return if the user just presses enter. If no defaultInput is defined, we keep asking. If the input is 'x' or 'q', we raise a SystemExit to quit the program. """ while True: userInput = raw_input(queryPrompt) if userInput in ['x', 'q']: raise SystemExit elif userInput == "" and defaultInput: return defaultInput elif isGoodInput(userInput): return userInput else: print badAnswerMessage ### It's a little large, but most of it is commentary. The value of writing a general function like this is that the blocks above can now use getUserInput() to do the brunt of the work of handling user input in a nice way. Here's a quick example to show how it might work: ### >>> passwd = getUserInput("Password Please! ", ... lambda x: x == 'secret', ... 'Bad Password!', ... None) Password Please! abracadabra Bad Password! Password Please! please Bad Password! Password Please! secret >>> >>> >>> print passwd secret ### You can ignore the 'lambda' part for the moment; we can get get back to it in a moment. But you can see that it does a lot, for just a single call to getUserInput(). And that's powerful. For example, Block 3, which looked like: > while True: > print "If no maximum denominator entered, the default is 100" > maximumDenom = raw_input("Maximum denominator: ") > if maximumDenom in ["x", "q"]: > break > elif maximumDenom == "": > maximumDenom = defaultMaximumDenom > print "Maximum denominator is %g by default" % maximumDenom > else: > try: > maximumDenom = int(maximumDenom) > except: > print "That's not an integer! Try again." > continue > break > if maximumDenom in ["x", "q"]: > break can be reduced a single call to getUserInput() and a definition of a function that tells us if we're looking at an integer. ### def looksLikeInt(value): """Returns True if the value looks like an integer, and otherwise returns False.""" try: int(value) return True except ValueError: return False maximumDenom = int(getUserInput("Maximum denominator: ", looksLikeInt, "That's not an integer! Try again." defaultMaximumDenom)) ### Using getUserInput() is a little weirder than using a straightforward raw_input(), but it does have versatility. The key part of this is the following: we have to pass it some notion of what a good answer looks like, so that it knows when to keep asking. In the example above, we wrote a quick-and-dirty 'looksLikeInt()' function, and then passed that off to getUserInput(), so that getUserInput() can know what we think a satisfactory answer looks like. In Block 2, we can do something similar: ### def isErrorOrDenominatorChoice(value): return value in ['e', 'd'] choice = getUserInput("Minimum error (e) or maximum denominator (d)? ", isErrorOrDenominatorChoice, "Enter d or e", None) ### And again, we write a quick-and-dirty function to tell the system that 'e' or 'd' is a good value to accept, and pass it off to getUserInput(). Does this make sense so far? From jeff at ccvcorp.com Sat Jul 24 00:31:59 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Sat Jul 24 00:31:48 2004 Subject: [Tutor] Reading in file and processing it in a thread In-Reply-To: <20040723192228.GA10386@opus.thepenguin.org> References: <20040723152158.GA8637@opus.thepenguin.org> <20040723192228.GA10386@opus.thepenguin.org> Message-ID: <410191DF.8000500@ccvcorp.com> Vicki Stanfield wrote: >> #Test thread code >> thread2 = thread.start_new_thread(self.ThreadTest, ()) > > > Okay, I have set this up as the above code calling this: > > def ThreadTest(self): > print "Got into ThreadTest" > > inputfile = self.filesel.GetFilename() > input = open('C:/'+inputfile, 'r') > tokens="" > > > while STOP_READ != wx.TRUE or first_iteration == wx.TRUE: > for line in input.readlines(): > if len(line)>1: > first_iteration == wx.FALSE > tokens=line.split("|") > > self.command = tokens[0][0]+tokens[0][1] > self.arguments = tokens[0].lstrip(tokens[0][0]+tokens[0][1]+" ") > print self.command > print self.arguments > self.ProcessCommand(self.command, self.arguments) > #wx.GetApp().Yield() > else: > input.close() > > But I get a strange error: Using the same variable in multiple threads (in this case, 'self' if nothing else) is very likely to cause problems. In particular, access to any wx.Python GUI elements across threads is *not* safe. Make your threaded function entirely independent of the rest of your code (and make it a function rather than a method, unless it's a method of a new object), and then use documented-threadsafe methods to get information back from it. (IIRC, wx.PostEvent() will deliver an event to the main GUI thread in a safe manner; just define a custom event for the main thread to listen for, and have your threaded function post that event with the necessary information attached.) By the way, is there any reason that you're using the thread module instead of the threading module? The latter is a higher-level, more user-friendly interface built on top of thread, and is usually the recommended module for use. Jeff Shannon Technician/Programmer Credit International From magnus at thinkware.se Sat Jul 24 01:09:22 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Jul 24 01:16:09 2004 Subject: [Tutor] Reading in file and processing it in a thread In-Reply-To: <20040723152158.GA8637@opus.thepenguin.org> References: Message-ID: <5.2.1.1.0.20040724010736.02962ce0@www.thinkware.se> At 10:21 2004-07-23 -0500, Vicki Stanfield wrote: >I am doing threading for the first time in Python. I need to read in and >process a file recursively if a checkbox on my gui is checked (wxPython) >and stop at the end of the file if it is not. I used to have an EVT >handler which called the following code (I know it ain't pretty!): Have you read this? http://wiki.wxpython.org/index.cgi/LongRunningTasks -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From bvande at po-box.mcgill.ca Sat Jul 24 01:19:11 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 24 01:23:01 2004 Subject: [Tutor] os.popen() questions Message-ID: <41019CEF.90801@po-box.mcgill.ca> Hi all, I'm working through early chapter of Lutz's Programming Python and I am trying to learn how to use os.system() and os.popen(). At an early stage I am puzzled. :-( I've a virus scanner that was written for Unix and ported to Windows via Cygwin (about which I know little). I can run the program fine from a DOS command line. What I am wanting to do is write a python script that will run it as though it were typed on a command line and give the data back to the python script. Ultimately, I want to do this for every dir in my tree, using os.chdir before each invocation. I'm trying to use os.popen to do this, but obviously there is something I'm not getting. (This area is new to me, so it is entirely possible I am using the wrong tool.) I wrote a short program to try it and another os.popen() call to see that I could use it successfully in some cases. I'm using Python 2.3.4 and Windows Me. import os the_program = r'C:\clamav-devel\bin\clamscan.exe' os.chdir('C:/testdir') a = os.popen('dir *.*').readlines() # works fine os.system('start %s > testing.txt' %the_program) b = os.popen(the_program).readlines() print b # prints as [] print a Both a = os.popen('dir *.*').readlines() and os.system('start %s > testing.txt' %the_program) work as expected. The first gives me a list of lines just like the output from typing the command in a DOS box and the second produces a txt file with what is normally the screen output of running the target program in a DOS console. So, why does b = os.popen(the_program).readlines() make b an empty list (as per last line of the output)? Am I misunderstanding what is going on here? Nothing in the docs or Programming Python has shed light on this for me. Could it be some peculiarity of the program that I am running within the os.popen() call that is causing this? I have noticed that the file testing.txt has UNIX style EOL. But I also tried using b = os.popen(the_program, 'rb').readlines() and had the same results (b == []). Thanks for any pointers on these issues. Best, Brian vdB From suzuki at CSUA.Berkeley.EDU Sat Jul 24 02:52:32 2004 From: suzuki at CSUA.Berkeley.EDU (elle yoko suzuki) Date: Sat Jul 24 02:52:37 2004 Subject: [Tutor] using url component as arg in called script? Message-ID: <200407240052.i6O0qWf2035852@soda.csua.berkeley.edu> let's say that i have a script, someScript.py, that displays several words on a web page, as extracted from some external text file. each of the words when displayed, is displayed while associated with some hypertext link that when selected, runs another python script, doAction.py. the link is essentially the same, except that a unique value attached to a variable name gets attached to the end of the url. resulting output of someScript.py, html source fragment: host1 host2 ... host100 i'd like to be able to take the value (say, hostN, N=1,...,100) associated with 'hostname' in the url to be passed as an argument to the script that gets called, doAction.py. can this be done, and if so, how? (i saw the following in o'reilly's _python cookbook_: def getScriptname(): """ return the scriptname part of the url ("/path/to/my.cgi").""" return os.environ.get('SCRIPT_NAME', '') def getPathinfo(): """ return the remaining part of the url. """ pathinfo = os.environ.get('PATH_INFO', '') [...] return pathinfo is there a similar way to extract a 'path info' for the trailing part (?hostname=hostN) that gets passed along with a url?) thanks in advance, -elle yoko suzuki From dyoo at hkn.eecs.berkeley.edu Sat Jul 24 03:25:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 24 03:25:10 2004 Subject: [Tutor] using url component as arg in called script? In-Reply-To: <200407240052.i6O0qWf2035852@soda.csua.berkeley.edu> Message-ID: On Fri, 23 Jul 2004, elle yoko suzuki wrote: > > let's say that i have a script, someScript.py, that displays > several words on a web page, as extracted from some external > text file. each of the words when displayed, is displayed > while associated with some hypertext link that when > selected, runs another python script, doAction.py. the link > is essentially the same, except that a unique value attached > to a variable name gets attached to the end of the url. > > resulting output of someScript.py, html source fragment: > > host1 > host2 > ... > host100 > > i'd like to be able to take the value (say, hostN, > N=1,...,100) associated with 'hostname' in the url to be > passed as an argument to the script that gets called, > doAction.py. can this be done, and if so, how? Hi Elle, Ah! It sounds like you're looking for the 'cgi' module: http://www.python.org/doc/lib/module-cgi.html Just for reference: the environmental variable that holds the key/value parameters is os.environ.get('QUERY_STRING') However, you should probably try to avoid parsing QUERY_STRING by hand, since the 'cgi' module has a well-tested implementation. There are more details on doing CGI programming on the 'CGI Tools for Python' topic guide: http://www.python.org/topics/web/basic-cgi.html If you have more questions, please feel free to ask. Good luck! From rdm at rcblue.com Sat Jul 24 07:49:47 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 24 07:49:51 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> Message-ID: <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> I hope this is a legitimate question for tutor. My subject header is my question. Sure hope there's a way. BTW right now my command prompt opens at C:\Documents and Settings\Dick> Yeah, I know how to cd, but it's a PITA. Thanks, tutors. Dick Moores From tim.peters at gmail.com Sat Jul 24 08:16:53 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat Jul 24 08:16:55 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> In-Reply-To: <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> References: <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> Message-ID: <1f7befae040723231613699ce7@mail.gmail.com> [Dick Moores] > I hope this is a legitimate question for tutor. If it isn't, I'll yell at you . > My subject header is my question. Sure hope there's a way. > > BTW right now my command prompt opens at > C:\Documents and Settings\Dick> > Yeah, I know how to cd, but it's a PITA. What, exactly, do you do to open a DOS box ("command prompt window")? There are 100 ways to do everything on Windows, and answers depend on the specifics of the ways you've stumbled into. For example, I put a cmd.exe shortcut icon on my desktop, and if you did too then it's easy: right-click on the icon, select Properties, go to the Shortcut tab, type C:\Python23 in the "Start in:" box, click Apply, then click OK. From then on that shortcut icon will cd to C:\Python23 all by itself when you double-click it. You can also adjust the size of the window, font, and number of lines of scrollback history this way. From python at bernardlebel.com Sat Jul 24 10:53:48 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Jul 24 09:51:44 2004 Subject: [Tutor] Executing dos .bat file with Python script Message-ID: <001501c4715b$be1200b0$0095fea9@atyss> Hello, Let say I have a python script that write a .bat file, with the commands and arguments. Now how can I use that same python script to actually execute the .bat file in the Windows environment? Any direction would be appreciated. Thanks Bernard From rdm at rcblue.com Sat Jul 24 10:04:48 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 24 10:04:52 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> In-Reply-To: <1f7befae040723231613699ce7@mail.gmail.com> References: <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> <1f7befae040723231613699ce7@mail.gmail.com> Message-ID: <6.1.2.0.2.20040724010041.08245648@rcblue.com> Tim Peters wrote at 23:16 7/23/2004: >What, exactly, do you do to open a DOS box ("command prompt window")? >There are 100 ways to do everything on Windows, and answers depend on >the specifics of the ways you've stumbled into. I had a shortcut key in a folder on my start menu with a shortcut key set. >For example, I put a cmd.exe shortcut icon on my desktop, and if you >did too then it's easy: right-click on the icon, select Properties, >go to the Shortcut tab, type C:\Python23 in the "Start in:" box, click >Apply, then click OK. From then on that shortcut icon will cd to >C:\Python23 all by itself when you double-click it. You can also >adjust the size of the window, font, and number of lines of scrollback >history this way. Thank you! Thank you! Works like a charm. But I'm curious again. How do you make those other adjustments? Dick Moores From magnus at thinkware.se Sat Jul 24 12:42:11 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Jul 24 12:38:14 2004 Subject: [Tutor] os.popen() questions In-Reply-To: <41019CEF.90801@po-box.mcgill.ca> Message-ID: <5.2.1.1.0.20040724122231.0295cc30@www.thinkware.se> At 19:19 2004-07-23 -0400, Brian van den Broek wrote: >import os >the_program = r'C:\clamav-devel\bin\clamscan.exe' >os.chdir('C:/testdir') >a = os.popen('dir *.*').readlines() # works fine >os.system('start %s > testing.txt' %the_program) >b = os.popen(the_program).readlines() >print b # prints as [] >print a Are you sure that clamscan.exe writes to stdout? Maybe it actually writes to stderr? I don't think popen.readlines will catch that (but DOS ">" will). You might want to use popen3 or popen4 instead. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sat Jul 24 12:58:30 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Jul 24 12:54:32 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> In-Reply-To: <6.1.2.0.2.20040724010041.08245648@rcblue.com> References: <1f7befae040723231613699ce7@mail.gmail.com> <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> <1f7befae040723231613699ce7@mail.gmail.com> Message-ID: <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> First of all, why do you want to be in the C:\Python23 folder? Wouldn't it be better to be in a folder where you can keep your files without disturbing the Python installation. If your problem is that you want Python to start when you type "python", you need to edit your PATH variable so that it contains "C:\Python23". I don't remember if you do that differently in XP, but in Win 2000 you go to Control Panel -> System -> Advanced -> Environment Variables. At 01:04 2004-07-24 -0700, Dick Moores wrote: >Thank you! Thank you! Works like a charm. But I'm curious again. How do >you make those other adjustments? Click on the system menu icon in the top left corner of your CMD.EXE window. Choose "properties" in the menu. Change as you like. When you click "Ok" you get a dialog box with two options. Choose the one about saving properties for other windows with the same name... Make sure to use quick edit mode, insert mode, and at least a few hundred rows in the screen buffer. That certainly makes CMD.EXE less painful... BTW, is autocomple on TAB on by default in XP, or do you need to tweak the registry for that? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From alan.gauld at blueyonder.co.uk Sat Jul 24 13:15:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 13:15:04 2004 Subject: [Tutor] os.popen() questions References: <41019CEF.90801@po-box.mcgill.ca> Message-ID: <005401c4716f$81896430$6401a8c0@xp> > import os > the_program = r'C:\clamav-devel\bin\clamscan.exe' > b = os.popen(the_program).readlines() > print b # prints as [] > Could it be some peculiarity of the program that I am running within the > os.popen() call that is causing this? It could be that all the output you normally see is actually being sent to stderr not stdout. I think popen() only captures stdout. There are other popen variants (popen2, popen3) that cater for stderr too, you might need to use one of those. HTH, Alan G. From rdm at rcblue.com Sat Jul 24 15:39:54 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 24 15:40:00 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> In-Reply-To: <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> References: <1f7befae040723231613699ce7@mail.gmail.com> <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> <1f7befae040723231613699ce7@mail.gmail.com> <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> Message-ID: <6.1.2.0.2.20040724063131.02da4ec0@rcblue.com> Magnus Lyck? wrote at 03:58 7/24/2004: >First of all, why do you want to be in the C:\Python23 folder? >Wouldn't it be better to be in a folder where you can keep your >files without disturbing the Python installation. Only because that is what IDLE's File-->Open opens. And is also the default folder for saving a new script. Can this be configured? >If your problem is that you want Python to start when you >type "python", you need to edit your PATH variable so that >it contains "C:\Python23". Had already done that. >I don't remember if you do that differently in XP, but in Win >2000 you go to Control Panel -> System -> Advanced -> Environment >Variables. Sounds right. >At 01:04 2004-07-24 -0700, Dick Moores wrote: >>Thank you! Thank you! Works like a charm. But I'm curious again. How do >>you make those other adjustments? > >Click on the system menu icon in the top left corner of your >CMD.EXE window. Choose "properties" in the menu. Change as you >like. When you click "Ok" you get a dialog box with two >options. Choose the one about saving properties for other >windows with the same name... Terrific! >Make sure to use quick edit mode, insert mode, and at least >a few hundred rows in the screen buffer. That certainly makes >CMD.EXE less painful... Thanks for these tips. >BTW, is autocomple on TAB on by default in XP, or do you need >to tweak the registry for that? Don't remember the default. But autocomplete is on. Thanks very much for your help. Dick Moores From operate777 at adelphia.net Sat Jul 24 17:17:31 2004 From: operate777 at adelphia.net (operate777@adelphia.net) Date: Sat Jul 24 17:17:34 2004 Subject: [Tutor] hangman.py Message-ID: <20040724151731.LMLI26966.mta11.adelphia.net@mail.adelphia.net> how do you write a hangman program? From aztech1200 at yahoo.com Sat Jul 24 17:51:55 2004 From: aztech1200 at yahoo.com (Aztech Guy) Date: Sat Jul 24 17:51:58 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <40F9E3C4.80203@po-box.mcgill.ca> Message-ID: <20040724155155.99181.qmail@web53301.mail.yahoo.com> Hi, >Brian van den Broek wrote: > where sitting down for serious study of a > medium-sized chunk of code > would do me some real good. > I'd call it a bit smaller than medium-sized, but this project of mine may be of use as a sample of code to study: http://sourceforge.net/projects/xtopdf It uses procedural Python, object-oriented Python (some), dictionaries, lists, file I/O, and also a third-party library. It's a project to provide ways to convert other file formats to PDF. Needs the freely available open source version of the ReportLab toolkit (www.reportlab.org) which is also written in Python. Also needs Python 2.2 or higher. I took care to make the code fairly well-written, with mnemonic identifiers, reasonably modular design, and lots of comments. There are also test programs with test input files. And the whole thing works, correctly :-) - at least, I did a lot of testing, and there were no known bugs when I released it - except one, which I would call a known bug, because its something I'm aware of, but haven't fixed yet - too long lines of text get truncated in the output PDF file. Other than that, didn't find any, nor has anyone reported any to me yet. That doesn't mean there are none, though, but its likely that there are only a few, if any. My $0.02. Feel free to ask questions about the code. HTH Az Tech. __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From orbitz at ezabel.com Sat Jul 24 18:00:15 2004 From: orbitz at ezabel.com (orbitz) Date: Sat Jul 24 18:02:18 2004 Subject: [Tutor] hangman.py In-Reply-To: <20040724151731.LMLI26966.mta11.adelphia.net@mail.adelphia.net> References: <20040724151731.LMLI26966.mta11.adelphia.net@mail.adelphia.net> Message-ID: <4102878F.3040803@ezabel.com> Generally you sit in a chair, preferably comfortable, with arms extended to reach the keyboard. Type furiously for a few hours, then get some pizza. This is the act of programming. operate777@adelphia.net wrote: >how do you write a hangman program? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From rdm at rcblue.com Sat Jul 24 18:20:53 2004 From: rdm at rcblue.com (Dick Moores) Date: Sat Jul 24 18:20:59 2004 Subject: [Tutor] hangman.py In-Reply-To: <20040724151731.LMLI26966.mta11.adelphia.net@mail.adelphia. net> References: <20040724151731.LMLI26966.mta11.adelphia.net@mail.adelphia.net> Message-ID: <6.1.2.0.2.20040724091609.071d2d70@rcblue.com> operate777@adelphia.net wrote at 08:17 7/24/2004: >how do you write a hangman program? One was posted by Matt Smith yesterday. I've attached one that is from the disk that accompanies _Python Programming for the absolute beginner_, by Michael Dawson. Dick Moores -------------- next part -------------- # Hangman Game # # The classic game of Hangman. The computer picks a random word # and the player wrong to guess it, one letter at a time. If the player # can't guess the word in time, the little stick figure gets hanged. # # Michael Dawson # imports import random # constants HANGMAN = ( """ ------ | | | | | | | | | ---------- """, """ ------ | | | O | | | | | | ---------- """, """ ------ | | | O | -+- | | | | | ---------- """, """ ------ | | | O | /-+- | | | | | ---------- """, """ ------ | | | O | /-+-/ | | | | | ---------- """, """ ------ | | | O | /-+-/ | | | | | | ---------- """, """ ------ | | | O | /-+-/ | | | | | | | | | ---------- """, """ ------ | | | O | /-+-/ | | | | | | | | | | | ---------- """) MAX_WRONG = len(HANGMAN) - 1 WORDS = ("OVERUSED", "CLAM", "GUAM", "PUCK", "TAFFETA", "PYTHON") # initialize variables word = random.choice(WORDS) # the word to be guessed so_far = "-" * len(word) # one dash for each letter in word to be guessed wrong = 0 # number of wrong guesses player has made used = [] # letters already guessed print "Welcome to Hangman. Good luck!" while (wrong < MAX_WRONG) and (so_far != word): print HANGMAN[wrong] print "\nYou've used the following letters:\n", used print "\nSo far, the word is:\n", so_far guess = raw_input("\n\nEnter your guess: ") guess = guess.upper() while (guess in used): print "You've already guessed the letter:", guess guess = raw_input("Enter your guess: ") guess = guess.upper() used.append(guess) if (guess in word): print "\nYes!", guess, "is in the word!" # create a new so_far to include guess new = "" for i in range(len(word)): if guess == word[i]: new += guess else: new += so_far[i] so_far = new else: print "\nSorry,", guess, "isn't in the word." wrong += 1 if (wrong == MAX_WRONG): print HANGMAN[wrong] print "\nYou've been hanged!" else: print "\nYou guessed it!" print "\nThe word was", word #raw_input("\n\nPress the enter key to exit.") From bvande at po-box.mcgill.ca Sat Jul 24 18:34:34 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 24 18:35:19 2004 Subject: [Tutor] hangman.py In-Reply-To: <4102878F.3040803@ezabel.com> References: <20040724151731.LMLI26966.mta11.adelphia.net@mail.adelphia.net> <4102878F.3040803@ezabel.com> Message-ID: <41028F9A.2000806@po-box.mcgill.ca> orbitz said unto the world upon 24/07/2004 12:00: > Generally you sit in a chair, preferably comfortable, with arms extended > to reach the keyboard. Type furiously for a few hours, then get some > pizza. This is the act of programming. > > > operate777@adelphia.net wrote: > >> how do you write a hangman program? >> The 'expanded' version: read at least one thing from Read . Read it again. Program. Get stuck. Consult the tutorial you are using, and the documentation. If still stuck post specific questions. Get useful answers. Repeat. Best, Brian vdB From vicki at thepenguin.org Sat Jul 24 19:05:41 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Sat Jul 24 19:07:26 2004 Subject: [Tutor] Reading in file and processing it in a thread In-Reply-To: <5.2.1.1.0.20040724010736.02962ce0@www.thinkware.se> References: <5.2.1.1.0.20040724010736.02962ce0@www.thinkware.se> Message-ID: <32984.12.223.198.92.1090688741.squirrel@12.223.198.92> > At 10:21 2004-07-23 -0500, Vicki Stanfield wrote: >>I am doing threading for the first time in Python. I need to read in and >>process a file recursively if a checkbox on my gui is checked (wxPython) >>and stop at the end of the file if it is not. I used to have an EVT >>handler which called the following code (I know it ain't pretty!): > > Have you read this? > http://wiki.wxpython.org/index.cgi/LongRunningTasks > > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language > No, I hadn't found this yet. It appears to be what I need to do. I'll see if I can follow it to change my code. THanks. --vicki From vicki at thepenguin.org Sat Jul 24 19:08:30 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Sat Jul 24 19:10:14 2004 Subject: [Tutor] Reading in file and processing it in a thread In-Reply-To: <410191DF.8000500@ccvcorp.com> References: <20040723152158.GA8637@opus.thepenguin.org> <20040723192228.GA10386@opus.thepenguin.org> <410191DF.8000500@ccvcorp.com> Message-ID: <32995.12.223.198.92.1090688910.squirrel@12.223.198.92> > Using the same variable in multiple threads (in this case, 'self' if > nothing else) is very likely to cause problems. In particular, access > to any wx.Python GUI elements across threads is *not* safe. Make > your threaded function entirely independent of the rest of your code > (and make it a function rather than a method, unless it's a method of > a new object), and then use documented-threadsafe methods to get > information back from it. (IIRC, wx.PostEvent() will deliver > an event to the main GUI thread in a safe manner; just define a custom > event for the main thread to listen for, and have your threaded > function post that event with the necessary information attached.) Thanks. I need to digest all that you wrote here. I am totally new to threaded programmming, and there seems to be a shortage of published books on the subject. I'm sure I'll have more questions as I go along. > > By the way, is there any reason that you're using the thread module > instead of the threading module? The latter is a higher-level, more > user-friendly interface built on top of thread, and is usually the > recommended module for use. Only lack of knowledge. I found the thread module first. Thanks again, Vicki From bvande at po-box.mcgill.ca Sat Jul 24 18:53:42 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 24 19:25:09 2004 Subject: [Tutor] taking Python to next level In-Reply-To: <20040724155155.99181.qmail@web53301.mail.yahoo.com> References: <20040724155155.99181.qmail@web53301.mail.yahoo.com> Message-ID: <41029416.9040301@po-box.mcgill.ca> Aztech Guy said unto the world upon 24/07/2004 11:51: > Hi, > > >>Brian van den Broek wrote: >>where sitting down for serious study of a >>medium-sized chunk of code >>would do me some real good. >> > > > I'd call it a bit smaller than medium-sized, but this > project of mine may be of use as a sample of code to > study: > > http://sourceforge.net/projects/xtopdf > > It uses procedural Python, object-oriented Python > (some), dictionaries, lists, file I/O, and also a > third-party library. > HTH > Az Tech. > Thanks for the suggestion. You may well live to be plagued by questions from me ;-) Best, Brian vdB From bvande at po-box.mcgill.ca Sat Jul 24 19:43:02 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 24 19:45:20 2004 Subject: [Tutor] os.popen() questions In-Reply-To: <5.2.1.1.0.20040724122231.0295cc30@www.thinkware.se> References: <5.2.1.1.0.20040724122231.0295cc30@www.thinkware.se> Message-ID: <41029FA5.2050005@po-box.mcgill.ca> Magnus Lyck? said unto the world upon 24/07/2004 06:42: > At 19:19 2004-07-23 -0400, Brian van den Broek wrote: > >> import os >> the_program = r'C:\clamav-devel\bin\clamscan.exe' >> os.chdir('C:/testdir') >> a = os.popen('dir *.*').readlines() # works fine >> os.system('start %s > testing.txt' %the_program) >> b = os.popen(the_program).readlines() >> print b # prints as [] >> print a > > > > Are you sure that clamscan.exe writes to stdout? Maybe it > actually writes to stderr? I don't think popen.readlines > will catch that (but DOS ">" will). > > You might want to use popen3 or popen4 instead. > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language Thanks Magnus (and Alan for a similar response), that did it. The clamscan.exe program did indeed write to stderr rather than stdout. (The 50+ pdf doc with the program said so -- I don't know if I missed it, or, being new to this area, missed its significance :-[ ) I've a follow-up, if you don't mind. I looked at Python in a Nutshell to see how to apply the advice I was given. There I found a brief discussion of the difference between the flavours of popen. Martelli says: popen2 is simpler to use than popen3 when it's okay for cmd's standard error to go to the same destination as your own process's standard error, and popen4 is simpler when it's okay for cmd's standard error and output to be mixed with each other. What determines whether these things are "okay"? Is it highly program dependant, or is there some generally applicable criteria for when this is fine to do? Thanks, Brian vdB From rschroev_nospam_ml at fastmail.fm Sat Jul 24 21:05:00 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat Jul 24 21:05:02 2004 Subject: [Tutor] A bit long, but would appreciate anyone's help, if time permits! In-Reply-To: References: Message-ID: <4102B2DC.60901@fastmail.fm> Hee-Seng Kye wrote: > The following is the output of a function I wrote. The first 6 lines > are all possible rotations of [0,1,3,6,7,10], and this takes care of > step 1 mentioned above. The last line provides the differences (mod > 12). If the last line were denoted as r, r[0] lists the differences > from first to last element of each rotation (p0 through p5), r[1] the > differences from first to second-to-last element, and so on. I have the impression that the task gets much simpler when the differences are stored differently. I would store all the differences from the first rotation in r[0], all the differences from the second rotation in r[1], etc. > >>> from normal import normal > >>> normal([0,1,3,6,7,10]) > [0, 1, 3, 6, 7, 10] #p0 > [1, 3, 6, 7, 10, 0] #p1 > [3, 6, 7, 10, 0, 1] #p2 > [6, 7, 10, 0, 1, 3] #p3 > [7, 10, 0, 1, 3, 6] #p4 > [10, 0, 1, 3, 6, 7] #p5 > > [[10, 11, 10, 9, 11, 9], [7, 9, 9, 7, 8, 8], [6, 6, 7, 6, 6, 5], [3, 5, > 4, 4, 5, 3], [1, 2, 3, 1, 3, 2]] #r That would become (when using tuples instead of lists, but that's not important): [(10, 7, 6, 3, 1), (11, 9, 6, 5, 2), (10, 9, 7, 4, 3), (9, 7, 6, 4, 1), (11, 8, 6, 5, 3), (9, 8, 5, 3, 2)] A simple sort() will put the element you want in the first spot, unless there's something I'm missing. Problem solved! Just add this to the end of normal(s): transposed = zip(*v) print '\n', transposed withindices = zip(transposed, range(len(transposed))) result = min(withindices)[1] print '\n\n', result, r[result] (I added the indices to keep track of which element got selected by min()) Result is: ------begin------ [0, 1, 3, 6, 7, 10] [1, 3, 6, 7, 10, 0] [3, 6, 7, 10, 0, 1] [6, 7, 10, 0, 1, 3] [7, 10, 0, 1, 3, 6] [10, 0, 1, 3, 6, 7] [[10, 11, 10, 9, 11, 9], [7, 9, 9, 7, 8, 8], [6, 6, 7, 6, 6, 5], [3, 5, 4, 4, 5, 3], [1, 2, 3, 1, 3, 2]] [(10, 7, 6, 3, 1), (11, 9, 6, 5, 2), (10, 9, 7, 4, 3), (9, 7, 6, 4, 1), (11, 8, 6, 5, 3), (9, 8, 5, 3, 2)] 3 [6, 7, 10, 0, 1, 3] --------end------- which I think is what you're looking for. Instead of transposing via zip(*v) it might also be possible to generate the data in that way in the first place. -- "Codito ergo sum" Roel Schroeven From alan.gauld at blueyonder.co.uk Sat Jul 24 21:22:19 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 21:22:00 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> References: <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> Message-ID: <001201c471b3$8b8bb4d0$6401a8c0@xp> > My subject header is my question. Sure hope there's a way. > > BTW right now my command prompt opens at > C:\Documents and Settings\Dick> > Yeah, I know how to cd, but it's a PITA. The easiest way is to create a shortcut then edit the properties to change the start in folder. You can also add a command in the Autorun section of the registry to CD and that will apply to any prompt window (provided it doesn't override it with a cmd line option!) BTW If using W2K or XP it's worth doing a "help cmd" at the dos prompt, the XP cmd is quite powerful - it even has Unix style file and folder completion available etc... But most of the power is switched off by default for backwards compatibility with DOS... Alan G. From alan.gauld at blueyonder.co.uk Sat Jul 24 21:25:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 21:24:56 2004 Subject: [Tutor] Executing dos .bat file with Python script References: <001501c4715b$be1200b0$0095fea9@atyss> Message-ID: <001701c471b3$f5aff290$6401a8c0@xp> > Let say I have a python script that write a .bat file, with the commands and > arguments. Now how can I use that same python script to actually execute the > .bat file in the Windows environment? Any direction would be appreciated. Use os.system() or os.popen() if you want to read the output... Alan G. From alan.gauld at blueyonder.co.uk Sat Jul 24 21:36:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 21:35:59 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> References: <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com><1f7befae040723231613699ce7@mail.gmail.com> <6.1.2.0.2.20040724010041.08245648@rcblue.com> Message-ID: <001c01c471b5$81479d70$6401a8c0@xp> > Thank you! Thank you! Works like a charm. But I'm curious again. How do > you make those other adjustments? They are all in the properties box. Tabs along the top. Alan G. From alan.gauld at blueyonder.co.uk Sat Jul 24 21:50:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 21:49:41 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> References: <1f7befae040723231613699ce7@mail.gmail.com><6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com><1f7befae040723231613699ce7@mail.gmail.com> <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> Message-ID: <003101c471b7$6badc280$6401a8c0@xp> > Make sure to use quick edit mode, insert mode, and at least > a few hundred rows in the screen buffer. That certainly makes > CMD.EXE less painful... > And set up DOSKEY to run by modifying HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun In Regedit > BTW, is autocomple on TAB on by default in XP, or do you need > to tweak the registry for that? Its a registry hack under: HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar for File completion and HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar For Folder completion You have to specify the decimal or hex ASCII value of the key 27 for escape, 9 for tab... And you need to modify the shortcut to start CMD with CMD /F:ON Its all in the help you get when you type CMD /? at the DOS prompt. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From python at bernardlebel.com Sat Jul 24 22:54:38 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Jul 24 21:52:37 2004 Subject: [Tutor] Executing dos .bat file with Python script References: <001501c4715b$be1200b0$0095fea9@atyss> <001701c471b3$f5aff290$6401a8c0@xp> Message-ID: <003701c471c0$70be3670$0095fea9@atyss> (sorry Alan if you have received this privately, I'm not used to the need to use reply-all to send back to the list) Thanks Alan. However.... it doesn't seem to work as expected? My bat file starts a dos command prompt within the Softimage|XSI environment. But when executing the command, well, a command prompt pops but closes immediately! Python code: oFile = file( 'C:\\Python23\\Lib\\experimentation\\xsi.bat', 'r' ) os.system( str( oFile.read() ) ) Bat file (xsi.bat) code (this code is the actual code used to launch the XSI command prompt): @echo off title "SI Command Prompt" cmd /K call C:\Softimage\XSI_3.5.1\Application\bin\setenv.bat echo on I suspect that the problem is with the fact that my bat file is calling another bat file, but usually if I double-click on a bat file containing that code it works.... Thanks Bernard ----- Original Message ----- From: "Alan Gauld" To: "Bernard Lebel" ; Sent: Saturday, July 24, 2004 8:25 PM Subject: Re: [Tutor] Executing dos .bat file with Python script > > Let say I have a python script that write a .bat file, with the > commands and > > arguments. Now how can I use that same python script to actually > execute the > > .bat file in the Windows environment? Any direction would be > appreciated. > > Use os.system() > > or os.popen() if you want to read the output... > > Alan G. > > > From alan.gauld at blueyonder.co.uk Sat Jul 24 21:57:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 21:57:17 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> References: <1f7befae040723231613699ce7@mail.gmail.com><6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com><1f7befae040723231613699ce7@mail.gmail.com><5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> <6.1.2.0.2.20040724063131.02da4ec0@rcblue.com> Message-ID: <003601c471b8$7b1150b0$6401a8c0@xp> > Don't remember the default. But autocomplete is on. Defaults are CTR-F for File completion and CTRL_D for path completion Alan G From alan.gauld at blueyonder.co.uk Sat Jul 24 22:00:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 22:00:26 2004 Subject: [Tutor] hangman.py References: <20040724151731.LMLI26966.mta11.adelphia.net@mail.adelphia.net> Message-ID: <003b01c471b8$ebeb15f0$6401a8c0@xp> > how do you write a hangman program? First question, can you program in any language yet? Secondly, can you program in Python yet? If yes to both questions then check the tutor archives for the last week, somebody posted the guts of a solution. For a fuller solution download my games framework from Useless python and look at the example there - its an OO GUI solution. Or buy the paper book version of my tutorial, it has the detailed description with both command line and GUI versions... :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rschroev_nospam_ml at fastmail.fm Sat Jul 24 22:01:11 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat Jul 24 22:01:13 2004 Subject: [Tutor] A bit long, but would appreciate anyone's help, if time permits! In-Reply-To: <4102B2DC.60901@fastmail.fm> References: <4102B2DC.60901@fastmail.fm> Message-ID: <4102C007.5060001@fastmail.fm> Roel Schroeven wrote: > Just add this to the end of normal(s): > > transposed = zip(*v) > print '\n', transposed > withindices = zip(transposed, range(len(transposed))) > result = min(withindices)[1] > print '\n\n', result, r[result] > > Instead of transposing via zip(*v) it might also be possible to generate > the data in that way in the first place. I just took a closer look at your code, and I noticed your list q contains exactly what you need. That means you don't need the first zip, you can just do withindices = zip(q, range(len(q))) result = min(withindices)[1] Or alternatively, maybe it's better not to keep track of the indices and just do a search in the list: result = q.index(min(q)) -- "Codito ergo sum" Roel Schroeven From python at bernardlebel.com Sat Jul 24 23:13:28 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Jul 24 22:11:27 2004 Subject: [Tutor] Executing dos .bat file with Python script References: <001501c4715b$be1200b0$0095fea9@atyss> <001701c471b3$f5aff290$6401a8c0@xp> Message-ID: <004601c471c3$128bf4e0$0095fea9@atyss> Well, os.startfile( path_to_file ) is exactly what I was looking for. Thanks! Bernard ----- Original Message ----- From: "Alan Gauld" To: "Bernard Lebel" ; Sent: Saturday, July 24, 2004 8:25 PM Subject: Re: [Tutor] Executing dos .bat file with Python script > > Let say I have a python script that write a .bat file, with the > commands and > > arguments. Now how can I use that same python script to actually > execute the > > .bat file in the Windows environment? Any direction would be > appreciated. > > Use os.system() > > or os.popen() if you want to read the output... > > Alan G. > > > From alan.gauld at blueyonder.co.uk Sat Jul 24 23:08:11 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Jul 24 23:07:45 2004 Subject: [Tutor] os.popen() questions References: <5.2.1.1.0.20040724122231.0295cc30@www.thinkware.se> <41029FA5.2050005@po-box.mcgill.ca> Message-ID: <006101c471c2$53dfb360$6401a8c0@xp> > > popen2 is simpler to use than popen3 when it's okay for cmd's standard > > error to go to the same destination as your own process's standard error, > > What determines whether these things are "okay"? > Is it highly program dependant, Yes. It is OK if you are not doing something specific with error output from your own program. Thus if you were logging your own error output to a file for processing later but you were reading the stderr from popen and using it within your program you wouldn't be wise to use popen2. At least thats what I think it means, I've only ever used vanilla popen() myself... ;-) Alan G From david at graniteweb.com Sun Jul 25 04:17:55 2004 From: david at graniteweb.com (David Rock) Date: Sun Jul 25 04:17:59 2004 Subject: [Tutor] Executing dos .bat file with Python script In-Reply-To: <003701c471c0$70be3670$0095fea9@atyss> References: <001501c4715b$be1200b0$0095fea9@atyss> <001701c471b3$f5aff290$6401a8c0@xp> <003701c471c0$70be3670$0095fea9@atyss> Message-ID: <20040725021755.GA20382@wdfs.attbi.com> * Bernard Lebel [2004-07-24 21:54]: > (sorry Alan if you have received this privately, I'm not used to the need to > use reply-all to send back to the list) > > > Thanks Alan. > > However.... it doesn't seem to work as expected? > My bat file starts a dos command prompt within the Softimage|XSI > environment. But when executing the command, well, a command prompt pops but > closes immediately! > > Python code: > oFile = file( 'C:\\Python23\\Lib\\experimentation\\xsi.bat', 'r' ) > os.system( str( oFile.read() ) ) your python code should be: os.system( 'C:\\Python23\\Lib\\experimentation\\xsi.bat' ) That spawns a shell and runs the given command within it. Also, look at the commands module if you need to get status or output, too. http://docs.python.org/lib/module-commands.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/20040724/4adb26bc/attachment.pgp From gustabares at verizon.net Sun Jul 25 04:46:52 2004 From: gustabares at verizon.net (Gus Tabares) Date: Sun Jul 25 04:47:11 2004 Subject: [Tutor] Converting month names to abbreviated form Message-ID: <000f01c471f1$a95b81a0$0200a8c0@blackbetty> Hello all, Are there any known routines for converting month names to their abbreviated form (i.e., December->Dec) ? I was looking at the time module, but it didn't look very promising. Thanks, Gus From tim.peters at gmail.com Sun Jul 25 05:10:04 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun Jul 25 05:10:10 2004 Subject: [Tutor] Converting month names to abbreviated form In-Reply-To: <000f01c471f1$a95b81a0$0200a8c0@blackbetty> References: <000f01c471f1$a95b81a0$0200a8c0@blackbetty> Message-ID: <1f7befae040724201035754369@mail.gmail.com> [Gus Tabares] > Are there any known routines for converting month names to their > abbreviated form (i.e., December->Dec) ? If you're thinking about American month names, the abbreviation of a month name is just its first 3 letters. >>> 'December'[:3] 'Dec' >>> 'January'[:3] 'Jan' >>> etc. From gustabares at verizon.net Sun Jul 25 05:32:08 2004 From: gustabares at verizon.net (Gus Tabares) Date: Sun Jul 25 05:32:22 2004 Subject: [Tutor] Converting month names to abbreviated form In-Reply-To: <1f7befae040724201035754369@mail.gmail.com> Message-ID: <000201c471f7$fa70e520$0200a8c0@blackbetty> Ah, yes. So foolish of me. Thank you... Gus -----Original Message----- From: Tim Peters [mailto:tim.peters@gmail.com] Sent: Saturday, July 24, 2004 11:10 PM To: Gus Tabares Cc: tutor@python.org Subject: Re: [Tutor] Converting month names to abbreviated form [Gus Tabares] > Are there any known routines for converting month names to their > abbreviated form (i.e., December->Dec) ? If you're thinking about American month names, the abbreviation of a month name is just its first 3 letters. >>> 'December'[:3] 'Dec' >>> 'January'[:3] 'Jan' >>> etc. From isrgish at fastem.com Sun Jul 25 05:55:12 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Jul 25 05:55:01 2004 Subject: [Tutor] Re: Please critique my hangman.py program Message-ID: <20040725035458.786AE1E4002@bag.python.org> Hi Alan, [snip] >> # Setup list to hold correct letters >> correct_so_far = [] >> for i in range(word_length): >> correct_so_far.append("_") > > correct_so_far = ['_'] * word_length > >But you could just use a string which is esier to print later: > > xcorrect_so_far = '_' * word_length > >> # Setup some other variables >> incorrect = [] >> guesses = 0 >> letters_guessed = 0 > > guesses, letters_guessed = 0, 0 > >> # Start main game loop. >> print "\nI am thinking of a word",word_length,"letters long" >> while letters_guessed < word_length: >> >> # Print status of game on each pass. >> print >> print_status (correct_so_far,incorrect,guesses) >> >> # Get guess from user >> while 1: >> guess = raw_input("Which letter would you like to try? >") >> guess = string.lower(guess) >> if len(guess) != 1: >> print "You can only guess one letter at a time!" >> elif guess in incorrect or guess in correct_so_far: >> print "You've already tried that letter!" >> elif guess not in >["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"]: >> print "That's not a valid letter." >> else: >> break >> guesses = guesses + 1 >> >> # Evaluate guess against word >> letter_correct = 0 >> for i in range(word_length): >> if guess == word[i]: >> correct_so_far[i] = guess >> letter_correct=1 >> letters_guessed = letters_guessed + 1 > >Personally I'd use a while loop here: > > i,letter_correct = 0,False > while i < word_length and not letter_correct: > if guess == word[i]: > correct_so_far[i] = guess > letter_correct=True > letters_guessed += 1 > i += 1 > >Same length but I just think the test expresses the intention of >the loop better. I think that there may be a problem with this. For a word that has 2 of the same letter. The original way checks for that, while the latter way would make "letter_correct" = to "True" by the first pass andsthe while loop would terminate. All the best, Isr [snip] > >Hope those ideas help. They are not definitively better just some >alternatives. > >Alan G. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kyeser at earthlink.net Sun Jul 25 09:40:00 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Sun Jul 25 09:40:04 2004 Subject: [Tutor] Permutations? Message-ID: def perm(k): # Compute the list of all permutations of k if len(k) <= 1: return [k] r = [] for i in range(len(k)): s = k[:i] + k[i+1:] p = perm(s) for x in p: r.append(k[i:i+1] + x) return r Could someone tell me how I can modify the above function so that it produces a list of permutations of k that only begins on k[0]? If k = [0,1,2,3], I want to modify perm(k) so that it only produces [[0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1]]. I could produce the list of ALL permutations of k and then delete the ones which don't begin with k[0], but for a large list, this could really slow things down. I was thinking of algorithm that computes only the ones I want. I would appreciate anyone's suggestion. Thanks. Best, Kye p.s. By the way, does anyone have any idea if it would drive my computer (667 MHz and 512MB RAM) nuts to perm(range(12))? From visional_freeman at yahoo.com Sun Jul 25 10:04:27 2004 From: visional_freeman at yahoo.com (ivan low) Date: Sun Jul 25 09:56:13 2004 Subject: [Tutor] Please help me to see what's wrong with the code Message-ID: word = [] function = None while function != "0": entry = raw_input("enter function: ") #continue the game if function == "0": print "Welcome to word game 2.0" #add word to the list elif function == "1": add = raw_input("Please add word: ") new = (add) word.append(new) Does anybody know what is wrong with the code. When I enter function #1 I can't access the "please add word" The loop just continue displaying the number I had enter in "entry" Ivan From darnold02 at sprynet.com Sun Jul 25 10:01:58 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun Jul 25 10:01:42 2004 Subject: [Tutor] Please help me to see what's wrong with the code In-Reply-To: Message-ID: Your input variable is entry, not function. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of ivan low Sent: Sunday, July 25, 2004 3:04 AM To: python Subject: [Tutor] Please help me to see what's wrong with the code word = [] function = None while function != "0": entry = raw_input("enter function: ") #continue the game if function == "0": print "Welcome to word game 2.0" #add word to the list elif function == "1": add = raw_input("Please add word: ") new = (add) word.append(new) Does anybody know what is wrong with the code. When I enter function #1 I can't access the "please add word" The loop just continue displaying the number I had enter in "entry" Ivan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sun Jul 25 10:33:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 10:33:00 2004 Subject: [Tutor] Re: Please critique my hangman.py program References: <20040725035458.786AE1E4002@bag.python.org> Message-ID: <00a201c47222$1244f4a0$6401a8c0@xp> > >> # Evaluate guess against word > >> letter_correct = 0 > >> for i in range(word_length): > >> if guess == word[i]: > >> correct_so_far[i] = guess > >> letter_correct=1 > >> letters_guessed = letters_guessed + 1 > > > >Personally I'd use a while loop here: > > > > i,letter_correct = 0,False > > while i < word_length and not letter_correct: > > if guess == word[i]: > > correct_so_far[i] = guess > > letter_correct=True > > letters_guessed += 1 > > i += 1 > > > >Same length but I just think the test expresses the intention of > >the loop better. > > I think that there may be a problem with this. For a word that > has 2 of the same letter. The original way checks for that, > while the latter way would make "letter_correct" = to "True" > by the first pass and the while loop would terminate. Good catch! Although it actually highlights a bug in the first version too in that a single letter occurruing twice will show up twice in the letters_guessed total. But I guess(sic) that thats less of an issue than not filling in all of the blanks... :-) It can be fixed by pulling it out of the loop and using an if statement: # Evaluate guess against word letter_correct = False for i in range(word_length): if guess == word[i]: correct_so_far[i] = guess letter_correct=True if letter_ correct: letters_guessed = letters_guessed + 1 And my mistake can also be fixed by simply eliminating the second clause of the while test, but then its not much advantage over the for/range combo... Alan G. From alan.gauld at blueyonder.co.uk Sun Jul 25 10:35:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 10:34:34 2004 Subject: [Tutor] Permutations? References: Message-ID: <00a701c47222$4a7347a0$6401a8c0@xp> > p.s. By the way, does anyone have any idea if it would drive my > computer (667 MHz and 512MB RAM) nuts to perm(range(12))? No, it might take a while but the PC should function just fine while its doimg it. Provided you aren't running DOS of course... Alan G. From alan.gauld at blueyonder.co.uk Sun Jul 25 10:43:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 10:42:35 2004 Subject: [Tutor] Please help me to see what's wrong with the code References: Message-ID: <00ae01c47223$69fa9c30$6401a8c0@xp> > word = [] > function = None > while function != "0": > > entry = raw_input("enter function: ") function = raw_input(...) > > #continue the game > if function == "0": > print "Welcome to word game 2.0" > > #add word to the list > elif function == "1": > add = raw_input("Please add word: ") > new = (add) > word.append(new) > > Does anybody know what is wrong with the code. You never modify function, it is permanently set to None... Also what is the new=(add) line supposed to do? The parens are pointless and you could just append add directly? Alan G. From rdm at rcblue.com Sun Jul 25 11:29:33 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 25 11:29:37 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> Message-ID: <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> I've had various responses to my request for a critique of my Frac.py (I mispelled it as Fraq.py in the subject header--must have had Iraq on my mind.) Before I begin to try to implement your valuable suggestions for Frac.py, I'd like to try again for a response to a specific question I asked in that post: In Frac.py I wanted to give the user a chance to quit at any prompt (and have the program close smoothly), by entering a "q" or an "x". I did this by the statement, if answer in ["q", "x"]: break The problem with this is that it only breaks out of the inner loop. I have to repeat this statement in the outer loop. So I'm asking if there's a better way. Raising an exception doesn't do it. Is there a way (other than mine) to enable the user to quit smoothly when he's inside a loop which is inside a loop? Here's a silly game/test script I wrote to try to illustrate my question: """ print "This is an appropriate response test." print "Enter q or x to give up." while True: while True: answer = raw_input("How are you today: ") if answer == "x": print "Give up? O.K., you can try again tomorrow." break elif answer != "Fine, thank you. And you?": print "C'mon. That's dumb. Try again." continue else: print "Congratulations! You passed the test!" break break "" At two points in the inner loop I've got a break. But I need another at the end of the outer loop to get out smoothly. Thanks, Dick Moores From bvande at po-box.mcgill.ca Sun Jul 25 11:37:32 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 25 11:37:51 2004 Subject: [Tutor] Permutations? In-Reply-To: References: Message-ID: <41037F5C.8060201@po-box.mcgill.ca> Hee-Seng Kye said unto the world upon 25/07/2004 03:40: > def perm(k): > # Compute the list of all permutations of k > if len(k) <= 1: > return [k] > r = [] > for i in range(len(k)): > s = k[:i] + k[i+1:] > p = perm(s) > for x in p: > r.append(k[i:i+1] + x) > return r > > Could someone tell me how I can modify the above function so that it > produces a list of permutations of k that only begins on k[0]? > > If k = [0,1,2,3], I want to modify perm(k) so that it only produces > [[0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1]]. > > I could produce the list of ALL permutations of k and then delete the > ones which don't begin with k[0], but for a large list, this could > really slow things down. I was thinking of algorithm that computes only > the ones I want. > > I would appreciate anyone's suggestion. Thanks. > > Best, > Kye > > p.s. By the way, does anyone have any idea if it would drive my computer > (667 MHz and 512MB RAM) nuts to perm(range(12))? > Hi Kye, since your function is calling itself, nothing immediately occurs to me that would manage to do what you want in a single function and be readable/good style. (Though I could be overlooking something simpler.) I think you should be able to do this all in a single function by tracking on what level of the recursive call you are at. You could do this with a variable in the global namespace. This would be defined outside the function or within it with a global statement. (This last way also would need some try/except logic to prevent reinitializing your tracker each time you call the function.) The idea then would be to strip of the first element only on the first level of perm() calling and reattach it to all permutations before returning out of that level. But, 5 minutes of trying to set this up convinced this still new python programmer that this will, if workable, be harder to read and maintain than the simple of leaving your original function as is and adding this function to your program: def perm_all_but_head(k): permed_tail = perm(k[1:]) for p in permed_tail: p = p.insert(0, k[0]) return permed_tail Then, instead of calling your perm(), call perm_all_but_head(). Hope that helps, Brian vdB From bvande at po-box.mcgill.ca Sun Jul 25 11:44:02 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 25 11:44:20 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> Message-ID: <410380E2.1030202@po-box.mcgill.ca> Dick Moores said unto the world upon 25/07/2004 05:29: > I've had various responses to my request for a critique of my Frac.py (I > mispelled it as Fraq.py in the subject header--must have had Iraq on my > mind.) > > Before I begin to try to implement your valuable suggestions for > Frac.py, I'd like to try again for a response to a specific question I > asked in that post: > > In Frac.py I wanted to give the user a chance to quit at any prompt (and > have the program close smoothly), by entering a "q" or an "x". I did > this by the statement, > > if answer in ["q", "x"]: > break > > The problem with this is that it only breaks out of the inner loop. I > have to repeat this statement in the outer loop. > > So I'm asking if there's a better way. Raising an exception doesn't do > it. Is there a way (other than mine) to enable the user to quit smoothly > when he's inside a loop which is inside a loop? > > Here's a silly game/test script I wrote to try to illustrate my question: > """ > print "This is an appropriate response test." > print "Enter q or x to give up." > while True: > while True: > answer = raw_input("How are you today: ") > if answer == "x": > print "Give up? O.K., you can try again tomorrow." > break > elif answer != "Fine, thank you. And you?": > print "C'mon. That's dumb. Try again." > continue > else: > print "Congratulations! You passed the test!" > break > break > "" > At two points in the inner loop I've got a break. But I need another at > the end of the outer loop to get out smoothly. > > Thanks, > > Dick Moores > Hi Dick, I haven't followed your thread closely so I don't recall your program. Thus, it might not meet your definition of "smooth" in the case at hand, but have you tried sys.exit() ? Best, Brian vdB From rdm at rcblue.com Sun Jul 25 12:20:18 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 25 12:21:31 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <410380E2.1030202@po-box.mcgill.ca> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <410380E2.1030202@po-box.mcgill.ca> Message-ID: <6.1.2.0.2.20040725030308.02679ec0@rcblue.com> At 02:44 7/25/2004, Brian van den Broek wrote: >>"" >>At two points in the inner loop I've got a break. But I need another at >>the end of the outer loop to get out smoothly. >>Thanks, >>Dick Moores > >Hi Dick, > >I haven't followed your thread closely so I don't recall your program. >Thus, it might not meet your definition of "smooth" in the case at hand, >but have you tried sys.exit() ? Brian, Yes! I modified that silly test/game script to: import sys """ print "This is an appropriate response test." print "Enter q or x to give up." while True: while True: answer = raw_input("How are you today: ") if answer == "x": print "Give up? O.K., you can try again tomorrow." sys.exit() elif answer != "Fine, thank you. And you?": print "C'mon. That's dumb. Try again." else: print "Congratulations! You passed the test!" sys.exit() """ Until yesterday, when tutors taught me the wonders of the Win XP command line, I was testing scripts only on IDLE. On IDLE, sys.exit() employed as above gets a big red Traceback (most recent call last): File "C:/Python23/DumbTest2.py", line 10, in -toplevel- sys.exit() SystemExit Executing via the command line gets a smooth quit. This is the second time in a couple of weeks that IDLE has failed to execute code correctly. The first was when I was trying to use msvcrt.getch(). Whew! Guess I should stick just with the command line for execution of scripts from now on. Thanks, Dick From bvande at po-box.mcgill.ca Sun Jul 25 12:27:58 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 25 12:29:15 2004 Subject: [Tutor] Permutations? In-Reply-To: References: Message-ID: <41038B2E.2050502@po-box.mcgill.ca> Hee-Seng Kye said unto the world upon 25/07/2004 03:40: > def perm(k): # Compute the list of all permutations of k if len(k) <= > 1: return [k] r = [] for i in range(len(k)): s = k[:i] + k[i+1:] p = > perm(s) for x in p: r.append(k[i:i+1] + x) return r > > Could someone tell me how I can modify the above function so that it > produces a list of permutations of k that only begins on k[0]? > > If k = [0,1,2,3], I want to modify perm(k) so that it only produces > [[0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1]]. > > I could produce the list of ALL permutations of k and then delete the > ones which don't begin with k[0], but for a large list, this could > really slow things down. I was thinking of algorithm that computes > only the ones I want. > > I would appreciate anyone's suggestion. Thanks. > > Best, Kye > > p.s. By the way, does anyone have any idea if it would drive my > computer (667 MHz and 512MB RAM) nuts to perm(range(12))? > > _______________________________________________ Tutor maillist - > Tutor@python.org http://mail.python.org/mailman/listinfo/tutor > Hi, I just realized I should have said the following a bit better: > I think you should be able to do this all in a single function by > tracking on what level of the recursive call you are at. You could do > this with a variable in the global namespace. This would be defined > outside the function or within it with a global statement. (This last > way also would need some try/except logic to prevent reinitializing > your tracker each time you call the function.) The idea then would be > to strip of the first element only on the first level of perm() calling > and reattach it to all permutations before returning out of that level. In thinking about how to explain my intent better, I realized why I had hit a snag in my attempt to code up the approach earlier. So, code rather than English ;-) def perm2(k): # Compute the list of all permutations of k that leave k[0] in place try: track = track + 1 # Will raise exception first time through except NameError: track = 0 # Set to 0 only on first pass global track if len(k) <= 1: track = track - 1 return [k] r = [] if track == 0: first = k[0] k = k[1:] for i in range(len(k)): s = k[:i] + k[i+1:] p = perm2(s) for x in p: r.append(k[i:i+1] + x) if track == 0: for p in r: p = p.insert(0, first) track = track - 1 return r But for readability and keeping the global namespace clean{*}, I like my first reply's solution better. Plus on long inputs, it should run faster as skipping the try/except blocks of this version. {*} The global is a potential problem because you have to be sure there is no track object already in the namespace the function can see when called. It's asking for trouble to use one when you can avoid it. Best, brian vdB From bvande at po-box.mcgill.ca Sun Jul 25 12:49:46 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 25 12:50:17 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <6.1.2.0.2.20040725030308.02679ec0@rcblue.com> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <410380E2.1030202@po-box.mcgill.ca> <6.1.2.0.2.20040725030308.02679ec0@rcblue.com> Message-ID: <4103904A.7000301@po-box.mcgill.ca> Dick Moores said unto the world upon 25/07/2004 06:20: > At 02:44 7/25/2004, Brian van den Broek wrote: > >>> "" >>> At two points in the inner loop I've got a break. But I need another >>> at the end of the outer loop to get out smoothly. >>> Thanks, >>> Dick Moores >> >> >> Hi Dick, >> >> I haven't followed your thread closely so I don't recall your program. >> Thus, it might not meet your definition of "smooth" in the case at >> hand, but have you tried sys.exit() ? > > > Brian, > > Yes! I modified that silly test/game script to: > > > Until yesterday, when tutors taught me the wonders of the Win XP command > line, I was testing scripts only on IDLE. On IDLE, sys.exit() employed > as above gets a big red > > Traceback (most recent call last): > File "C:/Python23/DumbTest2.py", line 10, in -toplevel- > sys.exit() > SystemExit > > Executing via the command line gets a smooth quit. > > This is the second time in a couple of weeks that IDLE has failed to > execute code correctly. The first was when I was trying to use > msvcrt.getch(). > > Whew! Guess I should stick just with the command line for execution of > scripts from now on. > > Thanks, > > Dick Hi Dick, glad that helped :-) I don't know much about msvcrt.getch(). But for sys.exit(), I don't think it is right the IDLE is dong it 'wrong'. IDLE is configured to display all exceptions in the interactive window. sys.exit() ends programs by raising the SystemExit exception, and IDLE displays it, as it should with exceptions. IDLE could be coded to let SystemExit exceptions silently terminate your script. But I think that in a more complicated case than your program this could make it harder for you to figure out why your program terminated. Worse yet, imagine you imported a package and hadn't read the source (or couldn't if it was in C and like me, you can't make use of C-source yet). If it raised a SystemExit and IDLE didn't tell you, you'd have quite a puzzle working out why your script stopped. With the exception, you at least have a better starting point than "it stopped. I wonder why?" ;-) (import this #2). Also, since it is a Tkinter program, you shouldn't run Tkinter scripts via IDLE -- IDLE can't sort out which Tkinter things are meant for it and which for your script. Best, Brian vdB From rdm at rcblue.com Sun Jul 25 13:45:16 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 25 13:45:23 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <4103904A.7000301@po-box.mcgill.ca> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <410380E2.1030202@po-box.mcgill.ca> <6.1.2.0.2.20040725030308.02679ec0@rcblue.com> <4103904A.7000301@po-box.mcgill.ca> Message-ID: <6.1.2.0.2.20040725043901.02552170@rcblue.com> At 03:49 7/25/2004, Brian van den Broek wrote: >Hi Dick, > >glad that helped :-) > >I don't know much about msvcrt.getch(). But for sys.exit(), I don't think >it is right the IDLE is dong it 'wrong'. > >IDLE is configured to display all exceptions in the interactive window. >sys.exit() ends programs by raising the SystemExit exception, and IDLE >displays it, as it should with exceptions. By executing scripts using IDLE, I didn't mean at the interactive prompt. I should have made that clear. I meant I write a script using a new IDLE window that I get by ^N. Then I would test it by saving the script, not closing it, and execute it by F5. It's when executing this way that sys.exit() does not work "correctly", i.e., does not permit me to use it to exit smoothly (silently?), the way I've written the code to do. I do use the IDLE interactive prompt to test bits of code, but not a whole script. Does this straighten out what I meant? >IDLE could be coded to let SystemExit exceptions silently terminate your >script. But I think that in a more complicated case than your program this >could make it harder for you to figure out why your program terminated. >Worse yet, imagine you imported a package and hadn't read the source (or >couldn't if it was in C and like me, you can't make use of C-source yet). >If it raised a SystemExit and IDLE didn't tell you, you'd have quite a >puzzle working out why your script stopped. With the exception, you at >least have a better starting point than "it stopped. I wonder why?" ;-) >(import this #2). Yes, I see your point. >Also, since it is a Tkinter program, you shouldn't run Tkinter scripts via >IDLE -- IDLE can't sort out which Tkinter things are meant for it and >which for your script. I've already experienced that with some Tkinter scripts. Thanks again, Dick From alan.gauld at blueyonder.co.uk Sun Jul 25 13:59:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 13:58:51 2004 Subject: [Tutor] Please critique my Fraq.py References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> Message-ID: <00c601c4723e$d5c6a240$6401a8c0@xp> > In Frac.py I wanted to give the user a chance to quit at any prompt (and > have the program close smoothly), by entering a "q" or an "x". I did > this by the statement, > > if answer in ["q", "x"]: > break if answer in "qxQX": break is probably neater - to my eyes anyway, certainly less storage although thats not likely to be an issue! :-) > The problem with this is that it only breaks out of the inner loop. I > have to repeat this statement in the outer loop. > > So I'm asking if there's a better way. Raising an exception doesn't do > it. Why does raising SystemExit not do it? In particular if you move all cleanup code - closing files etc into a try/finally block the exception route is the preferred method. > Is there a way (other than mine) to enable the user to quit smoothly > when he's inside a loop which is inside a loop? Nope, an exception is the only reliable way to jump out of nested loops. It could be SystemExit to quit the program or it could be a user defined one class LoopExit(exception): pass try: while True: while True: try: raise LoopBreak finally: print "Done!" except LoopBreak: print "I escaped!" HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sun Jul 25 14:23:18 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 25 14:23:22 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <00c601c4723e$d5c6a240$6401a8c0@xp> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <00c601c4723e$d5c6a240$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040725050938.056d7878@rcblue.com> At 04:59 7/25/2004, Alan Gauld wrote: > > In Frac.py I wanted to give the user a chance to quit at any prompt >(and > > have the program close smoothly), by entering a "q" or an "x". I >did > > this by the statement, > > > > if answer in ["q", "x"]: > > break > >if answer in "qxQX": break I'm happy to learn another way. I suppose I could do this with all types of sequences. >is probably neater - to my eyes anyway, certainly less storage >although thats not likely to be an issue! :-) > > > The problem with this is that it only breaks out of the inner loop. >I > > have to repeat this statement in the outer loop. > > > > So I'm asking if there's a better way. Raising an exception doesn't >do > > it. > >Why does raising SystemExit not do it? >In particular if you move all cleanup code - closing files etc >into a try/finally block the exception route is the preferred method. How about Brian van den Broek's suggestion of about an hour ago, of using sys.exit(). That does what I was after, if I execute at the XP command line. With IDLE, it doesn't. > > Is there a way (other than mine) to enable the user to quit smoothly > > when he's inside a loop which is inside a loop? > >Nope, an exception is the only reliable way to jump out of nested >loops. Could you explain what you mean by reliable? For the problem I posed, one answer is to use sys.exit(). >It could be SystemExit to quit the program or it could be a user >defined >one > >class LoopExit(exception): pass > >try: > while True: > while True: > try: raise LoopBreak > finally: print "Done!" >except LoopBreak: > print "I escaped!" I'll give your suggestion a try, but I don't understand classes yet. Thanks very much, Dick From rmkrauter at yahoo.com Sun Jul 25 16:21:34 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sun Jul 25 16:25:59 2004 Subject: [Tutor] Permutations? In-Reply-To: References: Message-ID: <1090765294.26145.16.camel@localhost.localdomain> On Sun, 2004-07-25 at 03:40, Hee-Seng Kye wrote: > def perm(k): > # Compute the list of all permutations of k > if len(k) <= 1: > return [k] > r = [] > for i in range(len(k)): > s = k[:i] + k[i+1:] > p = perm(s) > for x in p: > r.append(k[i:i+1] + x) > return r > > Could someone tell me how I can modify the above function so that it > produces a list of permutations of k that only begins on k[0]? > > If k = [0,1,2,3], I want to modify perm(k) so that it only produces > [[0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1]]. > You could just call your function as-is with a slice of the original list, and then append the initial list element(s) to the results: lst = [0,1,2,3] results = perm(lst[1:]) print map(lambda res,i=lst[0]:[i]+res,results) Good luck. Rich From rmkrauter at yahoo.com Sun Jul 25 17:39:07 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Sun Jul 25 17:38:49 2004 Subject: [Tutor] Permutations? In-Reply-To: <1090765294.26145.16.camel@localhost.localdomain> References: <1090765294.26145.16.camel@localhost.localdomain> Message-ID: <1090769947.26145.26.camel@localhost.localdomain> On Sun, 2004-07-25 at 10:21, Rich Krauter wrote: > > You could just call your function as-is with a slice of the original > list, and then append the initial list element(s) to the results: > > lst = [0,1,2,3] > results = perm(lst[1:]) > print map(lambda res,i=lst[0]:[i]+res,results) > Sorry, Brian. I see you suggested something similar in your first reply. Rich From rdm at rcblue.com Sun Jul 25 19:05:14 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 25 19:05:18 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> In-Reply-To: <003101c471b7$6badc280$6401a8c0@xp> References: <1f7befae040723231613699ce7@mail.gmail.com> <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> <1f7befae040723231613699ce7@mail.gmail.com> <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> <003101c471b7$6badc280$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040725093459.0261dec0@rcblue.com> At 12:50 7/24/2004, Alan Gauld wrote: > > Make sure to use quick edit mode, insert mode, and at least > > a few hundred rows in the screen buffer. That certainly makes > > CMD.EXE less painful... > > > >And set up DOSKEY to run by modifying > >HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun > >In Regedit > > > BTW, is autocomple on TAB on by default in XP, or do you need > > to tweak the registry for that? > >Its a registry hack under: Both doskey and autocompletion were there for me with Win XP Pro when I bought my current computer in January. At least I can't remember making any register hack for it. Or any register hacks period. Both File completion and Folder completion worked with the Tab key. And access to the command history with the up-arrow key. Searching Google Groups I found how to set a list of doskey macros. See http://tinyurl.com/3pt5z . The macros in the file I created are set automatically when I use the shortcut key for cmd.exe (the shortcut "target" is %SystemRoot%\system32\cmd.exe. >HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar > >for File completion and > >HKEY_LOCAL_MACHINE\Software\Microsoft\Command >Processor\PathCompletionChar > >For Folder completion > >You have to specify the decimal or hex ASCII value of the key > >27 for escape, 9 for tab... > >And you need to modify the shortcut to start CMD with > >CMD /F:ON I haven't needed to do this either. >Its all in the help you get when you type CMD /? at the DOS prompt. Dick Moores >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sun Jul 25 19:10:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 19:09:27 2004 Subject: [Tutor] Please critique my Fraq.py References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <00c601c4723e$d5c6a240$6401a8c0@xp> <6.1.2.0.2.20040725050938.056d7878@rcblue.com> Message-ID: <00cf01c4726a$3c404000$6401a8c0@xp> > >Why does raising SystemExit not do it? > >In particular if you move all cleanup code - closing files etc > >into a try/finally block the exception route is the preferred method. > > How about Brian van den Broek's suggestion of about an hour ago, of using > sys.exit(). That does what I was after, Raising SystemExit is exactly the same, thats all sys.exit() does... > if I execute at the XP command line. With IDLE, it doesn't. That's because IDLE catches SystemExit. It quite reasonably assumes that you don't want to restart IDLE every time you run your program to an exit. > >Nope, an exception is the only reliable way to jump out of nested > >loops. > > Could you explain what you mean by reliable? For the problem I posed, one > answer is to use sys.exit(). As I say calling sys.exit() is just another way of raising the SystemExit exception. Try this: import sys try: sys.exit() except SystemExit: print "Told you so!" > >class LoopExit(exception): pass > > > >try: > > while True: > > while True: > > try: raise LoopBreak > > finally: print "Done!" > >except LoopBreak: except LoopExit: # Oops twas a bug... > > print "I escaped!" > > I'll give your suggestion a try, but I don't understand classes yet. The only bit of classes there is the first line, and in fact you don't really need that, I just wanted to show that you could define your own exception type to distinguish between it and SystemExit. I could just have done: try: while True: while True: try: raise SystemExit finally: print "Done!" except SystemExit: print "I escaped!" HTH, Alan G. From missive at hotmail.com Sun Jul 25 19:10:48 2004 From: missive at hotmail.com (Lee Harr) Date: Sun Jul 25 19:16:15 2004 Subject: [Tutor] Re: Converting month names to abbreviated form Message-ID: >Are there any known routines for converting month names to their >abbreviated form (i.e., December->Dec) ? > >I was looking at the time module, but it didn't look very promising. > Sometimes the time module will surprise you. >>>import time >>>time.strptime('December', '%B') (1900, 12, 1, 0, 0, 0, 5, 335, -1) >>>time.strftime('%b', time.strptime('December', '%B')) 'Dec' _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From bvande at po-box.mcgill.ca Sun Jul 25 19:12:51 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Jul 25 19:21:39 2004 Subject: [Tutor] Permutations? In-Reply-To: <1090769947.26145.26.camel@localhost.localdomain> References: <1090765294.26145.16.camel@localhost.localdomain> <1090769947.26145.26.camel@localhost.localdomain> Message-ID: <4103EA13.4090206@po-box.mcgill.ca> Rich Krauter said unto the world upon 25/07/2004 11:39: > On Sun, 2004-07-25 at 10:21, Rich Krauter wrote: > > >>You could just call your function as-is with a slice of the original >>list, and then append the initial list element(s) to the results: >> >>lst = [0,1,2,3] >>results = perm(lst[1:]) >>print map(lambda res,i=lst[0]:[i]+res,results) >> > > > Sorry, Brian. I see you suggested something similar > in your first reply. > > Rich Hi Rich, no worries. :-) I've not made much use of lambda yet; it doesn't naturally occur to me. I'm glad I saw your way, too. But I do feel that my named-function approach is a bit easier to read and reuse. Best, Brian vdB From rdm at rcblue.com Sun Jul 25 19:34:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 25 19:34:09 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <00cf01c4726a$3c404000$6401a8c0@xp> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <00c601c4723e$d5c6a240$6401a8c0@xp> <6.1.2.0.2.20040725050938.056d7878@rcblue.com> <00cf01c4726a$3c404000$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040725102548.0257a6e0@rcblue.com> At 10:10 7/25/2004, Alan Gauld wrote: >That's because IDLE catches SystemExit. >It quite reasonably assumes that you don't want to restart >IDLE every time you run your program to an exit. (You're referring to the use of sys.exit().) But if I hit F5 to run a program I've been editing in IDLE, I have to restart the program anyway if it exits via sys.exit() (because, as you say, it catches SystemExit). I hope I'm not being obtuse here, but that's the way it seems to me. Thanks for your persistence in trying to help me about this. Dick Moores From tim.peters at gmail.com Sun Jul 25 19:34:05 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun Jul 25 19:34:13 2004 Subject: [Tutor] Permutations? In-Reply-To: References: Message-ID: <1f7befae040725103470a0bad4@mail.gmail.com> [Hee-Seng Kye, playing with permutations] > ... > p.s. By the way, does anyone have any idea if it would drive my > computer (667 MHz and 512MB RAM) nuts to perm(range(12))? Yes, that can't work. There are n! permutations of a collection with n elements, and 12! = 479001600. You'll run out of memory long before materializing a list of nearly half a billion 12-element lists. You can use generators, though, to produce the permutations one at a time. The memory burden is trivial then, although it will still take a long time to generate half a billion results. For example, def perm(k): if k: for i, ith in enumerate(k): for x in perm(k[:i] + k[i+1:]): x.insert(0, ith) yield x else: yield [] >>> for p in perm([1, 2, 3]): ... print p [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] >>> From alan.gauld at blueyonder.co.uk Sun Jul 25 19:46:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 19:45:27 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> References: <1f7befae040723231613699ce7@mail.gmail.com> <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> <1f7befae040723231613699ce7@mail.gmail.com> <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> <003101c471b7$6badc280$6401a8c0@xp> <6.1.2.0.2.20040725093459.0261dec0@rcblue.com> Message-ID: <00d701c4726f$444cb2b0$6401a8c0@xp> > Both doskey and autocompletion were there for me with Win XP Pro when I > bought my current computer in January. Interesting, somebody must have set something up because neither are the default options. > Searching Google Groups I found how to set a list of doskey macros. Yes I only discovered the ability to create macros in DOSKEY myself while researching this thread! I successfully created one but then couldn't figure out how to save it, thanks for the URL. > >And you need to modify the shortcut to start CMD with > > > >CMD /F:ON > > I haven't needed to do this either. I'm not sure how that's been done then, I couldn't see a way of turning it on in the registry other than as part of the shortcut stuff... Alan G. From alan.gauld at blueyonder.co.uk Sun Jul 25 19:48:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 19:47:53 2004 Subject: [Tutor] Please critique my Fraq.py References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <00c601c4723e$d5c6a240$6401a8c0@xp> <6.1.2.0.2.20040725050938.056d7878@rcblue.com> <00cf01c4726a$3c404000$6401a8c0@xp> <6.1.2.0.2.20040725102548.0257a6e0@rcblue.com> Message-ID: <00e901c4726f$9aad6e10$6401a8c0@xp> > >That's because IDLE catches SystemExit. > >It quite reasonably assumes that you don't want to restart > >IDLE every time you run your program to an exit. > > (You're referring to the use of sys.exit().) > > But if I hit F5 to run a program I've been editing in IDLE, I have to > restart the program anyway if it exits via sys.exit() Yes you restart your program by hitting F5 again, but you don't need to restart IDLE itself. If IDLE didn't catch SystemExit then IDLE would die when our program did! Since IDLE is a development environment that is a reasonable behaviour, once you run the program outside of IDLE then it will exit cleanly as expected. Alan G. From tim.peters at gmail.com Sun Jul 25 19:50:39 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sun Jul 25 19:50:41 2004 Subject: [Tutor] Please critique my Fraq.py In-Reply-To: <4103904A.7000301@po-box.mcgill.ca> References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com> <6.1.2.0.2.20040725015816.02562aa8@rcblue.com> <410380E2.1030202@po-box.mcgill.ca> <6.1.2.0.2.20040725030308.02679ec0@rcblue.com> <4103904A.7000301@po-box.mcgill.ca> Message-ID: <1f7befae0407251050979c362@mail.gmail.com> [Brian van den Broek, on Dick Moores's IDLE experience] ... > I don't know much about msvcrt.getch(). I do . The functions in msvcrt call low-level Microsoft-supplied routines of the same names, and are (of course) specific to Windows. They do what the MS routines do, and getch() works only with MS console windows ("DOS boxes"). It's really a mistake on the user's part to *try* to use getch() with any other kind of input device. IDLE can't do anything about this. Alas, Python is implemented in C, and C supplies no portable way to detect the state of the keyboard; "the keyboard" isn't even a concept in C. So anyone needing to do this needs to use platform-specific tricks, and all such tricks work in quirky, platform-specific ways. If someone cared to volunteer the work, I expect it would be possible to write a keyboard-sensing function for Tk, and then that could be used in (but only in) Tk-based programs (like IDLE). From alan.gauld at blueyonder.co.uk Sun Jul 25 19:51:49 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Jul 25 19:51:10 2004 Subject: [Tutor] Please critique my Fraq.py References: <6.1.2.0.2.20040719075401.027ad490@rcblue.com><6.1.2.0.2.20040725015816.02562aa8@rcblue.com><410380E2.1030202@po-box.mcgill.ca> <6.1.2.0.2.20040725030308.02679ec0@rcblue.com> Message-ID: <00ee01c47270$0fad5d60$6401a8c0@xp> > This is the second time in a couple of weeks that IDLE has failed to > execute code correctly. The first was when I was trying to use > msvcrt.getch(). As I explained elsewhere IDLE is being sensible in this case. But... > Whew! Guess I should stick just with the command line for execution of > scripts from now on. ...this is one reason why I only use IDLE for testing things out or writing small programs, I tend to use Vim and a DOS box for anything serious, and I know I'm not alone in this. OTOH I do know Python programmers who live in IDLE quite happily, they learn its foibles and live with them. Alan G. From rdm at rcblue.com Sun Jul 25 19:56:42 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Jul 25 19:56:45 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> In-Reply-To: <00d701c4726f$444cb2b0$6401a8c0@xp> References: <1f7befae040723231613699ce7@mail.gmail.com> <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> <1f7befae040723231613699ce7@mail.gmail.com> <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> <003101c471b7$6badc280$6401a8c0@xp> <6.1.2.0.2.20040725093459.0261dec0@rcblue.com> <00d701c4726f$444cb2b0$6401a8c0@xp> Message-ID: <6.1.2.0.2.20040725105513.046769c8@rcblue.com> At 10:46 7/25/2004, Alan Gauld wrote: > > Both doskey and autocompletion were there for me with Win XP Pro >when I > > bought my current computer in January. > >Interesting, somebody must have set something up because neither >are the default options. I would have had to be Dell, then. Dick From operate777 at adelphia.net Sun Jul 25 23:41:57 2004 From: operate777 at adelphia.net (operate777@adelphia.net) Date: Sun Jul 25 23:42:02 2004 Subject: [Tutor] need help with first program Message-ID: <20040725214157.BMBX26966.mta11.adelphia.net@mail.adelphia.net> i've read the tutorial, but i still don't get whats spam and input. From bvande at po-box.mcgill.ca Mon Jul 26 00:10:58 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Jul 26 00:11:22 2004 Subject: [Tutor] need help with first program In-Reply-To: <20040725214157.BMBX26966.mta11.adelphia.net@mail.adelphia.net> References: <20040725214157.BMBX26966.mta11.adelphia.net@mail.adelphia.net> Message-ID: <41042FF2.7050308@po-box.mcgill.ca> operate777@adelphia.net said unto the world upon 25/07/2004 17:41: > i've read the tutorial, but i still don't get whats spam and input. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, you really have to give people a bit more context for them to help you ;-) Take a look at . Really. (It is one of the things I suggested in my reply to your previous post.) "spam" is nothing more than python people's way of saying "some stuff here" or "replace this with something meaningful to your context". Its just a placeholder with a conventional name so you can tell you aren't supposed to literally use it. Most languages use "foo" and "bar" in their examples, but python folk like "spam" because of a Monty Python sketch involving that word. (This will also account for the occasional reference to lumberjacks and the Spanish Inquisition ;-) Best, brian vdB From alan.gauld at blueyonder.co.uk Mon Jul 26 01:14:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Jul 26 01:13:50 2004 Subject: [Tutor] need help with first program References: <20040725214157.BMBX26966.mta11.adelphia.net@mail.adelphia.net> Message-ID: <011e01c4729d$2596ac80$6401a8c0@xp> In Python... > i've read the tutorial, but i still don't get whats spam and input. Spam is sually just a useful name in an example input is a (slightly dangerous) function to read user input. If you aren't already a programmer start with one of the non programmers intros rather than the official tutorial. Like mine say :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From david at graniteweb.com Mon Jul 26 01:43:52 2004 From: david at graniteweb.com (David Rock) Date: Mon Jul 26 01:43:55 2004 Subject: [Tutor] Converting month names to abbreviated form In-Reply-To: <1f7befae040724201035754369@mail.gmail.com> References: <000f01c471f1$a95b81a0$0200a8c0@blackbetty> <1f7befae040724201035754369@mail.gmail.com> Message-ID: <20040725234352.GB23276@wdfs.attbi.com> * Tim Peters [2004-07-24 23:10]: > [Gus Tabares] > > Are there any known routines for converting month names to their > > abbreviated form (i.e., December->Dec) ? > > If you're thinking about American month names, the abbreviation of a > month name is just its first 3 letters. > > >>> 'December'[:3] > 'Dec' > >>> 'January'[:3] > 'Jan' > >>> I believe the strftime module will let you get this information. Specifically, you want the %b format specifier. http://docs.python.org/lib/module-time.html#l2h-1765 -- 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/20040725/2ff3043c/attachment.pgp From vk33 at mail.ru Mon Jul 26 09:45:06 2004 From: vk33 at mail.ru (Dmitriy D.) Date: Mon Jul 26 09:45:09 2004 Subject: [Tutor] source code processing Message-ID: Could you please suggest some case-studies or tutorials concerning source code (preferred) or just plain text analyzing with python? I'm writing a script for retrieving comments from Delphi code and preparing documentation. Something like javadoc utility. I'm a newbie in Python and I'd like to see the way such tasks are usually done. Thanks in advance! Dmitriy. ----------------------------- Don't limit your challenges, Challenge your limits! From bvande at po-box.mcgill.ca Mon Jul 26 09:57:11 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Jul 26 09:57:30 2004 Subject: [Tutor] source code processing In-Reply-To: References: Message-ID: <4104B957.8010901@po-box.mcgill.ca> Dmitriy D. said unto the world upon 26/07/2004 03:45: > Could you please suggest some case-studies or tutorials concerning > source code (preferred) or just plain text analyzing with python? I'm > writing a script for retrieving comments from Delphi code and preparing > documentation. Something like javadoc utility. I'm a newbie in Python > and I'd like to see the way such tasks are usually done. > > Thanks in advance! > > Dmitriy. > Hi Dmitriy, I've only glanced at it so far, but judging by his Charming Python column, David Mertz's Text Processing in Python might be worth a close look. It's out in a printed version, but he makes it available on his site in plain text. Best, Brian vdB From vk33 at mail.ru Mon Jul 26 10:54:43 2004 From: vk33 at mail.ru (Dmitriy D.) Date: Mon Jul 26 10:54:45 2004 Subject: [Tutor] source code processing In-Reply-To: <4104B957.8010901@po-box.mcgill.ca> Message-ID: Thanks a lot, Brian! Hopefully I'll be able to get the printed version, seems like it's a really useful book. That's a pity he didn't convert it to PDF... -----Original Message----- From: Brian van den Broek To: tutor@python.org Date: Mon, 26 Jul 2004 03:57:11 -0400 Subject: Re: [Tutor] source code processing > > Dmitriy D. said unto the world upon 26/07/2004 03:45: > > Could you please suggest some case-studies or tutorials concerning > > source code (preferred) or just plain text analyzing with python? I'm > > writing a script for retrieving comments from Delphi code and preparing > > documentation. Something like javadoc utility. I'm a newbie in Python > > and I'd like to see the way such tasks are usually done. > > > > Thanks in advance! > > > > Dmitriy. > > > > Hi Dmitriy, > > I've only glanced at it so far, but judging by his Charming Python column, > David Mertz's Text Processing in Python might be > worth a close look. It's out in a printed version, but he makes it > available on his site in plain text. > > Best, > > Brian vdB > ----------------------------- Don't limit your challenges, Challenge your limits! From rschroev_nospam_ml at fastmail.fm Mon Jul 26 11:30:50 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon Jul 26 11:30:52 2004 Subject: [Tutor] How to get Win XP command prompt to open at C:\Python23> In-Reply-To: <00d701c4726f$444cb2b0$6401a8c0@xp> References: <1f7befae040723231613699ce7@mail.gmail.com> <6.1.2.0.2.20040723224140.06c0e7b0@rcblue.com> <1f7befae040723231613699ce7@mail.gmail.com> <5.2.1.1.0.20040724124517.02960ee0@www.thinkware.se> <003101c471b7$6badc280$6401a8c0@xp> <6.1.2.0.2.20040725093459.0261dec0@rcblue.com> <00d701c4726f$444cb2b0$6401a8c0@xp> Message-ID: <4104CF4A.4050502@fastmail.fm> Alan Gauld wrote: >>Both doskey and autocompletion were there for me with Win XP Pro > > when I > >>bought my current computer in January. > > > Interesting, somebody must have set something up because neither > are the default options. In Windows 2000 they aren't default, but I think they are in Windows XP. -- "Codito ergo sum" Roel Schroeven From nick at javacat.f2s.com Mon Jul 26 11:33:16 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Mon Jul 26 11:33:19 2004 Subject: [Tutor] source code processing In-Reply-To: References: Message-ID: <1090834396.4104cfdcc383d@webmail.freedom2surf.net> Quoting "Dmitriy D." : > Thanks a lot, Brian! > Hopefully I'll be able to get the printed version, seems like it's a really > useful book. > That's a pity he didn't convert it to PDF... > Hi Dmitriy, I've got the book, and I dont know at what level your Python skills are at, but it's not for the fainthearted. You really need to be clued up with python before the book will make much sense. Well thats my opinion anyway ;) Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From vk33 at mail.ru Mon Jul 26 11:57:53 2004 From: vk33 at mail.ru (Dmitriy D.) Date: Mon Jul 26 11:57:56 2004 Subject: [Tutor] source code processing In-Reply-To: <1090834396.4104cfdcc383d@webmail.freedom2surf.net> Message-ID: Hi, Nick! Well, yes, I'm quite new to Python though I have extensive experience with java. It's just the matter of "media", I prefer reading from paper sitting in the open air, that's it. ;) And imho there's no use writing numerous 'hello world' programs, some real tasks would be better for learning. And the task I've described, I think it should be quite natural for this programming language (am I wrong?). Actually this is the purpose I need it for. :) Thanks for the reply! -----Original Message----- From: nick@javacat.f2s.com To: "Dmitriy D." Date: Mon, 26 Jul 2004 10:33:16 +0100 Subject: Re: Re[2]: [Tutor] source code processing > > Quoting "Dmitriy D." : > > > Thanks a lot, Brian! > > Hopefully I'll be able to get the printed version, seems like it's a really > > useful book. > > That's a pity he didn't convert it to PDF... > > > > Hi Dmitriy, > > I've got the book, and I dont know at what level your Python skills are at, but > it's not for the fainthearted. You really need to be clued up with python > before the book will make much sense. > > Well thats my opinion anyway ;) > > Nick. > > > ------------------------------------------------- > Everyone should have http://www.freedom2surf.net/ > ----------------------------- Don't limit your challenges, Challenge your limits! From lonetwin at gmail.com Mon Jul 26 12:33:27 2004 From: lonetwin at gmail.com (Steve) Date: Mon Jul 26 12:33:30 2004 Subject: [Tutor] source code processing In-Reply-To: References: Message-ID: <5a309bd30407260333190bc3e6@mail.gmail.com> Hi Dimitriy, Just a suggestion, even though you mentioned you were a newbie to python ... > I'm writing a script for retrieving comments from Delphi code and preparing > documentation. Something like javadoc utility. I'm a newbie in Python and I'd like to see > the way such tasks are usually done. I have never worked with Delphi so I do not know if it provides doc-string like features through the language itself. However, the way that I would go about seeing "...the way such tasks are usually done." would be by looking at the source code of similar tools whenever possible. Although, you might already know this, since you didn't mention it, I'd like to point out that python has an equivalent of javadoc called pydoc(*). You can examine the code of the modules 'pydoc' and 'inspect' to see how things are done for python. Just my 2 cents ... HTH Regards Steve (*) run /pydoc.py pydoc to see what it does. On Mon, 26 Jul 2004 11:45:06 +0400, Dmitriy D. wrote: > Could you please suggest some case-studies or tutorials concerning source code (preferred) or just plain text analyzing with python? > I'm writing a script for retrieving comments from Delphi code and preparing documentation. Something like javadoc utility. I'm a newbie in Python and I'd like to see the way such tasks are usually done. > > Thanks in advance! > > Dmitriy. > > ----------------------------- > Don't limit your challenges, > Challenge your limits! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent_johnson at skillsoft.com Mon Jul 26 15:18:14 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Jul 26 15:18:17 2004 Subject: [Tutor] source code processing In-Reply-To: References: Message-ID: <6.1.0.6.0.20040726091520.029c4bd8@mail4.skillsoft.com> The Python Cookbooks have many text-processing recipes, both in the online version and the printed edition The printed Cookbook is an excellent resource for learning about how things are usually done in Python. Kent At 11:45 AM 7/26/2004 +0400, you wrote: >Could you please suggest some case-studies or tutorials concerning source >code (preferred) or just plain text analyzing with python? >I'm writing a script for retrieving comments from Delphi code and >preparing documentation. Something like javadoc utility. I'm a newbie in >Python and I'd like to see the way such tasks are usually done. > >Thanks in advance! > >Dmitriy. > >----------------------------- >Don't limit your challenges, >Challenge your limits! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From vicki at thepenguin.org Mon Jul 26 18:06:57 2004 From: vicki at thepenguin.org (vicki@thepenguin.org) Date: Mon Jul 26 18:08:45 2004 Subject: [Tutor] file read - rewind? In-Reply-To: <5.2.1.1.0.20040724010736.02962ce0@www.thinkware.se> References: <5.2.1.1.0.20040724010736.02962ce0@www.thinkware.se> Message-ID: <35646.206.53.226.235.1090858017.squirrel@206.53.226.235> I want to read in a file, act on each line of the file, and then start at the beginning again. I don't see a rewind function in the fileinput module, yet it still does not work by simply executing the for line in inputfile again. What am I missing? The while loop should repeat until STOP_READ is set to TRUE. --Vicki --------------------------------------------------------------------------- STOP_READ = wx.FALSE first_iteration = wx.TRUE #While not STOP_READ, iterate through lines in file while STOP_READ == wx.FALSE or first_iteration == wx.TRUE: print "Got into while loop" for line in input.readlines(): if len(line)>1: first_iteration == wx.FALSE tokens=line.split("|") self.command = tokens[0][0]+tokens[0][1] self.arguments = tokens[0].lstrip(tokens[0][0]+tokens[0][1]+" ") print self.command print self.arguments self.ProcessCommand(self.command, self.arguments) wx.GetApp().Yield() From nick at javacat.f2s.com Mon Jul 26 18:27:59 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Jul 26 18:26:22 2004 Subject: [Tutor] file read - rewind? In-Reply-To: <35646.206.53.226.235.1090858017.squirrel@206.53.226.235> Message-ID: Hi Vicki, I dont use the wx toolkit, but to rewind a file you want to use seek() Eg >>> f = open('/nvmixer.log') >>> for line in f: ... print line, ... [InstallShield Silent] Version=v6.00.000 File=Log File [ResponseResult] ResultCode=0 [Application] Name=NvMixer Version=1.50.000 Company=NVIDIA Corporation Lang=0009 >>> f.tell() 176L >>> f.seek(0) >>> f.tell() 0L filename.seek(0) will rewind the file back to the beginning. There's no easy way to rewind back to a certain line number that Im aware of. >filename.seek(0) >filename.seek(10) will now start reading from the 10th character, remembering that line chars start at 0. Hope that helps Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of vicki@thepenguin.org Sent: 26 July 2004 17:07 To: tutor@python.org Subject: [Tutor] file read - rewind? I want to read in a file, act on each line of the file, and then start at the beginning again. I don't see a rewind function in the fileinput module, yet it still does not work by simply executing the for line in inputfile again. What am I missing? The while loop should repeat until STOP_READ is set to TRUE. --Vicki --------------------------------------------------------------------------- STOP_READ = wx.FALSE first_iteration = wx.TRUE #While not STOP_READ, iterate through lines in file while STOP_READ == wx.FALSE or first_iteration == wx.TRUE: print "Got into while loop" for line in input.readlines(): if len(line)>1: first_iteration == wx.FALSE tokens=line.split("|") self.command = tokens[0][0]+tokens[0][1] self.arguments = tokens[0].lstrip(tokens[0][0]+tokens[0][1]+" ") print self.command print self.arguments self.ProcessCommand(self.command, self.arguments) wx.GetApp().Yield() _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Mon Jul 26 20:52:27 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Jul 26 20:51:09 2004 Subject: [Tutor] Converting month names to abbreviated form In-Reply-To: <000f01c471f1$a95b81a0$0200a8c0@blackbetty> References: <000f01c471f1$a95b81a0$0200a8c0@blackbetty> Message-ID: <6.1.0.6.0.20040726125106.03c7d5e0@mail.mric.net> At 08:46 PM 7/24/2004, Gus Tabares wrote: >Hello all, > >Are there any known routines for converting month names to their >abbreviated form (i.e., December->Dec) ? The preferred usage is e.g. rather than i.e. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From Dragonfirebane at aol.com Mon Jul 26 23:31:01 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Mon Jul 26 23:31:17 2004 Subject: [Tutor] tkMessageBox options Message-ID: <7b.2f4c5f6d.2e36d215@aol.com> Hello all, I'm reading a tutorial on Tkinter, but its a little sparing on the details. It says to change the icon for I have to use options, but it doesn't say how. I tried to implement it myself using different variations of the code below, but each time I got: Traceback (most recent call last): File "C:/Program Files/hello.py", line 16, in -toplevel- filerror() File "C:/Program Files/hello.py", line 6, in filerror if tkMessageBox.askquestion(title="File Error",message="Cannot open this file:\n%s\nWould you like to open a different file?" % fn, icon='WARNING'): File "C:\PROGRA~1\lib\lib-tk\tkMessageBox.py", line 91, in askquestion return _show(title, message, QUESTION, YESNO, **options) TypeError: _show() got multiple values for keyword argument 'icon' I don't know what I'm doing wrong or right or where to go from here. Any help would be appreciated. def filerror(): try: fn = raw_input("Name of file to open: ") fp = open(fn) except: if tkMessageBox.askquestion(title="File Error",message="Cannot open this file:\n%s\nWould you like to open a different file?" % fn, icon='WARNING'): filerror() return else: for line in fp.readlines(): print line import tkMessageBox filerror() 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/20040726/0f16ec34/attachment.html From klappnase at freenet.de Tue Jul 27 00:08:18 2004 From: klappnase at freenet.de (Michael Lange) Date: Tue Jul 27 00:05:53 2004 Subject: [Tutor] tkMessageBox options In-Reply-To: <7b.2f4c5f6d.2e36d215@aol.com> References: <7b.2f4c5f6d.2e36d215@aol.com> Message-ID: <20040727000818.5110052e.klappnase@freenet.de> On Mon, 26 Jul 2004 17:31:01 EDT Dragonfirebane@aol.com wrote: > Hello all, > > I'm reading a tutorial on Tkinter, but its a little sparing on the details. > It says to change the icon for I have to use options, > but it doesn't say how. I tried to implement it myself using different > variations of the code below, but each time I got: > > Traceback (most recent call last): > File "C:/Program Files/hello.py", line 16, in -toplevel- > filerror() > File "C:/Program Files/hello.py", line 6, in filerror > if tkMessageBox.askquestion(title="File Error",message="Cannot open this > file:\n%s\nWould you like to open a different file?" % fn, icon='WARNING'): > File "C:\PROGRA~1\lib\lib-tk\tkMessageBox.py", line 91, in askquestion > return _show(title, message, QUESTION, YESNO, **options) > TypeError: _show() got multiple values for keyword argument 'icon' > I've had similar problems, reading the sources helped: ######### def _show(title=None, message=None, icon=None, type=None, **options): if icon: options["icon"] = icon if type: options["type"] = type if title: options["title"] = title if message: options["message"] = message return Message(**options).show() def askquestion(title=None, message=None, **options): "Ask a question" return _show(title, message, QUESTION, YESNO, **options) ######### So you see, tkMessageBox._show() is your friend here, the standard methods like askyesno() and askquestion() are just convenience shortcuts to _show() with some of the parameters predefined (in case of askquestion() the icon is always QUESTION). The call for the message box you wanted should be something like: >>> m = tkMessageBox._show(type='yesno', icon='warning', message='May I call you Frank?') >>> print m yes >>> At the top of tkMessageBox.py you find the possible values for any of _show()'s options. I hope this helped Michael From jeffpeery at yahoo.com Tue Jul 27 01:45:57 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue Jul 27 01:46:01 2004 Subject: [Tutor] floats acting like integers??? In-Reply-To: <20040727000818.5110052e.klappnase@freenet.de> Message-ID: <20040726234557.27045.qmail@web60109.mail.yahoo.com> hello, I have a problem with my IDLE or script. I put in something like a=1/7 and I print a and get zero? but this is only for division, numbers go to integers? anyone have an idea of why this is happening? thanks. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040726/7845a538/attachment.html From bigapple631 at optonline.net Tue Jul 27 01:52:31 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Tue Jul 27 01:51:01 2004 Subject: [Tutor] mode?? Message-ID: <001401c4736b$9d74d0f0$bc4ebb18@hochstein> I am having trouble understanding how you would get a program to output the mode of a group of numbers. I got it to do the mean and median but if there are 7 n umbers and all are different how would you get a mode. Further more if there a re 7 numbers and 2 or 3 are the same, I understand thats the mode but how do you get it to output? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040726/e5b87d99/attachment-0001.htm From kyeser at earthlink.net Tue Jul 27 01:51:25 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Tue Jul 27 01:51:30 2004 Subject: [Tutor] floats acting like integers??? In-Reply-To: <20040726234557.27045.qmail@web60109.mail.yahoo.com> References: <20040726234557.27045.qmail@web60109.mail.yahoo.com> Message-ID: Hi. To get floats for divisions, either the number you are dividing or being divided should be a floating point. >>> a = 1.0 / 7 # or a = 1 / 7.0 >>> a 0.14285714285714285 >>> print a 0.142857142857 Best, Kye On Jul 26, 2004, at 7:45 PM, Jeff Peery wrote: > hello, I have a problem with my IDLE or script. I put in something > like a=1/7 and I print a and get zero?? but this is only for division, > numbers go to integers? anyone have an idea of why this is happening? > thanks. > > ? > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Jul 27 02:38:49 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 27 02:38:53 2004 Subject: [Tutor] floats acting like integers??? In-Reply-To: Message-ID: On Mon, 26 Jul 2004, Hee-Seng Kye wrote: > Hi. To get floats for divisions, either the number you are dividing or > being divided should be a floating point. > > >>> a = 1.0 / 7 # or a = 1 / 7.0 > >>> a > 0.14285714285714285 > >>> print a > 0.142857142857 Hi Jeff, Just as a side note: this does come up often enough as an issue that there's a long-term plan to change the division operator: http://www.python.org/peps/pep-0238.html The default is still the old behavior (int divided by int -> int). But it's possible to enable 'True Division' mode by putting: ### from __future__ import division ### at the very top of your program. Good luck to you! From kent_johnson at skillsoft.com Tue Jul 27 02:42:19 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Jul 27 02:42:28 2004 Subject: [Tutor] mode?? In-Reply-To: <001401c4736b$9d74d0f0$bc4ebb18@hochstein> References: <001401c4736b$9d74d0f0$bc4ebb18@hochstein> Message-ID: <6.1.0.6.0.20040726204043.028b55f0@mail4.skillsoft.com> Here is one way to do it. This will find the mode(s) of a list of any kind of items, not just numbers. Kent def mode(items): "Find the mode(s) of a list of items" # If items is empty then there is no mode if not items: return None # Create a dictionary that maps each item to the number of times it occurs # (i.e. a histogram) hist = {} for item in items: count = hist.get(item, 0) hist[item] = count + 1 # Get the results to a list and sort by number of occurrances result = [ (count, item) for item, count in hist.items() ] result.sort() result.reverse() # The first entry has the number of times the mode occurs maxcount = result[0][0] # Find all the items that occur maxcount times modes = [ item for count, item in result if count == maxcount ] return modes print mode([1,2,2,5,3,4,6,5]) print mode([]) print mode(['a', 2, 'b', 2, 'a', 'a']) prints [5, 2] None ['a'] At 07:52 PM 7/26/2004 -0400, jason hochstein wrote: >I am having trouble understanding how you would get a program to output >the mode of a group of numbers. I got it to do the mean and median but if >there are 7 n umbers and all are different how would you get a mode. >Further more if there a re 7 numbers and 2 or 3 are the same, I understand >thats the mode but how do you get it to output? >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Jul 27 02:53:55 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 27 02:53:58 2004 Subject: [Tutor] mode?? In-Reply-To: <001401c4736b$9d74d0f0$bc4ebb18@hochstein> Message-ID: On Mon, 26 Jul 2004, jason hochstein wrote: > I am having trouble understanding how you would get a program to output > the mode of a group of numbers. I got it to do the mean and median but > if there are 7 n umbers and all are different how would you get a mode. > Further more if there a re 7 numbers and 2 or 3 are the same, I > understand thats the mode but how do you get it to output? Hi Jason, First, we have to make clear that this sounds like a homework problem, so any help that you get from us will be limited mostly to references. We are not allowed to give homework answers. Your question actually doesn't seem related to Python programming in particular, but may have more to do with math definitions. Can you define what you mean by "mode"? The description you gave above is making assumptions that we know what you mean by "mean", "median", and "mode". For the moment, I'll assume that: http://mathworld.wolfram.com/Mode.html describes what you mean by 'mode'. According to the definition in the Mathworld article, it's perfectly possible to have multiple 'modes' for a given set of numbers. Is this what you expect? Good luck to you. From dyoo at hkn.eecs.berkeley.edu Tue Jul 27 03:09:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 27 03:09:26 2004 Subject: [Tutor] mode?? In-Reply-To: <6.1.0.6.0.20040726204043.028b55f0@mail4.skillsoft.com> Message-ID: On Mon, 26 Jul 2004, Kent Johnson wrote: > Here is one way to do it. This will find the mode(s) of a list of any kind > of items, not just numbers. [answer cut] Hmmmm... next time, it might be best to wait for a bit, and hold off on direct answers until we know more. I don't think it's enough to give answers --- we have to find out why Jason had trouble with the problem. The root cause for his difficulty is still an unknown. We have no idea if it's because he's misunderstanding the definition of 'mode', or if he's having problems with using Python's data structures effectively. From what he said earlier, it sounded like he didn't understand what 'mode' meant, but that's only my guess. I guess I'm trying to say: don't do his homework! *grin* From dyoo at hkn.eecs.berkeley.edu Tue Jul 27 03:20:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 27 03:20:55 2004 Subject: [Tutor] source code processing In-Reply-To: Message-ID: On Mon, 26 Jul 2004, Dmitriy D. wrote: > Well, yes, I'm quite new to Python though I have extensive experience > with java. It's just the matter of "media", I prefer reading from paper > sitting in the open air, that's it. ;) And imho there's no use writing > numerous 'hello world' programs, some real tasks would be better for > learning. And the task I've described, I think it should be quite > natural for this programming language (am I wrong?). Actually this is > the purpose I need it for. :) Hi Dmitriy, By source code processing, do you mean things like parsing source code into abstract syntax trees? If so, then you may find: http://theory.stanford.edu/~amitp/Yapps/ or: http://systems.cs.uchicago.edu/ply/ useful. What kind of source code processing are you planning to do? Good luck to you! From vk33 at mail.ru Tue Jul 27 09:01:38 2004 From: vk33 at mail.ru (Dmitriy D.) Date: Tue Jul 27 09:01:40 2004 Subject: [Tutor] source code processing In-Reply-To: Message-ID: > By source code processing, do you mean things like parsing source code > into abstract syntax trees? Well, not exactly. I do not analyze the source code itself. My task looks much simpler - just to retrieve classes and methods signatures along with the comments provided in a specific form and make an html API-reference. For example: {** This is my awards-winning function doing nothing but returning 'hello world' string repeated many times @param Num The number of times the string should be repeated @return 'Hello world' string repeated specified number of times **} function GetHelloWorld(Num: integer): string; Having found this in the source code I want to format the comments into something readable in HTML-form. Thanks for all of your replies. I need some time to look through the links you've kindly provided. Have a nice day! ----------------------------- Don't limit your challenges, Challenge your limits! From STEVEN.M.FAULCONER at saic.com Tue Jul 27 20:23:16 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Tue Jul 27 20:31:09 2004 Subject: [Tutor] Request for Comments Message-ID: <207DA77D2384D411A48B0008C7095D81C1DE97@us-melbourne.mail.saic.com> Well, I finally finished my first graphical script. I am reluctant to send it in, but I figure I won't learn anything unless someone tells me a better way. So, attached to the email is the script. The premise of the script is a graphical front-end to command line programs we wrote in-house. It requires some commercial software to run the binaries (not included) but suffice to say the functionality is there. I'd like to have a better way of creating the gui elements. Since there are currently 5 checkers, I've got a lengthy bit of code to create the widgets. It would be nice to have a method that loops over a data structure (dictionary/list) and builds the gui elements from the contents. I'll have to work on that for the next version. So, please feel free to send constructive criticism or comments. Thanks for your time. Steven Faulconer -------------- next part -------------- A non-text attachment was scrubbed... Name: GuiCheck.pyw Type: application/octet-stream Size: 26666 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040727/d0d06a45/GuiCheck-0001.obj From alan.gauld at blueyonder.co.uk Tue Jul 27 22:48:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 27 22:48:39 2004 Subject: [Tutor] source code processing References: Message-ID: <004001c4741b$16909690$6401a8c0@xp> > Could you please suggest some case-studies or tutorials concerning > source code (preferred) or just plain text analyzing with python? Look at the sample code that comes with Python, I think it includes a pretty printer of some sort,. And of course the unix 2 dos converter is a basic text processor. Finally go looking for David Mertz' online version of his book Text Processing in Python - although it can get pretty deep... Alan G.. From alan.gauld at blueyonder.co.uk Tue Jul 27 23:29:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 27 23:29:23 2004 Subject: [Tutor] file read - rewind? References: <5.2.1.1.0.20040724010736.02962ce0@www.thinkware.se> <35646.206.53.226.235.1090858017.squirrel@206.53.226.235> Message-ID: <006201c47420$c896ad70$6401a8c0@xp> > I want to read in a file, act on each line of the file, and then start at > the beginning again. I don't see a rewind function in the fileinput Try seek(0) instead Alan G. From alan.gauld at blueyonder.co.uk Tue Jul 27 23:34:42 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Jul 27 23:34:44 2004 Subject: [Tutor] floats acting like integers??? References: <20040726234557.27045.qmail@web60109.mail.yahoo.com> Message-ID: <007201c47421$87992540$6401a8c0@xp> > hello, I have a problem with my IDLE or script. I put in something > like a=1/7 and I print a and get zero? You are seeing integer division. One divided by seven is zero with one seventh "left over" If either number is a float you will get float division. Or you can import from future the new style division... There is a brief explanation of this in the simple sequences topic of my tutor. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From dyoo at hkn.eecs.berkeley.edu Wed Jul 28 02:24:52 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 28 02:24:56 2004 Subject: [Tutor] mode?? (fwd) Message-ID: Hi Jason, Thanks for the response! Ok, let me forward your response to Tutor so that the folks on the list can help. If your email client allows it, try to use 'Reply to All', which should include the Tutor list in CC. One suggestion is to look at how Python lists work: you definitely want to look at how to work with lists, since you're dealing with a collection of numbers. I wouldn't worry about modules yet; they're not hard, but aren't necessary for your problem. Lists allow us to use a single container to read in an arbitrary amount of things. For example: ### >>> list_of_numbers = [] >>> print list_of_numbers [] >>> list_of_numbers.append(3) >>> list_of_numbers.append(1) >>> list_of_numbers.append(4) >>> list_of_numbers.append(1) >>> list_of_numbers.append(5) >>> list_of_numbers [3, 1, 4, 1, 5] ### Whenever we want to add a new number at the end of our list, we can append() it. Note that we don't need separate variables like 'first_element' or 'second_element' or 'third_element': we can access them all by using the list 'list_of_elements'. And getting at an arbitrary element of our list isn't so bad either. We "index" an element of our list by using the following bracket notation: ### >>> list_of_numbers[0] 3 >>> list_of_numbers[1] 1 >>> list_of_numbers[2] 4 ### Lists support a few things that are nice: we can ask how many times an element occurs in a list by counting it: ### >>> list_of_numbers.count(1) 2 >>> list_of_numbers.count(42) 0 >>> list_of_numbers.count(3) 1 ### And as one last thing, lists can be "looped" or "iterated" across: ### >>> for n in list_of_numbers: ... print n, n*2, n*3 ... 3 6 9 1 2 3 4 8 12 1 2 3 5 10 15 ### I'm doing a really fast overview of lists; does this make some sense so far? The problem that you're working on will become much easier if you use a collection. Trying to do it without a collection is really ugly; it's doable, but the correct code to do it ends up being one big mess of a special-case thing... and it'll probably be hardcoded to only deal with seven elements. *grin* Play around with lists first to get some familiarity with them, and then go back and try solving the statistical problems with them; it should turn out to be a snap with lists. You mentioned that you looked at a few tutorials; you may find: http://www.ibiblio.org/obp/thinkCSpy/chap08.htm one of the more useful ones, since it concentrates specifically on how to play with Python lists. But the other tutorials on: http://www.python.org/topics/learn/non-prog.html should also have sections on list manipulation that should help. And again, feel free to ask questions about how to use lists on Tutor; we'll be happy to help. Good luck! ---------- Forwarded message ---------- Date: Tue, 27 Jul 2004 18:57:03 -0400 From: jason hochstein To: Danny Yoo Subject: Re: [Tutor] mode?? I understand what the meaning of mode is. I also looked at the mathworld site prior to starting this program. I am at a total loss as to how I would get my program to output the mode of a group of numbers. The mode being the most common number in the bunch. Here is what I have so far: print "This program will give you the Average, Statistical median and Mode of any 7 numbers." print "Please enter your numbers in ascending order." print "Try it if you think I am lying!!" first = input ("What is your first number? ") second = input ("What is your second number? ") third = input ("What is your third number? ") fourth = input ("What is your fourth number? ") fifth = input ("What is your fifth number? ") sixth = input ("What is your sixth number? ") seventh = input ("What is your seventh number? ") average = first + second + third + fourth + fifth + sixth + seventh / 7 median = fourth mode = print "The average of these numbers is", average print "The median of this list is", fourth Python data structures is definitly my problem. Lists and modules and things of that nature are eluding me for some reason. I can't figure out how to inport and export either. I am very new to programming and Python is my first attempt at it. I have been through massive amounts of tutorials. Any help explaining how some of these things work would be greatly appreciated. By no means am I trying to get someone to do the work for me. I want to learn how to do it myself. Thanks again. ----- Original Message ----- From: "Danny Yoo" To: "Kent Johnson" Cc: Sent: Monday, July 26, 2004 9:09 PM Subject: Re: [Tutor] mode?? > > > On Mon, 26 Jul 2004, Kent Johnson wrote: > > > Here is one way to do it. This will find the mode(s) of a list of any kind > > of items, not just numbers. > > [answer cut] > > > Hmmmm... next time, it might be best to wait for a bit, and hold off on > direct answers until we know more. I don't think it's enough to give > answers --- we have to find out why Jason had trouble with the problem. > The root cause for his difficulty is still an unknown. > > > We have no idea if it's because he's misunderstanding the definition of > 'mode', or if he's having problems with using Python's data structures > effectively. From what he said earlier, it sounded like he didn't > understand what 'mode' meant, but that's only my guess. > > > I guess I'm trying to say: don't do his homework! *grin* > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From kyeser at earthlink.net Thu Jul 29 05:46:07 2004 From: kyeser at earthlink.net (Hee-Seng Kye) Date: Thu Jul 29 05:46:10 2004 Subject: [Tutor] Use of List Comprehension? Message-ID: I was wondering under which circumstances one might use list comprehension. Does it have any effect on computation time, or is it used for a matter of simplicity (though could be less easier to read)? Best, Kye From bgailer at alum.rpi.edu Thu Jul 29 06:23:46 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Jul 29 06:21:58 2004 Subject: [Tutor] Use of List Comprehension? In-Reply-To: References: Message-ID: <6.1.0.6.0.20040728221857.03e2bf78@mail.mric.net> At 09:46 PM 7/28/2004, Hee-Seng Kye wrote: >I was wondering under which circumstances one might use list >comprehension. Does it have any effect on computation time, or is it used >for a matter of simplicity (though could be less easier to read)? For me list comprehension is a shorthand (idiomatic) replacement for a list initialization followed by one (or more nested) for loop(s), append calls and if statements. A lot can be said in terse code. It is easier to write and read. Computation time is probably faster. Compare: l = [] for x in y: if x > 3: l.append(x) with: l = [x for x in y if x > 3] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From Ralf.Steckel at AtosOrigin.com Thu Jul 29 09:25:45 2004 From: Ralf.Steckel at AtosOrigin.com (Steckel, Ralf) Date: Thu Jul 29 09:25:48 2004 Subject: [Tutor] Python for Windows: module re, re.LOCALE different for Idle and p ython shell? Message-ID: <42BF8717D22EB1409F03483C993F46A70DE8F9@DEACX002.ikossvan.de> Dear list, i've written a python script to extract all words from a text file and to print how often they are used. For doing that i use the re module with: r=re.compile('[\w]+', re.LOCALE | re.IGNORECASE) The re.LOCALE flag promises that the operating systems local character set is used. As i live in Germany and use a German Windows NT machine i want to include the German 'Umlaute' ('???????') in the words of my wordlist. This works fine if i'm running my script from Idle, but running it from the Windows command prompt or by starting it from the Windows explorer, it doesn't include the German 'Umlaute' in the words, but filters them. My question is: how do i get for the command line the same environment as for Idle? I guess this is rather a Windows question than a Python one, because Windows and DOS both support German 'Umlaute', but it seems they do it with different character codes. Best wishes, Ralf PS: OS is Windows NT 4.0 work station (German) Python is Python 2.3.3 for Windows From adam at monkeez.org Thu Jul 29 11:46:47 2004 From: adam at monkeez.org (adam) Date: Thu Jul 29 11:46:53 2004 Subject: [Tutor] wxPython buttons in a loop Message-ID: <49986.217.206.168.163.1091094407.spork@webmail.monkeez.org> I'm trying to create a wxPython app which goes through a loop and produces a wxBitmapButton for every letter of the alphabet. However, when I run the code below, I get three a's duplicated, although the debugging print statements show that 'alphabet_graphics/b.bmp' has also been called. Is this problem related to bmp being a constant here? If so, how would I go about overwriting it? I tried creating a list of 'bmp' but I always got IndexError: list index out of range when I ran it. Any help gratefully appreciated. Adam alphabet = ['a','b','c'] alphabetgraphics = ['a.bmp', 'b.bmp', 'c.bmp'] #bmp =[] # Not currently used #grafic = [] # Not currently used for i in range(len(alphabet)): print alphabetgraphics[i] # Debug tool. bmp = wxBitmap('alphabet_graphics/' + alphabetgraphics[i], wxBITMAP_TYPE_BMP) self.grafic =wxBitmapButton(self,30,bmp,wxPoint(160,20), wxSize(bmp.GetWidth()+10,bmp.GetHeight()+10)) self.sizer2.Add(self.grafic,1,wxEXPAND) print bmp # Debug tool. From klappnase at freenet.de Thu Jul 29 12:11:57 2004 From: klappnase at freenet.de (Michael Lange) Date: Thu Jul 29 12:09:28 2004 Subject: [Tutor] Request for Comments In-Reply-To: <207DA77D2384D411A48B0008C7095D81C1DE97@us-melbourne.mail.saic.com> References: <207DA77D2384D411A48B0008C7095D81C1DE97@us-melbourne.mail.saic.com> Message-ID: <20040729121157.7cc769d3.klappnase@freenet.de> On Tue, 27 Jul 2004 11:23:16 -0700 "Faulconer, Steven M." wrote: > I'd like to have a better way of creating the gui elements. Since there are > currently 5 checkers, I've got a lengthy bit of code to create the widgets. > It would be nice to have a method that loops over a data structure > (dictionary/list) and builds the gui elements from the contents. I'll have > to work on that for the next version. > Hi, Steven, you currently have five methods in your CheckerApp class that look all the same; I think you might replace these with a single method like this: def RunChecker(self, checkerName): if checker in self.checkerNames:# with self.checkerNames as a list that contains the possible checkers # Build the commandline sequence command = self.SSBIN + self.BINPATH + checkerName + self.PROJPATH + \ self.PROJECT + ".prj" + " " + path.joinpath( self.DBPATH, self.DATABASE ) # Build the path to the report file report = self.DBPATH.joinpath( self.DATABASE ) + ".cnt" # If the report file exists, remove it. The creation of the report file # is used to determine if the program ran correctly. if exists( report ): remove( report ) # Run the checker command CheckerWindow( self.newroot, self, checkerName, command, report ) The same should be possible for creating the gui elements if you add a class that contains all the elements you need for the five checkers: class CheckerGroup(Tkinter.Frame): def __init__(self, master, checkerName, **kw): Tkinter.Frame.__init__(self, master, **kw) # replace attributes of the CheckerApp class with something appropriate in the code below self.fnd_dup_group = Pmw.Group( master, tag_text = title ) self.fnd_dup_group.pack( pady = 2, padx = 2, expand = 'yes', fill = 'both' ) self.fnd_dup_run = Tkinter.StringVar() if self.OPTIONS['find_dup_feat'][ 0 ] == "": self.fnd_dup_run.set( "Last ran on : Never" ) else: self.fnd_dup_run.set( "Last ran on : " + self.OPTIONS['find_dup_feat'][ 0 ] ) Tkinter.Label( self.fnd_dup_group.interior(), textvariable = self.fnd_dup_run ).pack( anchor = Tkinter.W ) self.fnd_dup_btns = Pmw.ButtonBox( self.fnd_dup_group.interior() ) self.fnd_dup_btns.pack( fill = 'both', expand = 'yes', padx = 5, pady = 5 ) self.fnd_dup_btns.add( 'Run Checker', command = lambda arg1 = 'find_dup_feat': self.RunChecker( arg1 ) ) self.fnd_dup_btns.add( 'View Report', command = lambda arg1 = "find_dup_feat": self.ViewReport( arg1 ) ) then you could write in the CheckerApp class something like: self.checkers = {}# collect the CheckerGroups in a dictionary to keep a reference for checker in self.checkerNames: newchecker = CheckerGroup(self.newroot, checker) newchecker.pack() self.checkers[checker] = newchecker (now that I've written this I think that maybe a dictionary might be better than a list for self.checkerNames, and maybe the RunChecker() method should be an attribute of the CheckerGroup class rather than one of CheckerApp; anyway, I guess you'll see my point.) I hope this helps Michael From Ralf.Steckel at AtosOrigin.com Thu Jul 29 13:22:11 2004 From: Ralf.Steckel at AtosOrigin.com (Steckel, Ralf) Date: Thu Jul 29 13:22:12 2004 Subject: [Tutor] Python for Windows: module re, re.LOCALE different fo r Idle and p ython shell? Message-ID: <42BF8717D22EB1409F03483C993F46A70DE8FA@DEACX002.ikossvan.de> Hi Steve, thanx for your suggestion (what actually made me to improve my script by opening the file via codecs), but this doesn't fix the problem. In my first script i used f.open() and lines = f.readlines() to get the input. After converting the lines to unicode, printing out German Umlaute as characters shows, that in Idle the Umlaute are printed correctly but in Python shell some DOS-special chars are printed. By using the codecs.open with encoding = 'iso-8859-1' my basic problem (re doesn't recognize German Umlaute as valid characters in re in Python shell) still exists. Greetings, Ralf PS: Please See Sample: -file umlaute.txt: ??????? End. -end file umlaute.txt -script: umlaute.py: import codecs import re r = re.compile('[\w]+', re.LOCALE ) f = codecs.open('umlaute.txt', 'r', 'iso-8859-1') lines = f.readlines() for line in lines: print 'line', line l = len(line) i = 0 while i < l: print 'character:', line[i], ord(line[i]) i = i + 1 words = r.findall(line) print 'words:', words f.close() dummy = raw_input('') -end script -output from Idle: >>> ================================ RESTART ================================ >>> line ??????? character: ? 246 character: ? 228 character: ? 252 character: ? 196 character: ? 214 character: ? 220 character: ? 223 character: 13 character: 10 words: [u'\xf6\xe4\xfc\xc4\xd6\xdc\xdf'] line End. character: E 69 character: n 110 character: d 100 character: . 46 character: 13 character: 10 words: [u'End'] >>> -end output from Idle -output from python shell: D:\Src\Python\wordcount>python umlaute.py line ??????? character: ? 246 character: ? 228 character: ? 252 character: ? 196 character: ? 214 character: ? 220 character: ? 223 13aracter: character: 10 words: [] line End. character: E 69 character: n 110 character: d 100 character: . 46 13aracter: character: 10 words: [u'End'] D:\Src\Python\wordcount> -end output from python shell > -----Original Message----- > From: Steve [mailto:lonetwin@gmail.com] > Sent: Thursday, July 29, 2004 11:57 AM > To: Steckel, Ralf > Subject: Re: [Tutor] Python for Windows: module re, re.LOCALE > different > for Idle and p ython shell? > > > Hi Ralf, > Just a wild guess here ....haven't actually tried this .. > > On Thu, 29 Jul 2004 09:25:45 +0200, Steckel, Ralf > wrote: > > i've written a python script to extract all words from a > text file and to > > print how often they are used. For doing that i use the re > module with: > > > > r=re.compile('[\w]+', re.LOCALE | re.IGNORECASE) > <...snip...> > > My question is: how do i get for the command line the same > environment as > > for Idle? > > > > I guess this is rather a Windows question than a Python > one, because Windows > > and DOS both support German 'Umlaute', but it seems they do it with > > different character codes. > > How are you actually passing the contents of the file to the > re expression ? Probably you'd have to enforce your particular > encoding before have the re parse the string. Something like: > > s = file('foo.txt').read() > unicode(s, ) > re.search(r, s) > > HTH > Steve > From lonetwin at gmail.com Thu Jul 29 15:20:25 2004 From: lonetwin at gmail.com (Steve) Date: Thu Jul 29 15:20:28 2004 Subject: [Tutor] Python for Windows: module re, re.LOCALE different fo r Idle and p ython shell? In-Reply-To: <42BF8717D22EB1409F03483C993F46A70DE8FA@DEACX002.ikossvan.de> References: <42BF8717D22EB1409F03483C993F46A70DE8FA@DEACX002.ikossvan.de> Message-ID: <5a309bd304072906206ebefd11@mail.gmail.com> Hi Ralf, On Thu, 29 Jul 2004 13:22:11 +0200, Steckel, Ralf wrote: > thanx for your suggestion (what actually made me to improve my script by > opening the file via codecs), but this doesn't fix the problem. You are welcome. <...snip...> > By using the codecs.open with encoding = 'iso-8859-1' my basic problem (re > doesn't recognize German Umlaute as valid characters in re in Python shell) > still exists. Oh ok. Well unfortunately, I am reading this using the gmail web interface and I ran your script on my linux box, and so I can't reproduce the behaviour that you are experiencing. In any case, this seems to be (like you, yourself mentioned) a problem with the environment rather than with python, so here's another shot in the dark. ....have you considered setting a default locale for the script by using the 'locale' module ?? ie: import locale locale.setlocale(locale.LC_ALL, 'de_DE') HTH Steve From bwinton at latte.ca Thu Jul 29 15:28:20 2004 From: bwinton at latte.ca (Blake Winton) Date: Thu Jul 29 15:28:25 2004 Subject: [Tutor] Efficiency? In-Reply-To: <8BA83E18-E130-11D8-A4A8-000393479EE8@earthlink.net> References: <410139D3.7020907@latte.ca> <8BA83E18-E130-11D8-A4A8-000393479EE8@earthlink.net> Message-ID: <4108FB74.3070005@latte.ca> Hee-Seng Kye wrote: > Hi, I was reading you e-mail again the other day, and I realized that I > wanted to ask you about efficiency of function. Sure. (I've renamed the functions so that I can talk about them a little easier.) (And I think I'm going to Cc: the tutor list, since re-reading my email, I'm touching on some points that other people might find useful... And hey, maybe the other tutors will time some of these functions, and let us know which actually is faster, and why one might be faster than another.) > You said the function below is much less efficient though shorter, and I > discovered that the one below is significantly slower, as you said. Why > is that? I thought list comprehension is usually faster than 'for' > loops. Is it because the one below uses 'reduce' function? The > function above is even appending to an empty list, which I thought slow > things down, and yet much faster. Well, we can always rewrite the list comprehension as a for loop, which will show us where the inefficiency lies. So this: >> >>> def findSmallestNumber1(r): >> ... return [i for i in range(len(r)) if r[i] == reduce( min, r ) ] turns into: >>> def findSmallestNumber2(r): ... retval = [] ... for i in range( len( r ) ): ... if r[i] == reduce( min, r ): ... retval.append(i) ... return retval The for-loop version of this will be a little slower than the list-comprehension version, but they're both doing much more work than the first version I sent you. How are they doing more work, you ask? Well, the reduce function has to go through every element of the list every time it's called to find the minimum. ("reduce(min,r)" basically finds the smallest element in the list "r".) So the code in findSmallestNumber1 and 2 goes through the whole list once (the "for i in range( len( r ) ):" loop), and then "n" more times (the "reduce( min, r )" call), where "n" is the number of elements in the loop. If we think of going through the loop once as "n", then this code will go through it "n + n*n" (or "n + n^2", or "n^2 + n") times, which I'll write as O(n^2 + n). (Do you know Big-O Notation? Maybe you call it "The Order of a function". It's a way of describing how fast your code will run, given large inputs. I'll show you another example below. If you're impatient, googling for "Big-O Notation" gives you a lot of hits, all of which seem to be on-topic.) Now, calling reduce runs through the list at the speed of C, which is faster than doing it at the speed of Python, but it's still going to be quite slow if your loop is large. And even worse, the minimum number isn't going to change between one run and the next, so we should really only calculate it once, and store it in a variable, which we can call, say "s". And that's essentially what this code does: >> >>> def findSmallestNumber3(r): >> ... s = reduce( min, r ) >> ... return [i for i in range(len(r)) if r[i] == s ] or its for-loop version: >>> def findSmallestNumber3(r): ... retval = "" ... s = reduce( min, r ) ... for i in range(len(r)): ... if r[i] == s: ... retval.append(i) ... return retval This will run through the loop once (the "reduce( min, r )" call), and then once more (the "for i in range(len(r)):" loop), for a total of 2 times, which I'm going to write as O(2n). > When you say the one below is a little more efficient than the above, do > you mean that the one below is more clear to read? Or do you mean the > one below runs a little faster? I don't understand how the one above is > different from the one below, except for a matter of notation. It should run a little faster. Perhaps not a lot faster, perhaps a lot faster. Intuitively, I think it would depend on the length of the list. If you time it, let me know. And do you understand why it should run faster? And let's go back to the first example: >> >>> def findSmallestNumber0( r ): >> ... indices = [] >> ... for index in range(len(r)): >> ... if len(indices) == 0 or r[index] < r[ indices[0] ]: >> ... indices = [index] >> ... elif r[index] == r[ indices[0] ]: >> ... indices.append( index ) >> ... return indices So, this runs through the loop once (the "for index in range(len(r)):" loop), and... That's all. So it will be O(n), and therefore should be the fastest of all. (It might not be, but that depends on some other factors, which I could list out for you if you want.) > Thanks again. As I'm new to programming, I thought that shorter codes > run faster than longer ones (though could be less easier to read), but > the two versions of your function alerted me that it's not necessarily > true. I hope I didn't confuse you too much, with all this theoretical stuff ;) Figuring out how quickly a program will run is a very tricky business, which is why you have to time stuff before and after any change if you're trying to improve performance. (I've spent 12 years writing programs professionally, (and probably another 5 before that writing them in school,) so I've developed a sense of what will run fast, and what won't. You will too, over time. And in the meantime, using Big-O notation can give you a hint as to what might run faster. O(n^2 + n) is slower than O(2n) is slower than O(n). Later, Blake. From Ralf.Steckel at AtosOrigin.com Thu Jul 29 16:29:58 2004 From: Ralf.Steckel at AtosOrigin.com (Steckel, Ralf) Date: Thu Jul 29 16:30:01 2004 Subject: [Tutor] Python for Windows: module re, re.LOCALE differen t fo r Idle and p ython shell? Message-ID: <42BF8717D22EB1409F03483C993F46A70DE8FB@DEACX002.ikossvan.de> Hi Steve, the locale module led me on the right track: In Idle 'loc=locale.getlocale(locale.LC_CTYPE)' prints '['de_DE', '1252']'. In python shell 'loc=locale.getlocale(locale.LC_CTYPE)' prints '(None,None)'. Setting the default locale by 'locale.setlocale(locale.LC_ALL, '')' sets the locale to ['de_DE', '1252']. Setting 'de_DE' or 'en_EN' or 'POSIX' always reports 'unsupported locale setting'. The only other possible locale setting which i got working is 'C'. By the way if i call in Idle 'locale.getlocale(locale.LC_ALL)' before setting the LC_ALL i get the following runtime error: Traceback (most recent call last): File "D:\Src\Python\wordcount\umlaute.py", line 3, in -toplevel- loc = locale.getlocale(locale.LC_ALL) File "D:\Python23\Lib\locale.py", line 364, in getlocale raise TypeError, 'category LC_ALL is not supported' TypeError: category LC_ALL is not supported But nevertheless, by setting the locale to the default locale on a German Windows OS i get what I want. Thank you, Steve! - Ralf > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On > Behalf Of Steve > Sent: Thursday, July 29, 2004 3:20 PM > To: tutor@python.org > Subject: Re: RE: [Tutor] Python for Windows: module re, re.LOCALE > different fo r Idle and p ython shell? > > > Hi Ralf, > > On Thu, 29 Jul 2004 13:22:11 +0200, Steckel, Ralf > wrote: > > thanx for your suggestion (what actually made me to improve > my script by > > opening the file via codecs), but this doesn't fix the problem. > > You are welcome. > > <...snip...> > > By using the codecs.open with encoding = 'iso-8859-1' my > basic problem (re > > doesn't recognize German Umlaute as valid characters in re > in Python shell) > > still exists. > > Oh ok. Well unfortunately, I am reading this using the gmail web > interface and I ran your script on my linux box, and so I can't > reproduce the behaviour that you are experiencing. > In any case, this seems to be (like you, yourself mentioned) a > problem with the environment rather than with python, so here's > another shot in the dark. ....have you considered setting a default > locale for the script by using the 'locale' module ?? > > ie: > import locale > locale.setlocale(locale.LC_ALL, 'de_DE') > > > > HTH > Steve > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From seamonkeys at gmail.com Thu Jul 29 18:12:36 2004 From: seamonkeys at gmail.com (Britt Green) Date: Thu Jul 29 18:12:39 2004 Subject: [Tutor] Simple chat server? Message-ID: <305be88204072909125b3f6d9b@mail.gmail.com> Hey all! I was wondering if there was an example of a threaded chat server somewhere. Ideally one with good documentation on it. I found Danny's example here: http://hkn.eecs.berkeley.edu/~dyoo/python/chatserver/chatserver.py but it seems he never got around to writing up that documentation for it! ;) Sooo...is there another example that's explained a bit more in depth? Or better yet, would Mister Yoo care to walk us thru his code? Best, Britt From csmwxl at bath.ac.uk Thu Jul 29 18:42:43 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Thu Jul 29 18:42:46 2004 Subject: [Tutor] Help for Python connection problem. Message-ID: <1091119363.4109290357e55@webmail.bath.ac.uk> Hi, I want to write a program in Python to connect MUD client at mudlib.anarres.org port:5000 for my bot, but I do not know how to connect it ( just simply say hello to people on the MUD). Anyone can help? W X From olavi at city.ee Thu Jul 29 19:02:33 2004 From: olavi at city.ee (Olavi Ivask) Date: Thu Jul 29 19:04:34 2004 Subject: [Tutor] Help for Python connection problem. In-Reply-To: <1091119363.4109290357e55@webmail.bath.ac.uk> References: <1091119363.4109290357e55@webmail.bath.ac.uk> Message-ID: <41092DA9.2020409@city.ee> example: file.py #! /usr/bin/python2.3 import os print "Starting...." os.system('telnet mudlib.anarres.org 5000') olavi ivask W X Liu wrote: >Hi, > >I want to write a program in Python to connect MUD client at >mudlib.anarres.org port:5000 for my bot, but I do not know how to connect it ( >just simply say hello to people on the MUD). Anyone can help? > >W X > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From gustabares at verizon.net Thu Jul 29 20:03:53 2004 From: gustabares at verizon.net (Gus Tabares) Date: Thu Jul 29 20:03:48 2004 Subject: [Tutor] Moving file pointer Message-ID: <000101c47596$69356e30$1300a8c0@global.avidww.com> Hi all, I'm trying to set the file pointer for a file on a posix machine. For instance, I have a simple 5-byte file with data 'abcde'. I want to 'extend' the file to 10-bytes, but not initialize any data in those extra 5-bytes. They should be all zeros. This is analogous to win32file.SetFilePointer routine. Does anyone have any pointers (no pun intended) to a solution? Thanks, Gus From bgailer at alum.rpi.edu Thu Jul 29 20:34:47 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Jul 29 20:32:37 2004 Subject: [Tutor] Moving file pointer In-Reply-To: <000101c47596$69356e30$1300a8c0@global.avidww.com> References: <000101c47596$69356e30$1300a8c0@global.avidww.com> Message-ID: <6.1.0.6.0.20040729123242.026f2468@mail.mric.net> At 12:03 PM 7/29/2004, Gus Tabares wrote: >I'm trying to set the file pointer for a file on a posix machine. For >instance, I have a simple 5-byte file with data 'abcde'. I want to >'extend' the file to 10-bytes, but not initialize any data in those >extra 5-bytes. They should be all zeros. > >This is analogous to win32file.SetFilePointer routine. > >Does anyone have any pointers (no pun intended) to a solution? We have no OBJECTion to puns. And Python is a pointerless language ( or else its all pointers under the covers ). Best I can think of is to write 5 zero bytes at the end of the file. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From tim.peters at gmail.com Thu Jul 29 20:51:48 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu Jul 29 20:51:51 2004 Subject: [Tutor] Moving file pointer In-Reply-To: <000101c47596$69356e30$1300a8c0@global.avidww.com> References: <000101c47596$69356e30$1300a8c0@global.avidww.com> Message-ID: <1f7befae04072911517b874c4f@mail.gmail.com> [Gus Tabares] > I'm trying to set the file pointer for a file on a posix machine. For > instance, I have a simple 5-byte file with data 'abcde'. I want to > 'extend' the file to 10-bytes, but not initialize any data in those > extra 5-bytes. They should be all zeros. > > This is analogous to win32file.SetFilePointer routine. > > Does anyone have any pointers (no pun intended) to a solution? Portable across POSIX and WinNT/2K/XP: >>> f = open('blah', 'r+b') >>> import os >>> print os.path.getsize('blah') 5 >>> f.seek(10) # seek to whatever position you want >>> f.truncate() # force the file size to match >>> f.close() >>> print os.path.getsize('blah') # now it's 10 bytes 10 >>> open('blah', 'rb').read() # and 5 NULs were appended 'abcde\x00\x00\x00\x00\x00' >>> This will also change the file length on Win95/98/SE, but on those there's no predicting what the additional bytes will contain -- they're whatever bytes happened to be sitting on the disk at those positions. Seeking beyond the end of the file alone is not enough to change the file size. You need to "do something" after that. f.truncate() is one way, or you could simply starting writing to the file then. From gustabares at verizon.net Thu Jul 29 20:56:43 2004 From: gustabares at verizon.net (Gus Tabares) Date: Thu Jul 29 20:56:31 2004 Subject: [Tutor] Moving file pointer In-Reply-To: <1f7befae04072911517b874c4f@mail.gmail.com> Message-ID: <000001c4759d$caec1000$1300a8c0@global.avidww.com> Tim, This is exactly what I was looking for...thank you. /Gus -----Original Message----- From: Tim Peters [mailto:tim.peters@gmail.com] Sent: Thursday, July 29, 2004 2:52 PM To: Gus Tabares Cc: tutor@python.org Subject: Re: [Tutor] Moving file pointer [Gus Tabares] > I'm trying to set the file pointer for a file on a posix machine. For > instance, I have a simple 5-byte file with data 'abcde'. I want to > 'extend' the file to 10-bytes, but not initialize any data in those > extra 5-bytes. They should be all zeros. > > This is analogous to win32file.SetFilePointer routine. > > Does anyone have any pointers (no pun intended) to a solution? Portable across POSIX and WinNT/2K/XP: >>> f = open('blah', 'r+b') >>> import os >>> print os.path.getsize('blah') 5 >>> f.seek(10) # seek to whatever position you want >>> f.truncate() # force the file size to match >>> f.close() >>> print os.path.getsize('blah') # now it's 10 bytes 10 >>> open('blah', 'rb').read() # and 5 NULs were appended 'abcde\x00\x00\x00\x00\x00' >>> This will also change the file length on Win95/98/SE, but on those there's no predicting what the additional bytes will contain -- they're whatever bytes happened to be sitting on the disk at those positions. Seeking beyond the end of the file alone is not enough to change the file size. You need to "do something" after that. f.truncate() is one way, or you could simply starting writing to the file then. From kent_johnson at skillsoft.com Thu Jul 29 21:24:50 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Jul 29 21:24:59 2004 Subject: [Tutor] Efficiency? In-Reply-To: <4108FB74.3070005@latte.ca> References: <410139D3.7020907@latte.ca> <8BA83E18-E130-11D8-A4A8-000393479EE8@earthlink.net> <4108FB74.3070005@latte.ca> Message-ID: <6.1.0.6.0.20040729145532.0287bec8@mail4.skillsoft.com> OK I'll bite. First I should say I am not an expert at Python optimizations, I tried this out for my own learning as much as anything. My understanding is that the most important factor in optimizing Python is to move functionality into C code by calling builtins as much as possible. Performance of these functions is going to vary depending on the length of the input list and the relative frequency with which the minimum value occurs. I wrote a test program that uses the integer value of the characters in a text file for the list. The text file is just the index file for my web page; if you want to use the same data you can get it at http://www.kentsjohnson.com/index.html. The resulting list has 1759 numbers in it. I ran each of these functions 10 times and reported the number of seconds it takes. First, the original poster's function: def findSmallestNumber1(r): return [i for i in range(len(r)) if r[i] == reduce( min, r ) ] As Blake noted, this is O(n^2) and thus very slow for a long list. On my machine it took 9.491670 seconds to run 10 times. The second attempt takes the reduce() call out of the loop. This is MUCH faster, it took 0.009332 seconds def findSmallestNumber2(r): s = reduce( min, r ) return [i for i in range(len(r)) if r[i] == s ] There is actually no need for the reduce() call, min() can take a list argument directly. This version takes 0.005174 secs: def findSmallestNumber3(r): s = min(r) return [i for i in range(len(r)) if r[i] == s ] OK, now we have Blake's version that makes just one pass through the list. It takes 0.016333 secs - longer than the list comprehension versions. BTW this and the previous two functions are all O(n); big-O notation disregards constant factors. def findSmallestNumber4( r ): indices = [] for index in range(len(r)): if len(indices) == 0 or r[index] < r[ indices[0] ]: indices = [index] elif r[index] == r[ indices[0] ]: indices.append( index ) return indices findSmallestNumber4() has quite a few inefficiencies itself. The test for len(indices)==0 can be eliminated by initializing indices to [0] and starting the iteration at 1. The access to r[index] can be cached in a variable, and the accesses to r[indices[0]] can be eliminated by caching the smallest value itself. This version is faster but still not as fast as version 3; it takes 0.007563 secs. There's just too much code here. def findSmallestNumber5( r ): if not r: return [] indices = [0] smallest = r[0] for index in range(1, len(r)): val = r[index] if val < smallest: indices = [index] smallest = val elif val == smallest: indices.append( index ) return indices Maybe there is a way to avoid iterating in Python? There is a list.index() method that returns the index at which a value appears. What if we use it to repeatedly search for the minimum value? This works well, taking only 0.002769 secs! def findSmallestNumber6(r): smallest = min(r) indices = [] i = -1 try: while True: i = r.index(smallest, i+1) indices.append(i) except ValueError: pass return indices I did one further optimization by caching the bound methods for r.index and indices.append. This does the method lookup just once instead of once each time through the loop and squeezes a little more time out. This version takes 0.002617 secs: def findSmallestNumber7(r): smallest = min(r) indices = [] i = -1 indexFn = r.index appendFn = indices.append try: while True: i = indexFn(smallest, i+1) appendFn(i) except ValueError: pass return indices That's all for me. Here is the complete output from one run of the program, followed by the complete program so you can try it yourself with your own data. Enjoy! Kent Testing with 1759 items in list findSmallestNumber1: 9.491670 secs findSmallestNumber2: 0.009332 secs findSmallestNumber3: 0.005174 secs findSmallestNumber4: 0.016333 secs findSmallestNumber5: 0.007563 secs findSmallestNumber6: 0.002769 secs findSmallestNumber7: 0.002617 secs ##################################################### ''' Test various ways to find the indices of the minimum values of a list ''' import timeit # Use some text as the data data = open('index.html').read() data = [ ord(c) for c in data ] print 'Testing with %d items in list' % len(data) # Original version is O(n^2) because of use of reduce in the loop def findSmallestNumber1(r): return [i for i in range(len(r)) if r[i] == reduce( min, r ) ] # This version takes the computation of min out of the loop def findSmallestNumber2(r): s = reduce( min, r ) return [i for i in range(len(r)) if r[i] == s ] # There is no need to use reduce; min can take a list directly def findSmallestNumber3(r): s = min(r) return [i for i in range(len(r)) if r[i] == s ] # Alternate suggestion makes a single pass through the list def findSmallestNumber4( r ): indices = [] for index in range(len(r)): if len(indices) == 0 or r[index] < r[ indices[0] ]: indices = [index] elif r[index] == r[ indices[0] ]: indices.append( index ) return indices # Rework the above to remove an extra test and several redundant calculations def findSmallestNumber5( r ): if not r: return [] indices = [0] smallest = r[0] for index in range(1, len(r)): val = r[index] if val < smallest: indices = [index] smallest = val elif val == smallest: indices.append( index ) return indices # This version puts the search for indices into C code by using list.index def findSmallestNumber6(r): smallest = min(r) indices = [] i = -1 try: while True: i = r.index(smallest, i+1) indices.append(i) except ValueError: pass return indices # Eliminating method lookups gives a slight speedup def findSmallestNumber7(r): smallest = min(r) indices = [] i = -1 indexFn = r.index appendFn = indices.append try: while True: i = indexFn(smallest, i+1) appendFn(i) except (ValueError, IndexError): pass return indices correctAnswer = findSmallestNumber1(data) reps = 10 # number of reps in timeit def timeOne(fn): # First run the function and check that it gets the correct results actualAnswer = fn(data) if actualAnswer != correctAnswer: print fn.__name__, 'does not give the correct answer' return # Now time it setup = "from __main__ import data," + fn.__name__ stmt = fn.__name__ + '(data)' t = timeit.Timer(stmt, setup) secs = t.timeit(reps) print '%s: %f secs' % (fn.__name__, secs) fnsToTest = [ findSmallestNumber1, findSmallestNumber2, findSmallestNumber3, findSmallestNumber4, findSmallestNumber5, findSmallestNumber6, findSmallestNumber7, ] for fn in fnsToTest: timeOne(fn) ########################################################### At 09:28 AM 7/29/2004 -0400, Blake Winton wrote: >Hee-Seng Kye wrote: >>Hi, I was reading you e-mail again the other day, and I realized that I >>wanted to ask you about efficiency of function. > >Sure. (I've renamed the functions so that I can talk about them a little >easier.) (And I think I'm going to Cc: the tutor list, since re-reading >my email, I'm touching on some points that other people might find >useful... And hey, maybe the other tutors will time some of these >functions, and let us know which actually is faster, and why one might be >faster than another.) > >>You said the function below is much less efficient though shorter, and I >>discovered that the one below is significantly slower, as you said. Why >>is that? I thought list comprehension is usually faster than 'for' >>loops. Is it because the one below uses 'reduce' function? The function >>above is even appending to an empty list, which I thought slow things >>down, and yet much faster. > >Well, we can always rewrite the list comprehension as a for loop, which >will show us where the inefficiency lies. > >So this: > >> >>> def findSmallestNumber1(r): > >> ... return [i for i in range(len(r)) if r[i] == reduce( min, r ) ] > >turns into: > >>> def findSmallestNumber2(r): >... retval = [] >... for i in range( len( r ) ): >... if r[i] == reduce( min, r ): >... retval.append(i) >... return retval > >The for-loop version of this will be a little slower than the >list-comprehension version, but they're both doing much more work than the >first version I sent you. How are they doing more work, you ask? Well, >the reduce function has to go through every element of the list every time >it's called to find the minimum. ("reduce(min,r)" basically finds the >smallest element in the list "r".) > >So the code in findSmallestNumber1 and 2 goes through the whole list once >(the "for i in range( len( r ) ):" loop), and then "n" more times (the >"reduce( min, r )" call), where "n" is the number of elements in the >loop. If we think of going through the loop once as "n", then this code >will go through it "n + n*n" (or "n + n^2", or "n^2 + n") times, which >I'll write as O(n^2 + n). (Do you know Big-O Notation? Maybe you call it >"The Order of a function". It's a way of describing how fast your code >will run, given large inputs. I'll show you another example below. If >you're impatient, googling for "Big-O Notation" gives you a lot of hits, >all of which seem to be on-topic.) > >Now, calling reduce runs through the list at the speed of C, which is >faster than doing it at the speed of Python, but it's still going to be >quite slow if your loop is large. And even worse, the minimum number >isn't going to change between one run and the next, so we should really >only calculate it once, and store it in a variable, which we can call, say "s". > >And that's essentially what this code does: > >> >>> def findSmallestNumber3(r): > >> ... s = reduce( min, r ) > >> ... return [i for i in range(len(r)) if r[i] == s ] > >or its for-loop version: > >>> def findSmallestNumber3(r): >... retval = "" >... s = reduce( min, r ) >... for i in range(len(r)): >... if r[i] == s: >... retval.append(i) >... return retval > >This will run through the loop once (the "reduce( min, r )" call), and >then once more (the "for i in range(len(r)):" loop), for a total of 2 >times, which I'm going to write as O(2n). > >>When you say the one below is a little more efficient than the above, do >>you mean that the one below is more clear to read? Or do you mean the >>one below runs a little faster? I don't understand how the one above is >>different from the one below, except for a matter of notation. > >It should run a little faster. Perhaps not a lot faster, perhaps a lot >faster. Intuitively, I think it would depend on the length of the >list. If you time it, let me know. > >And do you understand why it should run faster? > >And let's go back to the first example: > >> >>> def findSmallestNumber0( r ): > >> ... indices = [] > >> ... for index in range(len(r)): > >> ... if len(indices) == 0 or r[index] < r[ indices[0] ]: > >> ... indices = [index] > >> ... elif r[index] == r[ indices[0] ]: > >> ... indices.append( index ) > >> ... return indices > >So, this runs through the loop once (the "for index in range(len(r)):" >loop), and... That's all. So it will be O(n), and therefore should be >the fastest of all. (It might not be, but that depends on some other >factors, which I could list out for you if you want.) > >>Thanks again. As I'm new to programming, I thought that shorter codes >>run faster than longer ones (though could be less easier to read), but >>the two versions of your function alerted me that it's not necessarily true. > >I hope I didn't confuse you too much, with all this theoretical stuff ;) >Figuring out how quickly a program will run is a very tricky business, >which is why you have to time stuff before and after any change if you're >trying to improve performance. (I've spent 12 years writing programs >professionally, (and probably another 5 before that writing them in >school,) so I've developed a sense of what will run fast, and what >won't. You will too, over time. And in the meantime, using Big-O >notation can give you a hint as to what might run faster. > >O(n^2 + n) is slower than O(2n) is slower than O(n). > >Later, >Blake. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Thu Jul 29 22:53:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 29 22:52:59 2004 Subject: [Tutor] Use of List Comprehension? References: Message-ID: <007701c475ae$1b286d10$6401a8c0@xp> > I was wondering under which circumstances one might use list > comprehension. You use it to build lists. > Does it have any effect on computation time, It usually performs faster than writing the equivalent Python code because the comprehensions are implemented in C. > used for a matter of simplicity (though could be less easier to read)? Some people seem to find comprehensions quite straightforward, personally I still prefer the older map/filter/reduce functions for readability, but that's because I'm used to their names in math. I'm slowly getting used to reading comprehensions but I still don't like the typical [x for x ....] syntax, I'd have liked to see some kind of separator, like say a colon: [x: for x...] My opinion FWIW, Alan G. From alan.gauld at blueyonder.co.uk Thu Jul 29 23:03:10 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 29 23:02:41 2004 Subject: [Tutor] Python for Windows: module re, re.LOCALE different fo r Idle and p ython shell? References: <42BF8717D22EB1409F03483C993F46A70DE8FB@DEACX002.ikossvan.de> Message-ID: <009601c475af$74aeb5f0$6401a8c0@xp> > In Idle 'loc=locale.getlocale(locale.LC_CTYPE)' prints '['de_DE', '1252']'. > In python shell 'loc=locale.getlocale(locale.LC_CTYPE)' prints > '(None,None)'. I don't think DOS is Locale aware, it uses a concept called codepages to select laguages and that requires a whole new technique to find the right characters. I think this is one of those places where you have to check the OS version and have an if OS == DOS branch in your code. :-( Alan G From alan.gauld at blueyonder.co.uk Thu Jul 29 23:37:01 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Jul 29 23:36:35 2004 Subject: [Tutor] Moving file pointer References: <000101c47596$69356e30$1300a8c0@global.avidww.com> Message-ID: <00b101c475b4$2f60e9a0$6401a8c0@xp> > I'm trying to set the file pointer for a file on a posix machine. For > instance, I have a simple 5-byte file with data 'abcde'. I want to > 'extend' the file to 10-bytes, but not initialize any data in those > extra 5-bytes. They should be all zeros. You can seek() the end of the file, then use write() to output 5 zeros. Or easier open the file in append mopde and just write 5 zero bytes. To actually write ASCII code zero you can use escaping: zero = '\000' five-zeros = zero * 5 Alternatively you could open in binary mode and use the struct module... As to initialising data, writing zeros is initialising it! HTH, Alan G From csmwxl at bath.ac.uk Fri Jul 30 01:48:33 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Fri Jul 30 01:48:38 2004 Subject: [Tutor] How to connect a MUD client? Message-ID: <1091144913.41098cd19c432@webmail.bath.ac.uk> I want to use python to wrote a program to connect a MUD client (mudlib.anarres.org port:5000) and simply show a " hello" on the MUD interface. anyone could help? many thanks. W X From bill at celestial.net Fri Jul 30 02:18:15 2004 From: bill at celestial.net (Bill Campbell) Date: Fri Jul 30 02:18:18 2004 Subject: [Tutor] File mode tests Message-ID: <20040730001815.GB51058@alexis.mi.celestial.com> I'm just getting my feet wet with python after programming primarily in perl since perl-3.something. I've read the Harms and McDonald ``The Quick Python Book'', and O'Reilly's ``Learning Python'', but haven't been able to find python equivalents to these perl tests (lots of others in os.path, but not these :-). if ( -x path ) # is is executable if ( -r path ) # is it readable if ( -w path ) # is it writeable I would love to find documentation, something like ``python for the perl hacker'' that would help in the transition. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Mechanical Engineers build weapons. Civil Engineers build targets.'' From dyoo at hkn.eecs.berkeley.edu Fri Jul 30 02:42:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 30 02:42:44 2004 Subject: [Tutor] How to connect a MUD client? In-Reply-To: <1091144913.41098cd19c432@webmail.bath.ac.uk> Message-ID: On Fri, 30 Jul 2004, W X Liu wrote: > I want to use python to wrote a program to connect a MUD client > (mudlib.anarres.org port:5000) and simply show a " hello" on the MUD > interface. Hi W X Liu, You may want to look at telnetlib: http://www.python.org/doc/lib/module-telnetlib.html For example: ### >>> tn = telnetlib.Telnet('mudlib.anarres.org', 5000) >>> tn.read_very_eager() 'Welcome to Anarres II\r\n\r\nRULES:\r\n1) Code may be distributed only with permission from Arren.\r\n2) Do not harass or abuse people.\r\n3) You may encounter material which you consider offensive.\r\n\r\nThe official address of this MUD is mudlib.anarres.org port 5000.\r\nPlease make SURE that you are using that address and not an alias.\r\n\r\nNew users or guests may log in with any name.\r\n\r\nWARNING === WARNING === WARNING [... text cut] ### So you should be able to communicate with your MUD with telnetlib. Good luck to you! From bryan at unitedgaribay.com Fri Jul 30 03:11:31 2004 From: bryan at unitedgaribay.com (Bryan Fields) Date: Fri Jul 30 03:16:03 2004 Subject: [Tutor] Ideas for beginning programs? Message-ID: <000001c475d2$264d5240$130a0a0a@shoran> Hi everyone. I am new to the list. I am going through the tutorial at python.org, I am about 1/3 of the way through it, and I have just finished the section on defining functions. Here are the topics I understand: variables, conditional execution, defining and calling functions, mathematical and comparison operators, and lists. I think those are about all the things I am comfortable with at the moment. I am learning more every day. I have to learn during my lunch breaks because I only have net access at work. My question to the list is: Can anyone present me with some good ideas for programs to write using the concepts I have studied so far? I really want to put these to use so I don?t forget anything, but am unable to think of any ideas... Thanks for your input, and I look forward to being a part of your community... Bryan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040729/4f6d8086/attachment.htm From flaxeater at yahoo.com Fri Jul 30 04:02:40 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Jul 30 04:02:44 2004 Subject: [Tutor] File mode tests Message-ID: <20040730020240.35137.qmail@web52610.mail.yahoo.com> Bill Campbell wrote: >I'm just getting my feet wet with python after programming primarily in >perl since perl-3.something. I've read the Harms and McDonald ``The Quick >Python Book'', and O'Reilly's ``Learning Python'', but haven't been able to >find python equivalents to these perl tests (lots of others in os.path, but >not these :-). > > if ( -x path ) # is is executable > if ( -r path ) # is it readable > if ( -w path ) # is it writeable > >I would love to find documentation, something like ``python for the perl >hacker'' that would help in the transition. > >Bill >-- >INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. >UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 >URL: http://www.celestial.com/ > >``Mechanical Engineers build weapons. Civil Engineers build targets.'' >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > Well I found something interesting at the New Mexico Tech Site http://infohost.nmt.edu/tcc/help/lang/python/pathinfo.html has an easy object interface to your questions. Perhaps the source will deliver a more meaningful answer because they say it's just sugar coating on the regular os module. Have a good day __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From linux-user at softhome.net Thu Jul 29 19:55:30 2004 From: linux-user at softhome.net (Conrad) Date: Fri Jul 30 07:53:49 2004 Subject: [Tutor] search function Message-ID: <1091123730.28491.5.camel@radiol> I'm writing a script that extracts values from config files in the form of: "variable"="value" "variable1"="value" I wrote this function, which takes a comma delimited list of variables to search for. (variable1,variable2,....), and then searches through each line of the config file, checking if the variable is there, and then printing out the variable found and the value: def display_var(variables): var_disp = re.compile(r'%s' % (variables.replace(',','|'))) line = config_file.readline() var_value = re.compile(r'"[^"]*?"$') var_name = re.compile(r'".*?"') while line != '': if var_disp.search(line): value = var_value.search(line) var = var_name.search(line) print "%s: %s" % (var.group()[1:-1], value.group()[1:-1]) else: pass line = config_file.readline() There are a few things that are bugging me about this. One is the heavy use of regular expressions, and two is that im using [1.-1] to strip the qoutes. Can anyone point out how to make this more pythonic? Your time is appreciated, Conrad From lonetwin at gmail.com Fri Jul 30 09:14:34 2004 From: lonetwin at gmail.com (Steve) Date: Fri Jul 30 09:14:37 2004 Subject: [Tutor] search function In-Reply-To: <1091123730.28491.5.camel@radiol> References: <1091123730.28491.5.camel@radiol> Message-ID: <5a309bd3040730001430c5e157@mail.gmail.com> Hi Conrad, > There are a few things that are bugging me about this. One is the heavy > use of regular expressions, and two is that im using [1.-1] to strip the > qoutes. Can anyone point out how to make this more pythonic? The pythonic way to handle this would be to have the ConfigParser module do all the dirty work: http://www.python.org/doc/current/lib/module-ConfigParser.html An example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 An alternate module to essentially do the same thing: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259175 HTH Steve From lonetwin at gmail.com Fri Jul 30 09:29:38 2004 From: lonetwin at gmail.com (Steve) Date: Fri Jul 30 09:29:41 2004 Subject: [Tutor] File mode tests In-Reply-To: <20040730001815.GB51058@alexis.mi.celestial.com> References: <20040730001815.GB51058@alexis.mi.celestial.com> Message-ID: <5a309bd304073000296a220d47@mail.gmail.com> Hi Bill, On Thu, 29 Jul 2004 17:18:15 -0700, Bill Campbell wrote: > I'm just getting my feet wet with python after programming primarily in > perl since perl-3.something. Welcome to the other side :) > I've read the Harms and McDonald ``The Quick > Python Book'', and O'Reilly's ``Learning Python'', but haven't been able to > find python equivalents to these perl tests (lots of others in os.path, but > not these :-). > > if ( -x path ) # is is executable > if ( -r path ) # is it readable > if ( -w path ) # is it writeable The function os.access() povides these, have a look here: http://python.org/doc/current/lib/os-file-dir.html > I would love to find documentation, something like ``python for the perl > hacker'' that would help in the transition. So would a lot many hackers who see the light :) ....here you go (urls may wrap): http://www.onlamp.com/pub/a/onlamp/2002/06/27/pythonandperl.html http://www.minihttpserver.net/showasin/Cat_cbook_En_perl_to_python_migration-0201734885.htm HTH Steve PS: forgive the cheeky-ness ....couldn't help myself :o) From nick at javacat.f2s.com Fri Jul 30 09:35:05 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Fri Jul 30 09:35:18 2004 Subject: [Tutor] File mode tests In-Reply-To: <20040730001815.GB51058@alexis.mi.celestial.com> References: <20040730001815.GB51058@alexis.mi.celestial.com> Message-ID: <1091172905.4109fa298fa5b@webmail.freedom2surf.net> Hi Bill Quoting Bill Campbell : > > if ( -x path ) # is is executable > if ( -r path ) # is it readable > if ( -w path ) # is it writeable > os.X_OK, os.R_OK and os.W_OK eg import os os.access('/etc/hosts', os.R_OK) True os.access('/etc/hosts', os.W_OK) False Hope that helps Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From kent_johnson at skillsoft.com Fri Jul 30 15:17:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Jul 30 15:18:05 2004 Subject: [Tutor] search function In-Reply-To: <1091123730.28491.5.camel@radiol> References: <1091123730.28491.5.camel@radiol> Message-ID: <6.1.0.6.0.20040730085820.029ccca0@mail4.skillsoft.com> Conrad, Regular expressions are your friends if you get to know them! You can do what you want with just one RE using subgroup matches. I don't know if it's more Pythonic, but it's more concise and a better use of REs. A more Pythonic way to iterate the config file is to use "for line in config_file". Say you want to search for two variables, v1 and v2. Then you can use this RE: r'"(v1|v2)"="([^"]*?)"$' The first group (v1|v2) will match the actual variable name and the second group ([^"]*?) will match the value. The quotes are outside the parentheses so they won't be included in the groups. (BTW I think this will work just as well: r'"(v1|v2)"="([^"]*)"' - I left in the ? and $ as they were in your original post) You could also allow for white space around the = by adding \s* on each side of it: r'"(v1|v2)"\s*=\s*"([^"]*)"' . One final note: If your input string with the variable names could have spaces after the commas, you might want to use re.split() to split it, or if you have control over the calling function maybe pass it as a list of names or a space-delimited string. Or use a combination of split, strip and join like this: altVars = '|'.join([s.strip() for s in variables.split(',')]) Below is a complete program with the re-written function and a simple test harness. Kent ##################################### import re def display_var(config_file, variables): altVars = variables.replace(',','|') var_disp = re.compile(r'"(%s)"="([^"]*?)"$' % altVars) for line in config_file: match = var_disp.search(line) if match: print "%s: %s" % match.group(1, 2) testData = ''' "var3"="33" "var1"="value1" "var2"="22" "dontcare"="42" ''' vars = 'var1,var2,var3' import StringIO config = StringIO.StringIO(testData) display_var(config, vars) At 10:55 AM 7/29/2004 -0700, Conrad wrote: >I'm writing a script that extracts values from config files in the form >of: > >"variable"="value" >"variable1"="value" > >I wrote this function, which takes a comma delimited list of variables >to search for. (variable1,variable2,....), and then searches through >each line of the config file, checking if the variable is there, and >then printing out the variable found and the value: > >def display_var(variables): > var_disp = re.compile(r'%s' % (variables.replace(',','|'))) > line = config_file.readline() > var_value = re.compile(r'"[^"]*?"$') > var_name = re.compile(r'".*?"') > while line != '': > if var_disp.search(line): > value = var_value.search(line) > var = var_name.search(line) > print "%s: %s" % (var.group()[1:-1], >value.group()[1:-1]) > else: > pass > line = config_file.readline() > >There are a few things that are bugging me about this. One is the heavy >use of regular expressions, and two is that im using [1.-1] to strip the >qoutes. Can anyone point out how to make this more pythonic? > >Your time is appreciated, > Conrad > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From pythonTutor at venix.com Fri Jul 30 03:45:18 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Jul 30 15:45:03 2004 Subject: [Tutor] File mode tests In-Reply-To: <20040730001815.GB51058@alexis.mi.celestial.com> References: <20040730001815.GB51058@alexis.mi.celestial.com> Message-ID: <1091151918.6929.8.camel@laptop.venix.com> On Thu, 2004-07-29 at 20:18, Bill Campbell wrote: > I'm just getting my feet wet with python after programming primarily in > perl since perl-3.something. I've read the Harms and McDonald ``The Quick > Python Book'', and O'Reilly's ``Learning Python'', but haven't been able to > find python equivalents to these perl tests (lots of others in os.path, but > not these :-). import os > > if ( -x path ) # is is executable if os.access(path, os.X_OK): > if ( -r path ) # is it readable if os.access(path, os.R_OK): > > if ( -w path ) # is it writeable if os.access(path, os.W_OK): http://docs.python.org/lib/os-file-dir.html This is the relevant piece of documentation for the os module. It is more verbose than perl since Python offers these functions through a module. > > > I would love to find documentation, something like ``python for the perl > hacker'' that would help in the transition. Google may be able to help with that. Otherwise browse through the Library reference: http://docs.python.org/lib/lib.html > > Bill > -- > INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. > UUCP: camco!bill PO Box 820; 6641 E. Mercer Way > FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 > URL: http://www.celestial.com/ > > ``Mechanical Engineers build weapons. Civil Engineers build targets.'' Interesting observation. > _______________________________________________ > 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 tolis at softhome.net Fri Jul 30 17:32:43 2004 From: tolis at softhome.net (=?iso-8859-7?B?0/Tl8ePf7/UgwfDv8/T86+fy?=) Date: Fri Jul 30 17:33:11 2004 Subject: [Tutor] Version conflict? Message-ID: <000501c4764a$799bfd20$45614a3e@nemesis> I use python 2.3 but when I double clicking a .py file I get 3 times a window message saying that python22.dll was not found. After pressing OK for 3 times the .py files starts. How can I fix the problem? The problem started many month after installing Python 2.3 I copy python23.dll to python22.dll (now having 2 .dll) and the message stopped. But, now I have an "ImportError: DLL load failed: bla bla..." when importing packages like Numeric. From orbitz at ezabel.com Thu Jul 29 23:12:51 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Jul 30 18:39:24 2004 Subject: [Tutor] Simple chat server? In-Reply-To: <305be88204072909125b3f6d9b@mail.gmail.com> References: <305be88204072909125b3f6d9b@mail.gmail.com> Message-ID: <41096853.9050505@ezabel.com> http://www.twistedmatrix.com/ Britt Green wrote: >Hey all! > >I was wondering if there was an example of a threaded chat server >somewhere. Ideally one with good documentation on it. I found Danny's >example here: http://hkn.eecs.berkeley.edu/~dyoo/python/chatserver/chatserver.py >but it seems he never got around to writing up that documentation for >it! ;) > >Sooo...is there another example that's explained a bit more in depth? >Or better yet, would Mister Yoo care to walk us thru his code? > >Best, > >Britt >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From orbitz at ezabel.com Fri Jul 30 09:08:57 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Jul 30 18:39:27 2004 Subject: [Tutor] search function In-Reply-To: <1091123730.28491.5.camel@radiol> References: <1091123730.28491.5.camel@radiol> Message-ID: <4109F409.2000007@ezabel.com> Why not just use a python file as your config? That is what I do, then I just import it. You can also use wat Steve suggested, but IMO just using python is more powerful since you can do things like tuples and what not trivially Conrad wrote: >I'm writing a script that extracts values from config files in the form >of: > >"variable"="value" >"variable1"="value" > >I wrote this function, which takes a comma delimited list of variables >to search for. (variable1,variable2,....), and then searches through >each line of the config file, checking if the variable is there, and >then printing out the variable found and the value: > >def display_var(variables): > var_disp = re.compile(r'%s' % (variables.replace(',','|'))) > line = config_file.readline() > var_value = re.compile(r'"[^"]*?"$') > var_name = re.compile(r'".*?"') > while line != '': > if var_disp.search(line): > value = var_value.search(line) > var = var_name.search(line) > print "%s: %s" % (var.group()[1:-1], >value.group()[1:-1]) > else: > pass > line = config_file.readline() > >There are a few things that are bugging me about this. One is the heavy >use of regular expressions, and two is that im using [1.-1] to strip the >qoutes. Can anyone point out how to make this more pythonic? > >Your time is appreciated, > Conrad > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From orbitz at ezabel.com Thu Jul 29 23:14:12 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Jul 30 18:39:34 2004 Subject: [Tutor] Help for Python connection problem. In-Reply-To: <41092DA9.2020409@city.ee> References: <1091119363.4109290357e55@webmail.bath.ac.uk> <41092DA9.2020409@city.ee> Message-ID: <410968A4.40100@ezabel.com> Look at the socket module. Such questions are usually a good sign that you shouldn't be attempting what you are. Olavi Ivask wrote: > example: > > file.py > > #! /usr/bin/python2.3 > > import os > > print "Starting...." > > os.system('telnet mudlib.anarres.org 5000') > > > > olavi ivask > > > W X Liu wrote: > >> Hi, >> >> I want to write a program in Python to connect MUD client at >> mudlib.anarres.org port:5000 for my bot, but I do not know how to >> connect it ( just simply say hello to people on the MUD). Anyone can >> help? >> >> W X >> >> >> _______________________________________________ >> 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 Francis.Moore at shaws.co.uk Fri Jul 30 10:56:00 2004 From: Francis.Moore at shaws.co.uk (Francis Moore) Date: Fri Jul 30 18:45:18 2004 Subject: [Tutor] File mode tests Message-ID: <6081EBC21D52F744B484088BBBE665C3199F30@sbserver.shaws.local> From: Bill Campbell [mailto:bill@celestial.net] > I would love to find documentation, something like > ``python for the perl hacker'' that would help in > the transition. The following book is out of print, but you may be able to find it secondhand on Amazon or similar: Perl to Python Migration by Martin C. Brown Publisher: Addison-Wesley Pub Co; 1st edition (November 2, 2001) ISBN: 0201734885 I can't vouch for the content, but Amazon does have two reviews that might help: http://www.amazon.com/exec/obidos/tg/detail/-/0201734885/104-5891939-711 2733?v=glance Cheers, Francis. From orbitz at ezabel.com Thu Jul 29 23:17:18 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Jul 30 19:29:24 2004 Subject: [Tutor] Moving file pointer In-Reply-To: <6.1.0.6.0.20040729123242.026f2468@mail.mric.net> References: <000101c47596$69356e30$1300a8c0@global.avidww.com> <6.1.0.6.0.20040729123242.026f2468@mail.mric.net> Message-ID: <4109695E.3000504@ezabel.com> From file objects documentation: *truncate*( [size]) Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file's current size, the result is platform-dependent: possibilities include that file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants. Bob Gailer wrote: > At 12:03 PM 7/29/2004, Gus Tabares wrote: > >> I'm trying to set the file pointer for a file on a posix machine. For >> instance, I have a simple 5-byte file with data 'abcde'. I want to >> 'extend' the file to 10-bytes, but not initialize any data in those >> extra 5-bytes. They should be all zeros. >> >> This is analogous to win32file.SetFilePointer routine. >> >> Does anyone have any pointers (no pun intended) to a solution? > > > We have no OBJECTion to puns. And Python is a pointerless language ( > or else its all pointers under the covers ). > > Best I can think of is to write 5 zero bytes at the end of the file. > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Jul 30 19:53:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 30 19:53:44 2004 Subject: [Tutor] How to connect a MUD client? (fwd) Message-ID: [I'll forward your question to Python-Tutor. Please continue to send your replies to Tutor, and not directly to me. This allows the other folks an opportunity to answer your questions, and also allows me to be lazy. *grin*] ---------- Forwarded message ---------- Date: Fri, 30 Jul 2004 09:14:28 +0100 From: W X Liu To: Danny Yoo Subject: Re: [Tutor] How to connect a MUD client? Sorry, I am not able to understand "tn.read_very_eager()", could you please explain it? W X > > > On Fri, 30 Jul 2004, W X Liu wrote: > > > I want to use python to wrote a program to connect a MUD client > > (mudlib.anarres.org port:5000) and simply show a " hello" on the MUD > > interface. > > Hi W X Liu, > > > You may want to look at telnetlib: > > > http://www.python.org/doc/lib/module-telnetlib.html > > > For example: > > ### > >>> tn = telnetlib.Telnet('mudlib.anarres.org', 5000) > >>> tn.read_very_eager() > 'Welcome to Anarres II\r\n\r\nRULES:\r\n1) Code may be distributed only > with permission from Arren.\r\n2) Do not harass or abuse people.\r\n3) You > may encounter material which you consider offensive.\r\n\r\nThe official > address of this MUD is mudlib.anarres.org port 5000.\r\nPlease make SURE > that you are using that address and not an alias.\r\n\r\nNew users or > guests may log in with any name.\r\n\r\nWARNING === WARNING === WARNING > [... text cut] > ### > > > So you should be able to communicate with your MUD with telnetlib. > > > Good luck to you! > > From linux-user at softhome.net Fri Jul 30 08:08:20 2004 From: linux-user at softhome.net (Conrad) Date: Fri Jul 30 20:06:39 2004 Subject: [Tutor] search function In-Reply-To: <5a309bd3040730001430c5e157@mail.gmail.com> References: <1091123730.28491.5.camel@radiol> <5a309bd3040730001430c5e157@mail.gmail.com> Message-ID: <1091167700.6871.1.camel@radiol> Thanks for the reply Steve, but I'm doing it more of as an exercise then anything particularly useful.Looking through the code gave me some insight though. Thanks for taking the time to respond! Conrad From bill at celestial.net Fri Jul 30 20:16:47 2004 From: bill at celestial.net (Bill Campbell) Date: Fri Jul 30 20:16:51 2004 Subject: [Tutor] File mode tests In-Reply-To: <5a309bd304073000296a220d47@mail.gmail.com> References: <20040730001815.GB51058@alexis.mi.celestial.com> <5a309bd304073000296a220d47@mail.gmail.com> Message-ID: <20040730181647.GA14357@alexis.mi.celestial.com> On Fri, Jul 30, 2004, Steve wrote: >Hi Bill, > >On Thu, 29 Jul 2004 17:18:15 -0700, Bill Campbell wrote: >> I'm just getting my feet wet with python after programming primarily in >> perl since perl-3.something. > >Welcome to the other side :) > >> I've read the Harms and McDonald ``The Quick >> Python Book'', and O'Reilly's ``Learning Python'', but haven't been able to >> find python equivalents to these perl tests (lots of others in os.path, but >> not these :-). >> >> if ( -x path ) # is is executable >> if ( -r path ) # is it readable >> if ( -w path ) # is it writeable > >The function os.access() povides these, have a look here: > >http://python.org/doc/current/lib/os-file-dir.html Thanks for the reference. >> I would love to find documentation, something like ``python for the perl >> hacker'' that would help in the transition. > >So would a lot many hackers who see the light :) ....here you go (urls >may wrap): > >http://www.onlamp.com/pub/a/onlamp/2002/06/27/pythonandperl.html >http://www.minihttpserver.net/showasin/Cat_cbook_En_perl_to_python_migration-0201734885.htm > >HTH >Steve > >PS: forgive the cheeky-ness ....couldn't help myself :o) Not a problem. I've been known to make a few similar comments myself. One of my major issues with python isn't the language per se, but the fact that I'm very dependent on vim/vi's ability to match braces using the ``%'' key which makes navigating source code very easy (don't say use emacs -- as many times as I've tried it, my fingers have 22 years of vi habits :-). My solution for this with shell programming has been to use comments #{ and #} around control flow blocks which works with python as well, but probably would drive a python purist nuts. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Systems, Inc. UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ There is no distinctly native American criminal class save Congress -- Mark Twain From Dragonfirebane at aol.com Fri Jul 30 20:19:47 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Fri Jul 30 20:20:00 2004 Subject: [Tutor] tkMessageBox options Message-ID: <67.2f30b57b.2e3beb43@aol.com> Hello all, I'm reading a tutorial on Tkinter, but its a little sparing on the details. It says to change the icon for I have to use options, but it doesn't say how. I tried to implement it myself using different variations of the code below, but each time I got: Traceback (most recent call last): File "C:/Program Files/hello.py", line 16, in -toplevel- filerror() File "C:/Program Files/hello.py", line 6, in filerror if tkMessageBox.askquestion(title="File Error",message="Cannot open this file:\n%s\nWould you like to open a different file?" % fn, icon='WARNING'): File "C:\PROGRA~1\lib\lib-tk\tkMessageBox.py", line 91, in askquestion return _show(title, message, QUESTION, YESNO, **options) TypeError: _show() got multiple values for keyword argument 'icon' I don't know what I'm doing wrong or right or where to go from here. Any help would be appreciated. def filerror(): try: fn = raw_input("Name of file to open: ") fp = open(fn) except: if tkMessageBox.askquestion(title="File Error",message="Cannot open this file:\n%s\nWould you like to open a different file?" % fn, icon='WARNING'): filerror() return else: for line in fp.readlines(): print line import tkMessageBox filerror() 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/20040730/04826cd3/attachment.html From bill at celestial.net Fri Jul 30 20:26:40 2004 From: bill at celestial.net (Bill Campbell) Date: Fri Jul 30 20:26:42 2004 Subject: [Tutor] File mode tests In-Reply-To: <6081EBC21D52F744B484088BBBE665C3199F30@sbserver.shaws.local> References: <6081EBC21D52F744B484088BBBE665C3199F30@sbserver.shaws.local> Message-ID: <20040730182639.GA19578@alexis.mi.celestial.com> On Fri, Jul 30, 2004, Francis Moore wrote: >From: Bill Campbell [mailto:bill@celestial.net] > >> I would love to find documentation, something like >> ``python for the perl hacker'' that would help in >> the transition. > >The following book is out of print, but you may be >able to find it secondhand on Amazon or similar: > >Perl to Python Migration >by Martin C. Brown >Publisher: Addison-Wesley Pub Co; >1st edition (November 2, 2001) >ISBN: 0201734885 Thanks for the pointer. I just ordered a copy through Amazon where they listed lots of copies, many new for about $6.00USD. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Things in our country run in spite of government. Not by aid of it!'' Will Rogers From dyoo at hkn.eecs.berkeley.edu Fri Jul 30 20:58:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 30 20:58:25 2004 Subject: [Tutor] File mode tests In-Reply-To: <20040730181647.GA14357@alexis.mi.celestial.com> Message-ID: > One of my major issues with python isn't the language per se, but the > fact that I'm very dependent on vim/vi's ability to match braces using > the ``%'' key which makes navigating source code very easy (don't say > use emacs -- as many times as I've tried it, my fingers have 22 years of > vi habits :-). Hi Bill, I'm one of those emacs users, so I probably can't help here. *grin* But I've heard some very good things about python-folding mode in vim: http://www.vim.org/scripts/script.php?script_id=515 http://www.halfcooked.com/mt/archives/000485.html so you may want to see if folding will help you. Best of wishes! From Dragonfirebane at aol.com Fri Jul 30 21:03:10 2004 From: Dragonfirebane at aol.com (Dragonfirebane@aol.com) Date: Fri Jul 30 21:03:20 2004 Subject: [Tutor] tkMessageBox options Message-ID: <9f.4ac62dfc.2e3bf56e@aol.com> In a message dated 7/30/2004 2:21:27 PM Eastern Standard Time, Dragonfirebane@aol.com writes: Hello all, I'm reading a tutorial on Tkinter, but its a little sparing on the details. It says to change the icon for Sorry, that should be . Thanks again, 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/20040730/df8e8d71/attachment.html From STEVEN.M.FAULCONER at saic.com Fri Jul 30 21:29:30 2004 From: STEVEN.M.FAULCONER at saic.com (Faulconer, Steven M.) Date: Fri Jul 30 21:36:09 2004 Subject: [Tutor] Request for Comments Message-ID: <207DA77D2384D411A48B0008C7095D81C1DEAC@us-melbourne.mail.saic.com> Michael, Thank you very much for your comments. I'm going to work them into my program. I had initially created a command-line version of this program that contained the checkers in a dictionary, and ran them based on menu selections. I didn't see a clean way of doing that in this program, but now I do. Thanks again. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Michael Lange Sent: Thursday, July 29, 2004 6:12 AM To: tutor@python.org Subject: Re: [Tutor] Request for Comments On Tue, 27 Jul 2004 11:23:16 -0700 "Faulconer, Steven M." wrote: > I'd like to have a better way of creating the gui elements. Since > there are currently 5 checkers, I've got a lengthy bit of code to > create the widgets. It would be nice to have a method that loops over > a data structure > (dictionary/list) and builds the gui elements from the contents. I'll have > to work on that for the next version. > Hi, Steven, you currently have five methods in your CheckerApp class that look all the same; I think you might replace these with a single method like this: def RunChecker(self, checkerName): if checker in self.checkerNames:# with self.checkerNames as a list that contains the possible checkers # Build the commandline sequence command = self.SSBIN + self.BINPATH + checkerName + self.PROJPATH + \ self.PROJECT + ".prj" + " " + path.joinpath( self.DBPATH, self.DATABASE ) # Build the path to the report file report = self.DBPATH.joinpath( self.DATABASE ) + ".cnt" # If the report file exists, remove it. The creation of the report file # is used to determine if the program ran correctly. if exists( report ): remove( report ) # Run the checker command CheckerWindow( self.newroot, self, checkerName, command, report ) The same should be possible for creating the gui elements if you add a class that contains all the elements you need for the five checkers: class CheckerGroup(Tkinter.Frame): def __init__(self, master, checkerName, **kw): Tkinter.Frame.__init__(self, master, **kw) # replace attributes of the CheckerApp class with something appropriate in the code below self.fnd_dup_group = Pmw.Group( master, tag_text = title ) self.fnd_dup_group.pack( pady = 2, padx = 2, expand = 'yes', fill = 'both' ) self.fnd_dup_run = Tkinter.StringVar() if self.OPTIONS['find_dup_feat'][ 0 ] == "": self.fnd_dup_run.set( "Last ran on : Never" ) else: self.fnd_dup_run.set( "Last ran on : " + self.OPTIONS['find_dup_feat'][ 0 ] ) Tkinter.Label( self.fnd_dup_group.interior(), textvariable = self.fnd_dup_run ).pack( anchor = Tkinter.W ) self.fnd_dup_btns = Pmw.ButtonBox( self.fnd_dup_group.interior() ) self.fnd_dup_btns.pack( fill = 'both', expand = 'yes', padx = 5, pady = 5 ) self.fnd_dup_btns.add( 'Run Checker', command = lambda arg1 = 'find_dup_feat': self.RunChecker( arg1 ) ) self.fnd_dup_btns.add( 'View Report', command = lambda arg1 = "find_dup_feat": self.ViewReport( arg1 ) ) then you could write in the CheckerApp class something like: self.checkers = {}# collect the CheckerGroups in a dictionary to keep a reference for checker in self.checkerNames: newchecker = CheckerGroup(self.newroot, checker) newchecker.pack() self.checkers[checker] = newchecker (now that I've written this I think that maybe a dictionary might be better than a list for self.checkerNames, and maybe the RunChecker() method should be an attribute of the CheckerGroup class rather than one of CheckerApp; anyway, I guess you'll see my point.) I hope this helps Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Fri Jul 30 22:14:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Jul 30 22:13:43 2004 Subject: [Tutor] Ideas for beginning programs? References: <000001c475d2$264d5240$130a0a0a@shoran> Message-ID: <00f001c47671$d2a383d0$6401a8c0@xp> HI Bryan, > Hi everyone. I am new to the list. I am going through the > tutorial at python.org, .... > .... I have to learn during my lunch breaks because > I only have net access at work. You can download the documentation to the PC. If you use Windows the documents (including the tutor) are part of the standard windows install package. And of course my more basic tutorial is available in multiple formats for download including Palm doc and PDF... :-) > present me with some good ideas for programs to write > using the concepts I have studied so far? Try an address book or a cd/video database. You might want to look at file handling too so that you can save the database between sessions! Also the "Useless Python" web site has a whole bunch of small (and not so small) projects to try. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From learning.python at dbmail.dk Fri Jul 30 22:20:39 2004 From: learning.python at dbmail.dk (Ole Jensen) Date: Fri Jul 30 22:20:41 2004 Subject: Fw: [Tutor] Ideas for beginning programs? Message-ID: <00b801c47672$ae150920$99c48f52@allmycore> (Just forwarding this mail to the tutor as I used the wrong email earliere!) > ----- Original Message ----- > From: Bryan Fields > Subject: [Tutor] Ideas for beginning programs? > > > Hi everyone. I am new to the list. I am going through the tutorial at > python.org, I am about 1/3 of the way through it, and I have just > finished the section on defining functions. Here are the topics I > understand: variables, conditional execution, defining and calling > functions, mathematical and comparison operators, and lists. I think > those are about all the things I am comfortable with at the moment. I > am learning more every day. I have to learn during my lunch breaks > because I only have net access at work. My question to the list is: Can > anyone present me with some good ideas for programs to write using the > concepts I have studied so far? I really want to put these to use so I > don't forget anything, but am unable to think of any ideas... Thanks > for your input, and I look forward to being a part of your community... > Bryan > > > > Hi Bryan > The first program I made was a BlackJack game, basically because it can > be made with the raw ingredients you described above. Here is a URL to > the rules of BJ http://blackjackinfo.com/blackjack-rules.php. The game > is pretty simple and I enjoyed making it as a tuturial. The only part > that requires some thought is how to take care of Aces... But I leave > you to ponder that ;) > > Regards OJ > > > From mjekl at clix.pt Fri Jul 30 22:36:03 2004 From: mjekl at clix.pt (mjekl) Date: Fri Jul 30 22:36:56 2004 Subject: [Tutor] Re: Ideas for beginning programs? References: <000001c475d2$264d5240$130a0a0a@shoran> Message-ID: Bryan Fields unitedgaribay.com> writes: > My question to the list is: Can anyone present me with some good ideas for > programs to write using the concepts I have studied so far? 1 - Guesser: You can make python generate a random number for you if you import the random module. If you're not confortable with modules - it's easy as Py! import from import And it's at your command! Just think of a module as a file with function or class definitions that you can call into your programs to use at will (basically that's all I'm able to tell you since I'm a newbie) If you don't want to use modules. You can make a list with many numbers and use it as the source for your (not very) secret number! 2 - Expand Guesser: Instead as having the prg ask you for a number. Have two players, the computer against human. Each defining a secret number and the other one guessing. Make a menu. Print results. This one can get pretty complex if you don't make it very structured. 3 - Write a program that gives asks you for temperature and the scale (Celcius / Farenheit) and then gives you the corresponding temperatures in (Farenheit / Celcius). 4 - Make a phone book using nested lists (or list and tuples)! Use a menu to search a phone number by name or vice-versa 5 - Make a phone book using a simple list! Use a menu to search a phone number by name or vice-versa *Compare these phonebooks with a phonebook made with a dictionary* *Make a version of Guesser using OOP* Some tutorials on the net with example programs/tasks: - Alan Gauld's tut - Livewires - "How to Think Like a Computer Cientist" - ... there are others... Going to try some of these myself ;-) Best regards, mjekl From dyoo at hkn.eecs.berkeley.edu Fri Jul 30 22:52:09 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 30 22:52:12 2004 Subject: [Tutor] Re: Ideas for beginning programs? [uselesspython.com / Sphere Online Judge] In-Reply-To: Message-ID: On Fri, 30 Jul 2004, mjekl wrote: > 3 - Write a program that gives asks you for temperature and the scale > (Celcius / Farenheit) and then gives you the corresponding temperatures > in (Farenheit / Celcius). > > 4 - Make a phone book using nested lists (or list and tuples)! Use a > menu to search a phone number by name or vice-versa > > 5 - Make a phone book using a simple list! Use a menu to search a phone > number by name or vice-versa > > *Compare these phonebooks with a phonebook made with a dictionary* *Make > a version of Guesser using OOP* Hi Bryan, You might also find Useless Python useful here: http://uselesspython.com/programmingcontests.html Rob has accumulated a lot of good projects that an aspiring programmer can sink their teeth into. (I need to find time to help Rob revive Useless Python... Not enough hours in a day... *sigh*) Wasn't there also a notice on Tutor a while back about an "online judge" contest? Let me check... Ah! Ok, Tomasz Noin'ski sent an announment about the Sphere Online Judge (SPOJ) a few weeks ago: http://mail.python.org/pipermail/tutor/2004-July/030460.html The website for SPOJ is: http://spoj.sphere.pl/ Some of the problems are ridiculously doable: http://spoj.sphere.pl/?a=problem&pcode=TEST but others are more profound: http://spoj.sphere.pl/?a=problem&pcode=JASIEK So the problems from the Sphere Online Judge may be very helpful to learn how to apply Python to something fun and challenging. Good luck to you! From missive at hotmail.com Fri Jul 30 23:55:42 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Jul 30 23:55:53 2004 Subject: [Tutor] Re: How to connect a MUD client? (fwd) Message-ID: >> >>> tn = telnetlib.Telnet('mudlib.anarres.org', 5000) >> >>> tn.read_very_eager() >Sorry, I am not able to understand "tn.read_very_eager()", could you please >explain it? http://python.org/doc/current/lib/telnet-objects.html Or do you mean explain more than that? What exactly do you not understand about read_very_eager() ? _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From nick at javacat.f2s.com Sat Jul 31 00:24:14 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sat Jul 31 00:22:25 2004 Subject: [Tutor] Re: How to connect a MUD client? (fwd) In-Reply-To: Message-ID: >> >>> tn = telnetlib.Telnet('mudlib.anarres.org', 5000) >> >>> tn.read_very_eager() >Sorry, I am not able to understand "tn.read_very_eager()", could you please >explain it? Hi there, just to let you know (in case you dont :] ) the python command line has a useful help() function. Try this import telnetlib help(telnetlib.Telnet.read_very_eager) This works for most python modules, eg import socket help(socket) On another note, if your interested in doing some network programs with python, twisted as mentioned in a previous post is exceptionally good for it. Im a learner pythonist like yourself, and i started off writing a couple of network programs using the socket module, then I came across twisted, and it really is a good framework for network programming. I managed to create a simple chatserver using twisted quite easily. I strongly recommend you to visit http://docs.python.org/tut/tut.html and then www.twistedmatrix.com . Good luck Nick. From bvande at po-box.mcgill.ca Sat Jul 31 02:22:36 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Jul 31 03:14:07 2004 Subject: [Tutor] redirecting help -- is this a bad idea? Message-ID: <410AE64C.3050107@po-box.mcgill.ca> Hi all, I'm making my first use of classes and also over-riding python builtins. I'd like to run what I am doing by the list as a sanity check and see if I get a giant *don't do that!* back :-) What I am trying to do is create a set of programs for use by a friend who is even less computer literate than I. =-O Part of my aim is to make it self-documenting in an easy to use way. So, I want to redirect the help command to my own help function for my set of programs, while still preserving the normal help behaviour under another name. Having dipped into site.py to see how help was able to work both by typing "help" and by typing "help()", I saw it was implemented with a class: class _Helper: def __repr__(self): return "Type help() for interactive help, " \ "or help(object) for help about object." def __call__(self, *args, **kwds): import pydoc return pydoc.help(*args, **kwds) __builtin__.help = _Helper() I used this as the basis of my redirection of "help". The function that does the work of my help system is tell(). So I've done the following: class _Helper: def __repr__(self): return "Type help() for interactive help, " \ "or help(object) for help about object.\n" \ "(For Python's own help function, type pyhelp.)" def __call__(self, *args, **kwds): return tell(*args, **kwds) help = _Helper() class _PyHelper: def __repr__(self): return "Type pyhelp() for interactive help, " \ "or pyhelp(object) for help about object." def __call__(self, *args, **kwds): import pydoc return pydoc.help(*args, **kwds) pyhelp = _PyHelper() Profoundly wrong or just fine? Best, Brian vdB From beowolf at the-barracks.net Thu Jul 29 00:29:34 2004 From: beowolf at the-barracks.net (Beowolf) Date: Sat Jul 31 04:43:20 2004 Subject: [Tutor] .insert(0.0, whole_thing) - nevermind Message-ID: <410828CE.4070600@the-barracks.net> Seems like I sent you working code in my last email. For some reason it works now, though I made no changes...I think. From beowolf at the-barracks.net Thu Jul 29 00:14:16 2004 From: beowolf at the-barracks.net (Beowolf) Date: Sat Jul 31 05:38:16 2004 Subject: [Tutor] .insert(0.0, whole_thing) problem Message-ID: <41082538.5020904@the-barracks.net> Hi, I just started learning Python :D I'm making a simple script with a GUI, reading from a text file, but the problem is that the contents won't insert into the text area, though they do print ok in the console window. Here is my code, can you see what I am doing wrong? (in the def open_file(self) section) # Notepad 2 # Acts like Notepad # Nick Bakewell - 7/28/04 from Tkinter import * class Application(Frame): """ GUI application which counts button clicks. """ def __init__(self, master): """ Initialize the frame. """ Frame.__init__(self, master) self.grid() self.create_widget() self.open_file() self.save_count = int("1") def create_widget(self): """ create the button and status """ self.lbl = Label(self, text = "Unsaved") self.lbl.grid(row = 0, col = 0) self.bttn = Button(self) self.bttn["text"] = "Save File" self.bttn["command"] = self.save_file self.bttn.grid(row = 0, col = 1) self.lbl2 = Label(self, text = "Editing file 'test.txt'") self.lbl2.grid(row = 3, col = 0, columnspan = 2) def open_file(self): """ open the file for writing and reading """ self.text_file = open("test.txt", "r") self.whole_thing = self.text_file.read() self.user_txt = Text(self, width = 50, height = 30, wrap = WORD) self.user_txt.grid(row = 2, col = 0, columnspan = 2, sticky = W) self.user_txt.delete(0.0, END) self.user_txt.insert(0.0, self.whole_thing) print self.whole_thing def save_file(self): """ update the button count on click """ contents = self.user_txt.get(0.0, END) self.new_file = open("test.txt", "w") self.new_file.write(contents) self.lbl["text"] = "File Saved", str(self.save_count) self.save_count += 1 print "File saved." # main root = Tk() root.title("Button Test") root.geometry("400x500") app = Application(root) root.mainloop() From kent_johnson at skillsoft.com Sat Jul 31 15:13:41 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Jul 31 15:13:50 2004 Subject: [Tutor] redirecting help -- is this a bad idea? In-Reply-To: <410AE64C.3050107@po-box.mcgill.ca> References: <410AE64C.3050107@po-box.mcgill.ca> Message-ID: <6.1.0.6.0.20040731090137.028dca40@mail4.skillsoft.com> Brian, A couple of thoughts: - You might consider just making your classes work well with pydoc. The built-in help is introspecting the docstrings for the module you ask for help on. If you write docstrings for your module, built-in help will document it. Take a look at some library modules and the corresponding help to see how this works. If you go this way, your help will be integrated with the help for built-in objects, so your user won't have to figure out which help to use. - If you continue down the path you show below, there is no need to define _PyHelper. You can just assign pyhelp = help Then define your own helper and assign it to help. BTW you are not redefining __builtin__.help when you do this, you are shadowing it with a definition of help in the current global namespace. Kent At 08:22 PM 7/30/2004 -0400, Brian van den Broek wrote: >Hi all, > >I'm making my first use of classes and also over-riding python builtins. >I'd like to run what I am doing by the list as a sanity check and see if I >get a giant *don't do that!* back :-) > >What I am trying to do is create a set of programs for use by a friend who >is even less computer literate than I. =-O Part of my aim is to make it >self-documenting in an easy to use way. So, I want to redirect the help >command to my own help function for my set of programs, while still >preserving the normal help behaviour under another name. > >Having dipped into site.py to see how help was able to work both by typing >"help" and by typing "help()", I saw it was implemented with a class: > >class _Helper: > def __repr__(self): > return "Type help() for interactive help, " \ > "or help(object) for help about object." > def __call__(self, *args, **kwds): > import pydoc > return pydoc.help(*args, **kwds) > >__builtin__.help = _Helper() > > >I used this as the basis of my redirection of "help". The function that >does the work of my help system is tell(). So I've done the following: > >class _Helper: > def __repr__(self): > return "Type help() for interactive help, " \ > "or help(object) for help about object.\n" \ > "(For Python's own help function, type pyhelp.)" > def __call__(self, *args, **kwds): > return tell(*args, **kwds) > >help = _Helper() > >class _PyHelper: > def __repr__(self): > return "Type pyhelp() for interactive help, " \ > "or pyhelp(object) for help about object." > def __call__(self, *args, **kwds): > import pydoc > return pydoc.help(*args, **kwds) > >pyhelp = _PyHelper() > > >Profoundly wrong or just fine? > >Best, > >Brian vdB > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From jfabiani at yolo.com Sat Jul 31 19:07:19 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat Jul 31 19:07:23 2004 Subject: [Tutor] Understanding DBAPI cursor.execute Message-ID: <200407311007.19763.jfabiani@yolo.com> I'm using MySQLdb (but I'd like to use others DB too) and I'm trying to understand the DBAPI cursor.execute. when I use cursor.execute("SELECT * FROM mytest where address = %s",string1) above works but?? cursor.execute("SELECT * FROM mytest where address = %s" % string1) above does not work. So?why?did? ?cursor.execute("SELECT?*?FROM?mytest?where?clientID?=?%d"?%?numb) work? clientID,address was created using clientID int not null auto_increment primary key address varchar(40) Can someone explain why the difference and does the same thing work with other DBAPI drivers? Thanks for the help - someday soon I hope I'll be able to help. John From pythonTutor at venix.com Sat Jul 31 20:14:23 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Jul 31 20:14:34 2004 Subject: [Tutor] Understanding DBAPI cursor.execute In-Reply-To: <200407311007.19763.jfabiani@yolo.com> References: <200407311007.19763.jfabiani@yolo.com> Message-ID: <1091297663.5417.22.camel@laptop.venix.com> On Sat, 2004-07-31 at 13:07, John Fabiani wrote: > I'm using MySQLdb (but I'd like to use others DB too) and I'm trying to > understand the DBAPI cursor.execute. > when I use > cursor.execute("SELECT * FROM mytest where address = %s",string1) This is the most reliable form. The module will escape special characters and create a valid SQL statement placing your parameters into the slots marked by %s. > above works but > cursor.execute("SELECT * FROM mytest where address = %s" % string1) cursor.execute("SELECT * FROM mytest where address = '%s'" % string1) ^ ^ would have worked. If you do the string interpolation, you need to follow all of the MySQLdb requirements in formating the parameters. > above does not work. > So why did > cursor.execute("SELECT * FROM mytest where clientID = %d" % numb) A numeric value does not need quotes to set it off in the SQL command string. > work? > clientID,address was created using > clientID int not null auto_increment primary key > address varchar(40) > > Can someone explain why the difference and does the same thing work with other > DBAPI drivers? There are multiple parameter styles among the DB modules. The primary documentation is the DB API spec (version 2). You might want to subscribe to the DB-SIG mail list. It is low volume, but monitored by the people who write the DB modules and a terrific source of help if you need it. > > Thanks for the help - someday soon I hope I'll be able to help. > John > > _______________________________________________ > 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 jfabiani at yolo.com Sat Jul 31 22:33:37 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat Jul 31 22:33:41 2004 Subject: [Tutor] Understanding DBAPI cursor.execute In-Reply-To: <1091297663.5417.22.camel@laptop.venix.com> References: <200407311007.19763.jfabiani@yolo.com> <1091297663.5417.22.camel@laptop.venix.com> Message-ID: <200407311333.37915.jfabiani@yolo.com> thanks I think I understand the quoting issue. But you suggested that I should follow "MySQLdb requirements in formating the parameters.". Where do I find such information and this implies that not all DBAPI modules are NOT the same. I thought the purpose of the DBAPI was to create a standard interface??? I'm guessing it failed or the params issue was not addressed. Thanks for your help. John From jfabiani at yolo.com Sat Jul 31 22:46:48 2004 From: jfabiani at yolo.com (John Fabiani) Date: Sat Jul 31 22:46:53 2004 Subject: [Tutor] Re: Q Message-ID: <200407311346.48477.jfabiani@yolo.com> Andy Todd wrote: > John Fabiani wrote: >> thanks that worked but I don't understand why. >> cursor.execute("SELECT * FROM mytest where address = %s",string1) >> above works but - following your suggestion: >> cursor.execute("SELECT * FROM mytest where address = %s" % string1) >> above does not work. So why did >> cursor.execute("SELECT * FROM mytest where clientID = %d" % numb) >> work??????????????? >> john >> F. GEIGER wrote: >> >> >>>"John Fabiani" schrieb im Newsbeitrag >>>news:lGIOc.4961$AY5.4762@newssvr21.news.prodigy.com... >>> >>>>Hi, >>>> I'm a newbie and I'm attempting to learn howto create a select >>>> statement. >>>>When I use >>>> >>>>>>>string1='18 Tadlock Place' >>>>>>>cursor.execute("SELECT * FROM member") >>>> >>>>All works as expected. But >>>> >>>>>>>numb=10 >>>>>>>cursor.execute("SELECT * FROM mytest where clientID = %d",numb) >>> >>>I'm used to do that this way: >>> >>>cursor.execute("SELECT * FROM mytest where clientID = %d" % numb) >>> >>>HTH >>>Franz GEIGER >>> >>> >>>>Traceback (innermost last): >>>> File "", line 1, in ? >>>> File "/usr/lib64/python2.3/site-packages/MySQLdb/cursors.py", line 95, >>> >>>in >>> >>>>execute >>>> return self._execute(query, args) >>>> File "/usr/lib64/python2.3/site-packages/MySQLdb/cursors.py", line >>>> 110, >>> >>>in >>> >>>>_execute >>>> self.errorhandler(self, TypeError, m) >>>> File "/usr/lib64/python2.3/site-packages/MySQLdb/connections.py", line >>> >>>33, >>> >>>>in defaulterrorhandler >>>> raise errorclass, errorvalue >>>>TypeError: int argument required >>>> >>>>ClientID was created using "clientID int not null auto_increment primary >>>>key" >>>> >>>> >>>>What is the correct way passing the numb var to the string? >>>>Thanks John >> >> > > It's not too intuitive, but when using the 'format' parameter style in > DB-API modules[1] (as used here) you *always* use '%s' to indicate that > a substitution should take place. > > The solution that F GEIGER proposed uses string formatting and will not > take advantage of parameter binding properly. So instead of > > >>> cursor.execute("SELECT * FROM mytest where clientID = %d" % numb) > > You should use > > >>> cursor.execute("SELECT * FROM mytest where clientID = %s", numb) > > The first version 'works' because the string is parsed before it is > passed to the MySQLdb module, so if numb is 10 it's the exact same as; > > >>> cursor.execute("SELECT * FROM mytest where clientID = 10") > > The second (and correct) suggestion uses parameter binding, so if you > execute the statement a number of times (with different values of > 'numb') the database has to do less work - and therefore your code will > run faster. This is important but probably outside the scope of this > discussion. > > [1] http://www.python.org/peps/pep-0249.html > > Regards, > Andy Thanks very much - I think a little light was just turned on. It makes sense that the number (numb in this case) be converted to a string - since I'm passing a string to the DB module (I want to call it a driver/interface). I was writing up this long note to myself trying to explain the way to pass number and strings. But now I realize how simple the issue really was. Well I'm learning daily. john From pythonTutor at venix.com Sat Jul 31 22:56:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Jul 31 22:56:43 2004 Subject: [Tutor] Understanding DBAPI cursor.execute In-Reply-To: <200407311333.37915.jfabiani@yolo.com> References: <200407311007.19763.jfabiani@yolo.com> <1091297663.5417.22.camel@laptop.venix.com> <200407311333.37915.jfabiani@yolo.com> Message-ID: <1091307390.5417.75.camel@laptop.venix.com> http://python.org/topics/database/ This is a good starting point for Python DB-SIG info. The API version 2 explains the rules for all of the modules and how to determine how they implement the parms processing. I tend to agree that common parm passing rules would be better, but I don't know enough about the issues to know why alternatives were allowed. On Sat, 2004-07-31 at 16:33, John Fabiani wrote: > thanks I think I understand the quoting issue. But you suggested that I > should follow "MySQLdb requirements in formating the parameters.". Where do > I find such information and this implies that not all DBAPI modules are NOT > the same. I thought the purpose of the DBAPI was to create a standard > interface??? I'm guessing it failed or the params issue was not addressed. > > Thanks for your help. > John > _______________________________________________ > 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