From nephish at gmail.com Tue May 1 00:13:58 2007 From: nephish at gmail.com (shawn bright) Date: Mon, 30 Apr 2007 17:13:58 -0500 Subject: [Tutor] best way to tell if i am connected to the internet Message-ID: <384c93600704301513n14f7785cp198d2dbaf3586aac@mail.gmail.com> hello there all, i am wondering, what would be the simplest way to get a true/false am i connected to the internet ? right now i am using httplib to fetch a webpage every 20 minutes to see, but i am thinking that there is a better way, any suggestions would be encouraging thanks shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070430/62431414/attachment.htm From jalilsan at gmail.com Tue May 1 05:11:17 2007 From: jalilsan at gmail.com (Jalil) Date: Mon, 30 Apr 2007 20:11:17 -0700 Subject: [Tutor] best way to tell if i am connected to the internet In-Reply-To: <384c93600704301513n14f7785cp198d2dbaf3586aac@mail.gmail.com> References: <384c93600704301513n14f7785cp198d2dbaf3586aac@mail.gmail.com> Message-ID: <5850ed90704302011w1279f493k37bea6b76fc03c6@mail.gmail.com> ping a host on the net if you get an echo response back you are good. better yet ping the host page you are scraping. On 4/30/07, shawn bright wrote: > > hello there all, > > i am wondering, what would be the simplest way to get a true/false > am i connected to the internet ? > > right now i am using httplib to fetch a webpage every 20 minutes to see, > but i am thinking that there is a better way, > > any suggestions would be encouraging > > thanks > shawn > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070430/254b176b/attachment.htm From nephish at gmail.com Tue May 1 06:09:16 2007 From: nephish at gmail.com (shawn bright) Date: Mon, 30 Apr 2007 23:09:16 -0500 Subject: [Tutor] best way to tell if i am connected to the internet In-Reply-To: <5850ed90704302011w1279f493k37bea6b76fc03c6@mail.gmail.com> References: <384c93600704301513n14f7785cp198d2dbaf3586aac@mail.gmail.com> <5850ed90704302011w1279f493k37bea6b76fc03c6@mail.gmail.com> Message-ID: <384c93600704302109la0d39fcya9b99580aa7dbc5d@mail.gmail.com> ok, cool. thanks sk On 4/30/07, Jalil wrote: > > ping a host on the net if you get an echo response back you are good. > better yet ping the host page you are scraping. > > > On 4/30/07, shawn bright < nephish at gmail.com> wrote: > > > > hello there all, > > > > i am wondering, what would be the simplest way to get a true/false > > am i connected to the internet ? > > > > right now i am using httplib to fetch a webpage every 20 minutes to see, > > but i am thinking that there is a better way, > > > > any suggestions would be encouraging > > > > thanks > > shawn > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070430/865bcc31/attachment.htm From alan.gauld at btinternet.com Tue May 1 09:22:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 May 2007 08:22:06 +0100 Subject: [Tutor] best way to tell if i am connected to the internet References: <384c93600704301513n14f7785cp198d2dbaf3586aac@mail.gmail.com> Message-ID: "shawn bright" wrote > i am wondering, what would be the simplest way to get a true/false > am i connected to the internet ? > > right now i am using httplib to fetch a webpage every 20 minutes to > see, but > i am thinking that there is a better way, You don't need to fetch it just connect. If there are no errors you are online. Alan G From dotancohen at gmail.com Tue May 1 12:08:48 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 1 May 2007 13:08:48 +0300 Subject: [Tutor] Fixing garbled email addresses Message-ID: <880dece00705010308r553aec8cqb86309c98c18011@mail.gmail.com> I have had the misfortune of having a university Windows machine garble all the email addresses in my addressbook (a txt file so that I can use it both on my home Fedora machine and on the university Windows machines). I figure this is as good a time as any to start learning python and fix the file. How can I iteriate through a text file that looks like this: "=?UTF-8?B?157XqNeZ15Qg15nXoNeY16bXnw==?=" , "=?UTF-8?B?157XqNenINen15nXmNek15XXkQ==?=" , "=?UTF-8?B?157XqdeUINem15LXkNeZ?=" , and have it return: someuser at t2.technion.ac.il, someuser at gmail.com, someuser at walla.co.il, Thanks in advance. Dotan Cohen http://lyricslist.com/ http://what-is-what.com/ From washakie at gmail.com Tue May 1 12:10:14 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 12:10:14 +0200 Subject: [Tutor] if in an iteration, quick Q!! Message-ID: I can't recall how to do this: I want: a = [int(x) for x in tmp] but, my tmp has some empty elements, so it fails... Therefore I want to be able to say: a = [int(x) for x in tmp IF x in tmp] I know there's a way! Ive seen it before, but now cannot find it! 'if' is a pretty generic thing to search for :s Thanks!! From kent37 at tds.net Tue May 1 12:18:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 01 May 2007 06:18:08 -0400 Subject: [Tutor] if in an iteration, quick Q!! In-Reply-To: References: Message-ID: <463713E0.6030705@tds.net> John Washakie wrote: > I can't recall how to do this: > > I want: > a = [int(x) for x in tmp] > > but, my tmp has some empty elements, so it fails... > > Therefore I want to be able to say: > > a = [int(x) for x in tmp IF x in tmp] That's almost right, except it checks the wrong thing. Try a = [int(x) for x in tmp if x] Depending on what an 'empty' element is you may have to refine that. Kent From washakie at gmail.com Tue May 1 12:20:32 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 12:20:32 +0200 Subject: [Tutor] if in an iteration, quick Q!! In-Reply-To: <463713E0.6030705@tds.net> References: <463713E0.6030705@tds.net> Message-ID: Thanks!!!! > > Depending on what an 'empty' element is you may have to refine that. > I also noted, if I used: tmp = data[6].strip().split() rather than: tmp = data[6].strip().split(' ') I eliminated the 'empty' elements... From nephish at gmail.com Tue May 1 15:04:35 2007 From: nephish at gmail.com (shawn bright) Date: Tue, 1 May 2007 08:04:35 -0500 Subject: [Tutor] best way to tell if i am connected to the internet In-Reply-To: References: <384c93600704301513n14f7785cp198d2dbaf3586aac@mail.gmail.com> Message-ID: <384c93600705010604j5f1c7a06ja49281d2ade3016@mail.gmail.com> good enough, i suppose i can use a try, except to test if i am online and from that have a true / false. That is what i was looking for. I just didn't think it necessary to pull a webpage every 20 minutes. thanks shawn k On 5/1/07, Alan Gauld wrote: > > > "shawn bright" wrote > > > i am wondering, what would be the simplest way to get a true/false > > am i connected to the internet ? > > > > right now i am using httplib to fetch a webpage every 20 minutes to > > see, but > > i am thinking that there is a better way, > > You don't need to fetch it just connect. If there are no errors you > are online. > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070501/55217d98/attachment.html From jbrink at npsd.k12.wi.us Tue May 1 14:56:50 2007 From: jbrink at npsd.k12.wi.us (Jessica Brink) Date: Tue, 01 May 2007 07:56:50 -0500 Subject: [Tutor] Running a program Message-ID: <4636F2C1.CB8D.003F.0@npsd.k12.wi.us> I know this seems elementary, but if I write a program and save it as a .py file, how do I then run that program on the command line or in the Python Shell (GUI)? Or is there something I'm missing? I swear I was able to do this once, and now I can't remember what I did... Jessica Brink Business/Computer Teacher Northland Pines High School Eagle River, WI 715-479-4473 ext. 0701 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070501/ec2c9716/attachment.htm From washakie at gmail.com Tue May 1 15:34:07 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 15:34:07 +0200 Subject: [Tutor] Running a program In-Reply-To: <4636F2C1.CB8D.003F.0@npsd.k12.wi.us> References: <4636F2C1.CB8D.003F.0@npsd.k12.wi.us> Message-ID: Jessica, Assuming you have python installed on your system (Windows?, *nix?), then all you have to do is double click the .py file and it will run. If you want, you can run it from the command line: C:\> python yourfile.py On 5/1/07, Jessica Brink wrote: > > > I know this seems elementary, but if I write a program and save it as a .py > file, how do I then run that program on the command line or in the Python > Shell (GUI)? Or is there something I'm missing? I swear I was able to do > this once, and now I can't remember what I did... > > > Jessica Brink > Business/Computer Teacher > Northland Pines High School > Eagle River, WI > 715-479-4473 ext. 0701 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From bensherman at gmail.com Tue May 1 16:39:12 2007 From: bensherman at gmail.com (Ben Sherman) Date: Tue, 1 May 2007 10:39:12 -0400 Subject: [Tutor] Fixing garbled email addresses In-Reply-To: <880dece00705010308r553aec8cqb86309c98c18011@mail.gmail.com> References: <880dece00705010308r553aec8cqb86309c98c18011@mail.gmail.com> Message-ID: <5a56471e0705010739m19827aa1q13c923475e35a16f@mail.gmail.com> On 5/1/07, Dotan Cohen wrote: > I have had the misfortune of having a university Windows machine > garble all the email addresses in my addressbook (a txt file so that I > can use it both on my home Fedora machine and on the university > Windows machines). I figure this is as good a time as any to start > learning python and fix the file. How can I iteriate through a text > file that looks like this: > > "=?UTF-8?B?157XqNeZ15Qg15nXoNeY16bXnw==?=" , > "=?UTF-8?B?157XqNenINen15nXmNek15XXkQ==?=" , > "=?UTF-8?B?157XqdeUINem15LXkNeZ?=" , > > and have it return: > someuser at t2.technion.ac.il, > someuser at gmail.com, > someuser at walla.co.il, > > Thanks in advance. > > Dotan Cohen > > http://lyricslist.com/ > http://what-is-what.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hi Dotan! Welcome to python! Here is some code that will do what you need. It uses the re module, which are regular expressions. # You need to import the module: import re # Then you need to read in the file that contains your list. email_list = open("brokenemails.txt","r") # We need to generate your regular expression. The grabs anything in # the file that is between < and >, but it includes the <> re_mail=re.compile(r"\<(.*)\>") # Then filter each line of the file through the regex, discarding the # <> from above, and puts each address into a list. addresses = [re_mail.search(line).group(1) for line in email_list.readlines()] # Now we print them out, comma and newline separated print ",\n".join(addresses) Let me know if you need more detail! Your pal, Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070501/4dd28356/attachment.html From dotancohen at gmail.com Tue May 1 16:43:51 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 1 May 2007 17:43:51 +0300 Subject: [Tutor] Fixing garbled email addresses In-Reply-To: <5a56471e0705010734o3006f996l680f128391b6f831@mail.gmail.com> References: <880dece00705010308r553aec8cqb86309c98c18011@mail.gmail.com> <5a56471e0705010704l57587eb0g18c329224f668cae@mail.gmail.com> <880dece00705010717n47294793qe922eae64de2e89c@mail.gmail.com> <5a56471e0705010734o3006f996l680f128391b6f831@mail.gmail.com> Message-ID: <880dece00705010743v2bdd3042pad1a1b8e6b0311d8@mail.gmail.com> On 01/05/07, Ben Sherman wrote: > Hey there - it would be better if you replied to the list - that way the > answers below could help others.. > > On 5/1/07, Dotan Cohen wrote: > [snip] > > > > # Then filter each line of the file through the regex, discarding the > > > <> from above, and puts each address into a list. > > > addresses = [re_mail.search(line).group(1) for line in > email_list.readlines()] > > > > Alright, I had to read that line twice. That's fine, though, I'm just > > getting started. > > This is a list comprehension - let's break it up so I can explain it a > little better. > > # a new list > addresses = [] > > # read each line of the file > for line in email_list.readline(): > # search each line, then print out what is in group 1 which is the text > between the > # parentheses in the compiled regex > address = re_mail.search(line).group(1) > # add the new address to out list > addresses.append(address) > > List comprehensions are the best thing ever! > > Happy to help, > Ben > With Gmail one must be careful and check that the To and Subject fields contain what you'd expect. Does 'list comprehension' mean a detailed explanation of the code? If so, then I'll be reading a lot of them in the near future. I really do appreciate the dedication and attention to detail. Thanks. Dotan Cohen http://what-is-what.com/what_is/sitepoint.html http://u-tube-com.com From alan.gauld at btinternet.com Tue May 1 16:53:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 May 2007 15:53:24 +0100 Subject: [Tutor] if in an iteration, quick Q!! References: Message-ID: "John Washakie" wrote > Therefore I want to be able to say: > > a = [int(x) for x in tmp IF x in tmp] > x will always be in tmp - thats where it comes from! You want to check if its non null. a = [int(x) for x in tmp if x] Alan G From alan.gauld at btinternet.com Tue May 1 16:57:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 May 2007 15:57:34 +0100 Subject: [Tutor] Running a program References: <4636F2C1.CB8D.003F.0@npsd.k12.wi.us> Message-ID: "Jessica Brink" wrote > I know this seems elementary, but if I write a program and > save it as a .py file, how do I then run that program on the > command line Just type "python script.py" at the OS prompt Or in *nix you can just type script.py if you havbe a shebang line at the top. > or in the Python Shell (GUI)? You can't run it as such but you can import it. If the script has no if __name__ == '__main__': main() stanza then it will run as if you had executed it, if it has the stanza then you need to call the main funbction manually: >>> import myscript >>> myscript.main() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 1 17:03:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 May 2007 16:03:03 +0100 Subject: [Tutor] Fixing garbled email addresses References: <880dece00705010308r553aec8cqb86309c98c18011@mail.gmail.com><5a56471e0705010704l57587eb0g18c329224f668cae@mail.gmail.com><880dece00705010717n47294793qe922eae64de2e89c@mail.gmail.com><5a56471e0705010734o3006f996l680f128391b6f831@mail.gmail.com> <880dece00705010743v2bdd3042pad1a1b8e6b0311d8@mail.gmail.com> Message-ID: "Dotan Cohen" wrote > Does 'list comprehension' mean a detailed explanation of the code? No its a programming construct found in Function programming languages such as Haskell (Python is partially functional in nature). Basically a list comprehension builds a list lc = [item_expression for item in collection if item_test] This is equivalent to lc = [] for item in collection: if item_expression: lc.append(item_expression) But it's shorter and usually faster. See the functional programming topic of my web tutor for more info and examples. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bensherman at gmail.com Tue May 1 17:06:52 2007 From: bensherman at gmail.com (Ben Sherman) Date: Tue, 1 May 2007 11:06:52 -0400 Subject: [Tutor] Fixing garbled email addresses In-Reply-To: <880dece00705010743v2bdd3042pad1a1b8e6b0311d8@mail.gmail.com> References: <880dece00705010308r553aec8cqb86309c98c18011@mail.gmail.com> <5a56471e0705010704l57587eb0g18c329224f668cae@mail.gmail.com> <880dece00705010717n47294793qe922eae64de2e89c@mail.gmail.com> <5a56471e0705010734o3006f996l680f128391b6f831@mail.gmail.com> <880dece00705010743v2bdd3042pad1a1b8e6b0311d8@mail.gmail.com> Message-ID: <5a56471e0705010806l53359597obb305ca28da72f7e@mail.gmail.com> On 5/1/07, Dotan Cohen wrote: > > [snip] > > > > List comprehensions are the best thing ever! > > > > Happy to help, > > Ben > > > > > With Gmail one must be careful and check that the To and Subject > fields contain what you'd expect. > > Does 'list comprehension' mean a detailed explanation of the code? If > so, then I'll be reading a lot of them in the near future. I really do > appreciate the dedication and attention to detail. Thanks. > > List comprehension are a python/programming term. They allow one to make a list without generating a blank one and appending to it. A very basic example: newlist = [item for item in spam(eggs)] is the same as newlist = [] for item in spam(eggs): newlist.append(item) If you walk through the code from earlier, you can see where a list comprehension saved some lines and made the flow easier to read. Official documentation is here: http://docs.python.org/tut/node7.html(section 5.1.4) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070501/4f95d0b5/attachment.htm From toanenadiz at gmail.com Tue May 1 17:41:18 2007 From: toanenadiz at gmail.com (Tony Waddell) Date: Tue, 1 May 2007 11:41:18 -0400 Subject: [Tutor] Dictionary Values Questions Message-ID: <77966a560705010841h13fc2b42v45159ebf40228eac@mail.gmail.com> I am wondering how look for a key in a dictionary, given a value. I have a dictionary similar to this: a = { 'a1':1, 'a2':2, 'a3':3, 'a4'.:4} If I have the value of 2, how would I look at the dictionary to turn that into 'a2'. From kent37 at tds.net Tue May 1 17:59:29 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 01 May 2007 11:59:29 -0400 Subject: [Tutor] Dictionary Values Questions In-Reply-To: <77966a560705010841h13fc2b42v45159ebf40228eac@mail.gmail.com> References: <77966a560705010841h13fc2b42v45159ebf40228eac@mail.gmail.com> Message-ID: <463763E1.1080709@tds.net> Tony Waddell wrote: > I am wondering how look for a key in a dictionary, given a value. > > I have a dictionary similar to this: > a = { 'a1':1, 'a2':2, 'a3':3, 'a4'.:4} > > If I have the value of 2, how would I look at the dictionary to turn > that into 'a2'. You have to search the values. This will produce a list of all keys that have a given value (there could be zero, one or more): [ key for key, value in a if value==2 ] If you have to do this often you might consider keeping a reverse-lookup dictionary or perhaps your key-value relationship is backwards. You might be interested in these recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415903 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252143 Kent From dyoo at cs.wpi.edu Tue May 1 17:59:58 2007 From: dyoo at cs.wpi.edu (Daniel Yoo) Date: Tue, 1 May 2007 11:59:58 -0400 (EDT) Subject: [Tutor] Fixing garbled email addresses Message-ID: Hi Dotan, Just for reference, the weirdness that you're seeing before the email addresses in your text file are "MIME-encoded" strings. http://en.wikipedia.org/wiki/MIME Concretely, the string "=?UTF-8?B?157XqNeZ15Qg15nXoNeY16bXnw==?=" is an encoding of a string in MIME format, and in particular, a utf-8 string in base-64 format. (See http://www.joelonsoftware.com/articles/Unicode.html for details on unicode if you need to brush up.) There are libraries in Python to help decode this stuff. In particular, the 'email' library. http://docs.python.org/lib/module-email.header.html ################################################### >>> from email.header import decode_header >>> from email.header import make_header >>> s = "=?UTF-8?B?157XqNeZ15Qg15nXoNeY16bXnw==?=" >>> h = make_header(decode_header(s)) ################################################### At this point, h is a "Header" object, whose unicode characters are: ######################################################### >>> unicode(h) u'\u05de\u05e8\u05d9\u05d4 \u05d9\u05e0\u05d8\u05e6\u05df' ######################################################### I have a console that supports printing utf-8, and when I look at this, it looks like Hebrew. A direct letter-for-letter transliteration would be: "Mem" "Resh" "Yod" "He" "Yod" "Nun" "Tet" "Tsadi" "Final Nun" I'm sure these consonants make more sense to you than they do to me, since I don't speak Hebrew. In any case, the point is that you may be able to maintain the name-to-email correspondence in your email lists by using Python's support for decoding those base64-encoded strings. From dotancohen at gmail.com Tue May 1 18:44:56 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 1 May 2007 19:44:56 +0300 Subject: [Tutor] Fixing garbled email addresses In-Reply-To: References: Message-ID: <880dece00705010944m2f5552fck403c0da49d9a773@mail.gmail.com> On 01/05/07, Daniel Yoo wrote: > Hi Dotan, > > > Just for reference, the weirdness that you're seeing before the email > addresses in your text file are "MIME-encoded" strings. > > http://en.wikipedia.org/wiki/MIME > > Concretely, the string > > "=?UTF-8?B?157XqNeZ15Qg15nXoNeY16bXnw==?=" > > is an encoding of a string in MIME format, and in particular, a utf-8 > string in base-64 format. Actually, I did realize that. > (See http://www.joelonsoftware.com/articles/Unicode.html for details on > unicode if you need to brush up.) > > > There are libraries in Python to help decode this stuff. In particular, > the 'email' library. > > http://docs.python.org/lib/module-email.header.html I will look into that, thanks. > ################################################### > >>> from email.header import decode_header > >>> from email.header import make_header > >>> s = "=?UTF-8?B?157XqNeZ15Qg15nXoNeY16bXnw==?=" > >>> h = make_header(decode_header(s)) > ################################################### > > > At this point, h is a "Header" object, whose unicode characters are: > > ######################################################### > >>> unicode(h) > u'\u05de\u05e8\u05d9\u05d4 \u05d9\u05e0\u05d8\u05e6\u05df' > ######################################################### > > I have a console that supports printing utf-8, and when I look at this, it > looks like Hebrew. A direct letter-for-letter transliteration would be: > > "Mem" "Resh" "Yod" "He" "Yod" "Nun" "Tet" "Tsadi" "Final Nun" > > I'm sure these consonants make more sense to you than they do to me, since > I don't speak Hebrew. In any case, the point is that you may be able to > maintain the name-to-email correspondence in your email lists by using > Python's support for decoding those base64-encoded strings. > There should be a space between the "he" and the second "yod", but that is correct. Thanks. Dotan Cohen http://what-is-what.com/what_is/computer.html http://hlup.com From washakie at gmail.com Tue May 1 19:37:31 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 19:37:31 +0200 Subject: [Tutor] Aaagh! Stack arrays!?! calc average Message-ID: Hello, I'm trying to calculate an average for columns in my array(data), there's a catch though, I want to create a new array of shorter length (NOTE: this crashes at line 8): 1) tinit = data[0][0] 2) for d in data: 3) if d[0] <= tinit+60: 4) sum = sum+d 5) else: 6) avg = sum/len(sum) 7) newData = append([newData],[avg],axis=0) 8) tinit = d[0] I cannot figure out how to append, column_stack, or otherwise deal with the newData array! Input on this simple task would be greatly appreciated!! From washakie at gmail.com Tue May 1 19:58:58 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 19:58:58 +0200 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: References: Message-ID: Oops, I meant it crashes at line 7.. > > 1) tinit = data[0][0] > 2) for d in data: > 3) if d[0] <= tinit+60: > 4) sum = sum+d > 5) else: > 6) avg = sum/len(sum) > 7) newData = append([newData],[avg],axis=0) > 8) tinit = d[0] > > From bensherman at gmail.com Tue May 1 20:07:23 2007 From: bensherman at gmail.com (Ben Sherman) Date: Tue, 1 May 2007 14:07:23 -0400 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: References: Message-ID: <5a56471e0705011107g22522431je8903443493bffaa@mail.gmail.com> On 5/1/07, John Washakie wrote: > > Oops, I meant it crashes at line 7.. > > > > > 1) tinit = data[0][0] > > 2) for d in data: > > 3) if d[0] <= tinit+60: > > 4) sum = sum+d > > 5) else: > > 6) avg = sum/len(sum) > > 7) newData = append([newData],[avg],axis=0) > > 8) tinit = d[0] > > You didn't include your append() function here, so it's hard to tell whats going on. Perhaps you mean to use newData.append(avg) assuming that newData is a list? Also, your average looks funky. If sum is something you can get a len() on, you can't divide it. It should be bombing here. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070501/0c3a1fe7/attachment.html From kent37 at tds.net Tue May 1 20:12:09 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 01 May 2007 14:12:09 -0400 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: References: Message-ID: <463782F9.6030809@tds.net> John Washakie wrote: > Hello, I'm trying to calculate an average for columns in my > array(data), there's a catch though, I want to create a new array of > shorter length (NOTE: this crashes at line 8): > > 1) tinit = data[0][0] > 2) for d in data: > 3) if d[0] <= tinit+60: > 4) sum = sum+d > 5) else: > 6) avg = sum/len(sum) > 7) newData = append([newData],[avg],axis=0) > 8) tinit = d[0] > > I cannot figure out how to append, column_stack, or otherwise deal > with the newData array! Input on this simple task would be greatly > appreciated!! Can you give some more details? What is newData? What do you want to add to it? what is the axis=0 for? Kent From washakie at gmail.com Tue May 1 20:48:47 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 20:48:47 +0200 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: <463782F9.6030809@tds.net> References: <463782F9.6030809@tds.net> Message-ID: Thanks for the feedback, The average was a little bit goofed up. Here's what I have now: for d in data: if d[0] <= tinit+60: d = column_stack(d) cnt=cnt+1 sum = sum+d else: avg = sum/cnt if init==0: newData = avg init=1 else: newData = append(newData,sum,axis=0) tinit,cnt = d[0],0 return newData it still seems awfully un-Python :o From washakie at gmail.com Tue May 1 21:25:26 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 21:25:26 +0200 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: References: <463782F9.6030809@tds.net> Message-ID: Ug, It still doesn't make sense due to the sum/cnt where cnt is just an int, and sum is a 1-dimensional array! I'm missing something here about working with numpy arrays... From bensherman at gmail.com Tue May 1 22:30:47 2007 From: bensherman at gmail.com (Ben Sherman) Date: Tue, 1 May 2007 16:30:47 -0400 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: References: <463782F9.6030809@tds.net> Message-ID: <5a56471e0705011330i1d1422fen54e33c2557da41e7@mail.gmail.com> On 5/1/07, John Washakie wrote: > > Ug, > > It still doesn't make sense due to the sum/cnt where cnt is just an > int, and sum is a 1-dimensional array! > > I'm missing something here about working with numpy arrays... You need to add all of the numbers in your list - you can't just divide a list by an int. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070501/85b43dae/attachment.html From washakie at gmail.com Tue May 1 22:53:15 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 22:53:15 +0200 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: <5a56471e0705011330i1d1422fen54e33c2557da41e7@mail.gmail.com> References: <463782F9.6030809@tds.net> <5a56471e0705011330i1d1422fen54e33c2557da41e7@mail.gmail.com> Message-ID: It aint pretty! And if I had just walked away, it probably would've taken half the time in the morning, but here's what I've come up with (any suggestions for improvements, or course are welcome): for d in data: w = len(d) if d[0] <= tinit+60: d = column_stack(d) cnt,sum = cnt+1,sum+d else: avg = sum/(ones(w)*cnt) tinit,cnt,sum = d[0],0,zeros(n) if init==0: newData,init = avg,1 else: newData = append(newData,avg,axis=0) return newData From washakie at gmail.com Tue May 1 22:53:50 2007 From: washakie at gmail.com (John Washakie) Date: Tue, 1 May 2007 22:53:50 +0200 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: <5a56471e0705011330i1d1422fen54e33c2557da41e7@mail.gmail.com> References: <463782F9.6030809@tds.net> <5a56471e0705011330i1d1422fen54e33c2557da41e7@mail.gmail.com> Message-ID: And of course, thanks all! From bensherman at gmail.com Wed May 2 00:57:22 2007 From: bensherman at gmail.com (Ben Sherman) Date: Tue, 1 May 2007 18:57:22 -0400 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: References: <463782F9.6030809@tds.net> <5a56471e0705011330i1d1422fen54e33c2557da41e7@mail.gmail.com> Message-ID: <5a56471e0705011557q3933763bkb8281bbed113a3df@mail.gmail.com> On 5/1/07, John Washakie wrote: > > It aint pretty! And if I had just walked away, it probably would've > taken half the time in the morning, but here's what I've come up with > (any suggestions for improvements, or course are welcome): > > for d in data: > w = len(d) > if d[0] <= tinit+60: > d = column_stack(d) > cnt,sum = cnt+1,sum+d > > else: > avg = sum/(ones(w)*cnt) > tinit,cnt,sum = d[0],0,zeros(n) > if init==0: > newData,init = avg,1 > else: > newData = append(newData,avg,axis=0) > > return newData > Sorry my last reply was so terse - I needed to catch a train. :) So you need to check out a couple of functions - namely sum. >>> numbers=[1,2,3,4,5] >>> numbers.append(6) >>> numbers [1, 2, 3, 4, 5, 6] >>> sum(numbers) 21 >>> len(numbers) 6 >>> sum(numbers)/len(numbers) 3 WAIT WAIT hold the phone!? 21/5 is NOT 3! It's 3.5! The short story here is that you have to make on of the numbers a floating point to get the result to return a float, so do this: >>> sum(numbers)*1.0/len(numbers) 3.5 So there is our average. If floor division doesn't make sense to you, you aren't alone. This changes in Python 3000. You can read about floor division here: http://www.python.org/doc/2.2.3/whatsnew/node7.html I don't quite know what your stack is for - it can probably be accomplished using some slices or other fun stuff. Good luck, and welcome to python! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070501/e0ce737a/attachment.htm From john at fouhy.net Wed May 2 01:14:02 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 2 May 2007 11:14:02 +1200 Subject: [Tutor] Aaagh! Stack arrays!?! calc average In-Reply-To: References: <463782F9.6030809@tds.net> <5a56471e0705011330i1d1422fen54e33c2557da41e7@mail.gmail.com> Message-ID: <5e58f2e40705011614x1fa5921fw87c30e20ac2571bd@mail.gmail.com> On 02/05/07, John Washakie wrote: > It aint pretty! And if I had just walked away, it probably would've > taken half the time in the morning, but here's what I've come up with > (any suggestions for improvements, or course are welcome): I'm still not sure exactly what you want to achieve... You're starting with a list of lists of integers, correct? Are the interior lists all the same length? Do you want to produce a new list which contains the average of all the sublists? In this case, you can do that using the sum() and len() functions -- check Ben's reply. A list comprehension would work well here (see the tutorial on python.org for information on list comprehensions). Is there anything else you want to do? -- John. From digitalxero at gmail.com Wed May 2 23:13:52 2007 From: digitalxero at gmail.com (Dj Gilcrease) Date: Wed, 2 May 2007 14:13:52 -0700 Subject: [Tutor] Finding an object by ID Message-ID: I was wondering if it was possible to find and object by it's ID. what I want to do is something like def incomingConnection(self, stuff): (incSock, incAdder) = self.__sock.accept() #Add the adder socket ID and other info to a DB def sendMessage(self, adder, message): #query the DB and get the socket ID stored there sock = getSocketByID(sockID) #do my send data The reason I want to do this is right now I store all the data in a dict of class eg class connections: def __init__(self, *args, **kwargs): self.sock = args[0] self.myotherdata = stuff ... def incomingConnection(self, stuff): (incSock, incAdder) = self.__sock.accept() self.conns[incAdder] = connections(incSock, ...) This takes up about 20 megs per person connecting, which is very high IMHO, and I am hoping by storing all the data in the database and only retrieving it when I need it will help reduce the memory footprint of my server From ravi.kukreja at gmail.com Thu May 3 00:36:51 2007 From: ravi.kukreja at gmail.com (Ravi Kukreja) Date: Wed, 2 May 2007 15:36:51 -0700 Subject: [Tutor] Webcasts, video tutorials, for Python Message-ID: <7e7580d00705021536n1538706age65da497074754b0@mail.gmail.com> Hello, I am just getting started on learning Python. Does anyone know good (hopefully) video/webcasts tutorials to get started on Python? Thanks for your response. Ravi -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070502/1738676b/attachment.htm From alan.gauld at btinternet.com Thu May 3 00:51:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 May 2007 23:51:34 +0100 Subject: [Tutor] Finding an object by ID References: Message-ID: "Dj Gilcrease" wrote >I was wondering if it was possible to find and object by it's ID. Its probably possible but almost certainly the wrong thing to do... > what I want to do is something like > snipped... > The reason I want to do this is right now I store all the data in a > dict of class > > eg > class connections: > def __init__(self, *args, **kwargs): > self.sock = args[0] > self.myotherdata = stuff > ... > def incomingConnection(self, stuff): > (incSock, incAdder) = self.__sock.accept() > self.conns[incAdder] = connections(incSock, ...) > > > This takes up about 20 megs per person connecting, which is very > high But I'm not sure hpow storing IDs will help, the objects still need to be in memory. The only saving is in the actual dictionary itself which is relatively small. Also you could probably save memory more easily by storing the data to disk using pickle or shelve, but you'd need to be very sure that you could retrieve the objects fast enough to process your incoming connections - what is the peak rate? > IMHO, and I am hoping by storing all the data in the database and > only You only seemed to be storing the ID - which is basically the memory location. If you are going to store all the data in memory then the ID as a key is pointless you might as well get the database to generate one for you or use a simple counter at clkass level because you will need to regenerate the instance in memory to use it and that will result in it having a different ID... If you really need to reduce footprint you should probably consider connection object pooling where you use a cache of connection objects and reuse them. That way you only need the number of connections that are active at any one time - and you will always need those regardless of what you do with the inactive ones. Also look at the format of your data, is that in the most efficient format? Could it be encoded using struct for example? Or zipped? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu May 3 00:57:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 May 2007 23:57:02 +0100 Subject: [Tutor] Webcasts, video tutorials, for Python References: <7e7580d00705021536n1538706age65da497074754b0@mail.gmail.com> Message-ID: "Ravi Kukreja" wrote > I am just getting started on learning Python. Does anyone know good > (hopefully) video/webcasts tutorials to get started on Python? > There is a site that does a wide range of Python video tutorials. Its called ShowMeDo: http://showmedo.com/videos/python I've watched a couple and they are quite good as these things go. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu May 3 03:08:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 May 2007 21:08:24 -0400 Subject: [Tutor] Finding an object by ID In-Reply-To: References: Message-ID: <46393608.30102@tds.net> Dj Gilcrease wrote: > This takes up about 20 megs per person connecting, which is very high > IMHO, and I am hoping by storing all the data in the database and only > retrieving it when I need it will help reduce the memory footprint of > my server You seem to think that it is the socket that takes up 20 megs. This seems unlikely to me. What other data are you storing for the connection? Could that be stored in a database or in another form? Kent From andreengels at gmail.com Thu May 3 07:39:31 2007 From: andreengels at gmail.com (Andre Engels) Date: Thu, 3 May 2007 07:39:31 +0200 Subject: [Tutor] Finding an object by ID In-Reply-To: References: Message-ID: <6faf39c90705022239k4f98e878v462a0cbb897ed59e@mail.gmail.com> It seems to me that this is is an issue that is not resolved in Python, but in your database's language. Every database language that's word the name has a command like "get the record that has such-and-such value for this-and-that property". What command it is, depends on the database. Or am I now completely misunderstanding your meaning of the word 'database'? 2007/5/2, Dj Gilcrease : > I was wondering if it was possible to find and object by it's ID. > > what I want to do is something like > > def incomingConnection(self, stuff): > (incSock, incAdder) = self.__sock.accept() > > #Add the adder socket ID and other info to a DB > > def sendMessage(self, adder, message): > #query the DB and get the socket ID stored there > > sock = getSocketByID(sockID) > > #do my send data > > > > The reason I want to do this is right now I store all the data in a > dict of class > > eg > class connections: > def __init__(self, *args, **kwargs): > self.sock = args[0] > self.myotherdata = stuff > ... > > > def incomingConnection(self, stuff): > (incSock, incAdder) = self.__sock.accept() > self.conns[incAdder] = connections(incSock, ...) > > > This takes up about 20 megs per person connecting, which is very high > IMHO, and I am hoping by storing all the data in the database and only > retrieving it when I need it will help reduce the memory footprint of > my server > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From Dean.Gardner at barco.com Thu May 3 14:01:43 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Thu, 3 May 2007 14:01:43 +0200 Subject: [Tutor] Text matching Message-ID: Hi Folks I wish to isolate certain changelog entries and display them to the user, for example: Changelog.txt ----------Some Module ---------- M 000751 - Title > what was amended Reviewed by: Someone ----------Some Module ---------- A 000752 - Title > what was amended Reviewed by: Someone ----------Some Module ---------- A 000751 - Title > what was amended Reviewed by: Someone For this text file I wish to find all entries for 000751 and then present each of the changelog entries. My thought was to identify the "----" with a regular expression identifying this as the changelog start attempt to find the item number if it isn't found move on, if it is found then add this to a list. But I feel as though there must be a simpler and more effecient way. Thanks in advance Dean Gardner Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com dean.gardner at barco.com DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070503/e2b57b50/attachment.htm From jcoggins828 at charter.net Thu May 3 04:09:28 2007 From: jcoggins828 at charter.net (Jason Coggins) Date: Wed, 2 May 2007 22:09:28 -0400 Subject: [Tutor] os.path.join question Message-ID: <001201c78d28$154ca020$dde17744@dunamis34752e9> Is it possible to use os.path.join to link to a file located in the directory above where you are currently located? If so, what is the syntax? Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070502/cf4778eb/attachment.html From kent37 at tds.net Thu May 3 14:45:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 May 2007 08:45:38 -0400 Subject: [Tutor] Text matching In-Reply-To: References: Message-ID: <4639D972.20709@tds.net> Gardner, Dean wrote: > Hi Folks > > I wish to isolate certain changelog entries and display them to the > user, for example: > > Changelog.txt > > ----------Some Module ---------- > M 000751 - Title >> what was amended > Reviewed by: Someone > > For this text file I wish to find all entries for 000751 and then > present each of the changelog entries. > > My thought was to > identify the "----" with a regular expression > identifying this as the changelog start You probably don't need a regex here, something like if line.startswith('----------'): will probably work > attempt to find the item number if line.split()[1] == '000751': > if it isn't found move on, if it is found then add this to a list. > > But I feel as though there must be a simpler and more effecient way. This sounds good to me except for the regex. Can you show us your code? Kent From detroit371 at gmail.com Thu May 3 14:46:43 2007 From: detroit371 at gmail.com (Lawrence Shafer) Date: Thu, 03 May 2007 07:46:43 -0500 Subject: [Tutor] Trouble with "RuntimeError: underlying C/C++ object has been deleted". Message-ID: <4639D9B3.6030700@gmail.com> Hello List, I am just learning Python/PyQt4, and have a problem I cannot figure out. Here's what happens. Traceback (most recent call last): File "iac.py", line 124, in on_actionOpen_triggered self.open() File "iac.py", line 66, in open if self.isUntitled and self.textBrowser.document().isEmpty() and not self.isWindowModified(): RuntimeError: underlying C/C++ object has been deleted I have copied several parts of other programs, so that's probably where this is coming from. All I want is to load a .txt file into self.textBrowser, so some of the functionality is unneeded at this time, except for filter saving and loading. If someone understands what is going on, that would be great! The source can be downloaded from here http://lawrence.orbwireless.net/iac_src.tar.gz Thanks! Lawrence From Dean.Gardner at barco.com Thu May 3 15:16:19 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Thu, 3 May 2007 15:16:19 +0200 Subject: [Tutor] Text matching In-Reply-To: <4639D972.20709@tds.net> References: <4639D972.20709@tds.net> Message-ID: Here is a test sample of what I have: This currently correctly identifies the start and the end of the changelog entries and I can identify the requested item records. What I am struggling with at present is to how to create records of the full changelog entries for each of the found items. Again any help greatly appreciated. uid = "000028.txt" file = open("C:\projects\SuiteSpecification\Notes\ChangeLog.txt") output = file.readlines() changeLogList = [] itemList = [] for strOut in output: if "----" in strOut: changeLogStart = 1 itemList.append(strOut) if "Reviewed:" in strOut: changeLogStart=0 for item in itemList: if uid in item: print item Dean Gardner Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com dean.gardner at barco.com -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: 03 May 2007 13:46 To: Gardner, Dean Cc: tutor at python.org Subject: Re: [Tutor] Text matching Gardner, Dean wrote: > Hi Folks > > I wish to isolate certain changelog entries and display them to the > user, for example: > > Changelog.txt > > ----------Some Module ---------- M 000751 - Title >> what was amended > Reviewed by: Someone > > For this text file I wish to find all entries for 000751 and then > present each of the changelog entries. > > My thought was to > identify the "----" with a regular expression identifying this as the > changelog start You probably don't need a regex here, something like if line.startswith('----------'): will probably work > attempt to find the item number if line.split()[1] == '000751': > if it isn't found move on, if it is found then add this to a list. > > But I feel as though there must be a simpler and more effecient way. This sounds good to me except for the regex. Can you show us your code? Kent DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. From kent37 at tds.net Thu May 3 15:39:17 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 May 2007 09:39:17 -0400 Subject: [Tutor] Text matching In-Reply-To: References: <4639D972.20709@tds.net> Message-ID: <4639E605.6040809@tds.net> Gardner, Dean wrote: > Here is a test sample of what I have: This currently correctly > identifies the start and the end of the changelog entries and I can > identify the requested item records. What I am struggling with at > present is to how to create records of the full changelog entries for > each of the found items. > > Again any help greatly appreciated. > > > uid = "000028.txt" > > > file = open("C:\projects\SuiteSpecification\Notes\ChangeLog.txt") > > output = file.readlines() > changeLogList = [] > itemList = [] > for strOut in output: > > if "----" in strOut: > changeLogStart = 1 > itemList.append(strOut) > if "Reviewed:" in strOut: > changeLogStart=0 > for item in itemList: > if uid in item: > print item I usually solve problems like this by pulling multiple lines from the file within the loop. Something like this: f = open('...ChangeLog.txt') try: while True: line = f.next() if line.startswith('----'): line1 = line line2 = f.next() line3 = f.next() line4 = f.next() # Do something to process the lines line = f.next() except StopIteration: pass The basic idea is that you can collect multiple lines by calling f.next() explicitly inside the loop. Kent From Dean.Gardner at barco.com Thu May 3 15:46:10 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Thu, 3 May 2007 15:46:10 +0200 Subject: [Tutor] Text matching In-Reply-To: <4639E605.6040809@tds.net> References: <4639D972.20709@tds.net> <4639E605.6040809@tds.net> Message-ID: Thanks I will try that. Your help is very much appreciated. Dean Gardner Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com dean.gardner at barco.com -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: 03 May 2007 14:39 To: Gardner, Dean Cc: tutor at python.org Subject: Re: [Tutor] Text matching Gardner, Dean wrote: > Here is a test sample of what I have: This currently correctly > identifies the start and the end of the changelog entries and I can > identify the requested item records. What I am struggling with at > present is to how to create records of the full changelog entries for > each of the found items. > > Again any help greatly appreciated. > > > uid = "000028.txt" > > > file = open("C:\projects\SuiteSpecification\Notes\ChangeLog.txt") > > output = file.readlines() > changeLogList = [] > itemList = [] > for strOut in output: > > if "----" in strOut: > changeLogStart = 1 > itemList.append(strOut) > if "Reviewed:" in strOut: > changeLogStart=0 > for item in itemList: > if uid in item: > print item I usually solve problems like this by pulling multiple lines from the file within the loop. Something like this: f = open('...ChangeLog.txt') try: while True: line = f.next() if line.startswith('----'): line1 = line line2 = f.next() line3 = f.next() line4 = f.next() # Do something to process the lines line = f.next() except StopIteration: pass The basic idea is that you can collect multiple lines by calling f.next() explicitly inside the loop. Kent DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. From bill at celestial.net Thu May 3 17:32:37 2007 From: bill at celestial.net (Bill Campbell) Date: Thu, 3 May 2007 08:32:37 -0700 Subject: [Tutor] os.path.join question In-Reply-To: <001201c78d28$154ca020$dde17744@dunamis34752e9> References: <001201c78d28$154ca020$dde17744@dunamis34752e9> Message-ID: <20070503153237.GA17584@ayn.mi.celestial.com> On Wed, May 02, 2007, Jason Coggins wrote: > > Is it possible to use os.path.join to link to a file located in the > directory above where you are currently located? os.path.join('..', filename) os.path.realpath(os.path.join('..', filename)) Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``Democracy extends the sphere of individual freedom, Democracy attaches all possible value to each man, while socialism makes each man a mere agent, a mere number. Democracy and socialism have nothing in common but one word: equality. But notice the difference: while democracy seeks equality in liberty, socialism seeks equality in restraint and servitude.'' de Tocqueville == 1848 From 3dbernard at gmail.com Thu May 3 18:04:41 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 3 May 2007 12:04:41 -0400 Subject: [Tutor] Regular expression questions Message-ID: <61d0e2b40705030904v2d7726f7k3b9d5e2e43e5d88e@mail.gmail.com> Hello, Once again struggling with regular expressions. I have a string that look like "something_shp1". I want to replace "_shp1" by "_shp". I'm never sure if it's going to be 1, if there's going to be a number after "_shp". So I'm trying to use regular expression to perform this replacement. But I just can't seem to get a match! I always get a None match. I would think that this would have done the job: r = re.compile( r"(_shp\d)$" ) The only way I have found to get a match, is using r = re.compile( r"(\S+_shp\d)$" ) My second question is related more to the actual string replacement. Using regular expressions, what would be the way to go? I have tried the following: newstring = r.sub( '_shp', oldstring ) But the new string is always "_shp" instead of "something_shp". Thanks Bernard From john.clark at cabbage-rose.com Thu May 3 17:11:26 2007 From: john.clark at cabbage-rose.com (John Clark) Date: Thu, 3 May 2007 11:11:26 -0400 Subject: [Tutor] New York City Python Users Group Meeting - Tuesday May 8th Message-ID: <00b101c78d95$53be1c40$fefea8c0@haengma> Greetings! The next New York City Python Users Group meeting is this Tuesday, May 8th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. RSVP to clajo04 at mac.com to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython/ Hope to see you there! -John -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070503/0b1c52e5/attachment.htm From kent37 at tds.net Thu May 3 21:43:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 May 2007 15:43:45 -0400 Subject: [Tutor] Regular expression questions In-Reply-To: <61d0e2b40705030904v2d7726f7k3b9d5e2e43e5d88e@mail.gmail.com> References: <61d0e2b40705030904v2d7726f7k3b9d5e2e43e5d88e@mail.gmail.com> Message-ID: <463A3B71.5010805@tds.net> Bernard Lebel wrote: > Hello, > > Once again struggling with regular expressions. > > I have a string that look like "something_shp1". > I want to replace "_shp1" by "_shp". I'm never sure if it's going to > be 1, if there's going to be a number after "_shp". > > So I'm trying to use regular expression to perform this replacement. > But I just can't seem to get a match! I always get a None match. > > I would think that this would have done the job: > > r = re.compile( r"(_shp\d)$" ) > > The only way I have found to get a match, is using > > r = re.compile( r"(\S+_shp\d)$" ) My guess is you are calling r.match() rather than r.search(). r.match() only looks for matches at the start of the string; r.search() will find a match anywhere. > My second question is related more to the actual string replacement. > Using regular expressions, what would be the way to go? I have tried > the following: > > newstring = r.sub( '_shp', oldstring ) > > But the new string is always "_shp" instead of "something_shp". Because your re matches something_shp. I think newstring = re.sub('_shp\d' '_shp', oldstring ) will do what you want. Kent From arthur at nowsol.com Thu May 3 21:48:12 2007 From: arthur at nowsol.com (Arthur Coleman) Date: Thu, 3 May 2007 12:48:12 -0700 Subject: [Tutor] C API Tutorial Class Question Message-ID: <013701c78dbb$fc198480$1fa8a8c0@nowsol.com> I am using Windows XP and have successfully build the Boost libraries, plus boost_python.dll. I am trying to work through the C API tutorial where the file hello.cpp is found at libs/python/example/tutorial. I have been able to compile and execute the first example building the supplied hello.cpp file that allows Python to import a C function, but when I move onto the next example in the tutorial: struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; #include using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_("World") .def("greet", &World::greet) .def("set", &World::set) ; } I replace the original contents of hello.cpp with the above code and using bjam tried to build hello.pyd. I receive the following errors: ...found 1513 targets... ...updating 4 targets... vc-C++ bin\tutorial\hello.pyd\vc-8_0\debug\threading-multi\hello.obj hello.cpp hello.cpp(22) : error C2976: 'boost::python::class_' : too few template arguments G:\boost_1_33_1\boost/python/def_visitor.hpp(14) : see declaration of 'boost::python::class_' hello.cpp(22) : error C2440: '' : cannot convert from 'const char [6]' to 'boost::python::class_' Source or target has incomplete type hello.cpp(22) : error C2228: left of '.def' must have class/struct/union hello.cpp(22) : error C2228: left of '.def' must have class/struct/union hello.cpp(22) : error C2143: syntax error : missing ';' before '}' CALL "C:\Program Files\Microsoft Visual Studio 8\VC\bin\vcvars32.BAT" >nul "C:\Program Files\Microsoft Visual Studio 8\VC\bin\cl" /Zm800 -nologo /EHsc -c -DBOOST_PYTHON_DYNAMIC_LIB /Z7 /Od /Ob0 /EHsc /GR /MDd /Zc:forScope /Zc:wchar_t -I"bin\tutorial" -I"G:\boost_1_33_1" -I"c:\Python25\include" -Fo"bin\tutorial\hello.pyd\vc-8_0\debug\threading-multi\hello.obj" -Tp"hello.cpp" ...failed vc-C++ bin\tutorial\hello.pyd\vc-8_0\debug\threading-multi\hello.obj... ...skipped <@tutorial\hello.pyd\vc-8_0\debug\threading-multi>hello.CMD for lack of <@tutorial\hello.pyd\vc-8_0\debug\threading-multi>hello.obj... ...skipped <@tutorial\hello.pyd\vc-8_0\debug\threading-multi>hello.pyd for lack of <@tutorial\hello.pyd\vc-8_0\debug\threading-multi>hello.CMD... ...skipped <@tutorial\hello.pyd\vc-8_0\debug\threading-multi>hello.lib for lack of <@tutorial\hello.pyd\vc-8_0\debug\threading-multi>hello.CMD... ...failed updating 1 target... ...skipped 3 targets... I reviewed the definition of class_ in file def_visitor.hpp and found that it was defined as: template class class_; I have tried searching the FAQ and the Web and so far no luck. I would appreciate any help. Arthur -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070503/aaaeb344/attachment-0001.html From 3dbernard at gmail.com Thu May 3 22:46:12 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 3 May 2007 16:46:12 -0400 Subject: [Tutor] Regular expression questions In-Reply-To: <463A3B71.5010805@tds.net> References: <61d0e2b40705030904v2d7726f7k3b9d5e2e43e5d88e@mail.gmail.com> <463A3B71.5010805@tds.net> Message-ID: <61d0e2b40705031346m200c4697ke4f9ff83da99c75f@mail.gmail.com> Thanks a lot Kent, that indeed solves the issues altogether. Cheers Bernard On 5/3/07, Kent Johnson wrote: > Bernard Lebel wrote: > > Hello, > > > > Once again struggling with regular expressions. > > > > I have a string that look like "something_shp1". > > I want to replace "_shp1" by "_shp". I'm never sure if it's going to > > be 1, if there's going to be a number after "_shp". > > > > So I'm trying to use regular expression to perform this replacement. > > But I just can't seem to get a match! I always get a None match. > > > > I would think that this would have done the job: > > > > r = re.compile( r"(_shp\d)$" ) > > > > The only way I have found to get a match, is using > > > > r = re.compile( r"(\S+_shp\d)$" ) > > My guess is you are calling r.match() rather than r.search(). r.match() > only looks for matches at the start of the string; r.search() will find > a match anywhere. > > > My second question is related more to the actual string replacement. > > Using regular expressions, what would be the way to go? I have tried > > the following: > > > > newstring = r.sub( '_shp', oldstring ) > > > > But the new string is always "_shp" instead of "something_shp". > > Because your re matches something_shp. > > I think > newstring = re.sub('_shp\d' '_shp', oldstring ) > will do what you want. > > Kent > From tms43 at clearwire.net Fri May 4 00:15:02 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Thu, 3 May 2007 15:15:02 -0700 Subject: [Tutor] canvas -> make an object 'seem' to move Message-ID: <0C3757779992458D81F17ECB03E89989@TeresPC> Hi all: I am working on a program that will take a .gif and move it from origin, along a path where the mouse clicks. I understand that the move is simply changing the coordinates. I can place several .gif's on the canvas, but I would like to make the previous image go away (delete or be removed) and thus far been unable to do that. The example program I wrote simply takes the image and moves it. I should mention that I've tried 'move() and coord()' to get the object to move, but I am not getting the effect I want. When I use move in successive steps it just appears at the last move coordinates. And when I try to use delete, well, it doesn't work, I get an error message. I should mention that I'm using python25. Here is my rather early example code: from Tkinter import * root = Tk() root.title("Click me!") def next_image(event): global x, y, photo photoId = canvas1.create_image(x, y, image=photo) # I realize this isn't the best way to do it, but until I get something working... canvas1.create_image(x+10, y, image=photo) # this seems more successful, but the image remains canvas1.create_image(x+20, y, image=photo) # after I click. I don't want the image to remain, canvas1.create_image(x+30, y, image=photo) # I actually want to see a slow deliberate movement canvas1.create_image(x+40, y, image=photo) # to the final spot. canvas1.create_image(x+50, y, image=photo) canvas1.create_image(x+60, y, image=photo) canvas1.create_image(x+70, y, image=photo) #canvas1.move(, 100, 0) image = "DustY1.GIF" # use any gif, this is a cartoon of my dog photo = PhotoImage(file=image) # make canvas the size of image1/photo1 width1 = photo.width() height1 = photo.height() canvas1 = Canvas(width=width1, height=height1) canvas1.pack() # display photo, x, y is center x = (width1)/2.0 y = (height1)/2.0 # this is the first image canvas1.create_image(x, y, image=photo) canvas1.bind('', next_image) # bind left mouse click root.mainloop() Thank you for your help! T -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070503/4f3abb4e/attachment.htm From john at fouhy.net Fri May 4 01:36:22 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 4 May 2007 11:36:22 +1200 Subject: [Tutor] canvas -> make an object 'seem' to move In-Reply-To: <0C3757779992458D81F17ECB03E89989@TeresPC> References: <0C3757779992458D81F17ECB03E89989@TeresPC> Message-ID: <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> On 04/05/07, Teresa Stanton wrote: > the image and moves it. I should mention that I've tried 'move() and > coord()' to get the object to move, but I am not getting the effect I want. > When I use move in successive steps it just appears at the last move > coordinates. My Tkinter is quite rusty, but I think this is basically the approach you need to take. However, you will need to put a delay in between each call to coords, otherwise python will "optimise" by moving the image to its final destination before drawing. Something like: # given initial coords (x0,y0), final coords (x1, y1) img = canvas1.create_image(x0, y0, image=photo) # step: number of steps to move in step = 10.0 # duration: number of seconds to move the image dur = 2 for i in range(1, int(step)+1): xi = x0 + i*(x1-x0)/step yi = y0 + i*(y1-y0)/step canvas1.coords(img, xi, yi) time.sleep(dur/step) # you may need to add a call to canvas1.update_idletasks() here # untested HTH! -- John. From jcoggins828 at charter.net Fri May 4 03:28:25 2007 From: jcoggins828 at charter.net (Jason Coggins) Date: Thu, 3 May 2007 21:28:25 -0400 Subject: [Tutor] What's wrong with this? Message-ID: <008d01c78deb$8352ef70$59147044@dunamis34752e9> I have the following function in a program: os.popen('filename.py') What I want to do is launch the program in the os.popen() function. The file I am trying to launch is located in the same directory as the program the function is contained in. I also use Linux if that makes a difference. Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070503/f76b7d45/attachment.htm From andre.roberge at gmail.com Fri May 4 03:40:21 2007 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 3 May 2007 22:40:21 -0300 Subject: [Tutor] What's wrong with this? In-Reply-To: <008d01c78deb$8352ef70$59147044@dunamis34752e9> References: <008d01c78deb$8352ef70$59147044@dunamis34752e9> Message-ID: <7528bcdd0705031840ycd20c62mcfabfaaa4ea96203@mail.gmail.com> Perhaps the following might be helpful: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f1b60f4739591d6b/4417f807848b4b5d?lnk=gst&q=launching&rnum=4#4417f807848b4b5d (if the link does not work, google for "launching python program cross-platform" or go to http://aspn.activestate.com/ASPN/Mail/Message/python-list/3467794) Andr? On 5/3/07, Jason Coggins wrote: > > > I have the following function in a program: > > os.popen('filename.py') > > What I want to do is launch the program in the os.popen() function. The > file I am trying to launch is located in the same directory as the program > the function is contained in. I also use Linux if that makes a difference. > > Jason > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From Dean.Gardner at barco.com Fri May 4 10:27:46 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Fri, 4 May 2007 10:27:46 +0200 Subject: [Tutor] Text matching In-Reply-To: <4639E605.6040809@tds.net> References: <4639D972.20709@tds.net> <4639E605.6040809@tds.net> Message-ID: So here it is....it might not be pretty (it seems a bit un-python like to me) but it works exactly as required. If anyone can give any tips for possible optimisation or refactor I would be delighted to hear from them. Thanks uid = self.item.Uid() record=[] logList=[] displayList=[] f = open(filename) logTextFile="temp.txt" """ searched through the changelog 'breaking' it up into individual entries""" try: while 1: endofRecord=0 l = f.next() if l.startswith("----"): record.append(l) l=f.next() while endofRecord==0: if "Reviewed: 000" not in l: record.append(l) l=f.next() else: logList.append(record) record=[] endofRecord=1 except StopIteration: pass """ searches to determine if we can find entries for a particualr item""" for record in logList: currRec = record for item in currRec: if uid in item: displayList.append(currRec) """ creates a temporary file to write our find results to """ removeFile = os.path.normpath( os.path.join(os.getcwd(), logTextFile)) # if the file exists, get rid of it before writing our new findings if Shared.config.Exists(removeFile): os.remove(removeFile) recordLog = open(logTextFile,"a") for record in range(len(displayList)): for item in displayList[record]: recordLog.write(item) recordLog.close() #display our results commandline = "start cmd /C " + logTextFile os.system(commandline) Dean Gardner Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com dean.gardner at barco.com -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: 03 May 2007 14:39 To: Gardner, Dean Cc: tutor at python.org Subject: Re: [Tutor] Text matching Gardner, Dean wrote: > Here is a test sample of what I have: This currently correctly > identifies the start and the end of the changelog entries and I can > identify the requested item records. What I am struggling with at > present is to how to create records of the full changelog entries for > each of the found items. > > Again any help greatly appreciated. > > > uid = "000028.txt" > > > file = open("C:\projects\SuiteSpecification\Notes\ChangeLog.txt") > > output = file.readlines() > changeLogList = [] > itemList = [] > for strOut in output: > > if "----" in strOut: > changeLogStart = 1 > itemList.append(strOut) > if "Reviewed:" in strOut: > changeLogStart=0 > for item in itemList: > if uid in item: > print item I usually solve problems like this by pulling multiple lines from the file within the loop. Something like this: f = open('...ChangeLog.txt') try: while True: line = f.next() if line.startswith('----'): line1 = line line2 = f.next() line3 = f.next() line4 = f.next() # Do something to process the lines line = f.next() except StopIteration: pass The basic idea is that you can collect multiple lines by calling f.next() explicitly inside the loop. Kent DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. From kent37 at tds.net Fri May 4 12:26:10 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 May 2007 06:26:10 -0400 Subject: [Tutor] Text matching In-Reply-To: References: <4639D972.20709@tds.net> <4639E605.6040809@tds.net> Message-ID: <463B0A42.6040100@tds.net> Gardner, Dean wrote: > > So here it is....it might not be pretty (it seems a bit un-python like > to me) but it works exactly as required. If anyone can give any tips for > possible optimisation or refactor I would be delighted to hear from > them. > > Thanks > > uid = self.item.Uid() > record=[] > logList=[] > displayList=[] > f = open(filename) > logTextFile="temp.txt" > """ searched through the changelog 'breaking' it up into > individual entries""" > try: > while 1: > endofRecord=0 > l = f.next() > if l.startswith("----"): > record.append(l) > l=f.next() > while endofRecord==0: > if "Reviewed: 000" not in l: > record.append(l) > l=f.next() > else: > logList.append(record) > record=[] > endofRecord=1 > except StopIteration: > pass I don't think you need endofRecord and the nested loops here. In fact I think you could use a plain for loop here. AFAICT all you are doing is accumulating records with no special handling for anything except the end records. What about this: record = [] for line in f: if "Reviewed: 000" in line: logList.append(record) record = [] else: record.append(line) > """ searches to determine if we can find entries for > a particualr item""" > for record in logList: > currRec = record > for item in currRec: > if uid in item: > displayList.append(currRec) The currRec variable is not needed, just use record directly. If uid can only be in a specific line of the record you can test that directly, e.g. for record in logList: if uid in record[1]: > """ creates a temporary file to write our find results to """ > removeFile = os.path.normpath( os.path.join(os.getcwd(), > logTextFile)) > > # if the file exists, get rid of it before writing our new > findings > if Shared.config.Exists(removeFile): > os.remove(removeFile) > recordLog = open(logTextFile,"a") > > for record in range(len(displayList)): > for item in displayList[record]: > recordLog.write(item) for record in displayList: recordLog.writelines(record) > recordLog.close() > #display our results > commandline = "start cmd /C " + logTextFile > os.system(commandline) > Kent From tms43 at clearwire.net Fri May 4 20:09:58 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Fri, 4 May 2007 11:09:58 -0700 Subject: [Tutor] canvas -> make an object 'seem' to move In-Reply-To: <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> References: <0C3757779992458D81F17ECB03E89989@TeresPC> <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> Message-ID: <6DB291888DE6480084E9582A3E47693D@TeresPC> Here is how I've changed it, based on your message and the errors I received while putting it together: # load and display several images using Tkinter # Tkinter reads only GIF and PGM/PPM images # (for additional formats use Image, ImageTk from PIL) from Tkinter import * import time root = Tk() root.title("Click me!") def next_image(event): x0 = 0 y0 = 0 x1 = 1 y1 = 0 photoId = canvas1.create_image(x0, y0, image=photo) step = 10.0 dur = .3 for i in range(1, int(step)+3): xi = x0 + i*(x1-x0)/step yi = y0 + i*(y1-y0)/step canvas1.coords(photoId, xi, yi) time.sleep(3) canvas1.update_idletasks() image = "DustY1.GIF" photo = PhotoImage(file=image) # make canvas the size of image1/photo1 width1 = photo.width() height1 = photo.height() canvas1 = Canvas(width=width1, height=height1) canvas1.pack() # display photo1, x, y is center (anchor=CENTER is default) x = (width1)/2.0 y = (height1)/2.0 canvas1.create_image(x, y, image=photo) canvas1.bind('', next_image) # bind left mouse click root.mainloop() its not really working at all now. I'm sure this is the right direction to go, but I'm still not getting anywhere. I tried using the update, but it didn't seem to do anything. At this point, I simply want movement from left to right. help... ? > On 04/05/07, Teresa Stanton wrote: >> the image and moves it. I should mention that I've tried 'move() and >> coord()' to get the object to move, but I am not getting the effect I >> want. >> When I use move in successive steps it just appears at the last move >> coordinates. > > My Tkinter is quite rusty, but I think this is basically the approach > you need to take. However, you will need to put a delay in between > each call to coords, otherwise python will "optimise" by moving the > image to its final destination before drawing. > > Something like: > > # given initial coords (x0,y0), final coords (x1, y1) > img = canvas1.create_image(x0, y0, image=photo) > > # step: number of steps to move in > step = 10.0 > # duration: number of seconds to move the image > dur = 2 > > for i in range(1, int(step)+1): > xi = x0 + i*(x1-x0)/step > yi = y0 + i*(y1-y0)/step > canvas1.coords(img, xi, yi) > time.sleep(dur/step) > # you may need to add a call to canvas1.update_idletasks() here > > # untested > > HTH! > > -- > John. > > From andreas at kostyrka.org Sat May 5 02:06:55 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 05 May 2007 02:06:55 +0200 Subject: [Tutor] What's wrong with this? In-Reply-To: <7528bcdd0705031840ycd20c62mcfabfaaa4ea96203@mail.gmail.com> References: <008d01c78deb$8352ef70$59147044@dunamis34752e9> <7528bcdd0705031840ycd20c62mcfabfaaa4ea96203@mail.gmail.com> Message-ID: <463BCA9F.5060604@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Andre Roberge wrote: > Perhaps the following might be helpful: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/f1b60f4739591d6b/4417f807848b4b5d?lnk=gst&q=launching&rnum=4#4417f807848b4b5d > > (if the link does not work, google for "launching python program > cross-platform" or go to > http://aspn.activestate.com/ASPN/Mail/Message/python-list/3467794) > Andr? > > On 5/3/07, Jason Coggins wrote: >> >> I have the following function in a program: >> >> os.popen('filename.py') >> >> What I want to do is launch the program in the os.popen() function. The >> file I am trying to launch is located in the same directory as the program >> the function is contained in. I also use Linux if that makes a difference. Well, first the current directory might not be the same as the directory where the script is stored. So you need something like this: import os, sys fp = op.popen(os.path.join(os.path.dirname(sys.argv[0]), "filename.py", "r") Andreas -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGO8qfHJdudm4KnO0RAvYTAKCtBp5ALtTWgtOCCbMfTBdqU7z71wCgxfNf FBkdKEoHOWX5c09Ru+bApcY= =J9pa -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Sat May 5 04:00:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 May 2007 03:00:28 +0100 Subject: [Tutor] What's wrong with this? References: <008d01c78deb$8352ef70$59147044@dunamis34752e9> Message-ID: "Jason Coggins" wrote > I have the following function in a program: > > os.popen('filename.py') So what happened? Did you get an error message? If so what? > What I want to do is launch the program in the os.popen() function. Do you want to lasunch it or interact with it. If its only launch then os.system might be easier. > The file I am trying to launch is located in the same directory > as the program the function is contained in. That may not be the same directory you start the program from. Its always safer to use (or build) the full path. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From marshall.jiang at gmail.com Sat May 5 19:13:22 2007 From: marshall.jiang at gmail.com (Shuai Jiang (Runiteking1)) Date: Sat, 5 May 2007 13:13:22 -0400 Subject: [Tutor] Convert .pyc to .py Message-ID: Hello, I was playing with pyInstaller and I moved the file to the directory. After I finished playing with it, I accidentally deleted it (I bypassed the recycle bin). Now I lost my project files and my file restoration didn't find it, but I still have the .pyc file though. I'm wondering weather I can convert the .pyc back to .py. I tried pyc2py but it came out with some weird stuff. Please help! Thanks Marshall -- I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals. Sir Winston Churchill -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070505/e791fcad/attachment.html From samrobertsmith at gmail.com Sat May 5 21:11:53 2007 From: samrobertsmith at gmail.com (linda.s) Date: Sat, 5 May 2007 12:11:53 -0700 Subject: [Tutor] version and path Message-ID: <1d987df30705051211w54d92bd3wffe678735c87aeef@mail.gmail.com> how to check how many versions of Python i have in my mac machine? also, how to put the path to the version I desire? Thanks a lot! From jason at asahnekec.com Sat May 5 21:50:33 2007 From: jason at asahnekec.com (Jason Coggins) Date: Sat, 5 May 2007 15:50:33 -0400 Subject: [Tutor] exec syntax Message-ID: <000c01c78f4e$a6000a30$bd157044@dunamis34752e9> Would someone please provide me with a simple example of the syntax to use the exec command to open a file. I can see how to use it to execute a script of code embedded in the program (that example was provided in the documentation) but I cannot figure out the syntax to use it to run another python program in another file. Thanks, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070505/09e4051c/attachment.htm From rikard.bosnjakovic at gmail.com Sat May 5 22:46:42 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Sat, 5 May 2007 22:46:42 +0200 Subject: [Tutor] exec syntax In-Reply-To: <000c01c78f4e$a6000a30$bd157044@dunamis34752e9> References: <000c01c78f4e$a6000a30$bd157044@dunamis34752e9> Message-ID: On 5/5/07, Jason Coggins wrote: > I can see how to use it to execute a script of code embedded in the program > (that example was provided in the documentation) but I cannot figure out the > syntax to use it to run another python program in another file. Use execfile(). -- - Rikard - http://bos.hack.org/cv/ From andreas at kostyrka.org Sun May 6 01:01:34 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 06 May 2007 01:01:34 +0200 Subject: [Tutor] Convert .pyc to .py In-Reply-To: References: Message-ID: <463D0CCE.9030004@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Check out http://www.crazy-compilers.com/decompyle/service.html Andreas Shuai Jiang (Runiteking1) wrote: > Hello, > > I was playing with pyInstaller and I moved the file to the directory. > After I finished playing with it, > I accidentally deleted it (I bypassed the recycle bin). Now I lost my > project files and my file > restoration didn't find it, but I still have the .pyc file though. > > I'm wondering weather I can convert the .pyc back to .py. I tried pyc2py > but it came out > with some weird stuff. > > Please help! > > Thanks > > Marshall > > > -- > I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as > equals. > Sir Winston Churchill > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGPQzOHJdudm4KnO0RAvMhAKDrXe6U+2tZBqfrfI/eKa36RB1VKgCePExI +2mxXCw0bNeL6PetA4i1KcU= =hcz6 -----END PGP SIGNATURE----- From marshall.jiang at gmail.com Sun May 6 01:12:44 2007 From: marshall.jiang at gmail.com (Shuai Jiang (Runiteking1)) Date: Sat, 5 May 2007 19:12:44 -0400 Subject: [Tutor] Convert .pyc to .py In-Reply-To: <463D0CCE.9030004@kostyrka.org> References: <463D0CCE.9030004@kostyrka.org> Message-ID: Is there no opensource (free) version? I'm a kid and I don't have a credit card or bank account. On 5/5/07, Andreas Kostyrka wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Check out http://www.crazy-compilers.com/decompyle/service.html > > Andreas > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.2 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFGPQzOHJdudm4KnO0RAvMhAKDrXe6U+2tZBqfrfI/eKa36RB1VKgCePExI > +2mxXCw0bNeL6PetA4i1KcU= > =hcz6 > -----END PGP SIGNATURE----- > -- I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals. Sir Winston Churchill From jason at asahnekec.com Sun May 6 02:30:27 2007 From: jason at asahnekec.com (Jason Coggins) Date: Sat, 5 May 2007 20:30:27 -0400 Subject: [Tutor] base directory Message-ID: <000801c78f75$c2d84f10$bd157044@dunamis34752e9> I am new to Linux. On Windows the base directory is c:\. If I wanted to open a file in a specific location in windows I would use a path such as c:\programs\fileName.py. What is the base directory for Linux? Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070505/2b7a5681/attachment.html From andreas at kostyrka.org Sun May 6 02:57:55 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 06 May 2007 02:57:55 +0200 Subject: [Tutor] base directory In-Reply-To: <000801c78f75$c2d84f10$bd157044@dunamis34752e9> References: <000801c78f75$c2d84f10$bd157044@dunamis34752e9> Message-ID: <463D2813.5020603@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Jason Coggins wrote: > I am new to Linux. On Windows the base directory is c:\. If I wanted > to open a file in a specific location in windows I would use a path such > as c:\programs\fileName.py. > > What is the base directory for Linux? / is called the root (directory). Andreas > > Jason > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGPSgTHJdudm4KnO0RAv5mAKCXIusXrDdI3ONt0KHd6R92cEdgnQCeOJzu PTfp7FuXYx6leWmGnzUCAvE= =2qQ1 -----END PGP SIGNATURE----- From washakie at gmail.com Sun May 6 11:20:21 2007 From: washakie at gmail.com (John Washakie) Date: Sun, 6 May 2007 11:20:21 +0200 Subject: [Tutor] Running and passing variables to/from Fortran Message-ID: I have a FORTRAN program which reads in unformatted sparse matrix data. Rather than rewriting the code in Python, I was hoping there is a way to call the Fortran program, passing filename variables TO Fortran, and returning the data (which is an array) back to my .py code for use there. Is there a simple example of this that someone knows of? From andreas at kostyrka.org Sun May 6 11:51:43 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 06 May 2007 11:51:43 +0200 Subject: [Tutor] Running and passing variables to/from Fortran In-Reply-To: References: Message-ID: <463DA52F.8070801@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Simple is the wrong idea. But I'd guess that you can access your Fortan from C. If so, Pyrex provides a C-for-Python-coder tool. OTOH, just reading the stuff in Python might be simpler than doing all the interfacing. (I presume that you are just reading the data. If you have verified working numeric code in Fortran, it's probably worthwhile to interface with it instead of porting it). Andreas John Washakie wrote: > I have a FORTRAN program which reads in unformatted sparse matrix > data. Rather than rewriting the code in Python, I was hoping there is > a way to call the Fortran program, passing filename variables TO > Fortran, and returning the data (which is an array) back to my .py > code for use there. > > Is there a simple example of this that someone knows of? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGPaUvHJdudm4KnO0RAtj2AJ9qqOxK0IxompMORJLEz7x62M8GSACdFSj/ kMxIV3hwO8eMPYG1FhYVLOQ= =zZXq -----END PGP SIGNATURE----- From rohan.deshpande at gmail.com Sun May 6 15:42:12 2007 From: rohan.deshpande at gmail.com (Rohan Deshpande) Date: Sun, 6 May 2007 14:42:12 +0100 Subject: [Tutor] when to introduce classes Message-ID: Hi All, I am wondering when is a good time to introduce classes into a python program. Is there any rule of thumb as to when they are necessary, and when it is okay to just stick with regular functions and variables? I.e. you have self defined methods and data working on the same type of task? Thank you. -Rohan From agilfoy at frontiernet.net Sun May 6 16:28:28 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sun, 06 May 2007 14:28:28 +0000 Subject: [Tutor] Working with error messages Message-ID: <20070506142828.8md7kk0wunk8os0s@webmail.frontiernet.net> I have a number-to-Roman numeral program that churns out ValueError messages with a few improper input cases: 1. not an integer 2. larger than 3999 3. smaller than 0 When I run the program via IDLE, and I give one of these improper inputs, the interpreter closes down the program and then displays the appropriate ValueError message. I would like the appropriate ValueError message to be displayed before the program shuts down, or at least a generic ValueError message. Is looking at my specific pieces of code necessary to help with this? I want this because if the program's being run as an application, the application window closes down as soon as the program closes, and the user doesn't get to see the message. [When I doubleclick on the .py file in Windows Explorer, it runs as a .exe, for example.] -- "Computers were the first God-Satan collaboration project." "Blind faith in bad leadership is not patriotism." "One of the most horrible features of war is that all the war-propaganda, all the screaming and lies and hatred, comes invariably from people who are not fighting."-George Orwell, _Homage to Catalonia From andreengels at gmail.com Sun May 6 16:40:07 2007 From: andreengels at gmail.com (Andre Engels) Date: Sun, 6 May 2007 16:40:07 +0200 Subject: [Tutor] Working with error messages In-Reply-To: <20070506142828.8md7kk0wunk8os0s@webmail.frontiernet.net> References: <20070506142828.8md7kk0wunk8os0s@webmail.frontiernet.net> Message-ID: <6faf39c90705060740l1042b03aj2111365eb5f13075@mail.gmail.com> 2007/5/6, Alan Gilfoy : > I have a number-to-Roman numeral program that churns out ValueError > messages with a few improper input cases: > > 1. not an integer > 2. larger than 3999 > 3. smaller than 0 > > When I run the program via IDLE, and I give one of these improper > inputs, the interpreter closes down the program and then displays the > appropriate ValueError message. > > I would like the appropriate ValueError message to be displayed before > the program shuts down, or at least a generic ValueError message. > > Is looking at my specific pieces of code necessary to help with this? > > I want this because if the program's being run as an application, the > application window closes down as soon as the program closes, and the > user doesn't get to see the message. [When I doubleclick on the .py > file in Windows Explorer, it runs as a .exe, for example.] You could try something like: try: except ValueError: raw_input("I got a ValueError. Press enter to end the program.") raise Of course, the more appropriate thing to do would be to catch the error at a lower level than the whole program - check where you get the ValueError, put that line in a try, and take an appropriate action in the except. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From jason at asahnekec.com Sun May 6 17:11:33 2007 From: jason at asahnekec.com (Jason Coggins) Date: Sun, 6 May 2007 11:11:33 -0400 Subject: [Tutor] command lines Message-ID: <000a01c78ff0$d6856d60$bd157044@dunamis34752e9> Is there a way to send a command to the Linux Terminal from inside a Python program? Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070506/0c3e0966/attachment.htm From rikard.bosnjakovic at gmail.com Sun May 6 17:44:23 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Sun, 6 May 2007 17:44:23 +0200 Subject: [Tutor] command lines In-Reply-To: <000a01c78ff0$d6856d60$bd157044@dunamis34752e9> References: <000a01c78ff0$d6856d60$bd157044@dunamis34752e9> Message-ID: On 5/6/07, Jason Coggins wrote: > Is there a way to send a command to the Linux Terminal from inside a Python > program? os.system(), os.popen(), etc. -- - Rikard - http://bos.hack.org/cv/ From kent37 at tds.net Sun May 6 18:48:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 May 2007 12:48:20 -0400 Subject: [Tutor] when to introduce classes In-Reply-To: References: Message-ID: <463E06D4.3050304@tds.net> Rohan Deshpande wrote: > Hi All, > > I am wondering when is a good time to introduce classes into a python > program. Is there any rule of thumb as to when they are necessary, > and when it is okay to just stick with regular functions and > variables? http://personalpages.tds.net/~kent37/stories/00014.html Kent From emilia12 at mail.bg Sun May 6 19:34:07 2007 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Sun, 06 May 2007 20:34:07 +0300 Subject: [Tutor] Running and passing variables to/from In-Reply-To: References: Message-ID: <1178472847.3f05858477742@mail.bg> hi john, what about f2py - Fortran to Python interface generator Port description for lang/f2py Writing Python C/API wrappers for Fortran routines can be a very tedious task, especially if a Fortran routine takes more than 20 arguments but only few of them are relevant for the problems that they solve. So, I have developed a tool that generates the C/API modules containing wrapper functions of Fortran routines. I call this tool as F2PY - Fortran to Python Interface Generator. It is completely written in Python language and can be called from the command line as f2py. WWW: http://cens.ioc.ee/projects/f2py2e/ e. ----------------------------- SCENA - ???????????? ????????? ???????? ?? ??????? ??????????? ? ??????????. http://www.bgscena.com/ From akap at isd.dp.ua Mon May 7 08:43:25 2007 From: akap at isd.dp.ua (Alexander Kapshuk) Date: Mon, 7 May 2007 09:43:25 +0300 Subject: [Tutor] can python run under windows 95? Message-ID: <70831DC71E5D814C9D1FA8A96653215E090D622B@server.isd.dp.ua> Hello Everyone, Quick question ... I've got an old Toshiba Satellite 110CT laptop with Windows 95 installed on it. It's got 40 MB of RAM and a 3 GB hard drive. Would I be able to run Python on it? If so, what version of Python should I install? I've tried installing Python 2.5 on it, but got a message saying that the installation file could not be unpacked. What could the problem be? Thanking you all in advance and looking forward to hearing from you, Alexander Kapshuk. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070507/a7adb0b4/attachment.htm From wheresdave at gmail.com Mon May 7 12:59:07 2007 From: wheresdave at gmail.com (Dave C) Date: Mon, 7 May 2007 03:59:07 -0700 Subject: [Tutor] trying to figure out what this means Message-ID: when you are doing print these two characters keep showing up in this book "%s" % What do they do? here is example of complete command. print "%s" % last_names[-2] Thank you, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070507/a73e93ba/attachment.htm From rikard.bosnjakovic at gmail.com Mon May 7 13:22:57 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Mon, 7 May 2007 13:22:57 +0200 Subject: [Tutor] trying to figure out what this means In-Reply-To: References: Message-ID: On 5/7/07, Dave C wrote: > when you are doing print these two characters keep showing up in this book > "%s" % > > What do they do? http://docs.python.org/lib/typesseq-strings.html -- - Rikard - http://bos.hack.org/cv/ From amonroe at columbus.rr.com Mon May 7 13:09:01 2007 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 7 May 2007 07:09:01 -0400 Subject: [Tutor] trying to figure out what this means In-Reply-To: References: Message-ID: <19132782200.20070507070901@columbus.rr.com> > when you are doing print these two characters keep showing up in this book > "%s" % > What do they do? "Fill in the blank" Kind of like generic paper forms where they have a blank underline for you to fill in your information. Give it a variable name, and it will fill in the "blank" (the %s) with the variable's value. Alan From andreas at kostyrka.org Mon May 7 21:49:27 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 07 May 2007 21:49:27 +0200 Subject: [Tutor] can python run under windows 95? In-Reply-To: <70831DC71E5D814C9D1FA8A96653215E090D622B@server.isd.dp.ua> References: <70831DC71E5D814C9D1FA8A96653215E090D622B@server.isd.dp.ua> Message-ID: <463F82C7.8060301@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm almost sure that Python as such runs on Win95. Some modules might not. But I'm also almost sure that the installer is not Win95 compatible. Andreas Alexander Kapshuk wrote: > Hello Everyone, > > > > Quick question ? > > > > I?ve got an old Toshiba Satellite 110CT laptop with Windows 95 installed > on it. It?s got 40 MB of RAM and a 3 GB hard drive. > > > > Would I be able to run Python on it? If so, what version of Python > should I install? > > > > I?ve tried installing Python 2.5 on it, but got a message saying that > the installation file could not be unpacked. What could the problem be? > > > > Thanking you all in advance and looking forward to hearing from you, > > > > Alexander Kapshuk. > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGP4LHHJdudm4KnO0RAliSAJ9OZcEexkHUmgzUor4SLF2yVY+u3gCffN/5 ISidyBUIkCiXHBZJcr3IFrU= =rqQK -----END PGP SIGNATURE----- From rdm at rcblue.com Mon May 7 22:53:08 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 07 May 2007 13:53:08 -0700 Subject: [Tutor] can python run under windows 95? In-Reply-To: <463F82C7.8060301@kostyrka.org> References: <70831DC71E5D814C9D1FA8A96653215E090D622B@server.isd.dp.ua> <463F82C7.8060301@kostyrka.org> Message-ID: <20070507205320.6989C1E4002@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070507/f8b7c0c4/attachment.html From tms43 at clearwire.net Mon May 7 23:56:25 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Mon, 7 May 2007 14:56:25 -0700 Subject: [Tutor] canvas -> make an object 'seem' to move In-Reply-To: <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> References: <0C3757779992458D81F17ECB03E89989@TeresPC> <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> Message-ID: <3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC> Thank you, that was the correct direction. What I ended up doing is this: def onClickVertical(newY, xp, yp): for i in range(newY): #nextX gives how many steps to the next position yp += .8 #moves to correct position canvasOne.coords(ph, xp, yp) time.sleep(.001) #creep along at a nice pace canvsasOne.update() It will move on the event, but then it moves back to the beginning and moves again after its been clicked. I had posted in the Tkinter messageboard previously, but no one responded. I am thinking that one is .... dead (for lack of a better term). I seem to be stuck again. I've attached my entire file (and the .gif I'm using. My son made this .gif, its our lab). The problem is my xp (the variable I use for my x coordinate) isn't updating after the .gif moves. I think I should probably organize the entire module better, but then again, I've never written anything this big in Python, and nothing like this in Tkinter. So, perhaps someone will have a suggestion? Thank you T ----- Original Message ----- From: "John Fouhy" To: "Teresa Stanton" Cc: Sent: Thursday, May 03, 2007 4:36 PM Subject: Re: [Tutor] canvas -> make an object 'seem' to move > On 04/05/07, Teresa Stanton wrote: >> the image and moves it. I should mention that I've tried 'move() and >> coord()' to get the object to move, but I am not getting the effect I >> want. >> When I use move in successive steps it just appears at the last move >> coordinates. > > My Tkinter is quite rusty, but I think this is basically the approach > you need to take. However, you will need to put a delay in between > each call to coords, otherwise python will "optimise" by moving the > image to its final destination before drawing. > > Something like: > > # given initial coords (x0,y0), final coords (x1, y1) > img = canvas1.create_image(x0, y0, image=photo) > > # step: number of steps to move in > step = 10.0 > # duration: number of seconds to move the image > dur = 2 > > for i in range(1, int(step)+1): > xi = x0 + i*(x1-x0)/step > yi = y0 + i*(y1-y0)/step > canvas1.coords(img, xi, yi) > time.sleep(dur/step) > # you may need to add a call to canvas1.update_idletasks() here > > # untested > > HTH! > > -- > John. > > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: canvasBack.pyw Url: http://mail.python.org/pipermail/tutor/attachments/20070507/4038f1f1/attachment-0001.asc From john at fouhy.net Tue May 8 00:22:23 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 8 May 2007 10:22:23 +1200 Subject: [Tutor] canvas -> make an object 'seem' to move In-Reply-To: <3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC> References: <0C3757779992458D81F17ECB03E89989@TeresPC> <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> <3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC> Message-ID: <5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com> On 08/05/07, Teresa Stanton wrote: > I seem to be stuck again. I've attached my entire file (and the .gif I'm > using. My son made this .gif, its our lab). The problem is my xp (the > variable I use for my x coordinate) isn't updating after the .gif moves. I > think I should probably organize the entire module better, but then again, > I've never written anything this big in Python, and nothing like this in > Tkinter. So, perhaps someone will have a suggestion? Some general comments: """ #This will build the north (top) wall of the maze canvasOne.create_line(10, 10, 790, 10, width = 3, fill = 'blue') #west to east canvasOne.create_line(20, 20, 395, 20, width = 3, fill = 'blue') #2nd line, west to middle canvasOne.create_line(395, 20, 395, 100, width = 3, fill = 'blue') #middle to south canvasOne.create_line(405, 20, 405, 100, width = 3, fill = 'blue')#2nd middle to south canvasOne.create_line(395, 100, 405, 100, width = 3, fill = 'blue') #short west to east canvasOne.create_line(405, 20, 780, 20, width = 3, fill = 'blue') #2nd line cont, middle to east """ This would be a good opportunity to define some functions. eg, you could do this: canvasOne = Canvas(width = 800, height = 700, bg = 'black') canvasOne.pack() def createWall((x0, y0), (x1, y1), colour='blue', width=3): """ Create a wall from (x0, y0) to (x1, y1). """ canvasOne.create_line(x0, y0, x1, y1, width=width, fill=colour) Then ... hmm, I see from running your code that your lines are all effectively continuous. So you could represent each wall by a series of points. eg: outerWall = [(10,10), (790,10), (790, 360), ...] # etc innerWall1 = [...] # etc walls = [outerWall, innerWall1, ...] Then you could draw them like: for wall in walls: for i in range(len(wall-1)): createWallall(outerWall[i], outerWall[i+1]) Second comment: """ xp = 100 yp = 600 # ... #onClick Vertical moves the .gif based on where the mouse is clicked #newY is new location for yp def onClickVertical(newY, xp, yp): print 'here' for i in range(newY): yp += .8 canvasOne.coords(ph, xp, yp) time.sleep(.001) canvasOne.update() return xp, yp """ I notice you have a statement: yp += .8 in this function. Are you aware that this will _not_ change the value of yp outside the scope of the function? If you want to change yp in the global scope, you need to tell python to treat it as a global variable, by putting the statement 'global yp' near the top of that function. A better course of action (global variables are a bit ugly) might be to encapsulate your maze into a class. eg: class Maze(object): def __init__(self): # initial position of actor self.xp = 100 self.yp = 600 # create maze, etc. def onClickVertical(self, newY, xp, yp): # etc HTH! -- John. From minyie at hotmail.com Tue May 8 03:23:07 2007 From: minyie at hotmail.com (Antonio Diaz) Date: Tue, 08 May 2007 01:23:07 +0000 Subject: [Tutor] Basic image editing program in python Message-ID: Hello!. I have a project in school and I was wondering if its possible to make a python program that uses Imaging library to make a GUI of the same functions that Imaging has. To make the program open the images inside the main program. If its possible to make it in glade.? And if all answers were possitive, where can i find documentation or tutorials? that can help me? (i hope) Thanks a lot in advance! _________________________________________________________________ Watch free concerts with Pink, Rod Stewart, Oasis and more.? Visit MSN In Concert today. http://music.msn.com/presents?icid=ncmsnpresentstagline From super_krital_000 at hotmail.com Tue May 8 08:07:33 2007 From: super_krital_000 at hotmail.com (super krital) Date: Tue, 08 May 2007 16:07:33 +1000 Subject: [Tutor] Help python coding not working Message-ID: Hi need to get this program running for school so my teacher said to use the forum etc. Its working fine except its not comparing my guess with the result. im only having trouble with the second half or def update_text_count can you please help find a solution so my program works please. i dont see why it is not. #Krital #Guess my number game assignment from Tkinter import * import random class Application(Frame): """GUI Application for game difficulty.""" def __init__(self,master): """initialise frame.""" Frame.__init__(self,master) self.grid() self.bttn3_clicks=0 self.create_widgets() #Creating user instruction labels def create_widgets(self): #create widgets for difficulty levels #create description label Label(self, text="Choose your difficalty level" ).grid(row=0,column=0,sticky=W) Label(self, text="Select one:" ).grid(row=1,column=0,sticky=W) #Since only one radio button can be selected, they share one special object that #reflects which of the radio buttons is selected. This object needs to be an instance of the #StringVar class frpm the Tkinter module, which allows a string to be stored and retrieved. #create a variable for game difficulty self.difficulty = StringVar() #Create the Easy radio button Radiobutton(self, text="Easy", variable=self.difficulty, value="easy", command=self.random_number ).grid(row=2, column=0, sticky=W) Radiobutton(self, text="Medium", variable=self.difficulty, value="medium", command=self.random_number ).grid(row=3, column=0, sticky=W) Radiobutton(self, text="Hard", variable=self.difficulty, value="hard", command=self.random_number ).grid(row=4, column=0, sticky=W) self.bttn = Button(self) self.bttn["text"]="Exit" self.bttn["command"]=self.stop self.bttn.grid(row=23,column=1,sticky=W) self.bttn2 = Button(self) self.bttn2["text"]="Reset" self.bttn2["command"]=self.reset self.bttn2.grid(row=23,column=0,sticky=W) #using the Grid layout manager to be specific about the labels placement self.inst_lbl=Label(self,text="Please guess a number.") self.inst_lbl.grid(row=6,column=0,columnspan=2, sticky=W) #Sticky W means the label is forced to the west-or is left justified! #sticky can be N,S,E or W #creating an entry widget to make a guess self.guess=Entry(self) self.guess.grid(row=7,column=0,sticky=W) #self.guess.focus_set() self.bttn3=Button(self,text="Total Goes=0",relief=FLAT,command=self.update_text_count) self.bttn3.grid(row=8,column=0, sticky=W) #create a button to enter the guess self.enter_bttn=Button(self) self.enter_bttn["text"]="Enter" self.enter_bttn["command"]=self.update_text_count self.enter_bttn.grid(row=7,column=1,sticky=W) #Createing the text box to display the user's selection self.message_txt=Text(self,width=40,height=5,wrap=WORD) self.message_txt.grid(row=11,column=0, columnspan=3) def random_number(self): #creating a definition for all the random numbers to be generated in difficulty=self.difficulty.get() if difficulty=="easy": self.number = random.randrange(10)+1 elif difficulty=="medium": self.number = random.randrange(50)+1 else: self.number = random.randrange(100)+1 def update_text_count(self): #Update counter and maximum user guesses self.bttn3_clicks+=1 self.bttn3["text"]="Total Goes= "+str(self.bttn3_clicks) difficulty=self.difficulty.get() if difficulty=="easy": if self.bttn3_clicks > 3: message="You have run out of guesses. The number you wanted was ", self.number if difficulty=="medium": if self.bttn3_clicks > 6: message="You have run out of guesses. The number you wanted was ", self.number if difficulty=="hard": if self.bttn3_clicks > 9: message="You have run out of guesses. The number you wanted was ", self.number #Update text area and display user's game difficulty self.guess = int(self.guess.get())#Having trouble on this line!!! if self.guess>self.number: message=str(self.guess)+" is too High.Guess again" if self.guess Some comments, short (typing on mobiles is no fun): * self.guess gets overridden after the first iteration with an integer. guess what, integer don't have get methods. * I'd suggest to use if/elif/else, not independant ifs. better to read anyway. * consider using a dictionary to parametrize your levels: guess_conf = dict(easy=3, medium=6, difficult=9) level="easy" guesses = guesses_conf[level] all 100% genuine untested tips Andreas _____ Urspr?ngliche Mitteilung _____ Betreff: [Tutor] Help python coding not working Autor: "super krital" Datum: 8. Mai 2007 8:7:33 Hi need to get this program running for school so my teacher said to use the forum etc. Its working fine except its not comparing my guess with the result. im only having trouble with the second half or def update_text_count can you please help find a solution so my program works please. i dont see why it is not. #Krital #Guess my number game assignment from Tkinter import * import random class Application(Frame): """GUI Application for game difficulty.""" def __init__(self,master): """initialise frame.""" Frame.__init__(self,master) self.grid() self.bttn3_clicks=0 self.create_widgets() #Creating user instruction labels def create_widgets(self): #create widgets for difficulty levels #create description label Label(self, text="Choose your difficalty level" ).grid(row=0,column=0,sticky=W) Label(self, text="Select one:" ).grid(row=1,column=0,sticky=W) #Since only one radio button can be selected, they share one special object that #reflects which of the radio buttons is selected. This object needs to be an instance of the #StringVar class frpm the Tkinter module, which allows a string to be stored and retrieved. #create a variable for game difficulty self.difficulty = StringVar() #Create the Easy radio button Radiobutton(self, text="Easy", variable=self.difficulty, value="easy", command=self.random_number ).grid(row=2, column=0, sticky=W) Radiobutton(self, text="Medium", variable=self.difficulty, value="medium", command=self.random_number ).grid(row=3, column=0, sticky=W) Radiobutton(self, text="Hard", variable=self.difficulty, value="hard", command=self.random_number ).grid(row=4, column=0, sticky=W) self.bttn = Button(self) self.bttn["text"]="Exit" self.bttn["command"]=self.stop self.bttn.grid(row=23,column=1,sticky=W) self.bttn2 = Button(self) self.bttn2["text"]="Reset" self.bttn2["command"]=self.reset self.bttn2.grid(row=23,column=0,sticky=W) #using the Grid layout manager to be specific about the labels placement self.inst_lbl=Label(self,text="Please guess a number.") self.inst_lbl.grid(row=6,column=0,columnspan=2, sticky=W) #Sticky W means the label is forced to the west-or is left justified! #sticky can be N,S,E or W #creating an entry widget to make a guess self.guess=Entry(self) self.guess.grid(row=7,column=0,sticky=W) #self.guess.focus_set() self.bttn3=Button(self,text="Total Goes=0",relief=FLAT,command=self.update_text_count) self.bttn3.grid(row=8,column=0, sticky=W) #create a button to enter the guess self.enter_bttn=Button(self) self.enter_bttn["text"]="Enter" self.enter_bttn["command"]=self.update_text_count self.enter_bttn.grid(row=7,column=1,sticky=W) #Createing the text box to display the user's selection self.message_txt=Text(self,width=40,height=5,wrap=WORD) self.message_txt.grid(row=11,column=0, columnspan=3) def random_number(self): #creating a definition for all the random numbers to be generated in difficulty=self.difficulty.get() if difficulty=="easy": self.number = random.randrange(10)+1 elif difficulty=="medium": self.number = random.randrange(50)+1 else: self.number = random.randrange(100)+1 def update_text_count(self): #Update counter and maximum user guesses self.bttn3_clicks+=1 self.bttn3["text"]="Total Goes= "+str(self.bttn3_clicks) difficulty=self.difficulty.get() if difficulty=="easy": if self.bttn3_clicks > 3: message="You have run out of guesses. The number you wanted was ", self.number if difficulty=="medium": if self.bttn3_clicks > 6: message="You have run out of guesses. The number you wanted was ", self.number if difficulty=="hard": if self.bttn3_clicks > 9: message="You have run out of guesses. The number you wanted was ", self.number #Update text area and display user's game difficulty self.guess = int(self.guess.get())#Having trouble on this line!!! if self.guess>self.number: message=str(self.guess)+" is too High.Guess again" if self.guess References: Message-ID: <46401F95.6020607@gmail.com> self.guess overwrites itself, that's a live you commented on. And why it doesn't display the game over message is you do the "game over" check before you do the "is this correct?" check, but don't check to see if the game is over before the 2nd check. If that didn't make sense, psudocode: if check_for_gameover: message = "Game Over!" if check_guessed_number: message = "You WIN!" You see the problem? The "message" variable gets overwritten by the guess check because it comes second. Other tips I might give are all about code style (I don't like yours >_>), so I'll just leave it at that. And yes, I did test these, they fix all your problems. Well, except that you only need a window 350x300... G super krital wrote: > Hi need to get this program running for school so my teacher said to use the > forum etc. Its working fine except its not comparing my guess with the > result. im only having trouble with the second half or def update_text_count > can you please help find a solution so my program works please. i dont see > why it is not. > > #Krital > #Guess my number game assignment > > from Tkinter import * > import random > > > class Application(Frame): > """GUI Application for game difficulty.""" > def __init__(self,master): > """initialise frame.""" > Frame.__init__(self,master) > self.grid() > self.bttn3_clicks=0 > self.create_widgets() > > #Creating user instruction labels > > def create_widgets(self): > #create widgets for difficulty levels > #create description label > Label(self, > text="Choose your difficalty level" > ).grid(row=0,column=0,sticky=W) > > Label(self, > text="Select one:" > ).grid(row=1,column=0,sticky=W) > > > #Since only one radio button can be selected, they share one special object > that > #reflects which of the radio buttons is selected. This object needs to be an > instance of the > #StringVar class frpm the Tkinter module, which allows a string to be stored > and retrieved. > > #create a variable for game difficulty > self.difficulty = StringVar() > > #Create the Easy radio button > Radiobutton(self, > text="Easy", > variable=self.difficulty, > value="easy", > command=self.random_number > ).grid(row=2, column=0, sticky=W) > > > Radiobutton(self, > text="Medium", > variable=self.difficulty, > value="medium", > command=self.random_number > ).grid(row=3, column=0, sticky=W) > > Radiobutton(self, > text="Hard", > variable=self.difficulty, > value="hard", > command=self.random_number > ).grid(row=4, column=0, sticky=W) > > self.bttn = Button(self) > self.bttn["text"]="Exit" > self.bttn["command"]=self.stop > self.bttn.grid(row=23,column=1,sticky=W) > > self.bttn2 = Button(self) > self.bttn2["text"]="Reset" > self.bttn2["command"]=self.reset > self.bttn2.grid(row=23,column=0,sticky=W) > > #using the Grid layout manager to be specific about the labels > placement > self.inst_lbl=Label(self,text="Please guess a number.") > self.inst_lbl.grid(row=6,column=0,columnspan=2, sticky=W) > #Sticky W means the label is forced to the west-or is left > justified! > #sticky can be N,S,E or W > > #creating an entry widget to make a guess > self.guess=Entry(self) > self.guess.grid(row=7,column=0,sticky=W) > #self.guess.focus_set() > > self.bttn3=Button(self,text="Total > Goes=0",relief=FLAT,command=self.update_text_count) > self.bttn3.grid(row=8,column=0, sticky=W) > > #create a button to enter the guess > > self.enter_bttn=Button(self) > self.enter_bttn["text"]="Enter" > self.enter_bttn["command"]=self.update_text_count > self.enter_bttn.grid(row=7,column=1,sticky=W) > > > #Createing the text box to display the user's selection > self.message_txt=Text(self,width=40,height=5,wrap=WORD) > self.message_txt.grid(row=11,column=0, columnspan=3) > > > def random_number(self): #creating a definition for all the random > numbers to be generated in > difficulty=self.difficulty.get() > if difficulty=="easy": > self.number = random.randrange(10)+1 > elif difficulty=="medium": > self.number = random.randrange(50)+1 > else: > self.number = random.randrange(100)+1 > > def update_text_count(self): > #Update counter and maximum user guesses > self.bttn3_clicks+=1 > self.bttn3["text"]="Total Goes= "+str(self.bttn3_clicks) > difficulty=self.difficulty.get() > if difficulty=="easy": > if self.bttn3_clicks > 3: > message="You have run out of guesses. The number you wanted > was ", self.number > if difficulty=="medium": > if self.bttn3_clicks > 6: > message="You have run out of guesses. The number you wanted > was ", self.number > if difficulty=="hard": > if self.bttn3_clicks > 9: > message="You have run out of guesses. The number you wanted > was ", self.number > > #Update text area and display user's game difficulty > self.guess = int(self.guess.get())#Having trouble on this line!!! > > if self.guess>self.number: > message=str(self.guess)+" is too High.Guess again" > if self.guess message=str(self.guess)+" is too low. Guess again" > > if self.guess==self.number: > message=str(self.guess)+" is correct!", > "goes= ",self.bttn3_clicks > > #deleting any text in the text box and inserting the string just created > as well as disabling the box > self.message_txt.config(state=NORMAL) > self.message_txt.delete(0.0, END) > self.message_txt.insert(0.0, message) > self.message_txt.config(state=DISABLED) > > def reset(self): #creating definition to reset the game > number=0 > self.bttn3_clicks=0 > self.create_widgets() > > def stop(self): > root.destroy() > > #wrap the program > > root=Tk() > root.title("~*Guess the Number Game*~") > root.geometry("500x400") > > app=Application(root) > > root.mainloop() > > _________________________________________________________________ > Advertisement: Senior Management roles paying $80k+ Search now at > www.seek.com.au > http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Fninemsn%2Eexecutive%2Eseek%2Ecom%2Eau%2F%3Ftracking%3Dsk%3Ahet%3Ase%3Anine%3A0%3Ahot%3Atext&_t=763838044&_r=seek_may07_snrmanagement&_m=EXT > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From Jason.Meiers at paybytouch.com Tue May 8 02:04:45 2007 From: Jason.Meiers at paybytouch.com (Jason Meiers) Date: Mon, 7 May 2007 17:04:45 -0700 Subject: [Tutor] Trouble creating DB2 drivers Message-ID: <4224CAC2A4CF064CB5C7A41D976EF63204693295@sfadmai01.solidusnetworks.com> Hi, Where you ever able to get this issue resolved, I've got the same issue? http://mail.python.org/pipermail/tutor/2007-February/052994.html Best Regards, Jason Meiers Production Monitoring Pay By Touch ------------------------------------------ 101 2nd Street, Suite 1500 San Francisco, CA. 94105 415.728.2157 (c) http://www.paybytouch.com This email and any attachment(s) thereto, are intended for the use of the addressee(s) named herein and may contain legally privileged and or confidential information under applicable law. If you are not the intended recipient of this e-mail, you are hereby notified any dissemination, distribution or copying of this email, and any attachment(s) thereto, is strictly prohibited. If you have received this communication in error, please notify the sender at 415-281-2200 or via return e-mail at postmaster at paybytouch.com and permanently delete the original copy and any copy of any e-mail, and any printout thereof. Thank you for your cooperation. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070507/aaec3725/attachment.htm From rabidpoobear at gmail.com Tue May 8 14:30:17 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 08 May 2007 07:30:17 -0500 Subject: [Tutor] Help python coding not working In-Reply-To: References: Message-ID: <46406D59.4080205@gmail.com> super krital wrote: > Hi need to get this program running for school so my teacher said to use the > forum etc. Its working fine except its not comparing my guess with the > result. im only having trouble with the second half or def update_text_count > can you please help find a solution so my program works please. i dont see > why it is not. > [snip inline code] please in the future send your code as attachments. Or at the very least, follow the convention of no lines longer than 80 chars. Your e-mail got wrapped to hell on my client, and I didn't even try to read the source, it was so messy. If you attach your code, it keeps the wrapping from occurring. -Luke From alan.gauld at btinternet.com Tue May 8 15:29:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 14:29:24 +0100 Subject: [Tutor] exec syntax References: <000c01c78f4e$a6000a30$bd157044@dunamis34752e9> Message-ID: "Rikard Bosnjakovic" wrote >> I can see how to use it to execute a script of code embedded in the >> program >> (that example was provided in the documentation) but I cannot >> figure out the >> syntax to use it to run another python program in another file. > > Use execfile(). But use it with caution, its usually the wrong thing to be doing. Why do you need to run another python program from within your python program? Is it not usable as a module? There are valid cases for execfile - otherwise it wouldn't exist! :-) But they are fairly rare. Alan G. From alan.gauld at btinternet.com Tue May 8 15:34:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 14:34:32 +0100 Subject: [Tutor] base directory References: <000801c78f75$c2d84f10$bd157044@dunamis34752e9> Message-ID: "Jason Coggins" wrote > I am new to Linux. On Windows the base directory > is c:\. Or D:\ or E:\ etc... In other words Windows has many base directories, one per physical drive. > What is the base directory for Linux? In *nix there is only one logical directory structure and all devices are mapped on to it. The base of this logical tree is /. Thus to use your example /programs/fileName.py. Except that there is a conventional set of names so a better path would be: /usr/local/bin/fileName.py Since /usr/local/bin is the traditional place to store programs installed by users (as opposed to admins or system utilities). bin here standing for binary and not the recycle bin! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 8 15:37:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 14:37:49 +0100 Subject: [Tutor] command lines References: <000a01c78ff0$d6856d60$bd157044@dunamis34752e9> Message-ID: "Rikard Bosnjakovic" wrote in message news:d9e88eaf0705060844t49f4b07aq2fe9ba7885695234 at mail.gmail.com... > On 5/6/07, Jason Coggins wrote: > >> Is there a way to send a command to the Linux Terminal >> from inside a Python program? To be picky you don't send the command to the Terminal but to the OS. But the output will appear in the terminal which is what I assume you mean... :-) > os.system(), os.popen(), etc. Also the commands module or the more recent subprocess module which is intended to replace all of the previous mechanisms eventually. See my OS topic in my tutor for examples of all of these. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 8 15:43:15 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 14:43:15 +0100 Subject: [Tutor] trying to figure out what this means References: Message-ID: "Dave C" wrote > when you are doing print these two characters keep showing up in > this book > "%s" % > > What do they do? Its called string formatting. %s means insert a string(the s) here. %d means insert a decimal number(the d) here There are a whole bunch of other codes and you can add extra fomatting info too(width, justification etc). This is covered in the Simple Sequences topic of my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 8 15:40:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 14:40:44 +0100 Subject: [Tutor] can python run under windows 95? References: <70831DC71E5D814C9D1FA8A96653215E090D622B@server.isd.dp.ua> Message-ID: "Alexander Kapshuk" wrote > I've got an old Toshiba Satellite 110CT laptop with Windows 95 > > Would I be able to run Python on it? > If so, what version of Python should I install? Python 1.5.1 definitely works on Win95. I suspect v2.0 will too. The 32 bit DOS version will also work. Anything later I can't comment on since I've never tried... Alan G. From alan.gauld at btinternet.com Tue May 8 15:46:23 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 14:46:23 +0100 Subject: [Tutor] Basic image editing program in python References: Message-ID: "Antonio Diaz" wrote > I have a project in school and I was wondering if its > possible to make a python program that uses > Imaging library to make a GUI of the same functions > that Imaging has. Yes thats very possible. > If its possible to make it in glade.? I assume so, I've never used Glade but I seem to recall it uses GT/K as its toolkit and that can do what you want. > And if all answers were possitive, where can i find > documentation or tutorials? that can help me? Documentation for Glade is on the Glade website. Similarly for pyGTK. General GUI guidance can be found in a wealth of places, including very basivc info in my tutorial. But a lot depends on your experience, it is not a trivial exercise, although not rocket science either. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 8 15:55:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 14:55:11 +0100 Subject: [Tutor] Running and passing variables to/from Fortran References: Message-ID: "John Washakie" wrote >I have a FORTRAN program which reads in unformatted sparse matrix > data. Rather than rewriting the code in Python, I was hoping there > is > a way to call the Fortran program, passing filename variables TO > Fortran, and returning the data (which is an array) back to my .py > code for use there. It depends on whether your Fortran code reads the variables from stdin (or on the command line) and spits out the result to stdout. If it does (or can be modified to do so on demand) then its an easy job using subprocess.Popen. If you actually need to communicate at the variable level its more difficult(!). If you cannot change the Fortran code at all or only have the binary version then its more difficult still! If you can change the Fortran then you can simply use files to communicate between them... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 8 17:45:37 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 8 May 2007 15:45:37 +0000 (GMT) Subject: [Tutor] base directory Message-ID: <992131.74760.qm@web86114.mail.ird.yahoo.com> >> Except that there is a conventional set of names so a >> better path would be: >> >> /usr/local/bin/fileName.py >That's incredibly helpful. As another Linux noob, would you mind if I >jump in with 2 follow-up questions: > >To continue the example above, for say, Opera and CoolEditor, I'd use: > /usr/local/bin/opera > corrrect? Probably, although some sites prefer local for stuff produced locally and would put opera in /usr/bin > And what would I use if I was the admin, and wanted to install > a program for all users? local/bin can be open to all, and usually is. Its more about the purpose of the program than its visibility. See if Wikipedia explains it better than me... http://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard Alan G. ___________________________________________________________ Yahoo! Mail is the world's favourite email. Don't settle for less, sign up for your free account today http://uk.rd.yahoo.com/evt=44106/*http://uk.docs.yahoo.com/mail/winter07.html From dsh0105 at comcast.net Tue May 8 20:36:32 2007 From: dsh0105 at comcast.net (dsh0105 at comcast.net) Date: Tue, 08 May 2007 18:36:32 +0000 Subject: [Tutor] Newbie Question on Exceptions... Message-ID: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> I'm working my way through the book "beginning python" and I came across an exercise that suggests using Exception trapping to see if a value is in a dictionary: fridge={"apple":"A shiny red apple","pear":"a nice ripe pear","grapes":"seadless grapes"} food_sought="apple" fridge_list=fridge.keys(); try: print "The fridge contains %s" %fridge[food_sought] except (KeyError): print "The fridge does not contain %s"%food_sought I'm fairly certain the book is in error in calling this a "short-cut" since the has_key method is much less verbose to use, but it brings up a question about exceptions in general: In Java using exceptions in the way shown above is a classic anti-pattern since Exceptions should only be used for..well exceptional conditions. Is the same true of Python? Or is ok to use Exception handling like the book suggests? Thanks in advance, David Hamilton From bgailer at alum.rpi.edu Tue May 8 21:05:01 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 08 May 2007 12:05:01 -0700 Subject: [Tutor] Newbie Question on Exceptions... In-Reply-To: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> References: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> Message-ID: <4640C9DD.4010105@alum.rpi.edu> dsh0105 at comcast.net wrote: > I'm working my way through the book "beginning python" and I came across an exercise that suggests using Exception trapping to see if a value is in a dictionary: > > fridge={"apple":"A shiny red apple","pear":"a nice ripe pear","grapes":"seadless grapes"} > food_sought="apple" > fridge_list=fridge.keys(); > try: > print "The fridge contains %s" %fridge[food_sought] > except (KeyError): > print "The fridge does not contain %s"%food_sought > > I'm fairly certain the book is in error in calling this a "short-cut" since the has_key method is much less verbose to use Perhaps the version of Python, when the book was written, did not have has_key? Less verbose? Let's see - if I do a straightforward translation I get: if fridge.has_key(food_sought): print "The fridge contains %s" %fridge[food_sought] else: print "The fridge does not contain %s"%food_sought That's 2 less words! But consider (same word count but even easier to read): if food_sought in fridge: > question about exceptions in general: > > In Java using exceptions in the way shown above is a classic anti-pattern since Exceptions should only be used for..well exceptional conditions. > Ah the dreaded "should". Who says? But then in Java exception handling is more complex, and avoiding it seems a good idea. > Is the same true of Python? Or is ok to use Exception handling like the book suggests? > Since there is no one on the Python side saying "should" (AFAIK) I can only opine: use whatever gets the job done, is readable and maintainable. Many things can be tested for with ease. But consider when you use raw_input to get a string, and you want to accept it only if it will convert to float. The only easy way I know is to use the float() function inside a try:. If you wanted to test it without try: you'd have to write a regular expression for floating point syntax and use re. Not as easy or readable. -- Bob Gailer 510-978-4454 From andreengels at gmail.com Tue May 8 21:14:03 2007 From: andreengels at gmail.com (Andre Engels) Date: Tue, 8 May 2007 21:14:03 +0200 Subject: [Tutor] Newbie Question on Exceptions... In-Reply-To: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> References: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> Message-ID: <6faf39c90705081214t4142b7e5p25512be71fb072a0@mail.gmail.com> 2007/5/8, dsh0105 at comcast.net : > I'm working my way through the book "beginning python" and I came across an exercise that suggests using Exception trapping to see if a value is in a dictionary: > > fridge={"apple":"A shiny red apple","pear":"a nice ripe pear","grapes":"seadless grapes"} > food_sought="apple" > fridge_list=fridge.keys(); > try: > print "The fridge contains %s" %fridge[food_sought] > except (KeyError): > print "The fridge does not contain %s"%food_sought > > I'm fairly certain the book is in error in calling this a "short-cut" since the has_key method is much less verbose to use, Is it? if fridge.has_key(food_sought): foo else: bar doesn't look much less verbose than: try: foo except (KeyError): bar > but it brings up a question about exceptions in general: > > In Java using exceptions in the way shown above is a classic anti-pattern since Exceptions should only be used for..well exceptional conditions. > > Is the same true of Python? Or is ok to use Exception handling like the book suggests? Exceptions are in general much more freely used in Python than in most other languages, it's called the "EAFP" (It's easier to ask forgiveness than to get permission) style, instead of the "LBYL" (look before you leap) style most other languages use. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From alan.gauld at btinternet.com Tue May 8 22:11:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 May 2007 21:11:08 +0100 Subject: [Tutor] Newbie Question on Exceptions... References: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> Message-ID: wrote > fridge={"apple":"A shiny red apple","pear":"a nice ripe > pear","grapes":"seadless grapes"} > food_sought="apple" > fridge_list=fridge.keys(); Not sure what this line is for... > try: > print "The fridge contains %s" %fridge[food_sought] > except (KeyError): > print "The fridge does not contain %s"%food_sought This is a fairly common Python idiom. > I'm fairly certain the book is in error in calling this a > "short-cut" I agree, its not much of a shortcut. but oit is a common Python idiom. > In Java using exceptions in the way shown above is > a classic anti-pattern since Exceptions should only > be used for..well exceptional conditions. There are a few reasons for this in Jave, not least that Exceptions are quite expensive in Java whereas they are relatively cheap in Python. > Or is ok to use Exception handling like the book suggests? Its generally OK but at the same time don't overdo it. Exceptions have a lot in common with gotos. They can obfuscate the flow of code unless the try block is short and simple. Personally I prefer to use exception for real exceptions when possible, but sometimes they do offer a neat way of expressing things. And of course accessing a non existent key is an exception! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Wed May 9 06:28:01 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 9 May 2007 16:28:01 +1200 Subject: [Tutor] Newbie Question on Exceptions... In-Reply-To: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> References: <050820071836.13385.4640C3300008B30A000034492207024553CACFCECF089C0B@comcast.net> Message-ID: <5e58f2e40705082128j2e7c36a6g8d8960c93a617555@mail.gmail.com> On 09/05/07, dsh0105 at comcast.net wrote: > try: > print "The fridge contains %s" %fridge[food_sought] > except (KeyError): > print "The fridge does not contain %s"%food_sought [...] > Is the same true of Python? Or is ok to use Exception handling like the book suggests? This general debate is called "look before you leap" vs "easier to ask forgiveness than permission". If you google for "python eafp lbyl" you will get a zillion pages of people debating it. Here's a quote from a post by Alex Martelli (http://en.wikipedia.org/wiki/Alex_Martelli): # from http://mail.python.org/pipermail/python-list/2003-May/205182.html """ There are umpteen good reasons why EAFP is vastly superior to LBYL. For example, we can just focus on the fact that these days we work mostly on multiprogrammed machines. While script A is running, some other programs B, C, D, ... are typically also running -- and they might be mucking with the same directories and/or files that A is working with. So, if A's structure is: if iswhatiwant(thefile): useappropriately(thefile) else: dealwithwrongness() then A is buggy. That is because, between the moment in which the test 'iswhatiwant' runs (and returns a true value), and the later moment in which procedure 'useappropriately' runs, *just about anything may have happened* -- in particular, some other program Z might have removed or modified 'thefile' so that it's NOT what A wants any more. I.e., A may lose control of the CPU between the moment it tests and the later time in which it uses the result of that test. This is known as a "race condition" and it's among the hardest problems you may run into. A may seem to be running just fine 99 times and then the 100th time BOOM -- because of accidents of timing between A and other stuff that may be running "at the same time"... a "race", so to speak, whence the name whereby this horrid condition is known. Fortunately, in a language with good support for exceptions such as Python, you are NOT doomed to enter the hell of race conditions -- just use EAFP instead of LBYL: try: useappropriately(thefile) except ItWasWrong, howwasitwrong: dealwithwrongness() See how deeply simpler this is? 'useappropriately' just ASSUMES the file is 'what A wants' and raises an ItWasWrong exception if the assumption proves to be unfounded. You don't have to code a separate 'iswhatiwant' test -- what you DO want is determined inherently by what 'useappropriately' tries to do. No race conditions, no code that must duplicate the set of conditions to be checked for, no duplicate work at runtime in terms of system calls to determine if a condition holds followed by system calls to take advantaqe of that condition. This risks leaving the impression that EAFP is a panacea - it isn't, and it has its own issues to watch for -- it's simply heads and shoulders above LBYL in most practical cases. Please see my more detailed discussions of this in the Cookbook and the Nutshell for something more about error-checking strategies. """ -- John. From Nick.Treloar at education.nsw.gov.au Wed May 9 06:50:48 2007 From: Nick.Treloar at education.nsw.gov.au (Treloar, Nick) Date: Wed, 9 May 2007 14:50:48 +1000 Subject: [Tutor] number guessing game Message-ID: <42E18E55C3B8C24FBE1633506D22EC130383330C@DET-MAIL-EVS03.DETISP.LOCAL> here is my code so far from Tkinter import* root = Tk() root.title("main screen") root.maxsize(width=350,height=200) root.minsize(width=350,height=200) root.resizable(width=YES,height=YES) def child1(): c1 = Toplevel(root) c1.guess_ent = Entry(c1, width = 35,) c1.guess_ent.grid(row = 14, column = 0) c1.box_txt = Text(c1, width = 35, height = 5, wrap = WORD) c1.box_txt.grid(row = 3, column = 0, columnspan=2) c1.title("easy") c1.geometry("200x200") Button(c1,text="clear").grid(row=1,column=0) Button(c1,text="new game",).grid(row=1,column=1) def child2(): c2 = Toplevel(root) box_txt = Text(c2, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c2.title("medium") c2.geometry("200x200") def child3(): c3 = Toplevel(root) box_txt = Text(c3, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c3.title("hard") c3.geometry("200x200") Label(root,text = "choose which game you would like to play").grid(row=0,column=0,columnspan=2) Button(root,text="easy",command=child1).grid(row=1,column=0) Button(root,text="medium",command=child2).grid(row=1,column=1) Button(root,text="hard",command=child3).grid(row=1,column=3) This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070509/c54cae4f/attachment.htm From Nick.Treloar at education.nsw.gov.au Wed May 9 06:47:46 2007 From: Nick.Treloar at education.nsw.gov.au (Treloar, Nick) Date: Wed, 9 May 2007 14:47:46 +1000 Subject: [Tutor] random number guessing game Message-ID: <42E18E55C3B8C24FBE1633506D22EC130383330B@DET-MAIL-EVS03.DETISP.LOCAL> i am tying to buil a program using child screens the program is going the make a random number and the user has to guess it . so far i have made the gui but how do i progame it to make the random number This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070509/a244d756/attachment-0001.html From bgailer at alum.rpi.edu Wed May 9 07:38:51 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 08 May 2007 22:38:51 -0700 Subject: [Tutor] random number guessing game In-Reply-To: <42E18E55C3B8C24FBE1633506D22EC130383330B@DET-MAIL-EVS03.DETISP.LOCAL> References: <42E18E55C3B8C24FBE1633506D22EC130383330B@DET-MAIL-EVS03.DETISP.LOCAL> Message-ID: <46415E6B.6030400@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070508/1b272c7c/attachment.htm From rikard.bosnjakovic at gmail.com Wed May 9 08:09:11 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Wed, 9 May 2007 08:09:11 +0200 Subject: [Tutor] random number guessing game In-Reply-To: <46415E6B.6030400@alum.rpi.edu> References: <42E18E55C3B8C24FBE1633506D22EC130383330B@DET-MAIL-EVS03.DETISP.LOCAL> <46415E6B.6030400@alum.rpi.edu> Message-ID: On 5/9/07, Bob Gailer wrote: [...] > If you don't have to include it, please consider omitting it. Considering the OP's domain name, he might not be able to omit it. -- - Rikard - http://bos.hack.org/cv/ From zebra05 at gmail.com Wed May 9 15:31:57 2007 From: zebra05 at gmail.com (OkaMthembo) Date: Wed, 9 May 2007 15:31:57 +0200 Subject: [Tutor] Python fast enough for ad server? Message-ID: Hi guys, I need to write an ad-serving application and i'm using Win XP as my dev platform. Naturally, i want it to be as painless as possible and i was thinking of writing it 100% in Python. However, i have not written any big apps in the language and i wonder if Python would have the performance or scale fast enough to a large user base. I also reluctantly think of using Python and Java, but Jython only supports Python 2.2 at the moment (same as my other option, Boost) and i'm using Python 2.5. what does everyone think? Best Regards, -- "The Stupidry Foundry" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070509/ea2efaa0/attachment.htm From tms43 at clearwire.net Wed May 9 17:37:14 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Wed, 9 May 2007 08:37:14 -0700 Subject: [Tutor] canvas -> CLASSES In-Reply-To: <5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com> References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC> <5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com> Message-ID: <989CF4DD96564F78A68A618A015C86CD@TeresPC> CLASSES: This is where I start getting confused. I've re-written the maze, per the guidance of John Fouhy (by the way, pretty cool!). Wish I had thought of doing it that way to begin with, lol. In any case, I'm trying to put it into a class, and for some reason it all starts to get jumbled here, which it shouldn't because I write in C++. None-the-less, I'm having some issues. I've attached the changes I've made, which worked before I started putting it in a class. I still need to work on the pathways, but figured I would get this into a class format before I go any further. Since I've put it in a class, my design is off because I don't know how to 'call' it, among other issues. Do the point definitions of the walls, boxes and T's get put inside the function? They could also be a file, but I don't think that would be necessary. Right now the function calls itself and I don't think its the best way to do it, mostly because I don't know what to pass it to begin with. Can someone please just stop my mind from going different directions? Well, perhaps not, but point me in the right direction? Thanks T ----- Original Message ----- From: "John Fouhy" To: "Python Tutor" Sent: Monday, May 07, 2007 3:22 PM Subject: Re: [Tutor] canvas -> make an object 'seem' to move > On 08/05/07, Teresa Stanton wrote: >> I seem to be stuck again. I've attached my entire file (and the .gif I'm >> using. My son made this .gif, its our lab). The problem is my xp (the >> variable I use for my x coordinate) isn't updating after the .gif moves. >> I >> think I should probably organize the entire module better, but then >> again, >> I've never written anything this big in Python, and nothing like this in >> Tkinter. So, perhaps someone will have a suggestion? > > Some general comments: > > """ > #This will build the north (top) wall of the maze > canvasOne.create_line(10, 10, 790, 10, width = 3, fill = 'blue') #west to > east > canvasOne.create_line(20, 20, 395, 20, width = 3, fill = 'blue') #2nd > line, west to middle > canvasOne.create_line(395, 20, 395, 100, width = 3, fill = 'blue') > #middle to south > canvasOne.create_line(405, 20, 405, 100, width = 3, fill = 'blue')#2nd > middle to south > canvasOne.create_line(395, 100, 405, 100, width = 3, fill = 'blue') > #short west to east > canvasOne.create_line(405, 20, 780, 20, width = 3, fill = 'blue') #2nd > line cont, middle to east > """ > > This would be a good opportunity to define some functions. eg, you > could do this: > > canvasOne = Canvas(width = 800, height = 700, bg = 'black') > canvasOne.pack() > > def createWall((x0, y0), (x1, y1), colour='blue', width=3): > """ Create a wall from (x0, y0) to (x1, y1). """ > canvasOne.create_line(x0, y0, x1, y1, width=width, fill=colour) > > Then ... hmm, I see from running your code that your lines are all > effectively continuous. So you could represent each wall by a series > of points. eg: > > outerWall = [(10,10), (790,10), (790, 360), ...] # etc > innerWall1 = [...] > # etc > > walls = [outerWall, innerWall1, ...] > > Then you could draw them like: > > for wall in walls: > for i in range(len(wall-1)): > createWallall(outerWall[i], outerWall[i+1]) > > Second comment: > > """ > xp = 100 > yp = 600 > > # ... > > #onClick Vertical moves the .gif based on where the mouse is clicked > #newY is new location for yp > def onClickVertical(newY, xp, yp): > print 'here' > for i in range(newY): > yp += .8 > canvasOne.coords(ph, xp, yp) > time.sleep(.001) > canvasOne.update() > return xp, yp > """ > > I notice you have a statement: > > yp += .8 > > in this function. Are you aware that this will _not_ change the value > of yp outside the scope of the function? > > If you want to change yp in the global scope, you need to tell python > to treat it as a global variable, by putting the statement 'global yp' > near the top of that function. > > A better course of action (global variables are a bit ugly) might be > to encapsulate your maze into a class. eg: > > class Maze(object): > def __init__(self): > # initial position of actor > self.xp = 100 > self.yp = 600 > # create maze, etc. > > def onClickVertical(self, newY, xp, yp): > # etc > > HTH! > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: maze.pyw Url: http://mail.python.org/pipermail/tutor/attachments/20070509/694db9bd/attachment.pot From eric at ericwalstad.com Wed May 9 17:41:54 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 09 May 2007 08:41:54 -0700 Subject: [Tutor] Python fast enough for ad server? In-Reply-To: References: Message-ID: <4641EBC2.8080304@ericwalstad.com> Hey OkaMthenbo, OkaMthembo wrote: > Hi guys, > > I need to write an ad-serving application and i'm using Win XP as my dev > platform. Naturally, i want it to be as painless as possible and i was > thinking of writing it 100% in Python. However, i have not written any > big apps in the language and i wonder if Python would have the > performance or scale fast enough to a large user base. Most certainly for some definitions of 'large' :) Most web apps these days are not written in a single language/technology and are often not running on a single piece of hardware. If you search the archives of your favorite Python web application framework I'm pretty sure you'll find a discussion on how to scale your app to handle a 'large' user base. At the risk of oversimplification, but in hopes of avoiding premature optimization, I'd focus first on achieving working code, then benchmark it, then optimize if optimization is still needed. Many others have achieved high volume Python web apps using a mix of all the wonderful open source tools available. If your content doesn't change quickly and the ratio of GETs/POSTs is high, a caching server in front of your python app might be just the trick (memcached, squid,etc). But don't waste your time if you don't need to. Define 'too slow' and then prove to yourself that your app passes that threshold. If so, then figure out why it's slow and optimize the slow parts. Good luck, Eric. From jbrink at npsd.k12.wi.us Wed May 9 20:37:51 2007 From: jbrink at npsd.k12.wi.us (Jessica Brink) Date: Wed, 09 May 2007 13:37:51 -0500 Subject: [Tutor] Type Conversion In-Reply-To: <989CF4DD96564F78A68A618A015C86CD@TeresPC> References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC> <5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com> <989CF4DD96564F78A68A618A015C86CD@TeresPC> Message-ID: <4641CEAE.CB8D.003F.0@npsd.k12.wi.us> I am doing a simple program that takes input from the user (a temp. in degrees Celsius) and converts it to a temperature in Fahrenheit. The following program works: def conversion (): C = input ("Enter the temperature in degrees Celcius:\n") F = (9.0 / 5.0) * C + 32 print F conversion () However, if I try to use the raw_input function, and then convert the variable to an integer, it does not work: def conversion (): C = raw_input ("Enter the temperature in degrees Celcius:\n") int (C) F = (9.0 / 5.0) * C + 32 print F conversion () Am I missing a step on converting the variable C from a string to an integer, or is it not possible to do this? I get the error that it is not possible to concatenate a str and int. Thanks! Jessica Brink Business/Computer Teacher Northland Pines High School Eagle River, WI 715-479-4473 ext. 0701 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070509/12dfa4ac/attachment.htm From Mike.Hansen at atmel.com Wed May 9 20:41:59 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 9 May 2007 12:41:59 -0600 Subject: [Tutor] Type Conversion In-Reply-To: <4641CEAE.CB8D.003F.0@npsd.k12.wi.us> References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC><5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com><989CF4DD96564F78A68A618A015C86CD@TeresPC> <4641CEAE.CB8D.003F.0@npsd.k12.wi.us> Message-ID: <57B026980605A64F9B23484C5659E32E7D4516@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Jessica Brink > Sent: Wednesday, May 09, 2007 12:38 PM > To: Teresa Stanton; Python Tutor > Subject: [Tutor] Type Conversion > > I am doing a simple program that takes input from the user (a > temp. in degrees Celsius) and converts it to a temperature in > Fahrenheit. The following program works: > > def conversion (): > C = input ("Enter the temperature in degrees Celcius:\n") > F = (9.0 / 5.0) * C + 32 > print F > > conversion () > > However, if I try to use the raw_input function, and then > convert the variable to an integer, it does not work: > > def conversion (): > C = raw_input ("Enter the temperature in degrees Celcius:\n") > int (C) > F = (9.0 / 5.0) * C + 32 > print F > > conversion () > > Am I missing a step on converting the variable C from a > string to an integer, or is it not possible to do this? I > get the error that it is not possible to concatenate a str and int. > > Thanks! > > Jessica Brink > Business/Computer Teacher > Northland Pines High School > Eagle River, WI > 715-479-4473 ext. 0701 Instead of int(C), I think you need C = int(C) Mike From alan.gauld at btinternet.com Wed May 9 22:08:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 May 2007 21:08:18 +0100 Subject: [Tutor] canvas -> CLASSES References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC><5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com> <989CF4DD96564F78A68A618A015C86CD@TeresPC> Message-ID: "Teresa Stanton" wrote > CLASSES: This is where I start getting confused. No kidding! :-) > put it into a class, and for some reason it all starts to get > jumbled here, > which it shouldn't because I write in C++. C++ OOP and Python are significantly different and some of those differences may be at work here. > Since I've put it in a class, my design is off because I don't know > how to > 'call' it, among other issues. You need an instance which you don;t have currently. > Do the point definitions of the walls, boxes and T's get > put inside the function? Probably not, probably etter to puut them in a list - as you do - and pass the list into the method. > Right now the function calls itself and I don't think its the best > way to do it, Nor do I, but I'mnot clear exactly what you are doing since the data is all hard coded inside the function so it looks to me like you will you will get into a loop... Some snippets and comments follow: > class Maze(object): > def __init__(self): > #initial position of .gif > self.xp = 100 > self.yp = 600 You don't seem to use selfd.xp/yp anywhere... In fact since you don't initialize any objects this never even gets called! > def createWall((x0, y0), (x1, y1), colour = 'blue', width = 3): > """ Create a wall from (x0, y0) to (x1, y1). """ > canvasOne.create_line(x0, y0, x1, y1, width = width, fill = > colour) You don't have a self parameter in the method. Recall that self is equivalent to this in C++ but needs to be explicitly declared in Python methods. Also you are declaring parameters to be tuples which I don't think you can do. You need to name the tuples, something like: def createWall(self, pt1,pt2, canvas = None, colour='blue', width=3) Also you use the canvasOne global value here which would be better passed in as am parameter as shown above. > outerWall = [(450, 640), (475, 640), (475, 640), > walls = [outerWall] Not sure why the second line is there. The first is static data which means the method never changes what it does. You never use the x0,y0, params passed in after the create line above... > for wall in walls: > for i in range(len(wall)-1): > createWall(outerWall[i], outerWall[i+1]) For each entry draw a kine then come back into this loop using the same data so we very quickly hit the Python recursion limit I suspect. > topLeftBox = [(130, 105), (130, 125), ... > secondTopLeftBox = [(160, 215), (160, 225), ... > ... > boxes = [topLeftBox, secondTopLeftBox, topRightBox, > secondTopRightBox] > > for box in boxes: > for i in range(len(box)-1): > createWall(topLeftBox[i], topLeftBox[i+1]), > createWall(secondTopLeftBox[i], > secondTopLeftBox[i+1]), Sorry, I have no idea how this is supposed to work. I just got confused about the mix of topLefts and box versus boxes etc. But remember that each call to createWall only uses the arguments to draw a single line, then the rest uses the same data over again. Also to acces createWall you should really be using self.createWall since createWall is a method of your Maze class. > x = 40 > for i in range(9): > x += 20 > canvasOne.create_rectangle(x, 610, x+5, 615, fill = > 'white') > > #left path built north to south > y = 290 > for i in range(15): > y += 20 > canvasOne.create_rectangle(220, y, 225, y+5, fill = > 'white') All these bits could be put into a function with the values as parameters, something like:: def buildPath(val1,val2, number, increment, deltax,deltay,orientation, fill='white') for i in range(number): val1 += increment if orientation = 0: x,y = val1,val2 else: x,y = val2,val1 canvas.create_rectangle(x,y,x+deltax,y+deltay,fill) > root = Tk() > root.title("Background") > > canvasOne = Canvas(width = 800, height = 700, bg = 'black') > createWall(450, 640, 475, 640) > canvasOne.pack() > > root.mainloop() Here yuou call createWall which is a method of Maze but you don't instantiate Maze. I'd expect so9mething like: maze = Maze(x,y) maze.createWall(....) But there's a lot of logic missing between there ared here. Alsoi if thats all you are doing there is no point of having a maze class, just write a createWall function. You need to figure out what a Maze object is for. What are its responsibilities in the program? What data does it manage? What actions do you want it top perform? Unfortunately from your code I can't work out what you were expecting of your Maze instances. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed May 9 22:10:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 May 2007 21:10:48 +0100 Subject: [Tutor] Type Conversion References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC><5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com><989CF4DD96564F78A68A618A015C86CD@TeresPC> <4641CEAE.CB8D.003F.0@npsd.k12.wi.us> Message-ID: "Jessica Brink" wrote > I am doing a simple program that takes input from the user Please don;t hijack a thread to ask something unrelkated. Start a new threead it helps keep things clear and makkes it easier to find responses later. Mike has answered your question in this case buit please in future start a new subject line. Alan G. From agilfoy at frontiernet.net Wed May 9 22:16:15 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Wed, 09 May 2007 20:16:15 +0000 Subject: [Tutor] Assembling multiple strings into one Message-ID: <20070509201615.evksn2zklb4k8o48@webmail.frontiernet.net> I have a program producing a list of multiple strings. The amount of strings in the list varies. I want to assemble a string that is: list item 0 + space + list item 1 + space, and so on, going through every string in the list. -- "Computers were the first God-Satan collaboration project." "Blind faith in bad leadership is not patriotism." "One of the most horrible features of war is that all the war-propaganda, all the screaming and lies and hatred, comes invariably from people who are not fighting."-George Orwell, _Homage to Catalonia From alan.gauld at btinternet.com Wed May 9 22:17:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 May 2007 21:17:22 +0100 Subject: [Tutor] Python fast enough for ad server? References: Message-ID: "OkaMthembo" wrote > I need to write an ad-serving application and i'm > using Win XP as my dev platform. The real issue is what are you using for your deployment platform,. If its Win XP then Python is probably fast enough since XP cannot handle huge volumes anyway. If its enterprise scale Windows or some other OS then there are other questions to ask. > i wonder if Python would have the performance or > scale fast enough to a large user base. Define large. Its not normally the number of users that matters but thenumber of concurrent users. Google has probably 10's of millions of users but less than a million at any one time. Are we talking google sizes? > Python and Java, but Jython only supports Python 2.2 Jython will not be significantly faster than Python. And unless you have a good optimising/JIT compiler neither will Java IMHO. But Python 2.2 would be adequate to write a server anyhow so you just lose a few of the latest bells and whistles, no big loss. Given the choice between Python 2.2. and Java 5 I know which I'd prefer... Alan G. From kent37 at tds.net Wed May 9 22:48:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 May 2007 16:48:30 -0400 Subject: [Tutor] Assembling multiple strings into one In-Reply-To: <20070509201615.evksn2zklb4k8o48@webmail.frontiernet.net> References: <20070509201615.evksn2zklb4k8o48@webmail.frontiernet.net> Message-ID: <4642339E.5070200@tds.net> Alan Gilfoy wrote: > I have a program producing a list of multiple strings. > The amount of strings in the list varies. > I want to assemble a string that is: > > list item 0 + space + list item 1 + space, > and so on, going through every string in the list. ' '.join(myList) Kent From jim at well.com Wed May 9 22:59:38 2007 From: jim at well.com (jim stockford) Date: Wed, 9 May 2007 13:59:38 -0700 Subject: [Tutor] Python fast enough for ad server? In-Reply-To: References: Message-ID: <07754de5adf3c760f52ba5e17a28e331@well.com> there's also the question of the delivery architecture: if there are multiple machines in a clustered configuration, even something such as DNS round robin, then improving performance is a matter of throwing machines at the front end. On May 9, 2007, at 1:17 PM, Alan Gauld wrote: > > "OkaMthembo" wrote > >> I need to write an ad-serving application and i'm >> using Win XP as my dev platform. > > The real issue is what are you using for your deployment > platform,. If its Win XP then Python is probably fast > enough since XP cannot handle huge volumes anyway. > If its enterprise scale Windows or some other OS then > there are other questions to ask. > >> i wonder if Python would have the performance or >> scale fast enough to a large user base. > > Define large. Its not normally the number of users > that matters but thenumber of concurrent users. > Google has probably 10's of millions of users > but less than a million at any one time. Are we > talking google sizes? > >> Python and Java, but Jython only supports Python 2.2 > > Jython will not be significantly faster than Python. > And unless you have a good optimising/JIT compiler > neither will Java IMHO. > > But Python 2.2 would be adequate to write a server > anyhow so you just lose a few of the latest bells > and whistles, no big loss. Given the choice between > Python 2.2. and Java 5 I know which I'd prefer... > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From agilfoy at frontiernet.net Wed May 9 22:41:43 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Wed, 09 May 2007 20:41:43 +0000 Subject: [Tutor] Another string-manipulation question Message-ID: <20070509204143.3hkdwydb6ckk0wgk@webmail.frontiernet.net> Given a string, how would I?: 1. Make sure only the first letter string_name[0], is capitalized. This would involve using string_name.lower() to lowercase everything else, but how do I use .upper(), or some other method, to capitalize only the first character? 2. Make sure that there are no symbols (non-letter, non-number) in the string, and, if one is found, remove it. Pseudocode time, as to a potential approach- for each character in the string: if character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": remove it -- "Computers were the first God-Satan collaboration project." "Blind faith in bad leadership is not patriotism." "One of the most horrible features of war is that all the war-propaganda, all the screaming and lies and hatred, comes invariably from people who are not fighting."-George Orwell, _Homage to Catalonia From washakie at gmail.com Wed May 9 23:42:34 2007 From: washakie at gmail.com (John Washakie) Date: Wed, 9 May 2007 23:42:34 +0200 Subject: [Tutor] Running and passing variables to/from Fortran In-Reply-To: References: Message-ID: I have access to the source code. And I probably could pass the data to stdout, so maybe .popen would work! I'll have a look... thanks! From Mike.Hansen at atmel.com Wed May 9 23:45:01 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 9 May 2007 15:45:01 -0600 Subject: [Tutor] Another string-manipulation question In-Reply-To: <20070509204143.3hkdwydb6ckk0wgk@webmail.frontiernet.net> References: <20070509204143.3hkdwydb6ckk0wgk@webmail.frontiernet.net> Message-ID: <57B026980605A64F9B23484C5659E32E7D454A@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gilfoy > Sent: Wednesday, May 09, 2007 2:42 PM > To: tutor at python.org > Subject: [Tutor] Another string-manipulation question > > Given a string, how would I?: > > 1. Make sure only the first letter string_name[0], is capitalized. > This would involve using string_name.lower() to lowercase everything > else, but how do I use .upper(), or some other method, to capitalize > only the first character? There's a string method called capitalize, so you can use string_name.capitalize() In [27]: x = "rakaNishu" In [28]: x = x.capitalize() In [29]: x Out[29]: 'Rakanishu' > > 2. Make sure that there are no symbols (non-letter, > non-number) in the > string, and, if one is found, remove it. > > Pseudocode time, as to a potential approach- > > for each character in the string: > if character not in > "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": > remove it Someone may have a better idea on this one. Off the top of my head, you can build a new string while checking each character using another string method isalpha. You might want to check the string first before even bothering with the loop. i.e. if not string_name.isalpha()...then enter this loop below... In [38]: x = "rakan345ishu" In [39]: newx = "" In [40]: for chr in x: ....: if chr.isalpha(): ....: newx += chr ....: In [41]: print newx rakanishu Mike From jdoege at da-test.com Wed May 9 23:47:18 2007 From: jdoege at da-test.com (Jason Doege) Date: Wed, 9 May 2007 17:47:18 -0400 Subject: [Tutor] Lexer implementation Message-ID: <0B363C44ED4B4945A08E20094B57144A0ED76A@venus-san> Hi All, Is there a classical way to implement a lexer in Python without using a parser toolkit? Something like the lexer MJD illustrates in Higher Order Perl, section 8.1.2. It's even better if it can act on a stream instead of a string. Best regards, Jason Doege -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070509/3883c6ee/attachment.htm From llenard_twem at yahoo.com Thu May 10 00:13:28 2007 From: llenard_twem at yahoo.com (Jeff Molinari) Date: Wed, 9 May 2007 15:13:28 -0700 (PDT) Subject: [Tutor] Alright... I'm new... Message-ID: <951134.84838.qm@web53212.mail.re2.yahoo.com> I've always been interested in learing to write my own programs but I never new where to start. Now I heard python is not only powerful but easy to use therefor making it good for begginers. So I looked it up, Downloaded python 2.5, I'm just in the middle of the first part of the first chapter ((don't get me wrong. I also looked up tutorials so I know most of what they already mentioned. I'm just stating that that is where I'm at in the book)) in "Python for Dummies" and I'm still lost. I'm understanding what its teaching me. Don't get me wrong. It's simple. Very straight forward. MUCH less confusing than C++. I've learned about, obviously, how to display text. I've learned about variables and having your user input data(such as a password. During the tutorial they taught me how to make a simple password type program thing.) Well!!! I'll get to the point now... I know I'm in the very early stages of programming. I'm just a big newb. But it just isn't clicking. I understand, as stated before, what I've been taught. But I don't understand how it could all come together to create a program. I understand that programs don't HAVE to have a GUI but when I think programs or software I think interactivity. I'm just not sure where this is leading me. I want to creat a fully functional program that actually does something USEFUL. It doesn't have to be big. But it has to actually do something other than add and subtract and display a simple string. Well I suppose I'm asking more for opinions and suggestions on how to go about learning. Thanks for listening to my nonsense. >_< --------------------------------- We won't tell. Get more on shows you hate to love (and love to hate): Yahoo! TV's Guilty Pleasures list. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070509/8b5cf8f1/attachment.html From nuin at genedrift.org Thu May 10 00:15:54 2007 From: nuin at genedrift.org (Paulo Nuin) Date: Wed, 09 May 2007 18:15:54 -0400 Subject: [Tutor] Queueing In-Reply-To: <0B363C44ED4B4945A08E20094B57144A0ED76A@venus-san> References: <0B363C44ED4B4945A08E20094B57144A0ED76A@venus-san> Message-ID: <4642481A.4010503@genedrift.org> Hi Everyone I need to a write a script that would do a queuing job on a cluster running openMosix Linux. I have checked the Queue module and that part I can say it is covered. My problem regards on thecode to check if the process has ended. As some most of the jobs would be run in different nodes I am having difficulties getting some example code to accomplish that. Thanks a lot for any helpful advice. Cheers Paulo From washakie at gmail.com Thu May 10 00:44:40 2007 From: washakie at gmail.com (John Washakie) Date: Thu, 10 May 2007 00:44:40 +0200 Subject: [Tutor] Alright... I'm new... In-Reply-To: <951134.84838.qm@web53212.mail.re2.yahoo.com> References: <951134.84838.qm@web53212.mail.re2.yahoo.com> Message-ID: > > I want to create a fully functional program that actually does something > USEFUL. And just what would that be? Ask yourself that.. then perhaps folks on the list could guide you in the right direction... -j From kent37 at tds.net Thu May 10 01:20:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 May 2007 19:20:37 -0400 Subject: [Tutor] Another string-manipulation question In-Reply-To: <20070509204143.3hkdwydb6ckk0wgk@webmail.frontiernet.net> References: <20070509204143.3hkdwydb6ckk0wgk@webmail.frontiernet.net> Message-ID: <46425745.1080801@tds.net> Alan Gilfoy wrote: > Given a string, how would I?: > 2. Make sure that there are no symbols (non-letter, non-number) in the > string, and, if one is found, remove it. > > Pseudocode time, as to a potential approach- > > for each character in the string: > if character not in > "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": > remove it A couple of solutions here: http://tinyurl.com/2qqy32 except substitute ascii_letters for printable. Kent From alan.gauld at btinternet.com Thu May 10 01:40:15 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 00:40:15 +0100 Subject: [Tutor] Alright... I'm new... References: <951134.84838.qm@web53212.mail.re2.yahoo.com> Message-ID: "Jeff Molinari" wrote > when I think programs or software I think interactivity. > I'm just not sure where this is leading me. > > I want to creat a fully functional program that actually > does something USEFUL. It doesn't have to be big. > But it has to actually do something other than add > and subtract and display a simple string. You have to start with small steps before you can run. Excel is considered by many to be a useful program but is at heart a program which reads strings and does simple math. It just does that a lot of times - once per cell. A Word Processor is essentially a program to read in strings and reformat them by inserting extra characters. A database stores data in files and searches for it again later. And most user programs (as opposed to servers) are essentially variations on those three themes. If we add manipulation of images and sound (which admittedly are more complex) and some basic networking(email/browsers) then you pretty much have the average PC users ambitions covered. But you have to understand the basics before you can put them together. Its likelearning the chords on a guitar before being able to accompany yourself, or composer a new tune. The better you grasp the basics the easier the more advanced stuff will be later. > Well I suppose I'm asking more for opinions and suggestions > on how to go about learning. Stick with a tutor and adapt the examples as you go. Be sure you understand what your changes did diffeently and why. As you keep going the examples will get bigger and more "real world" -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu May 10 01:42:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 00:42:36 +0100 Subject: [Tutor] Queueing References: <0B363C44ED4B4945A08E20094B57144A0ED76A@venus-san> <4642481A.4010503@genedrift.org> Message-ID: "Paulo Nuin" wrote > I need to a write a script that would do a queuing job on a cluster > running openMosix Linux. I have checked the Queue module and that > part I > can say it is covered. My problem regards on thecode to check if the > process has ended. While you may well get an answer here that is a bit advanced for a beginners mailing list. You will likely get more responses by posting on the main Python newsgroup comp.lang.python. Alan G. From eike.welk at gmx.net Thu May 10 02:13:08 2007 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 10 May 2007 02:13:08 +0200 Subject: [Tutor] Alright... I'm new... In-Reply-To: <951134.84838.qm@web53212.mail.re2.yahoo.com> References: <951134.84838.qm@web53212.mail.re2.yahoo.com> Message-ID: <200705100213.08971.eike.welk@gmx.net> On Thursday 10 May 2007 00:13, Jeff Molinari wrote: > I know I'm in the very early stages of programming. I'm just a > big newb. But it just isn't clicking. I understand, as stated > before, what I've been taught. But I don't understand how it could > all come together to create a program. I understand that programs > don't HAVE to have a GUI but when I think programs or software I > think interactivity. I'm just not sure where this is leading me. GUI programs are normally written with GUI toolkits (also called application frameworks). This way you don't have to write the drawing code for buttons and text and other standard GUI elements. The toolkits are usually written in C or C++ but many have Python bindings. Two prominent examples which I know of are: QT: http://doc.trolltech.com/4.2/index.html wxWidgets: http://www.wxwidgets.org/ Python however comes with an integrated GUI toolkit: Tkinter. http://www.pythonware.com/library/tkinter/introduction/ To give you an idea, here is a very simplistic example program. It should display a window with the words 'Hello world!' in it. Copy it into a file (for example test.py) and run it. #---------- program start--------------------------------- from Tkinter import * widget = Label(None, text='Hello world!') widget.pack() widget.mainloop() #---------- program end--------------------------------- I think you should follow the programming book, and when you are done with it you should ask on the list which GUI toolkit you should learn. Regards, Eike. From kent37 at tds.net Thu May 10 02:41:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 May 2007 20:41:19 -0400 Subject: [Tutor] Queueing In-Reply-To: <4642481A.4010503@genedrift.org> References: <0B363C44ED4B4945A08E20094B57144A0ED76A@venus-san> <4642481A.4010503@genedrift.org> Message-ID: <46426A2F.5040501@tds.net> Paulo Nuin wrote: > Hi Everyone > > I need to a write a script that would do a queuing job on a cluster > running openMosix Linux. I have checked the Queue module and that part I > can say it is covered. My problem regards on thecode to check if the > process has ended. As some most of the jobs would be run in different > nodes I am having difficulties getting some example code to accomplish that. I don't think the Queue module will help you with multi-processing, it is useful for inter-thread communication within a single process. There are several Python packages that help with multi-processing; one is here: http://www.parallelpython.com/ and others are referenced in the Links section of the above site. Also http://www.python.org/pypi?%3Aaction=search&term=parallel&submit=search HTH Kent From eike.welk at gmx.net Thu May 10 03:03:02 2007 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 10 May 2007 03:03:02 +0200 Subject: [Tutor] Alright... I'm new... In-Reply-To: <200705100213.08971.eike.welk@gmx.net> References: <951134.84838.qm@web53212.mail.re2.yahoo.com> <200705100213.08971.eike.welk@gmx.net> Message-ID: <200705100303.02222.eike.welk@gmx.net> Excuse me, there is one character too much in the example program. This time I send it as an attachment. Eike. -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: application/x-python Size: 96 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070510/ba7b2e62/attachment.bin From eike.welk at gmx.net Thu May 10 03:38:48 2007 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 10 May 2007 03:38:48 +0200 Subject: [Tutor] Alright... I'm new... In-Reply-To: <200705100303.02222.eike.welk@gmx.net> References: <951134.84838.qm@web53212.mail.re2.yahoo.com> <200705100213.08971.eike.welk@gmx.net> <200705100303.02222.eike.welk@gmx.net> Message-ID: <200705100338.48283.eike.welk@gmx.net> The attachment is also wrong! Delete the first character ('>') from the program and it will be syntactically correct. The addition of the '>' character is a bug in my mail program (KMail) I think. It is probably a remnant of the first two characters of a UTF8 file. Eike. From rikard.bosnjakovic at gmail.com Thu May 10 06:05:13 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Thu, 10 May 2007 06:05:13 +0200 Subject: [Tutor] Type Conversion In-Reply-To: References: <0C3757779992458D81F17ECB03E89989@TeresPC> <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> <3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC> <5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com> <989CF4DD96564F78A68A618A015C86CD@TeresPC> <4641CEAE.CB8D.003F.0@npsd.k12.wi.us> Message-ID: On 5/9/07, Alan Gauld wrote: > Please don;t hijack a thread to ask something unrelkated. > Start a new threead it helps keep things clear and makkes > it easier to find responses later. What do you mean by hijack a thread? Her subject "Type conversion" is the only occurence in this list, hence it's an original post. -- - Rikard - http://bos.hack.org/cv/ From bgailer at alum.rpi.edu Thu May 10 06:15:51 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 09 May 2007 21:15:51 -0700 Subject: [Tutor] Running and passing variables to/from Fortran In-Reply-To: References: Message-ID: <46429C77.9030702@alum.rpi.edu> John Washakie wrote: > I have access to the source code. Did you tell us why you want to keep the code in FORTRAN? Would converting it to Python solve the issue? -- Bob Gailer 510-978-4454 From akap at isd.dp.ua Thu May 10 08:40:48 2007 From: akap at isd.dp.ua (Alexander Kapshuk) Date: Thu, 10 May 2007 09:40:48 +0300 Subject: [Tutor] problems with running IDLE under Windows 95 Message-ID: <70831DC71E5D814C9D1FA8A96653215E090D6496@server.isd.dp.ua> Hello to All of the Python Community, I'd like to thank all those who replied to my last email about Python not installing under Windows 95. That problem's been overcome. Although, after installing Python 2.5.1 I ran into another difficulty. IDLE wouldn't start. Another thing I did was uninstall Python 2.5.1 and install Python 2.2.3 to see if it would make any difference. It didn't. I'd click on the IDLE icon, the hourglass thing would come up for a few seconds and then it would disappear. What could the problem be there? Thanking you in advance and looking forward to hearing from those of you who may have an answer. Regards, Alexander Kapshuk ISD Education Office ICQ#295-121-606 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/6b6a916e/attachment.htm From alan.gauld at btinternet.com Thu May 10 09:25:46 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 10 May 2007 07:25:46 +0000 (GMT) Subject: [Tutor] Type Conversion Message-ID: <534705.9099.qm@web86113.mail.ird.yahoo.com> On 5/9/07, Alan Gauld wrote: > > Please don;t hijack a thread to ask something unrelkated. > >Start a new threead it helps keep things clear and makkes > >it easier to find responses later. > > What do you mean by hijack a thread? > > Her subject "Type conversion" is the only occurence in this list, > hence it's an original post. My apologies in that case. On the gmane news feed it appears as a reply to the thread 'canvas->make an object move'... I must have been feeling extra grumpy yesterday. Alan G ___________________________________________________________ Web email has come of age. Don't settle for less than the All New Yahoo! Mail http://uk.docs.yahoo.com/nowyoucan.html From alan.gauld at btinternet.com Thu May 10 09:35:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 08:35:01 +0100 Subject: [Tutor] problems with running IDLE under Windows 95 References: <70831DC71E5D814C9D1FA8A96653215E090D6496@server.isd.dp.ua> Message-ID: "Alexander Kapshuk" wrote > .... I'd click on the IDLE icon, the hourglass thing > would come up for a few seconds and then it > would disappear. > > What could the problem be there? Can you try starting IDLE from a command prompt? ie. Using python idle.py That may produce some error messages in the console that will help diagnose the propblem. My suspicion is that although Python works on Win95 the underlying Tcl/Tk libraries do not. But that's a guess. Alan G From zebra05 at gmail.com Thu May 10 11:40:33 2007 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 10 May 2007 11:40:33 +0200 Subject: [Tutor] Python fast enough for ad server? In-Reply-To: <4641EBC2.8080304@ericwalstad.com> References: <4641EBC2.8080304@ericwalstad.com> Message-ID: Thanks for all your contributions. i think i will do it all in Python, it seems to me that the advantages far outweigh any negatives. Maybe once its a working project, we can then benchmark the code and see what gives. Thanks again, Lloyd On 5/9/07, Eric Walstad wrote: > > Hey OkaMthenbo, > > OkaMthembo wrote: > > Hi guys, > > > > I need to write an ad-serving application and i'm using Win XP as my dev > > platform. Naturally, i want it to be as painless as possible and i was > > thinking of writing it 100% in Python. However, i have not written any > > big apps in the language and i wonder if Python would have the > > performance or scale fast enough to a large user base. > Most certainly for some definitions of 'large' :) > > Most web apps these days are not written in a single language/technology > and are often not running on a single piece of hardware. If you search > the archives of your favorite Python web application framework I'm > pretty sure you'll find a discussion on how to scale your app to handle > a 'large' user base. At the risk of oversimplification, but in hopes of > avoiding premature optimization, I'd focus first on achieving working > code, then benchmark it, then optimize if optimization is still needed. > > Many others have achieved high volume Python web apps using a mix of all > the wonderful open source tools available. If your content doesn't > change quickly and the ratio of GETs/POSTs is high, a caching server in > front of your python app might be just the trick (memcached, squid,etc). > But don't waste your time if you don't need to. Define 'too slow' and > then prove to yourself that your app passes that threshold. If so, then > figure out why it's slow and optimize the slow parts. > > Good luck, > > Eric. > -- "The Stupidry Foundry" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/8a216432/attachment.html From kent37 at tds.net Thu May 10 12:23:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 May 2007 06:23:08 -0400 Subject: [Tutor] Hijacking a Thread (Re: Type Conversion) In-Reply-To: References: <0C3757779992458D81F17ECB03E89989@TeresPC> <5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com> <3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC> <5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com> <989CF4DD96564F78A68A618A015C86CD@TeresPC> <4641CEAE.CB8D.003F.0@npsd.k12.wi.us> Message-ID: <4642F28C.60703@tds.net> Rikard Bosnjakovic wrote: > On 5/9/07, Alan Gauld wrote: > >> Please don;t hijack a thread to ask something unrelkated. >> Start a new threead it helps keep things clear and makkes >> it easier to find responses later. > > What do you mean by hijack a thread? > > Her subject "Type conversion" is the only occurence in this list, > hence it's an original post. When you start a new thread by posting a message with an unrelated topic as a reply to a message on an existing thread, that is called hijacking the thread. The Type Conversion message was posted in this way as you can see if you look at the message headers; it is a reply to one of Teresa Stanton's messages. When you hijack a thread, threaded newsreaders will show the new message and its replies in the original thread. This is disruptive to the flow of the original thread. Also anyone who has stopped reading the original thread will miss the new one. The correct way to start a new thread is with a new email that is not a reply to another. Kent From akap at isd.dp.ua Thu May 10 15:06:38 2007 From: akap at isd.dp.ua (Alexander Kapshuk) Date: Thu, 10 May 2007 16:06:38 +0300 Subject: [Tutor] IDLE running fine now under Windows 95:-) Message-ID: <70831DC71E5D814C9D1FA8A96653215E090D6522@server.isd.dp.ua> IDLE in Python 2.2.3 working fine on my laptop now. I'd like to give Python 2.5.1 one more try though:-). Looks like it didn't 'seem' to run not because there was something wrong with the laptop or Windows as such, but because of the USER not being patient enough. It's an old beaten up thing that requires a certain amount of patience on the part of the user. I was able to run it successfully for the first time by accessing it directly from Python22\Tools\Idle\idle.py and then the 2nd time by clicking on the IDLE icon on my desktop. So, sorry for causing much ado about nothing:-). Thank you all once again. Regards, Alexander Kapshuk ISD Education Office ICQ#295-121-606 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/a5de7322/attachment.htm From pthanos at gmail.com Thu May 10 15:18:32 2007 From: pthanos at gmail.com (Thanos Panousis) Date: Thu, 10 May 2007 15:18:32 +0200 Subject: [Tutor] Web GUI for a network management tool Message-ID: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> Hello list, I have been developing a network managemetn app for quite some time now. The list has provided me with valuable information. The time has come to write some kind of gui for it, so that graphs, visualizations and configuration options are exposed to non developers. Do you think that a web app frame work like turbogears is appropriate in my case? Have you ever done anything like that, and how did you go about doing it? Would web frameworks (turbogears, Ruby on rails, Java frameworks) be any use to me in something like my case or I should just roll my own? Thanos. From alan.gauld at btinternet.com Thu May 10 16:37:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 15:37:48 +0100 Subject: [Tutor] Web GUI for a network management tool References: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> Message-ID: "Thanos Panousis" wrote > The time has come to write some kind of gui for it, so that graphs, > visualizations and configuration options are exposed to non > developers. Do you think that a web app frame work like turbogears > is > appropriate in my case? Graphs etc on web apps can be problematic, but thats true of all web apps regardless of framework. You may need to hunt for some graphing code to suit the framework you choose - or maybe a Java applet. > Have you ever done anything like that, and how did you go about > doing > it? Would web frameworks (turbogears, Ruby on rails, Java > frameworks) > be any use to me in something like my case or I should just roll my > own? Any web framework will be better than roilling your own if you are developing more than a few pages and particularly if you want to keep clean separation between your model and the UI aspects. There are a host of Python web frameworks, the most popular nowadays seem to be Django and TurboGears. I favour TG myself but to be honest they all offer much the same features: - a templating language to link HTML and code - A mapping mechanism from url to a python method - an object-database mapper HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu May 10 16:53:57 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 May 2007 10:53:57 -0400 Subject: [Tutor] Web GUI for a network management tool In-Reply-To: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> References: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> Message-ID: <46433205.2050003@tds.net> Thanos Panousis wrote: > Hello list, > > I have been developing a network managemetn app for quite some time > now. The list has provided me with valuable information. > > The time has come to write some kind of gui for it, so that graphs, > visualizations and configuration options are exposed to non > developers. Do you think that a web app frame work like turbogears is > appropriate in my case? It's not clear to me from your description that you want a web app. Does the management app run on a server or is it something that individual users run on their own machines? If the app runs on a server then a web framework can be very helpful. I like Django a lot but there are many other choices. If users run the app on their individual computers then you should look at one of the GUI toolkits like Tkinter or wxPython. > Have you ever done anything like that, and how did you go about doing > it? Would web frameworks (turbogears, Ruby on rails, Java frameworks) > be any use to me in something like my case or I should just roll my > own? I have used Django and matplotlib to create charts and display them in a web page. There is a simple example here: http://www.scipy.org/Cookbook/Matplotlib/Django Both Tkinter and wxPython are supported by matplotlib directly. Kent From tms43 at clearwire.net Thu May 10 18:59:19 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Thu, 10 May 2007 09:59:19 -0700 Subject: [Tutor] canvas -> CLASSES In-Reply-To: References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC><5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com><989CF4DD96564F78A68A618A015C86CD@TeresPC> Message-ID: OK.... Would it be ... er... uh... 'proper'... to put the maze in a module, then make the actual movement of the .gif's in a class in a seperate file (module)? I find the code required to build the maze to be quite large, even with the refinenements. For now, at least, I can't figure out how to do the maze in a class, and I want to get the .gif moving in a class because that makes sense. But I'm not sure how to put the .gif ON the maze if they are seperate files. I will, of course import the maze, but then, how do I put the gif on the maze from the class? Is it even possible? am I asking the right question? T ----- Original Message ----- From: "Alan Gauld" To: Sent: Wednesday, May 09, 2007 1:08 PM Subject: Re: [Tutor] canvas -> CLASSES > > "Teresa Stanton" wrote >> CLASSES: This is where I start getting confused. > > No kidding! :-) > >> put it into a class, and for some reason it all starts to get >> jumbled here, >> which it shouldn't because I write in C++. > > C++ OOP and Python are significantly different and some of > those differences may be at work here. > >> Since I've put it in a class, my design is off because I don't know >> how to >> 'call' it, among other issues. > > You need an instance which you don;t have currently. > >> Do the point definitions of the walls, boxes and T's get >> put inside the function? > > Probably not, probably etter to puut them in a list - as you do - and > pass the list into the method. > >> Right now the function calls itself and I don't think its the best >> way to do it, > > Nor do I, but I'mnot clear exactly what you are doing since > the data is all hard coded inside the function so it looks to me > like you will you will get into a loop... > > Some snippets and comments follow: > >> class Maze(object): >> def __init__(self): >> #initial position of .gif >> self.xp = 100 >> self.yp = 600 > > You don't seem to use selfd.xp/yp anywhere... > In fact since you don't initialize any objects this never even > gets called! > >> def createWall((x0, y0), (x1, y1), colour = 'blue', width = 3): >> """ Create a wall from (x0, y0) to (x1, y1). """ >> canvasOne.create_line(x0, y0, x1, y1, width = width, fill = >> colour) > > You don't have a self parameter in the method. Recall that > self is equivalent to this in C++ but needs to be explicitly > declared in Python methods. > > Also you are declaring parameters to be tuples which I don't > think you can do. You need to name the tuples, something like: > > def createWall(self, pt1,pt2, canvas = None, colour='blue', width=3) > > Also you use the canvasOne global value here which would > be better passed in as am parameter as shown above. > >> outerWall = [(450, 640), (475, 640), (475, 640), >> walls = [outerWall] > > Not sure why the second line is there. > The first is static data which means the method never changes > what it does. You never use the x0,y0, params passed in after > the create line above... > >> for wall in walls: >> for i in range(len(wall)-1): >> createWall(outerWall[i], outerWall[i+1]) > > For each entry draw a kine then come back into this loop > using the same data so we very quickly hit the Python > recursion limit I suspect. > >> topLeftBox = [(130, 105), (130, 125), ... >> secondTopLeftBox = [(160, 215), (160, 225), ... >> ... >> boxes = [topLeftBox, secondTopLeftBox, topRightBox, >> secondTopRightBox] >> >> for box in boxes: >> for i in range(len(box)-1): >> createWall(topLeftBox[i], topLeftBox[i+1]), >> createWall(secondTopLeftBox[i], >> secondTopLeftBox[i+1]), > > Sorry, I have no idea how this is supposed to work. I just got > confused about the mix of topLefts and box versus boxes etc. > > But remember that each call to createWall only uses the arguments > to draw a single line, then the rest uses the same data over again. > > Also to acces createWall you should really be using self.createWall > since createWall is a method of your Maze class. > >> x = 40 >> for i in range(9): >> x += 20 >> canvasOne.create_rectangle(x, 610, x+5, 615, fill = >> 'white') >> >> #left path built north to south >> y = 290 >> for i in range(15): >> y += 20 >> canvasOne.create_rectangle(220, y, 225, y+5, fill = >> 'white') > > > All these bits could be put into a function with the values as > parameters, something like:: > > def buildPath(val1,val2, number, increment, deltax,deltay,orientation, > fill='white') > for i in range(number): > val1 += increment > if orientation = 0: x,y = val1,val2 > else: x,y = val2,val1 > canvas.create_rectangle(x,y,x+deltax,y+deltay,fill) > > >> root = Tk() >> root.title("Background") >> >> canvasOne = Canvas(width = 800, height = 700, bg = 'black') >> createWall(450, 640, 475, 640) >> canvasOne.pack() >> >> root.mainloop() > > > Here yuou call createWall which is a method of Maze but you > don't instantiate Maze. I'd expect so9mething like: > > maze = Maze(x,y) > maze.createWall(....) > > But there's a lot of logic missing between there ared here. > Alsoi if thats all you are doing there is no point of having > a maze class, just write a createWall function. You need > to figure out what a Maze object is for. What are its > responsibilities in the program? What data does it manage? > What actions do you want it top perform? > > Unfortunately from your code I can't work out what you were > expecting of your Maze instances. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From nuin at genedrift.org Thu May 10 19:01:23 2007 From: nuin at genedrift.org (Paulo Nuin) Date: Thu, 10 May 2007 13:01:23 -0400 Subject: [Tutor] Queueing In-Reply-To: <46426A2F.5040501@tds.net> References: <0B363C44ED4B4945A08E20094B57144A0ED76A@venus-san> <4642481A.4010503@genedrift.org> <46426A2F.5040501@tds.net> Message-ID: <46434FE3.6080707@genedrift.org> Hi Thanks a lot Alan and Kent for the replies. Cheers Paulo Kent Johnson wrote: > Paulo Nuin wrote: >> Hi Everyone >> >> I need to a write a script that would do a queuing job on a cluster >> running openMosix Linux. I have checked the Queue module and that >> part I can say it is covered. My problem regards on thecode to check >> if the process has ended. As some most of the jobs would be run in >> different nodes I am having difficulties getting some example code to >> accomplish that. > > I don't think the Queue module will help you with multi-processing, it > is useful for inter-thread communication within a single process. > > There are several Python packages that help with multi-processing; one > is here: > http://www.parallelpython.com/ > > and others are referenced in the Links section of the above site. Also > http://www.python.org/pypi?%3Aaction=search&term=parallel&submit=search > > HTH > Kent From duncan at thermal.esa.int Thu May 10 18:25:08 2007 From: duncan at thermal.esa.int (Duncan Gibson) Date: Thu, 10 May 2007 18:25:08 +0200 Subject: [Tutor] Generating simple HTML from within Python Message-ID: <20070510162508.78A981E27@zeeman.thermal.esa.int> I'm updating an application at the moment that generates simple HTML files. However, it's all done using plain strings and brute force. It's hard to read, and isn't very robust in the face of special characters and matching start and end tags. I've been searching for a module to allow simple HTML generation, but most of them appear to be more concerned with *parsing* HTML and XML. The only one that looks promising from reviews dating back to 1998 or so is HTMLgen, but the link on starship.python.net appears long dead. So my question is, what is the preferred way of generating simple HTML or XHTML files these days? Is there a 'son of HTMLgen' or similar module? Cheers Duncan PS. Apologies if this shows up twice. My first post seems to be MIA. From eric at ericwalstad.com Thu May 10 20:01:12 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Thu, 10 May 2007 11:01:12 -0700 Subject: [Tutor] Web GUI for a network management tool In-Reply-To: References: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> Message-ID: <46435DE8.8070904@ericwalstad.com> Hi Thanos, Alan Gauld wrote: > "Thanos Panousis" wrote > >> The time has come to write some kind of gui for it, so that graphs, >> visualizations and configuration options are exposed to non >> developers. Do you think that a web app frame work like turbogears >> is >> appropriate in my case? > > Graphs etc on web apps can be problematic, but thats true of > all web apps regardless of framework. You may need to hunt > for some graphing code to suit the framework you choose > - or maybe a Java applet. I'm not sure how complex your charts/graphs need to be. Here's a simple Django solution for simple HTML Bar Charts that may give you some ideas for solving the problem: and an example of what it looks like: I'd be interested to hear about how you ultimately solve the problem when you are done. Best, Eric. From alan.gauld at btinternet.com Thu May 10 20:04:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 19:04:36 +0100 Subject: [Tutor] canvas -> CLASSES References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC><5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com><989CF4DD96564F78A68A618A015C86CD@TeresPC> Message-ID: "Teresa Stanton" wrote > Would it be ... er... uh... 'proper'... to put the maze in a module, It doesn't really matter except thatr putting it in a module makes it easier to reuse in another program later. > make the actual movement of the .gif's in a class in a seperate file > (module)? Yes that works too. > I find the code required to build the maze to be quite large, > even with the refinenements. What do you see the maze as doing? What methods will it have? I would expect it to know about - its layout and geometry - objects within the maze(their location) - How to draw itself - possibly be delegating some of that to the contained objects. > For now, at least, I can't figure out how to do the maze in > a class, If you only have a single instance of maze then you may not need a class and a set of plain old functions may be just as effective. > and I want to get the .gif moving in a class because > that makes sense. OK, So I'm asssuming these gifs represent something, not actual gif files? So the class should probably represent that something. > But I'm not sure how to put the .gif ON the maze if they > are seperate files. I'm not sure whjat you are finding hard hgere. If they are in separate modules just import the modules as needed? > I will, of course import the maze, but then, how do I put > the gif on the maze from the class? Pass the instances of the gif class (ie the objects) into the maze. Presumably you have some kinde of method for controlling these gif objects? Either you move the gif object or you ask the maze to move them. Given that only the maze knows its own geometry I'd suggest getting the maze to move them. It should either return a success code, the new location of the gif or an error code if the piece couldn't be moved - either because another gif blocks it or the geometry has no path in that direction. You also need to decide what movement method you will use - coordinates(x,y) or vectors(direction+magnitude) These are all design decision oinly you can make and any of the technioques can be made to work. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From Mike.Hansen at atmel.com Thu May 10 20:42:12 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 10 May 2007 12:42:12 -0600 Subject: [Tutor] Generating simple HTML from within Python In-Reply-To: <20070510162508.78A981E27@zeeman.thermal.esa.int> References: <20070510162508.78A981E27@zeeman.thermal.esa.int> Message-ID: <57B026980605A64F9B23484C5659E32E7D461B@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Duncan Gibson > Sent: Thursday, May 10, 2007 10:25 AM > To: tutor at python.org > Subject: [Tutor] Generating simple HTML from within Python > > > I'm updating an application at the moment that generates simple HTML > files. However, it's all done using plain strings and brute force. > It's hard to read, and isn't very robust in the face of special > characters and matching start and end tags. > > I've been searching for a module to allow simple HTML generation, but > most of them appear to be more concerned with *parsing* HTML and XML. > The only one that looks promising from reviews dating back to 1998 or > so is HTMLgen, but the link on starship.python.net appears long dead. > > So my question is, what is the preferred way of generating simple HTML > or XHTML files these days? Is there a 'son of HTMLgen' or > similar module? > > Cheers > Duncan > > PS. Apologies if this shows up twice. My first post seems to be MIA. Did you search the Cheese Shop. I did a search for "html generator", and there's a few couple of modules mike html 0.4.0 and markup.py 1.6.1 that look like they might do the trick. http://www.python.org/pypi Mike From kent37 at tds.net Thu May 10 20:50:09 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 May 2007 14:50:09 -0400 Subject: [Tutor] Generating simple HTML from within Python In-Reply-To: <20070510162508.78A981E27@zeeman.thermal.esa.int> References: <20070510162508.78A981E27@zeeman.thermal.esa.int> Message-ID: <46436961.90509@tds.net> Duncan Gibson wrote: > I've been searching for a module to allow simple HTML generation, but > most of them appear to be more concerned with *parsing* HTML and XML. > The only one that looks promising from reviews dating back to 1998 or > so is HTMLgen, but the link on starship.python.net appears long dead. > > So my question is, what is the preferred way of generating simple HTML > or XHTML files these days? Is there a 'son of HTMLgen' or similar module? There are many options. Here is a starting point: http://wiki.python.org/moin/Templating Some discussion of HTMLGen (and an offer of a zip file) here: http://tinyurl.com/2zz53e Kent From nephish at gmail.com Thu May 10 20:52:04 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 10 May 2007 13:52:04 -0500 Subject: [Tutor] how to stop output to terminal Message-ID: <384c93600705101152o59a81991yb5183bd0e8c97c26@mail.gmail.com> lo there all, i have a simple thread that i want to run without piping any output to the terminal. like if i do an x = os.system("ping -c 1 www.google.com") i don't want it to show all the stuff in the terminal. can i disable that ? can i disable it for only certain lines? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/bba335ad/attachment.htm From tms43 at clearwire.net Thu May 10 21:06:51 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Thu, 10 May 2007 12:06:51 -0700 Subject: [Tutor] canvas -> CLASSES In-Reply-To: References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC><5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com><989CF4DD96564F78A68A618A015C86CD@TeresPC> Message-ID: ----- Original Message ----- From: "Alan Gauld" To: Sent: Thursday, May 10, 2007 11:04 AM Subject: Re: [Tutor] canvas -> CLASSES > Alan said: > What do you see the maze as doing? T's reply: The maze is simply the backdrop. I've attached the new and improved code. Alan said: > OK, So I'm asssuming these gifs represent something, not actual gif > files? T's reply: um... actually, the .gif will be a photo that will be taken as part of the 'game'. In other words, eventually, the user will be able to take a series pictures of themselves if they have a webcam (I have a script that will do that). Then, the first pic (without going into too much detail) will be the main pic as it goes around the maze. When the pic 'collides' with items that will be placed (much like a pacman game) another pic will be displayed (happy for good items, sad for bad items). So, now I'm building the .gif class and will post questions, or successes as they occur. Thank you for your help and suggestions, and for any 'future' suggestions (wink). T From tms43 at clearwire.net Thu May 10 21:13:44 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Thu, 10 May 2007 12:13:44 -0700 Subject: [Tutor] canvas -> CLASSES In-Reply-To: References: <0C3757779992458D81F17ECB03E89989@TeresPC><5e58f2e40705031636t44976438kfe4ef0d0938af10a@mail.gmail.com><3AA8B394C35D427EB5CCE3BE35B1BAED@TeresPC><5e58f2e40705071522n53e8fd7dr6378164da54981d6@mail.gmail.com><989CF4DD96564F78A68A618A015C86CD@TeresPC> Message-ID: <6F8127BFD0D949ADAFC14FC960A8432F@TeresPC> Um... Here's the attached code, sorry. >> Alan said: >> What do you see the maze as doing? > > T's reply: > The maze is simply the backdrop. I've attached the new and improved code. > > Alan said: >> OK, So I'm asssuming these gifs represent something, not actual gif >> files? > > T's reply: > um... actually, the .gif will be a photo that will be taken as part of the > 'game'. In other words, eventually, the user will be able to take a > series > pictures of themselves if they have a webcam (I have a script that will do > that). Then, the first pic (without going into too much detail) will be > the > main pic as it goes around the maze. When the pic 'collides' with items > that will be placed (much like a pacman game) another pic will be > displayed > (happy for good items, sad for bad items). > > So, now I'm building the .gif class and will post questions, or successes > as > they occur. > > Thank you for your help and suggestions, and for any 'future' suggestions > (wink). > > T > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: mazeRev.pyw Url: http://mail.python.org/pipermail/tutor/attachments/20070510/4e4d1459/attachment-0001.asc From tms43 at clearwire.net Thu May 10 22:55:50 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Thu, 10 May 2007 13:55:50 -0700 Subject: [Tutor] Maze - classes Message-ID: <9EB03B64C50B41B0AC7B450F05003042@TeresPC> I hope you are not tired of me posting about this, but I'm determined to understand what I'm doing wrong, and that means I'm pounding away, searching and not able to fix it or find what the problem is. I've written the class to make the .gif move. Now, this did work (to a point) when I was writing it as more of a script. I could get the .gif to move from one place to another, only to start at the same place again. That is why the class became important, because I don't believe in globals. With my latest changes I get an error. I've attached the latest code. The problem is at the bottom where I'm trying to bind an event to . This is the error message I get: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) TypeError: unbound method direction() must be called with Images instance as first argument (got Event instance instead) I've done some searching in the Greyson book (finally downloaded it) and can't seem to see what's wrong. I also did a search on the 'TypeError:' which I find funny because I thought Python wasn't strongly typed. But I suppose that this is a simple error that one of you incredibly bright people will look at and I will respond with a 'Doh' (and a slap to the forehead). At least I hope so! Thanks T -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/43d0e82a/attachment.html -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: mazeRev.pyw Url: http://mail.python.org/pipermail/tutor/attachments/20070510/43d0e82a/attachment.pot -------------- next part -------------- A non-text attachment was scrubbed... Name: DustY.gif Type: image/gif Size: 6733 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070510/43d0e82a/attachment.gif From alan.gauld at btinternet.com Thu May 10 23:03:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 22:03:52 +0100 Subject: [Tutor] Generating simple HTML from within Python References: <20070510162508.78A981E27@zeeman.thermal.esa.int> Message-ID: "Duncan Gibson" wrote > I've been searching for a module to allow simple HTML generation, > but > most of them appear to be more concerned with *parsing* HTML and > XML. > The only one that looks promising from reviews dating back to 1998 > or > so is HTMLgen, but the link on starship.python.net appears long > dead. HTMLgen is OK but you might be better off looking at one of the templating tookits like Cheetah or Kid. Kid is fine for XHTML but I believe Cheetah is more flexible if you want non XML compliant HTML etc too. However I can only speak for Kid in the context of TurboGears... And if its not overly complex simple python string formatting might be all you need with the HTML inside a triple quoted string with formatting markers as needed. But a proper templating system will cope with repeating elements like tables much better. Alan G. From alan.gauld at btinternet.com Thu May 10 23:05:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 22:05:05 +0100 Subject: [Tutor] Generating simple HTML from within Python References: <20070510162508.78A981E27@zeeman.thermal.esa.int> Message-ID: "Duncan Gibson" wrote > I've been searching for a module to allow simple HTML generation Further to my last reply here are the urls: http://www.cheetahtemplate.org/ http://kid-templating.org/ HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu May 10 23:26:55 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 10 May 2007 21:26:55 +0000 (GMT) Subject: [Tutor] canvas -> CLASSES Message-ID: <605161.25153.qm@web86101.mail.ird.yahoo.com> > T's reply: > The maze is simply the backdrop. I've attached the new and improved code. As I said in the last post I think the maze probably needs to be quite a bit more than the backdrop. I think it knows about the rules of movement within the maze - which routes are blocked, where other players are sitting etc. > > OK, So I'm asssuming these gifs represent something, > um... actually, the .gif will be a photo that will be taken as > part of the 'game'. ... the first pic will be the main pic as > it goes around the maze. When the pic 'collides' with items > that will be placed another pic will be displayed OK, In that case it sounds like the gif is only how the object will draw itself. The object is actually some kind of player, which has a status which is reflected by the gif displayed? So the player c;lass will have methods to play the game, a status attribute, a collection of gifs to match the status, a location of some kind and a draw method that displays the appropriate gif when requested by the maze. With those two class definitions in mind I'd suggest an architecture where: A maze is created and populated by players The maze draws itself and then asks each player to draw itself. Players then do something (whatever the game requires) and that may involve asking the maze to move them to a new location. The maze will look at their position relative to the layout of the maze and the position of other players/objects. If the move can be made it moves the player and sets its new location. The maze then redaws itself, including asking the players/objects to redraw themselves at their new positions. (If you want to get really smart you could just redraw the sections of maze that have changed, but that's quite tricky to manage reliably) The whole thing could be controlled by an overall Game object which contains the maze and a list of players (some or all of which could be in the maze). The game object is responsible for ensuring each player makes plays at the appropriate time or receives the user events and matches them to a player as appropriate. Does that sound like a workable model? BTW Have you looked at PyGame (www.pygame.org) which has things like sprites etc which may make some of this stuff easier. HTH, Alan G. ___________________________________________________________ Inbox full of unwanted email? Get leading protection and 1GB storage with All New Yahoo! Mail. http://uk.docs.yahoo.com/nowyoucan.html From alan.gauld at btinternet.com Thu May 10 23:42:37 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2007 22:42:37 +0100 Subject: [Tutor] Maze - classes References: <9EB03B64C50B41B0AC7B450F05003042@TeresPC> Message-ID: "Teresa Stanton" wrote > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ > return self.func(*args) > TypeError: unbound method direction() must be called > with Images instance as first argument (got Event instance instead) This usually means you missed self as the first parameter in your method definition. > I also did a search on the 'TypeError:' which I find funny > because I thought Python wasn't strongly typed. Python is strongly typed, but its not statically typed. That is all arguments are type checked at run time based on their ability to respond to the operations required. Thus: >>> def add(x,y): return x+y ... >>> add(4,5) 9 >>> add('four',5) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in add TypeError: cannot concatenate 'str' and 'int' objects >>> add(5,'four') Traceback (most recent call last): File "", line 1, in ? File "", line 1, in add TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> Notice that the two errors are different because in the first it sees the string and tries to apply string contatenation with the int. In the second it sees an int and tries to add the string. But both are type errors because the arguments don't support the required operations. Alan G. From jeffpeery at yahoo.com Fri May 11 01:28:46 2007 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 10 May 2007 16:28:46 -0700 (PDT) Subject: [Tutor] whats the best way to structure my data? Message-ID: <75290.55852.qm@web43138.mail.sp1.yahoo.com> hello, I was wondering what might be the best way to structure my data within python. I am sampling data points, and in each there is a time, value, and text string associated with that sample. so I was thinking I'd make a list of 'measurement objects' and each object would have the attributes: time, value, and text... but I want to operate on the numerical values to find the average and stdev... so I'm not sure how to operate on my data if it is inside an object. right now I have three arrays, a date array, a value array, and a text array. so I can operate on each array without trouble. but it'd be cleaner in my code and easier to deal with if I had a list of these measurement objects. for example: # a class for my measurements class measurement: def __init__(self): self.text = '' self.value=0 self.time=datetime.today() # I start with an empty list measurements = [] # as I collect data in my code I append an object to the list measurements.append(sample) measurements[-1].value = value measurements[-1].text = text measurements[-1].time = time # now I don't know what to do here. I want the mean of all my data # but I need a list or array to operate on but instead my data is inside each object # I don't really want to make a temporary array, is there a way to operate on the # data in all my objects as if it were an array or list? mean = numpy.mean(????) is there a way to operate on the data when it is structured like this? thanks. Jeff --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/950fff79/attachment.htm From john at fouhy.net Fri May 11 01:38:28 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 11 May 2007 11:38:28 +1200 Subject: [Tutor] whats the best way to structure my data? In-Reply-To: <75290.55852.qm@web43138.mail.sp1.yahoo.com> References: <75290.55852.qm@web43138.mail.sp1.yahoo.com> Message-ID: <5e58f2e40705101638k6b73e6a0w6762ff24d7398ec4@mail.gmail.com> On 11/05/07, Jeff Peery wrote: > hello, I was wondering what might be the best way to structure my data > within python. I am sampling data points, and in each there is a time, > value, and text string associated with that sample. so I was thinking I'd > make a list of 'measurement objects' and each object would have the > attributes: time, value, and text... but I want to operate on the numerical > values to find the average and stdev... so I'm not sure how to operate on my > data if it is inside an object. [...] > mean = numpy.mean(????) > > is there a way to operate on the data when it is structured like this? You could use a list comprehension or a generator expression. eg: mean = sum(m.value for m in measurements)/len(measurements) Also, here is an alternative way you could store your data: as a list of tuples. You could write code like: # measurements is a list of tuples. Each element is a triple (value, text, time). measurements = [] Then, later on, when you get a new measurement, something like: measurements.append((value, text, time)) You can find the mean in the same way: mean = sum(m[0] for m in measurements)/len(measurement) -- John. From jeffpeery at yahoo.com Fri May 11 02:17:26 2007 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 10 May 2007 17:17:26 -0700 (PDT) Subject: [Tutor] whats the best way to structure my data? In-Reply-To: <5e58f2e40705101638k6b73e6a0w6762ff24d7398ec4@mail.gmail.com> Message-ID: <432936.1334.qm@web43135.mail.sp1.yahoo.com> ok, thanks. so is there a difference in performance if I do it this way versus if I use say a numpy function on an array? thanks. Jeff John Fouhy wrote: On 11/05/07, Jeff Peery wrote: > hello, I was wondering what might be the best way to structure my data > within python. I am sampling data points, and in each there is a time, > value, and text string associated with that sample. so I was thinking I'd > make a list of 'measurement objects' and each object would have the > attributes: time, value, and text... but I want to operate on the numerical > values to find the average and stdev... so I'm not sure how to operate on my > data if it is inside an object. [...] > mean = numpy.mean(????) > > is there a way to operate on the data when it is structured like this? You could use a list comprehension or a generator expression. eg: mean = sum(m.value for m in measurements)/len(measurements) Also, here is an alternative way you could store your data: as a list of tuples. You could write code like: # measurements is a list of tuples. Each element is a triple (value, text, time). measurements = [] Then, later on, when you get a new measurement, something like: measurements.append((value, text, time)) You can find the mean in the same way: mean = sum(m[0] for m in measurements)/len(measurement) -- John. --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/26103d07/attachment.html From john at fouhy.net Fri May 11 02:38:17 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 11 May 2007 12:38:17 +1200 Subject: [Tutor] whats the best way to structure my data? In-Reply-To: <432936.1334.qm@web43135.mail.sp1.yahoo.com> References: <5e58f2e40705101638k6b73e6a0w6762ff24d7398ec4@mail.gmail.com> <432936.1334.qm@web43135.mail.sp1.yahoo.com> Message-ID: <5e58f2e40705101738w46f12182u2784a3786283b77c@mail.gmail.com> On 11/05/07, Jeff Peery wrote: > ok, thanks. so is there a difference in performance if I do it this way > versus if I use say a numpy function on an array? thanks. I don't know enough about numpy to answer your quesiton, but you may be able to answer it yourself: check out the timeit module. Type 'import timeit' and then 'help(timeit)' from the python interpreter. -- John. From tms43 at clearwire.net Fri May 11 05:53:22 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Thu, 10 May 2007 20:53:22 -0700 Subject: [Tutor] canvas -> CLASSES Message-ID: <4A77B179D40D412E8C3ED014DA5B5554@TeresPC> It seems that all the player does is tell the .gif where to move based on a mouse click event. I don't understand redrawing or anything like that. This is begining Tkinter for me. So, perhaps you could dumb down what you were saying? I was able to move the .gif from one point to the next, based on the event, but it wasn't updating from the old x (or y) to the new position. So, it seemed that I needed to change it to a class. When I run it now, the .gif shows up on the maze, but I can't get it to move because of the error message that I showed previously. Would it be possible to look at the code I wrote and point out what I'm doing wrong with it? Or is it completely wrong and I need to start over? (God Forbid!!) I was modeling it after some of Greysons code. But his code isn't moving from one coordinate to another, and that may be the problem. not giving up!!! T -----Original Message----- From: ALAN GAULD [mailto:alan.gauld at btinternet.com] Sent: Thursday, May 10, 2007 2:27 PM To: Teresa Stanton Cc: tutor at python.org Subject: Re: [Tutor] canvas -> CLASSES > T's reply: > The maze is simply the backdrop. I've attached the new and improved code. As I said in the last post I think the maze probably needs to be quite a bit more than the backdrop. I think it knows about the rules of movement within the maze - which routes are blocked, where other players are sitting etc. > > OK, So I'm asssuming these gifs represent something, > um... actually, the .gif will be a photo that will be taken as > part of the 'game'. ... the first pic will be the main pic as > it goes around the maze. When the pic 'collides' with items > that will be placed another pic will be displayed OK, In that case it sounds like the gif is only how the object will draw itself. The object is actually some kind of player, which has a status which is reflected by the gif displayed? So the player c;lass will have methods to play the game, a status attribute, a collection of gifs to match the status, a location of some kind and a draw method that displays the appropriate gif when requested by the maze. With those two class definitions in mind I'd suggest an architecture where: A maze is created and populated by players The maze draws itself and then asks each player to draw itself. Players then do something (whatever the game requires) and that may involve asking the maze to move them to a new location. The maze will look at their position relative to the layout of the maze and the position of other players/objects. If the move can be made it moves the player and sets its new location. The maze then redaws itself, including asking the players/objects to redraw themselves at their new positions. (If you want to get really smart you could just redraw the sections of maze that have changed, but that's quite tricky to manage reliably) The whole thing could be controlled by an overall Game object which contains the maze and a list of players (some or all of which could be in the maze). The game object is responsible for ensuring each player makes plays at the appropriate time or receives the user events and matches them to a player as appropriate. Does that sound like a workable model? BTW Have you looked at PyGame (www.pygame.org) which has things like sprites etc which may make some of this stuff easier. HTH, Alan G. ___________________________________________________________ Inbox full of unwanted email? Get leading protection and 1GB storage with All New Yahoo! Mail. http://uk.docs.yahoo.com/nowyoucan.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070510/54fa6326/attachment.html From Nick.Treloar at education.nsw.gov.au Fri May 11 06:42:58 2007 From: Nick.Treloar at education.nsw.gov.au (Treloar, Nick) Date: Fri, 11 May 2007 14:42:58 +1000 Subject: [Tutor] were do i put the random number genorator Message-ID: <42E18E55C3B8C24FBE1633506D22EC130383330E@DET-MAIL-EVS03.DETISP.LOCAL> i am tyin to make a number guesing game were do i put the random genorator it the top of each child screen def here is my code from Tkinter import* root = Tk() root.title("main screen") root.maxsize(width=350,height=200) root.minsize(width=350,height=200) root.resizable(width=YES,height=YES) def child1(): c1 = Toplevel(root) c1.guess_ent = Entry(c1, width = 35,) c1.guess_ent.grid(row = 14, column = 0) c1.box_txt = Text(c1, width = 35, height = 5, wrap = WORD) c1.box_txt.grid(row = 3, column = 0, columnspan=2) c1.title("easy") c1.geometry("200x200") Button(c1,text="clear", command = NIck).grid(row=1,column=0) Button(c1,text="new game",).grid(row=1,column=1) def NIck(): child1.box_txt.delete(0.0, END) def child2(): c2 = Toplevel(root) box_txt = Text(c2, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c2.title("medium") c2.geometry("200x200") def child3(): c3 = Toplevel(root) box_txt = Text(c3, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c3.title("hard") c3.geometry("200x200") Label(root,text = "choose which game you would like to play").grid(row=0,column=0,columnspan=2) Button(root,text="easy",command=child1).grid(row=1,column=0) Button(root,text="medium",command=child2).grid(row=1,column=1) Button(root,text="hard",command=child3).grid(row=1,column=3) This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/9c05414b/attachment.html From bgailer at alum.rpi.edu Fri May 11 07:22:36 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 10 May 2007 22:22:36 -0700 Subject: [Tutor] were do i put the random number genorator In-Reply-To: <42E18E55C3B8C24FBE1633506D22EC130383330E@DET-MAIL-EVS03.DETISP.LOCAL> References: <42E18E55C3B8C24FBE1633506D22EC130383330E@DET-MAIL-EVS03.DETISP.LOCAL> Message-ID: <4643FD9C.1020809@alum.rpi.edu> Treloar, Nick wrote: > i am tyin to make a number guesing game were do i put the random > genorator it the top of each child screen def Did you write this program yourself? Do you understand it? What is it supposed to do? I personally don't understand it enough to address your question. > here is my code > from Tkinter import* > root = Tk() > root.title("main screen") > root.maxsize(width=350,height=200) > root.minsize(width=350,height=200) > root.resizable(width=YES,height=YES) > > def child1(): > c1 = Toplevel(root) > c1.guess_ent = Entry(c1, width = 35,) > c1.guess_ent.grid(row = 14, column = 0) > c1.box_txt = Text(c1, width = 35, height = 5, wrap = WORD) > c1.box_txt.grid(row = 3, column = 0, columnspan=2) > c1.title("easy") > c1.geometry("200x200") > Button(c1,text="clear", command = NIck).grid(row=1,column=0) > Button(c1,text="new game",).grid(row=1,column=1) > def NIck(): > child1.box_txt.delete(0.0, END) > > def child2(): > c2 = Toplevel(root) > box_txt = Text(c2, width = 35, height = 5, wrap = WORD) > box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) > c2.title("medium") > c2.geometry("200x200") > def child3(): > c3 = Toplevel(root) > box_txt = Text(c3, width = 35, height = 5, wrap = WORD) > box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) > c3.title("hard") > c3.geometry("200x200") > > Label(root,text = "choose which game you would like to > play").grid(row=0,column=0,columnspan=2) > Button(root,text="easy",command=child1).grid(row=1,column=0) > Button(root,text="medium",command=child2).grid(row=1,column=1) > Button(root,text="hard",command=child3).grid(row=1,column=3) > > > /This message is intended for the addressee named and may contain > privileged information or confidential information or both. If you are > not the intended recipient please delete it and notify the sender./ > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From alan.gauld at btinternet.com Fri May 11 09:29:19 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 May 2007 08:29:19 +0100 Subject: [Tutor] were do i put the random number genorator References: <42E18E55C3B8C24FBE1633506D22EC130383330E@DET-MAIL-EVS03.DETISP.LOCAL> Message-ID: "Treloar, Nick" wrote > i am tyin to make a number guesing game were do > i put the random genorator it the top of each child > screen def Frankly thats the least of your problems. You need to consider how you are going to pass references to the various widgets around, which, if you don't use classes/objects, will mean lots of global variables. For example your Nick() function tries to access a widget called child1.box_txt but no such widget exists. There is a box_txt local variable inside child1 but that variable is destroyed as soon as child1 exits. You will need to pass that value out to a global variable for Nick() - and any other event handler - to see it. The same applies to the Entry field. And the same applies to the widgets created in child2() Creating a random number is easily done in a separate function which can be called from anywhere in your program, you don't need to worry about where it is located. But until you have references to your widgets you won't be able to display the random number or do much of anything withb the windows you are creating. Also child2 and child3 are identical except for the title, so why not make them a single function with a title parameter. Then you can just call the function with the title text as an argument. here is my code from Tkinter import* root = Tk() root.title("main screen") root.maxsize(width=350,height=200) root.minsize(width=350,height=200) root.resizable(width=YES,height=YES) def child1(): c1 = Toplevel(root) c1.guess_ent = Entry(c1, width = 35,) c1.guess_ent.grid(row = 14, column = 0) c1.box_txt = Text(c1, width = 35, height = 5, wrap = WORD) c1.box_txt.grid(row = 3, column = 0, columnspan=2) c1.title("easy") c1.geometry("200x200") Button(c1,text="clear", command = NIck).grid(row=1,column=0) Button(c1,text="new game",).grid(row=1,column=1) def NIck(): child1.box_txt.delete(0.0, END) def child2(): c2 = Toplevel(root) box_txt = Text(c2, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c2.title("medium") c2.geometry("200x200") def child3(): c3 = Toplevel(root) box_txt = Text(c3, width = 35, height = 5, wrap = WORD) box_txt.grid(row = 3, column = 0, columnspan=2,sticky = W) c3.title("hard") c3.geometry("200x200") Label(root,text = "choose which game you would like to play").grid(row=0,column=0,columnspan=2) Button(root,text="easy",command=child1).grid(row=1,column=0) Button(root,text="medium",command=child2).grid(row=1,column=1) Button(root,text="hard",command=child3).grid(row=1,column=3) This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pthanos at gmail.com Fri May 11 10:13:05 2007 From: pthanos at gmail.com (Thanos Panousis) Date: Fri, 11 May 2007 10:13:05 +0200 Subject: [Tutor] Web GUI for a network management tool In-Reply-To: <46435DE8.8070904@ericwalstad.com> References: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> <46435DE8.8070904@ericwalstad.com> Message-ID: <4dcb3660705110113v6a0e44d3l39984e572437bc52@mail.gmail.com> The application is running on a server. It does things to the network and logs stuff in a db. My web gui will use the db to visualize the actions of the system, change configuration and so on. I 'm going to need some hardcore graphing functionalities. And for that reason alone, I think jfreechart is the only thing that provides free and decent solution, also designed with the web in mind. So everybody seems to prefer some framework even for not complicated (business) logic. I 'll try to go for something lightweight. Thanks. On 5/10/07, Eric Walstad wrote: > Hi Thanos, > > Alan Gauld wrote: > > "Thanos Panousis" wrote > > > >> The time has come to write some kind of gui for it, so that graphs, > >> visualizations and configuration options are exposed to non > >> developers. Do you think that a web app frame work like turbogears > >> is > >> appropriate in my case? > > > > Graphs etc on web apps can be problematic, but thats true of > > all web apps regardless of framework. You may need to hunt > > for some graphing code to suit the framework you choose > > - or maybe a Java applet. > > I'm not sure how complex your charts/graphs need to be. Here's a simple > Django solution for simple HTML Bar Charts that may give you some ideas > for solving the problem: > > and an example of what it looks like: > > > I'd be interested to hear about how you ultimately solve the problem > when you are done. > > Best, > > Eric. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From shiv_mbm at hotmail.com Fri May 11 11:59:49 2007 From: shiv_mbm at hotmail.com (shiv k) Date: Fri, 11 May 2007 09:59:49 +0000 Subject: [Tutor] (no subject) Message-ID: Dear All, I want to implement web services in Python for our project and i want to use these frm .NET framework. pls tell me how the .Net platform will interact with my these services. Shiv _________________________________________________________________ Palate Teasers: Straight from Master Chef! http://content.msn.co.in/Lifestyle/Moreonlifestyle/LifestylePT_101106_1530.htm -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/8244c91c/attachment.html From kent37 at tds.net Fri May 11 12:18:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 May 2007 06:18:11 -0400 Subject: [Tutor] .NET web services In-Reply-To: References: Message-ID: <464442E3.60401@tds.net> shiv k wrote: > Dear All, > I want to implement web services in Python for our project and i want to > use these frm .NET framework. pls tell me how the .Net platform will > interact with my these services. You might be interested in IronPython which is integrated with .NET http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython Kent From kent37 at tds.net Fri May 11 12:27:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 May 2007 06:27:26 -0400 Subject: [Tutor] Web GUI for a network management tool In-Reply-To: <4dcb3660705110113v6a0e44d3l39984e572437bc52@mail.gmail.com> References: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> <46435DE8.8070904@ericwalstad.com> <4dcb3660705110113v6a0e44d3l39984e572437bc52@mail.gmail.com> Message-ID: <4644450E.7060300@tds.net> Thanos Panousis wrote: > I 'm going to need some hardcore graphing functionalities. And for > that reason alone, I think jfreechart is the only thing that provides > free and decent solution, also designed with the web in mind. jfreechart is a Java library so it will not integrate easily into a Python web framework. Did you look at matplotlib? It is a very capable graphing library. You can see examples of its output here: http://matplotlib.sourceforge.net/screenshots.html > So everybody seems to prefer some framework even for not complicated > (business) logic. I 'll try to go for something lightweight. web.py is pretty light, I think: http://webpy.org/ Kent From zebra05 at gmail.com Fri May 11 13:36:50 2007 From: zebra05 at gmail.com (OkaMthembo) Date: Fri, 11 May 2007 13:36:50 +0200 Subject: [Tutor] Python fast enough for ad server? In-Reply-To: References: <4641EBC2.8080304@ericwalstad.com> Message-ID: Hi guys, I stumbled upon a tool called Psyco (http://psyco.sourceforge.net/) sounds like what i need. Thanks again, Lloyd On 5/10/07, OkaMthembo wrote: > > Thanks for all your contributions. i think i will do it all in Python, it > seems to me that the advantages far outweigh any negatives. > > Maybe once its a working project, we can then benchmark the code and see > what gives. > > Thanks again, > > Lloyd > > On 5/9/07, Eric Walstad wrote: > > > > Hey OkaMthenbo, > > > > OkaMthembo wrote: > > > Hi guys, > > > > > > I need to write an ad-serving application and i'm using Win XP as my > > dev > > > platform. Naturally, i want it to be as painless as possible and i was > > > thinking of writing it 100% in Python. However, i have not written any > > > > > big apps in the language and i wonder if Python would have the > > > performance or scale fast enough to a large user base. > > Most certainly for some definitions of 'large' :) > > > > Most web apps these days are not written in a single language/technology > > > > and are often not running on a single piece of hardware. If you search > > the archives of your favorite Python web application framework I'm > > pretty sure you'll find a discussion on how to scale your app to handle > > a 'large' user base. At the risk of oversimplification, but in hopes of > > avoiding premature optimization, I'd focus first on achieving working > > code, then benchmark it, then optimize if optimization is still needed. > > > > Many others have achieved high volume Python web apps using a mix of all > > the wonderful open source tools available. If your content doesn't > > change quickly and the ratio of GETs/POSTs is high, a caching server in > > front of your python app might be just the trick (memcached, squid,etc). > > But don't waste your time if you don't need to. Define 'too slow' and > > then prove to yourself that your app passes that threshold. If so, then > > > > figure out why it's slow and optimize the slow parts. > > > > Good luck, > > > > Eric. > > > > > > -- > "The Stupidry Foundry" -- "The Stupidry Foundry" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/ca8db8ea/attachment.html From Mike.Hansen at atmel.com Fri May 11 15:29:05 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 11 May 2007 07:29:05 -0600 Subject: [Tutor] .NET web services In-Reply-To: <464442E3.60401@tds.net> References: <464442E3.60401@tds.net> Message-ID: <57B026980605A64F9B23484C5659E32E7D469E@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson > Sent: Friday, May 11, 2007 4:18 AM > To: shiv k > Cc: tutor at python.org > Subject: Re: [Tutor] .NET web services > > shiv k wrote: > > Dear All, > > I want to implement web services in Python for our project > and i want to > > use these frm .NET framework. pls tell me how the .Net > platform will > > interact with my these services. > > You might be interested in IronPython which is integrated with .NET > http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython > > Kent Did the original poster mean to create a web service and have a .NET program consume it? Mike From andreas at kostyrka.org Fri May 11 15:40:37 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 11 May 2007 15:40:37 +0200 Subject: [Tutor] .NET web services Message-ID: I think he meant to access it from .NET, although the mail is quite unclear. Andreas -- Urspr?ngl. Mitteil. -- Betreff: Re: [Tutor] .NET web services Von: "Mike Hansen" Datum: 11.05.2007 13:37 > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson > Sent: Friday, May 11, 2007 4:18 AM > To: shiv k > Cc: tutor at python.org > Subject: Re: [Tutor] .NET web services > > shiv k wrote: > > Dear All, > > I want to implement web services in Python for our project > and i want to > > use these frm .NET framework. pls tell me how the .Net > platform will > > interact with my these services. > > You might be interested in IronPython which is integrated with .NET > http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython > > Kent Did the original poster mean to create a web service and have a .NET program consume it? Mike _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ethics at gmail.com Fri May 11 17:36:55 2007 From: ethics at gmail.com (Leon Keylin) Date: Fri, 11 May 2007 11:36:55 -0400 Subject: [Tutor] Truncating a Table Message-ID: Why would this not work? import pymssql con = pymssql.connect(host='server name',user='username',password='pwd',database='Database') cur = con.cursor() query="TRUNCATE TABLE Consolidatedmsgs;" cur.execute(query) print "Table Truncated: %d rows deleted" % cur.rowcount ----------- The return I get is that the program runs through but it doesn't actually truncate the table. The user that runs this has all the rights (read, write, truncate, etc...) Any ideas? And yes, I am using a pymssql extension module. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/9b68ed85/attachment.htm From mail at timgolden.me.uk Fri May 11 17:43:27 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 May 2007 16:43:27 +0100 Subject: [Tutor] Truncating a Table In-Reply-To: References: Message-ID: <46448F1F.1080400@timgolden.me.uk> Leon Keylin wrote: > Why would this not work? > > import pymssql > > con = pymssql.connect(host='server > name',user='username',password='pwd',database='Database') > cur = con.cursor() > > > query="TRUNCATE TABLE Consolidatedmsgs;" > cur.execute(query) > print "Table Truncated: %d rows deleted" % cur.rowcount > ----------- > The return I get is that the program runs through but it doesn't actually > truncate the table. > The user that runs this has all the rights (read, write, truncate, etc...) > > Any ideas? And yes, I am using a pymssql extension module. A couple of things, neither of which really answers your question. I wouldn't expect to get a cur.rowcount back from a TRUNCATE operation. And you don't need the semicolon at the end of the line. However, neither of those should prevent the truncation from occurring. Do you get an error? Or does the table still have rows in when you look? You can't, for example, truncate a table with active foreign keys. Does this same command work in Query Analyzer? TJG From andreas at kostyrka.org Fri May 11 17:42:46 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 11 May 2007 17:42:46 +0200 Subject: [Tutor] Truncating a Table Message-ID: Commit it? Andreas -- Urspr?ngl. Mitteil. -- Betreff: [Tutor] Truncating a Table Von: "Leon Keylin" Datum: 11.05.2007 15:39 Why would this not work? import pymssql con = pymssql.connect(host='server name',user='username',password='pwd',database='Database') cur = con.cursor() query="TRUNCATE TABLE Consolidatedmsgs;" cur.execute(query) print "Table Truncated: %d rows deleted" % cur.rowcount ----------- The return I get is that the program runs through but it doesn't actually truncate the table. The user that runs this has all the rights (read, write, truncate, etc...) Any ideas? And yes, I am using a pymssql extension module. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ethics at gmail.com Fri May 11 17:46:47 2007 From: ethics at gmail.com (Leon Keylin) Date: Fri, 11 May 2007 11:46:47 -0400 Subject: [Tutor] Truncating a Table In-Reply-To: <46448F1F.1080400@timgolden.me.uk> References: <46448F1F.1080400@timgolden.me.uk> Message-ID: Thanks Tim for a fast reply. The return gives me 0 Rows Truncated message and when I look at the table, every record is still there. There are no foreign keys on the table and no errors. Andreas asked if I should commit after, should I? I didn't think I needed to but I can try that. On 5/11/07, Tim Golden wrote: > > Leon Keylin wrote: > > Why would this not work? > > > > import pymssql > > > > con = pymssql.connect(host='server > > name',user='username',password='pwd',database='Database') > > cur = con.cursor() > > > > > > query="TRUNCATE TABLE Consolidatedmsgs;" > > cur.execute(query) > > print "Table Truncated: %d rows deleted" % cur.rowcount > > ----------- > > The return I get is that the program runs through but it doesn't > actually > > truncate the table. > > The user that runs this has all the rights (read, write, truncate, > etc...) > > > > Any ideas? And yes, I am using a pymssql extension module. > > A couple of things, neither of which really answers > your question. I wouldn't expect to get a cur.rowcount > back from a TRUNCATE operation. And you don't need the > semicolon at the end of the line. However, neither of > those should prevent the truncation from occurring. > > Do you get an error? Or does the table still have rows > in when you look? You can't, for example, truncate a > table with active foreign keys. Does this same command > work in Query Analyzer? > > TJG > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/af804946/attachment-0001.html From mail at timgolden.me.uk Fri May 11 17:54:52 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 May 2007 16:54:52 +0100 Subject: [Tutor] Truncating a Table In-Reply-To: References: <46448F1F.1080400@timgolden.me.uk> Message-ID: <464491CC.4040500@timgolden.me.uk> Leon Keylin wrote: > Thanks Tim for a fast reply. > > The return gives me 0 Rows Truncated message and when I look at the table, > every record is still there. > There are no foreign keys on the table and no errors. > > Andreas asked if I should commit after, should I? I didn't think I > needed to > but I can try that. Commits shouldn't make any difference at all to truncation -- that's the point of it, unless the interface lib is actually holding back from *issuing* the cursor command until you commit. (Though I doubt it). Does it work in Query Analyzer (or any other means you have of issuing the command)? Does truncation work on any other table? TJG From ethics at gmail.com Fri May 11 17:58:41 2007 From: ethics at gmail.com (Leon Keylin) Date: Fri, 11 May 2007 11:58:41 -0400 Subject: [Tutor] Truncating a Table In-Reply-To: <464491CC.4040500@timgolden.me.uk> References: <46448F1F.1080400@timgolden.me.uk> <464491CC.4040500@timgolden.me.uk> Message-ID: Yep, works if I do it manually, under the same user. On 5/11/07, Tim Golden wrote: > > Leon Keylin wrote: > > Thanks Tim for a fast reply. > > > > The return gives me 0 Rows Truncated message and when I look at the > table, > > every record is still there. > > There are no foreign keys on the table and no errors. > > > > Andreas asked if I should commit after, should I? I didn't think I > > needed to > > but I can try that. > > Commits shouldn't make any difference > at all to truncation -- that's the point of > it, unless the interface lib is actually > holding back from *issuing* the cursor command > until you commit. (Though I doubt it). > > Does it work in Query Analyzer (or any other > means you have of issuing the command)? Does > truncation work on any other table? > > TJG > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/788f4a44/attachment.htm From andreas at kostyrka.org Fri May 11 17:59:47 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 11 May 2007 17:59:47 +0200 Subject: [Tutor] Truncating a Table Message-ID: You either have autocommit enabled or you need to commit all data changes. Can't tell the details as I'm not at my laptop :( Andreas -- Urspr?ngl. Mitteil. -- Betreff: Re: [Tutor] Truncating a Table Von: "Leon Keylin" Datum: 11.05.2007 15:55 Thanks Tim for a fast reply. The return gives me 0 Rows Truncated message and when I look at the table, every record is still there. There are no foreign keys on the table and no errors. Andreas asked if I should commit after, should I? I didn't think I needed to but I can try that. On 5/11/07, Tim Golden wrote: > > Leon Keylin wrote: > > Why would this not work? > > > > import pymssql > > > > con = pymssql.connect(host='server > > name',user='username',password='pwd',database='Database') > > cur = con.cursor() > > > > > > query="TRUNCATE TABLE Consolidatedmsgs;" > > cur.execute(query) > > print "Table Truncated: %d rows deleted" % cur.rowcount > > ----------- > > The return I get is that the program runs through but it doesn't > actually > > truncate the table. > > The user that runs this has all the rights (read, write, truncate, > etc...) > > > > Any ideas? And yes, I am using a pymssql extension module. > > A couple of things, neither of which really answers > your question. I wouldn't expect to get a cur.rowcount > back from a TRUNCATE operation. And you don't need the > semicolon at the end of the line. However, neither of > those should prevent the truncation from occurring. > > Do you get an error? Or does the table still have rows > in when you look? You can't, for example, truncate a > table with active foreign keys. Does this same command > work in Query Analyzer? > > TJG > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From mail at timgolden.me.uk Fri May 11 18:06:24 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 May 2007 17:06:24 +0100 Subject: [Tutor] Truncating a Table In-Reply-To: References: <46448F1F.1080400@timgolden.me.uk> <464491CC.4040500@timgolden.me.uk> Message-ID: <46449480.4000407@timgolden.me.uk> Leon Keylin wrote: > Yep, works if I do it manually, under the same user. And on other tables? (Just trying to narrow down). Does this work: import pymssql db = pymssql (...) q = db.cursor () q.execute ("CREATE TABLE #a (i INT)") q.execute ("INSERT INTO #a (i) VALUES (1)") q.execute ("SELECT * FROM #a") q.fetchall () q.execute ("TRUNCATE TABLE #a") q.execute ("SELECT * FROM #a") q.fetchall () q.execute ("DROP TABLE #a") It works ok for me, so there's nothing fundamentally wrong with the concept. TJG From andreas at kostyrka.org Fri May 11 18:15:07 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 11 May 2007 18:15:07 +0200 Subject: [Tutor] Truncating a Table Message-ID: Try commiting it. Actually that might depend upon the dbserver used, but PostgreSQL for example requires commits for everything (including statements like CREATE TABLE). Andreas -- Urspr?ngl. Mitteil. -- Betreff: Re: [Tutor] Truncating a Table Von: "Leon Keylin" Datum: 11.05.2007 16:01 Yep, works if I do it manually, under the same user. On 5/11/07, Tim Golden wrote: > > Leon Keylin wrote: > > Thanks Tim for a fast reply. > > > > The return gives me 0 Rows Truncated message and when I look at the > table, > > every record is still there. > > There are no foreign keys on the table and no errors. > > > > Andreas asked if I should commit after, should I? I didn't think I > > needed to > > but I can try that. > > Commits shouldn't make any difference > at all to truncation -- that's the point of > it, unless the interface lib is actually > holding back from *issuing* the cursor command > until you commit. (Though I doubt it). > > Does it work in Query Analyzer (or any other > means you have of issuing the command)? Does > truncation work on any other table? > > TJG > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ethics at gmail.com Fri May 11 18:20:54 2007 From: ethics at gmail.com (Leon Keylin) Date: Fri, 11 May 2007 12:20:54 -0400 Subject: [Tutor] Truncating a Table In-Reply-To: References: Message-ID: Same result. I think the problem maybe with the extension module. I am going to look for a different way of running a truncate. Thanks to both of you for some excellent advice! On 5/11/07, Andreas Kostyrka wrote: > > Try commiting it. Actually that might depend upon the dbserver used, but > PostgreSQL for example requires commits for everything (including statements > like CREATE TABLE). > > Andreas > > -- Urspr?ngl. Mitteil. -- > Betreff: Re: [Tutor] Truncating a Table > Von: "Leon Keylin" > Datum: 11.05.2007 16:01 > > Yep, works if I do it manually, under the same user. > > On 5/11/07, Tim Golden wrote: > > > > Leon Keylin wrote: > > > Thanks Tim for a fast reply. > > > > > > The return gives me 0 Rows Truncated message and when I look at the > > table, > > > every record is still there. > > > There are no foreign keys on the table and no errors. > > > > > > Andreas asked if I should commit after, should I? I didn't think I > > > needed to > > > but I can try that. > > > > Commits shouldn't make any difference > > at all to truncation -- that's the point of > > it, unless the interface lib is actually > > holding back from *issuing* the cursor command > > until you commit. (Though I doubt it). > > > > Does it work in Query Analyzer (or any other > > means you have of issuing the command)? Does > > truncation work on any other table? > > > > TJG > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/dd932f29/attachment.html From mail at timgolden.me.uk Fri May 11 18:23:49 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 May 2007 17:23:49 +0100 Subject: [Tutor] Truncating a Table In-Reply-To: References: Message-ID: <46449895.6@timgolden.me.uk> Leon Keylin wrote: > Same result. I think the problem maybe with the > extension module. It could be (try using the more recent pyodbc instead?) but in fact it worked for me, albeit in the toy example I posted. However, there's only so much mileage in working round a module's possible inadequacies! TJG From atpridgen at mail.utexas.edu Fri May 11 22:12:24 2007 From: atpridgen at mail.utexas.edu (Adam Pridgen) Date: Fri, 11 May 2007 15:12:24 -0500 Subject: [Tutor] Declaring a Python/C Package and Accessing Python Constants from C API Message-ID: Hello everyone, I am trying to create a python package that includes both a native python module and then a python module created using the Python/C API. I have several questions pertaining to this area. First, how do I make the C API module aware of the python module. Specifically, I have declared all of my constant variables because it was much easier and cleaner, but I want to be able to access those constants from my C API module. I know I can declare the python module globally, but the python module and the C API module are part of the same package. I have read Python C/API guide, and I could not find anything like an example or explanation related to performing this task. I have also seen a couple of posts online, but they seem to miss over this point. Is there anyone out there that has done something like this before? I am on a Posix/Linux system. Thanks in advance, Adam From atpridgen at mail.utexas.edu Sat May 12 01:12:02 2007 From: atpridgen at mail.utexas.edu (Adam Pridgen) Date: Fri, 11 May 2007 18:12:02 -0500 Subject: [Tutor] Declaring a Python/C Package and Accessing Python Constants from C API In-Reply-To: References: Message-ID: I guess to follow this question up, I am trying to combine an Extension module and Python module under a single package, and I am not having any luck with it. I know I have an error in my configuration script, but I am not sure where or how. Here is my directory structure: I am trying to setup my modules so that I can do the following: import python_foo.foo_defines import python_foo.foo_interface setup.py build/ <-- results from set install python_foo/ __init__.py foo_defines.py foo_interface.c foo_interface.h import os from distutils.core import setup, Extension from distutils.sysconfig import get_python_inc incdir = os.path.join(get_python_inc(plat_specific=1)) module = Extension('foo_interface', include_dirs = [incdir], libraries = [], library_dirs = [], sources = ['python_foo/foo_interface.c']) setup(name = 'python_foo', packages = ['python_foo'], package_dir = {'python_foo' : 'python_foo'}, ext_modules = [module], py_modules = ['python_foo.foo_defines' ] ) I perform: python setup.py install and it compiles and installs without error, but when I try the following: import python_foo from python_foo import foo_interface It says it can not find the module. Thanks for any help in advance, Adam On 5/11/07, Adam Pridgen wrote: > Hello everyone, > > I am trying to create a python package that includes both a native > python module and then a python module created using the Python/C API. > I have several questions pertaining to this area. First, how do I > make the C API module aware of the python module. Specifically, I > have declared all of my constant variables because it was much easier > and cleaner, but I want to be able to access those constants from my C > API module. I know I can declare the python module globally, but the > python module and the C API module are part of the same package. I > have read Python C/API guide, and I could not find anything like an > example or explanation related to performing this task. I have also > seen a couple of posts online, but they seem to miss over this point. > Is there anyone out there that has done something like this before? I > am on a Posix/Linux system. > > Thanks in advance, > > Adam > From finnfamilyus at yahoo.com Sat May 12 01:27:07 2007 From: finnfamilyus at yahoo.com (Elizabeth Finn) Date: Fri, 11 May 2007 16:27:07 -0700 (PDT) Subject: [Tutor] newb - Problem reading binary files Message-ID: <109491.68305.qm@web54207.mail.re2.yahoo.com> This is probably a newbie question, and I apologize for the length ? but I have consulted several books / sites and haven?t found a good answer. I need to read a file that is in binary format, and then convert some of the values into integer values. These values can range from 1 to 4 bytes. First question ? is there an easy way to do this? I finally wrote my own little utility to handle multi-byte integers because I couldn?t find a built-in way (except for ord() which works only for single bytes) def getnum(num_str): """ Given a string representing a binary number, return the number. If string is more than one byte, calculate the number to return. Assume that each byte is signed magnitude """ x = len(num_str) ans = 0 for i in range( x ): nextstr = num_str[i:i+1] ans = ans * 256 ans = ans + ord(nextstr) return ans This ?brute force? method usually works, but - now here is the other question -sometimes the code does not pick up two full bytes when it is supposed to. I open the file and read a block that I want into a string: f=open(fname, 'rb') f.seek(offset, 0) block = f.read(2000) Then for each number I pull the bytes from the string, then call getnum() to calculate the number. test = block[0:1] # 1 byte test = block[1:4] # 3 bytes test = block[4:6] # 2 bytes test = block[20:12] # 2 bytes test = block[1996:2000] #4 bytes This method usually works, except that for some of the 2-byte numbers I get only the first byte and first half of the second byte ? for instance: 'x06\x33? comes out as ?x063?. This is very confusing especially because one 2-byte substring ? ?00 01? comes out as expected, but ?06 52? becomes ?065?. Any ideas? --------------------------------- Finding fabulous fares is fun. Let Yahoo! FareChase search your favorite travel sites to find flight and hotel bargains. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/1f26df8f/attachment.html From alan.gauld at btinternet.com Sat May 12 02:20:39 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 May 2007 01:20:39 +0100 Subject: [Tutor] newb - Problem reading binary files References: <109491.68305.qm@web54207.mail.re2.yahoo.com> Message-ID: "Elizabeth Finn" wrote > binary format, and then convert some of the values into > integer values. These values can range from 1 to 4 bytes. See the struct module, and for an exampole the binary file sidebar in the file handling topic of my tutor. But caveat: struct needs to know the sizes and types of data you are reading in advance. > .... for some of the 2-byte numbers I get only the first byte > and first half of the second byte - for instance: 'x06\x33' > comes out as 'x063'. This is very confusing Look closely and you will see that Python is telling you that the 06 represents the hex value of the byte. The second byte has no \x so is a character. The ASCII value of 0x33 is '3'... >>> hex(ord('3')) '0x33' >>> > ...but "06 52" becomes "065". Any ideas? Not on that one... x52 is 'R'... and chr(52) is '4' -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From adamurbas at hotmail.com Sat May 12 05:16:17 2007 From: adamurbas at hotmail.com (adam urbas) Date: Fri, 11 May 2007 22:16:17 -0500 Subject: [Tutor] (no subject) Message-ID: Hi,I just started python today and I would like a few pointers, if you don't mind. I tried using a tutorial, but was only able to get the correct results for the most basic problems. # Area calculation programprint ?Welcome to the Area calculation program?print ???????????????print# Print out the menu:print ?Please select a shape:?print ?1 Rectangle?print ?2 Circle?# Get the user?s choice:shape = input(?> ?)# Calculate the area:if shape == 1: height = input(?Please enter the height: ?) width = input(?Please enter the width: ?) area = height*width print ?The area is?, areaelse: radius = input(?Please enter the radius: ?) area = 3.14*(radius**2) print ?The area is?, areaI've been trying to get this to work. I was on a forum on Google and they said to put:input("press ENTER to continue")at the end. I did, but it didn't work. It runs the program but just shuts itself off when its done and i don't even get to select any of the option things that i'm supposed to be able to select. It just turns on then back off and I don't even get to see anything. Could someone help me out.ThanksAdam _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/1ece763a/attachment.html From bgailer at alum.rpi.edu Sat May 12 05:39:11 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 11 May 2007 20:39:11 -0700 Subject: [Tutor] Why don't I see anything when I run this program? In-Reply-To: References: Message-ID: <464536DF.9010201@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/ffc01188/attachment.htm From rabidpoobear at gmail.com Sat May 12 05:51:45 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 11 May 2007 22:51:45 -0500 Subject: [Tutor] how to stop output to terminal In-Reply-To: <384c93600705101152o59a81991yb5183bd0e8c97c26@mail.gmail.com> References: <384c93600705101152o59a81991yb5183bd0e8c97c26@mail.gmail.com> Message-ID: <464539D1.5030800@gmail.com> shawn bright wrote: > lo there all, > > i have a simple thread that i want to run without piping any output to > the terminal. > like if i do an > > x = os.system("ping -c 1 www.google.com ") > > i don't want it to show all the stuff in the terminal. if you use os.popen or the subprocess module you can execute system commands and have their output stored in file-like objects. then if you don't want any output, don't read from them. > > can i disable it for only certain lines? yeah, just read in all lines and display the ones which meet your criteria. > > thanks > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nephish at gmail.com Sat May 12 05:54:45 2007 From: nephish at gmail.com (shawn bright) Date: Fri, 11 May 2007 22:54:45 -0500 Subject: [Tutor] how to stop output to terminal In-Reply-To: <464539D1.5030800@gmail.com> References: <384c93600705101152o59a81991yb5183bd0e8c97c26@mail.gmail.com> <464539D1.5030800@gmail.com> Message-ID: <384c93600705112054t335475bdh2517636fe24430f7@mail.gmail.com> cool, thanks sk On 5/11/07, Luke Paireepinart wrote: > > shawn bright wrote: > > lo there all, > > > > i have a simple thread that i want to run without piping any output to > > the terminal. > > like if i do an > > > > x = os.system("ping -c 1 www.google.com ") > > > > i don't want it to show all the stuff in the terminal. > if you use os.popen or the subprocess module you can execute system > commands and have their output stored in file-like objects. > then if you don't want any output, don't read from them. > > > > can i disable it for only certain lines? > yeah, just read in all lines and display the ones which meet your > criteria. > > > > thanks > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070511/af973245/attachment.html From alan.gauld at btinternet.com Sat May 12 09:33:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 May 2007 08:33:06 +0100 Subject: [Tutor] Why don't I see anything when I run this program? References: <464536DF.9010201@alum.rpi.edu> Message-ID: "Bob Gailer" wrote >> print ?Welcome to the Area calculation program? > > I guess you used a word processor to write the program, And in case you missed Bob's point - don't do that! Use a text editor like Notepad, or better still IDLE or Pythonwin or any other editor designed to work with Python. But it must save the files as plain text. > Therefore: it is better to run the program by calling > python explicitly. Open a command prompt and > enter (for example):.... Or alternatively use an IDE like IDLE or Pythonwin to execute the program while you are testing it since they will stay open after an error. Once it works in IDLE you can run it by double clicking as usual. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat May 12 13:56:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 12 May 2007 07:56:21 -0400 Subject: [Tutor] newb - Problem reading binary files In-Reply-To: <109491.68305.qm@web54207.mail.re2.yahoo.com> References: <109491.68305.qm@web54207.mail.re2.yahoo.com> Message-ID: <4645AB65.3080605@tds.net> Elizabeth Finn wrote: > I need to read a file that is in binary format, and then convert some of > the values into integer values. These values can range from 1 to 4 bytes. > > First question ? is there an easy way to do this? I finally wrote my own > little utility to handle multi-byte integers because I couldn?t find a > built-in way (except for ord() which works only for single bytes) Alan suggested the struct module. It doesn't directly support 3-byte integers but perhaps you could pad them with a zero byte at the front. struct does let you unpack a whole string at once. The Construct library is a higher-level interface to similar functionality. It doesn't seem to support 3-byte integers either but it is extensible. > > def getnum(num_str): > """ > Given a string representing a binary number, return the number. > If string is more than one byte, calculate the number to return. > Assume that each byte is signed magnitude > """ > x = len(num_str) > ans = 0 > for i in range( x ): > nextstr = num_str[i:i+1] > ans = ans * 256 > ans = ans + ord(nextstr) > return ans Your loop could be written more simply as for nextstr in num_str: ans = ans * 256 ans = ans + ord(nextstr) > This ?brute force? method usually works, but - now here is the other > question -sometimes the code does not pick up two full bytes when it is > supposed to. I open the file and read a block that I want into a string: > > f=open(fname, 'rb') > f.seek(offset, 0) > block = f.read(2000) > > Then for each number I pull the bytes from the string, then call > getnum() to calculate the number. > > test = block[0:1] # 1 byte > test = block[1:4] # 3 bytes > test = block[4:6] # 2 bytes > test = block[20:12] # 2 bytes > test = block[1996:2000] #4 bytes > > This method usually works, except that for some of the 2-byte numbers I > get only the first byte and first half of the second byte ? for > instance: 'x06\x33? comes out as ?x063?. This is very confusing > especially because one 2-byte substring ? ?00 01? comes out as expected, > but ?06 52? becomes ?065?. Any ideas? It seems to work for me. I wonder if you are confused about the input you are giving it? Using your definition of getnum(), I get these results: In [31]: getnum('\x06\x33') Out[31]: 1587 In [33]: 6*256 + 0x33 Out[33]: 1587 In [34]: getnum('\x06\x52') Out[34]: 1618 In [35]: 6*256 + 0x52 Out[35]: 1618 So it seems to be doing the right thing. Can you put print repr(test) print getnum(test) into your test program and show us the results? Kent From agilfoy at frontiernet.net Sat May 12 16:15:03 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sat, 12 May 2007 14:15:03 +0000 Subject: [Tutor] Loop-checking question Message-ID: <20070512141503.e5hwvrzm4bs4soc4@webmail.frontiernet.net> My programs often have long, detailed loops in them, and would like to, as I'm executing the loop, view what part of the loop Python is currently processing. Thus, if my program gets stuck in one part of the loop, I would see that. Thus, if one part of my loop is never triggered, I would see that. I could use, within my loop, print 'I am here, at part X of the loop', but I believe that would be far to clunky to put in every section of my program's loop(s). -- "Computers were the first God-Satan collaboration project." "Blind faith in bad leadership is not patriotism." "One of the most horrible features of war is that all the war-propaganda, all the screaming and lies and hatred, comes invariably from people who are not fighting."-George Orwell, _Homage to Catalonia From agilfoy at frontiernet.net Sat May 12 16:31:04 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sat, 12 May 2007 14:31:04 +0000 Subject: [Tutor] Repeating an action Message-ID: <20070512143104.giyvhoev3n4ow8ko@webmail.frontiernet.net> How do you 'tell' Python to repeat a certain action X amount of times, and then stop. I could use a 'counter' (see below), but that seems kind of clunky. counter = 0 example = True while example: print "Do something" counter += 1 if counter == 100: example = False From aristotle831 at gmail.com Sat May 12 16:54:32 2007 From: aristotle831 at gmail.com (F.Lee) Date: Sat, 12 May 2007 10:54:32 -0400 Subject: [Tutor] Repeating an action In-Reply-To: <20070512143104.giyvhoev3n4ow8ko@webmail.frontiernet.net> References: <20070512143104.giyvhoev3n4ow8ko@webmail.frontiernet.net> Message-ID: <2ea9c4100705120754m1cb5279bp6a94c9a1ff3cca24@mail.gmail.com> On 5/12/07, Alan Gilfoy wrote: > How do you 'tell' Python to repeat a certain action X amount of times, > and then stop. > > I could use a 'counter' (see below), but that seems kind of clunky. > > > > counter = 0 > example = True > while example: > > print "Do something" > counter += 1 > > if counter == 100: > example = False > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, Have you considered a "for" loop? It's quite a bit less "clunky": for i in range(100) print "Do something" HTH, From andreengels at gmail.com Sat May 12 16:57:21 2007 From: andreengels at gmail.com (Andre Engels) Date: Sat, 12 May 2007 16:57:21 +0200 Subject: [Tutor] Repeating an action In-Reply-To: <20070512143104.giyvhoev3n4ow8ko@webmail.frontiernet.net> References: <20070512143104.giyvhoev3n4ow8ko@webmail.frontiernet.net> Message-ID: <6faf39c90705120757t3e591b4ci1d3fa15a6ba63fb2@mail.gmail.com> 2007/5/12, Alan Gilfoy : > How do you 'tell' Python to repeat a certain action X amount of times, > and then stop. > > I could use a 'counter' (see below), but that seems kind of clunky. > > > > counter = 0 > example = True > while example: > > print "Do something" > counter += 1 > > if counter == 100: > example = False You can use a for loop: for i in range(100): print "Do something" Your own code is unnecessary wordy too, by the way. The same thing can be done with: counter = 0 while counter < 100: print "Do something" counter += 1 but of course the 'for' solution is still shorter than this. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From eric at ericwalstad.com Sat May 12 17:53:48 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Sat, 12 May 2007 08:53:48 -0700 Subject: [Tutor] Python fast enough for ad server? In-Reply-To: References: <4641EBC2.8080304@ericwalstad.com> Message-ID: <4645E30C.6010706@ericwalstad.com> Hi OkaMthembo, Again, are you sure you need it? Have you done any benchmarking yet? It looks like you have to run Psyco on 32 bit x86 architecture. That may limit other parts of your system design that you want to speed up by running on x86-64, for example. OTOH, it's easy to add/remove psyco (at least it was easy to add it to one of my Django projects in the past). I think it's good to consider possible bottle necks at design time. Just remember that your assumptions may be wrong yielding your premature optimizations useless. Psyco may help, it may not. I suspect that you won't need it because Python is pretty darned fast already and the Python web-framework guys are *really smart* and have done the much of the optimization for you already. Best regards, Eric. OkaMthembo wrote: > Hi guys, > > I stumbled upon a tool called Psyco (http://psyco.sourceforge.net/) sounds > like what i need. > > Thanks again, > > Lloyd > > On 5/10/07, OkaMthembo wrote: >> >> Thanks for all your contributions. i think i will do it all in Python, it >> seems to me that the advantages far outweigh any negatives. >> >> Maybe once its a working project, we can then benchmark the code and see >> what gives. >> >> Thanks again, >> >> Lloyd >> >> On 5/9/07, Eric Walstad wrote: >> > >> > Hey OkaMthenbo, >> > >> > OkaMthembo wrote: >> > > Hi guys, >> > > >> > > I need to write an ad-serving application and i'm using Win XP as my >> > dev >> > > platform. Naturally, i want it to be as painless as possible and i >> was >> > > thinking of writing it 100% in Python. However, i have not written >> any >> > >> > > big apps in the language and i wonder if Python would have the >> > > performance or scale fast enough to a large user base. >> > Most certainly for some definitions of 'large' :) >> > >> > Most web apps these days are not written in a single >> language/technology >> > >> > and are often not running on a single piece of hardware. If you search >> > the archives of your favorite Python web application framework I'm >> > pretty sure you'll find a discussion on how to scale your app to handle >> > a 'large' user base. At the risk of oversimplification, but in >> hopes of >> > avoiding premature optimization, I'd focus first on achieving working >> > code, then benchmark it, then optimize if optimization is still needed. >> > >> > Many others have achieved high volume Python web apps using a mix of >> all >> > the wonderful open source tools available. If your content doesn't >> > change quickly and the ratio of GETs/POSTs is high, a caching server in >> > front of your python app might be just the trick (memcached, >> squid,etc). >> > But don't waste your time if you don't need to. Define 'too slow' and >> > then prove to yourself that your app passes that threshold. If so, >> then >> > >> > figure out why it's slow and optimize the slow parts. >> > >> > Good luck, >> > >> > Eric. From kent37 at tds.net Sat May 12 19:37:42 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 12 May 2007 13:37:42 -0400 Subject: [Tutor] Loop-checking question In-Reply-To: <20070512141503.e5hwvrzm4bs4soc4@webmail.frontiernet.net> References: <20070512141503.e5hwvrzm4bs4soc4@webmail.frontiernet.net> Message-ID: <4645FB66.7030603@tds.net> Alan Gilfoy wrote: > My programs often have long, detailed loops in them, and would like > to, as I'm executing the loop, view what part of the loop Python is > currently processing. > > Thus, if my program gets stuck in one part of the loop, I would see that. > Thus, if one part of my loop is never triggered, I would see that. > > I could use, within my loop, print 'I am here, at part X of the loop', > but I believe that would be far to clunky to put in every section of > my program's loop(s). I'm not really sure what you expect this view to look like. I don't know of any tool that will let you dynamically watch a program as it executes. Some alternatives: - A debugger lets you step through the code and see how it behaves. winpdb is a pretty nice GUI-based Python debugger and some Python development tools have built-in debuggers. http://www.digitalpeers.com/pythondebugger/ - If the program is stuck in a loop, pressing control-C will abort the loop and give a stack trace showing you where it was. - The Python profiler will tell you (after the fact) how much time you spend in each function. To see what part of a loop the program is in you would have to break the loop up into functions. http://docs.python.org/lib/profile.html - A code coverage tool will tell you (after the fact) which lines of the program were executed and which were not. (google python code coverage) Kent From finalyugi at sapo.pt Sat May 12 19:55:20 2007 From: finalyugi at sapo.pt (Rolando Pereira) Date: Sat, 12 May 2007 18:55:20 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4645FF88.3020806@sapo.pt> adam urbas escreveu: > Hi,I just started python today and I would like a few pointers, if you don't mind. I tried using a tutorial, but was only able to get the correct results for the most basic problems. # Area calculation programprint ?Welcome to the Area calculation program?print ???????????????print# Print out the menu:print ?Please select a shape:?print ?1 Rectangle?print ?2 Circle?# Get the user?s choice:shape = input(?> ?)# Calculate the area:if shape == 1: height = input(?Please enter the height: ?) width = input(?Please enter the width: ?) area = height*width print ?The area is?, areaelse: radius = input(?Please enter the radius: ?) area = 3.14*(radius**2) print ?The area is?, areaI've been trying to get this to work. I was on a forum on Google and they said to put:input("press ENTER to continue")at the end. I did, but it didn't work. It runs the program but just shuts itself off when its done and i don't even get to select any of the option things that i'm s upposed to be able to select. It just turns on then back off and I don't even get to see anything. Could someone help me out.ThanksAdam > _________________________________________________________________ > Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. > www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor First, welcome to the world of Python. :D Second. please give a title when you start a new thread on a mailing list. Third, format your posts and code. Since Python uses indented code, it's kinda hard to read it when it's all in one line (Don't worry, I'll paste it indented in a file attached to this email :D ) Now for the code. After arranging the code, the first thing I noticed were this characters ? ? I tried running the code, and if gave me a error there, so I just replace then with " ", and voil?, the code worked :D . So the lesson here is always use either " " or ' ' in the code. Oh, also another thing. Don't use input() to get the user input, because that command can run code and it may be evilly used. Always use raw_input() instead :D . Anyway, I hope I helped you, -- _ ASCII ribbon campaign ( ) - against HTML email X & vCards / \ -------------- next part -------------- A non-text attachment was scrubbed... Name: teste.py Type: text/x-python Size: 588 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070512/7e7596a6/attachment-0001.py From agilfoy at frontiernet.net Sat May 12 22:43:16 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sat, 12 May 2007 20:43:16 +0000 Subject: [Tutor] Checking/Debugging tools Message-ID: <20070512204316.dvv85ahpplcgc0gc@webmail.frontiernet.net> Quoting Kent Johnson : > Alan Gilfoy wrote: >> My programs often have long, detailed loops in them, and would like >> to, as I'm executing the loop, view what part of the loop Python >> is currently processing. >> >> Thus, if my program gets stuck in one part of the loop, I would see that. >> Thus, if one part of my loop is never triggered, I would see that. >> >> I could use, within my loop, print 'I am here, at part X of the >> loop', but I believe that would be far to clunky to put in every >> section of my program's loop(s). > > I'm not really sure what you expect this view to look like. I don't > know of any tool that will let you dynamically watch a program as it > executes. Some alternatives: > > - A debugger lets you step through the code and see how it behaves. > winpdb is a pretty nice GUI-based Python debugger and some Python > development tools have built-in debuggers. > http://www.digitalpeers.com/pythondebugger/ I got winpdb downloaded, but when I tried to run the script, it said I needed wxpython. I tried to go to the wxpytohn website, and it's evidently down right now. > > - If the program is stuck in a loop, pressing control-C will abort the > loop and give a stack trace showing you where it was. > > - The Python profiler will tell you (after the fact) how much time you > spend in each function. To see what part of a loop the program is in > you would have to break the loop up into functions. > http://docs.python.org/lib/profile.html My loop isn't broken into functions, just a truckload of if statements > > - A code coverage tool will tell you (after the fact) which lines of > the program were executed and which were not. (google python code > coverage) > Running that Google Search, I seem to be running into a lot of what is, to me, technical gobbeldygook. Can y'all help me choose a good code-coverage tool, and a good tutorial? > Kent Alan ----- End forwarded message ----- From alan.gauld at btinternet.com Sat May 12 23:13:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 May 2007 22:13:55 +0100 Subject: [Tutor] Loop-checking question References: <20070512141503.e5hwvrzm4bs4soc4@webmail.frontiernet.net> <4645FB66.7030603@tds.net> Message-ID: "Kent Johnson" wrote > I'm not really sure what you expect this view to look like. I don't > know > of any tool that will let you dynamically watch a program as it > executes. Not particularly relevant but there are some commercial tools that do this kind of thing, they are usually called program visualisers. The best one I've used was for C++ (called iLooK I think) and it displayed objects as little icons and showed arrows between objects to represent messages. It could cope with multi threading by colourising the arrows and you could stop/start the program like a debugger, attach breakpoints on particular instances etc. It won a Jolt award for productivity back around 1996/97. I think they might have done a Java one too, but I never used it. I think there is a .NET visualiser somewhere too. And there are several for SmallTalk and Lisp. None of which helps the OP in any way :-/ Alan G. From washakie at gmail.com Sun May 13 00:28:12 2007 From: washakie at gmail.com (John Washakie) Date: Sun, 13 May 2007 00:28:12 +0200 Subject: [Tutor] Running and passing variables to/from Fortran In-Reply-To: <46429C77.9030702@alum.rpi.edu> References: <46429C77.9030702@alum.rpi.edu> Message-ID: WAY too large a project I'm afraid. Yes, that would be the one which would make me an 'expert' in Python ;) Too bad there's just no time right now... On 5/10/07, Bob Gailer wrote: > John Washakie wrote: > > I have access to the source code. > Did you tell us why you want to keep the code in FORTRAN? Would > converting it to Python solve the issue? > From kent37 at tds.net Sun May 13 01:46:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 12 May 2007 19:46:01 -0400 Subject: [Tutor] Checking/Debugging tools In-Reply-To: <20070512204316.dvv85ahpplcgc0gc@webmail.frontiernet.net> References: <20070512204316.dvv85ahpplcgc0gc@webmail.frontiernet.net> Message-ID: <464651B9.1010804@tds.net> Alan Gilfoy wrote: > Quoting Kent Johnson : >> - A debugger lets you step through the code and see how it behaves. >> winpdb is a pretty nice GUI-based Python debugger and some Python >> development tools have built-in debuggers. >> http://www.digitalpeers.com/pythondebugger/ > > I got winpdb downloaded, but when I tried to run the script, it said I > needed wxpython. I tried to go to the wxpytohn website, and it's > evidently down right now. It seems to be working now: http://wxpython.org/ >> - The Python profiler will tell you (after the fact) how much time you >> spend in each function. To see what part of a loop the program is in >> you would have to break the loop up into functions. >> http://docs.python.org/lib/profile.html > > My loop isn't broken into functions, just a truckload of if statements Perhaps you could break out some pieces into functions. >> - A code coverage tool will tell you (after the fact) which lines of >> the program were executed and which were not. (google python code >> coverage) >> > Running that Google Search, I seem to be running into a lot of what > is, to me, technical gobbeldygook. Can y'all help me choose a good > code-coverage tool, and a good tutorial? The first link is an ad. The second link is for Ned Batcheldor's coverage module which seems to include pretty good docs. The third link is a recipe that creates a nice presentation of the output of coverage, with an example. Kent From marilyn at deliberate.com Sun May 13 01:31:41 2007 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat, 12 May 2007 16:31:41 -0700 (PDT) Subject: [Tutor] Inherit from int? Message-ID: Hello Tutors, I'm stumped. This silly bit of code doesn't work. I expect the output to be 8, not 18. What am I missing? #!/usr/bin/env python '''An Under10 class, just to fiddle with inheriting from int.''' class Under10(int): def __init__(self, number): number %= 10 int.__init__(self, number) if __name__ == '__main__': n = Under10(18) print n ''' $ ./new_style.py 18 ''' Any ideas? Thank you. Marilyn Davis From john at fouhy.net Sun May 13 02:11:34 2007 From: john at fouhy.net (John Fouhy) Date: Sun, 13 May 2007 12:11:34 +1200 Subject: [Tutor] Inherit from int? In-Reply-To: References: Message-ID: <5e58f2e40705121711k6e7a4771l556a641a038fcf64@mail.gmail.com> On 13/05/07, Marilyn Davis wrote: > #!/usr/bin/env python > '''An Under10 class, just to fiddle with inheriting from int.''' > > class Under10(int): > > def __init__(self, number): > number %= 10 > int.__init__(self, number) Subclassing int and other types is a bit special. Check out this page; it may help you: http://www.python.org/download/releases/2.2.3/descrintro/#__new__ -- John. From jim at well.com Sun May 13 02:32:20 2007 From: jim at well.com (jim stockford) Date: Sat, 12 May 2007 17:32:20 -0700 Subject: [Tutor] Inherit from int? In-Reply-To: <5e58f2e40705121711k6e7a4771l556a641a038fcf64@mail.gmail.com> References: <5e58f2e40705121711k6e7a4771l556a641a038fcf64@mail.gmail.com> Message-ID: the problem is in the return. if you append a print statement to the class function such as print "number is ",number # (properly indented, of course) you'll get 8 On May 12, 2007, at 5:11 PM, John Fouhy wrote: > On 13/05/07, Marilyn Davis wrote: >> #!/usr/bin/env python >> '''An Under10 class, just to fiddle with inheriting from int.''' >> >> class Under10(int): >> >> def __init__(self, number): >> number %= 10 >> int.__init__(self, number) > > Subclassing int and other types is a bit special. Check out this > page; it may help you: > http://www.python.org/download/releases/2.2.3/descrintro/#__new__ > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sun May 13 09:57:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 May 2007 08:57:29 +0100 Subject: [Tutor] Inherit from int? References: <5e58f2e40705121711k6e7a4771l556a641a038fcf64@mail.gmail.com> Message-ID: "John Fouhy" wrote > Subclassing int and other types is a bit special. Check out this > page; it may help you: > http://www.python.org/download/releases/2.2.3/descrintro/#__new__ > In case others have the same problem... John's link didn't work for me but I eventually found this relevant snippet here: http://www.python.org/download/releases/2.2/descrintro/#subclassing -------------------------------- Recall that you create class instances by calling the class. When the class is a new-style class, the following happens when it is called. First, the class's __new__ method is called, passing the class itself as first argument, followed by any (positional as well as keyword) arguments received by the original call. This returns a new instance. Then that instance's __init__ method is called to further initialize it. (This is all controlled by the __call__ method of the metaclass, by the way.) Here is an example of a subclass that overrides __new__ - this is how you would normally use it. >>> class inch(float): ... "Convert from inch to meter" ... def __new__(cls, arg=0.0): ... return float.__new__(cls, arg*0.0254) ... >>> print inch(12) 0.3048 >>> This class isn't very useful (it's not even the right way to go about unit conversions) but it shows how to extend the constructor of an immutable type. If instead of __new__ we had tried to override __init__, it wouldn't have worked: >>> class inch(float): ... "THIS DOESN'T WORK!!!" ... def __init__(self, arg=0.0): ... float.__init__(self, arg*0.0254) ... >>> print inch(12) 12.0 >>> The version overriding __init__ doesn't work because the float type's __init__ is a no-op: it returns immediately, ignoring its arguments. All this is done so that immutable types can preserve their immutability while allowing subclassing. If the value of a float object were initialized by its __init__ method, you could change the value of an existing float object! For example, this would work: >>> # THIS DOESN'T WORK!!! >>> import math >>> math.pi.__init__(3.0) >>> print math.pi 3.0 >>> From wescpy at gmail.com Sun May 13 11:12:14 2007 From: wescpy at gmail.com (wesley chun) Date: Sun, 13 May 2007 02:12:14 -0700 Subject: [Tutor] Inherit from int? In-Reply-To: References: Message-ID: <78b3a9580705130212ma15badcpe8b85b0eeebd3bfb@mail.gmail.com> > I'm stumped. This silly bit of code doesn't work. I expect the > output to be 8, not 18. What am I missing? > > class Under10(int): > def __init__(self, number): > number %= 10 > int.__init__(self, number) marilyn, i agree with most of the earlier replies... you need to use __new__() instead of __init__() in order to "tweak" the original value before the instance of the immutable object is created. once it's "frozen," you're stuck. note that __new__() is a class method, so you'll need a variable for the class (instead of self for the instance). also recall that __init__() is (the 1st method) called *after* an instance has been created, which for you, would be too late. in practice, i don't think __init__() is ever used for deriving from immutable types. does anyone have a counterexample? (since i know you've been reading Core Python, you can take a look at my example of subclassing an immutable type on p.552.) :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From marilyn at deliberate.com Sun May 13 15:58:14 2007 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun, 13 May 2007 06:58:14 -0700 (PDT) Subject: [Tutor] Inherit from int? In-Reply-To: <78b3a9580705130212ma15badcpe8b85b0eeebd3bfb@mail.gmail.com> Message-ID: Thank you everyone. I, indeed, found it in your book, Wes, after I knew it was something extra special. The explanations here are great! Thank you everyone. Marilyn On Sun, 13 May 2007, wesley chun wrote: > > I'm stumped. This silly bit of code doesn't work. I expect the > > output to be 8, not 18. What am I missing? > > > > class Under10(int): > > def __init__(self, number): > > number %= 10 > > int.__init__(self, number) > > marilyn, > > i agree with most of the earlier replies... you need to use __new__() > instead of __init__() in order to "tweak" the original value before > the instance of the immutable object is created. once it's "frozen," > you're stuck. note that __new__() is a class method, so you'll need a > variable for the class (instead of self for the instance). > > also recall that __init__() is (the 1st method) called *after* an > instance has been created, which for you, would be too late. in > practice, i don't think __init__() is ever used for deriving from > immutable types. does anyone have a counterexample? > > (since i know you've been reading Core Python, you can take a look at > my example of subclassing an immutable type on p.552.) :-) > > cheers, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -- From vladoportos at vladoportos.sk Sun May 13 19:02:22 2007 From: vladoportos at vladoportos.sk (Vladimir Strycek) Date: Sun, 13 May 2007 19:02:22 +0200 Subject: [Tutor] Getting value from web page Message-ID: <4647449E.2030002@vladoportos.sk> Hi all, i have a page which when i download from web by python and put tu variable have something like: 119/1157/43/40 neer end ( actualy this is only thing on that page.... + ) What i need actualy is to get this values 119/1157/43/40 to variables...., they are changing allthe time, but they stay numbers and "/" is always between numbers, they are always 4 I tried using re to search for it but without luck :( could somebody more experienced with re than me how to do it ? something like match = re.match('+/',htmltxt) (in htmltxt is the source code downloaded from web) <-- example not working ;) From python at wardroper.org Mon May 14 00:04:36 2007 From: python at wardroper.org (Alan) Date: Sun, 13 May 2007 15:04:36 -0700 Subject: [Tutor] Parsing text file Message-ID: <46478B74.1090705@wardroper.org> I'm looking for a more elegant way to parse sections of text files that are bordered by BEGIN/END delimiting phrases, like this: some text some more text BEGIN_INTERESTING_BIT someline1 someline2 someline3 END_INTERESTING_BIT more text more text What I have been doing is clumsy, involving converting to a string and slicing out the required section using split('DELIMITER'): import sys infile = open(sys.argv[1], 'r') #join list elements with @ character into a string fileStr = '@'.join(infile.readlines()) #Slice out the interesting section with split, then split again into lines using @ resultLine = fileStr.split('BEGIN_INTERESTING_BIT')[1].split('END_INTERESTING_BIT')[0].split('@') for line in resultLine: do things Can anyone point me at a better way to do this? Thanks -- -------------------------- Alan Wardroper alan at wardroper.org From john at fouhy.net Mon May 14 00:29:17 2007 From: john at fouhy.net (John Fouhy) Date: Mon, 14 May 2007 10:29:17 +1200 Subject: [Tutor] Parsing text file In-Reply-To: <46478B74.1090705@wardroper.org> References: <46478B74.1090705@wardroper.org> Message-ID: <5e58f2e40705131529lc7bb2c2u5360a4ef814de41e@mail.gmail.com> On 14/05/07, Alan wrote: > I'm looking for a more elegant way to parse sections of text files that > are bordered by BEGIN/END delimiting phrases, like this: > > some text > some more text > BEGIN_INTERESTING_BIT > someline1 > someline2 > someline3 > END_INTERESTING_BIT > more text > more text If the structure is pretty simple, you could use a state machine approach. eg: import sys infile = open(sys.argv[1], 'r') INTERESTING, BORING = 'interesting', 'boring' interestingLines = [] for line in infile: if line == 'BEGIN_INTERESTING_BIT': state = INTERESTING elif line == 'END_INTERESTING_BIT': state = BORING elif state == INTERESTING: interestingLines.append(line) return interestingLines If you want to put each group of interesting lines into its own section, you could do a bit of extra work (append a new empty list to interestingLines on 'BEGIN', then append to the list at position -1 on state==INTERESTING). HTH! -- John. From alan.gauld at btinternet.com Mon May 14 01:10:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 May 2007 00:10:26 +0100 Subject: [Tutor] Parsing text file References: <46478B74.1090705@wardroper.org> Message-ID: "Alan" wrote > I'm looking for a more elegant way to parse sections of text files > that > are bordered by BEGIN/END delimiting phrases, like this: > > some text > BEGIN_INTERESTING_BIT > someline1 > someline3 > END_INTERESTING_BIT > more text > > What I have been doing is clumsy, involving converting to a string > and > slicing out the required section using split('DELIMITER'): The method I usually use is only slightly less clunky - or maybe just as clunky! I iterate over the lines setting a flag at the start and unsetting it at the end. Pseudo code: amInterested = False for line in textfile: if amInterested and not isEndPattern(line): storeLine(line) amInterested = not isEndPattern(line) if line.find(begin_pattern): amInterested = True Whether thats any better than joining/splitting is debateable. (Obviously you need to write the isEndPattern helper function too) Alan G. From dos.fool at gmail.com Mon May 14 05:47:59 2007 From: dos.fool at gmail.com (max .) Date: Sun, 13 May 2007 21:47:59 -0600 Subject: [Tutor] web spider Message-ID: <857e4c3d0705132047w50c633faue94fc68b082787a1@mail.gmail.com> hello i am a beginner programmer and i am planning a project that will take a keyword enter that in google and start searching through links ans saving web pages if anyone can help or might know of any tutorials about: writing to websites searching links creating files and web spiders in general that would be great thanks for any help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070513/7696269d/attachment.htm From shiv_mbm at hotmail.com Mon May 14 10:11:54 2007 From: shiv_mbm at hotmail.com (ShivKumar Anand) Date: Mon, 14 May 2007 13:41:54 +0530 Subject: [Tutor] installing Turbogears without using Internet Message-ID: hello Tutors, I want solution to my problem. I want to install Turbogears and Cherrypy without using internet. means that locally is i have eggs. how it is possible? Shiv Kumar _________________________________________________________________ Palate Teasers: Straight from Master Chef! http://content.msn.co.in/Lifestyle/Moreonlifestyle/LifestylePT_101106_1530.htm -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/016f0166/attachment.htm From duncan at thermal.esa.int Mon May 14 10:24:53 2007 From: duncan at thermal.esa.int (Duncan Gibson) Date: Mon, 14 May 2007 10:24:53 +0200 Subject: [Tutor] Generating simple HTML from within Python In-Reply-To: <20070510162508.78A981E27@zeeman.thermal.esa.int> References: <20070510162508.78A981E27@zeeman.thermal.esa.int> Message-ID: <20070514102453.277fdc5c.duncan@thermal.esa.int> > I've been searching for a module to allow simple HTML generation, but > most of them appear to be more concerned with *parsing* HTML and XML. > The only one that looks promising from reviews dating back to 1998 or > so is HTMLgen, but the link on starship.python.net appears long dead. > > So my question is, what is the preferred way of generating simple HTML > or XHTML files these days? Is there a 'son of HTMLgen' or similar module? OK, my thanks to everyone who replied, either on the list or privately. I followed the links, and the links from those links, and poked around in the various documentation. What I want to generate depends on the contents of directories, etc. and is therefore has more variation than is handled easily in the templating systems. I chose the HyperText module (http://dustman.net/andy/python/HyperText/) because this fits more naturally with the code I'm updating, and also allows subclassing for customisation, etc. To give you a flavour, one code snippet changes from: if len(theCase.inputData.relatedFiles)>0: htmlFile.write('

The related file(s) for this case are:

\n') htmlFile.write('
    \n') for related_file in theCase.inputData.relatedFiles: htmlFile.write('
  • %s
  • \n' % ( related_file, related_file)) htmlFile.write('
\n') to the slightly more verbose, but much clearer and less error-prone: if len(testCaseData.inputData.relatedFiles) > 0: text = "The related file(s) for this case are:" heading = HTML.H2(text) document.append(heading) bulletList = HTML.UL() for fileName in testCaseData.inputData.relatedFiles: anchor = HTML.A(fileName, href=fileName) listItem = HTML.LI(anchor) bulletList.append(listItem) document.append(bulletList) and the module handles all of the start and end tags, indentation and other pretty printing. My only concern is that it is almost as old as HTMLgen :-( Cheers Duncan From sonmez at lavabit.com Mon May 14 09:59:47 2007 From: sonmez at lavabit.com (=?ISO-8859-1?Q?S=F6nmez_Kartal?=) Date: Mon, 14 May 2007 10:59:47 +0300 Subject: [Tutor] web spider In-Reply-To: <857e4c3d0705132047w50c633faue94fc68b082787a1@mail.gmail.com> References: <857e4c3d0705132047w50c633faue94fc68b082787a1@mail.gmail.com> Message-ID: <464816F3.9010901@lavabit.com> Hello, I'm working on a web spider project right now. And, I suggest you look at sgmllib and urllib modules of standard library, then you will realize some stuff in your mind. Happy coding... -- S?nmez Kartal From preecha88 at gmail.com Mon May 14 11:54:27 2007 From: preecha88 at gmail.com (Preecha Bundrikwong) Date: Mon, 14 May 2007 16:54:27 +0700 Subject: [Tutor] Adding a (Python) Command Button in Maya Message-ID: <30c6012b0705140254h277ae079ne3a682b63201c034@mail.gmail.com> Dear Tutor, I'm pretty new to Python. I want to add a command button in Maya. Once clicked, it runs Python's script/program. I'm not sure where I should write to ask Python or Maya; Not in details, please tell me briefly so that I can investigate more from there. Your suggestion would be highly appreciated! Regards, Preecha -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/0bd55f98/attachment-0001.html From kent37 at tds.net Mon May 14 12:26:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 May 2007 06:26:35 -0400 Subject: [Tutor] Getting value from web page In-Reply-To: <4647449E.2030002@vladoportos.sk> References: <4647449E.2030002@vladoportos.sk> Message-ID: <4648395B.2010005@tds.net> Vladimir Strycek wrote: > Hi all, > > i have a page which when i download from web by python and put tu > variable have something like: > > > > 119/1157/43/40 > > > neer end ( actualy this is only thing on that page.... + ) > > What i need actualy is to get this values 119/1157/43/40 to > variables...., they are changing allthe time, but they stay numbers and > "/" is always between numbers, they are always 4 > > I tried using re to search for it but without luck :( > > could somebody more experienced with re than me how to do it ? > > something like match = re.match('+/',htmltxt) (in htmltxt is the source > code downloaded from web) <-- example not working ;) You should use re.search(), not re.match() - match() only looks at the start of the text. Try match = re.search(r'(\d+)/(\d+)/(\d+)/(\d+)') Then match.groups(1, 2, 3, 4) will be a tuple of the string representations of the numbers. Kent From kent37 at tds.net Mon May 14 13:21:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 May 2007 07:21:02 -0400 Subject: [Tutor] installing Turbogears without using Internet In-Reply-To: References: Message-ID: <4648461E.2020806@tds.net> ShivKumar Anand wrote: > hello Tutors, > > I want solution to my problem. I want to install Turbogears and Cherrypy > without using internet. means that locally is i have eggs. how it is > possible? http://peak.telecommunity.com/DevCenter/EasyInstall#installing-on-un-networked-machines Kent From zebra05 at gmail.com Mon May 14 14:19:45 2007 From: zebra05 at gmail.com (OkaMthembo) Date: Mon, 14 May 2007 14:19:45 +0200 Subject: [Tutor] ActivePython and CPython Message-ID: Hi guys, What are the difference between ActiveState's Python distributions and the standard Python distribution from python.org, and which is better? Also, what IDE will give a user the ability to view HTML designs of a web application as well as the code view (like Dreamweaver does with PHP pages)? -- "The Stupidry Foundry" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/a49dbe24/attachment.htm From Senthil_OR at Dell.com Mon May 14 15:12:29 2007 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Mon, 14 May 2007 18:42:29 +0530 Subject: [Tutor] ActivePython and CPython In-Reply-To: References: Message-ID: What are the difference between ActiveState's Python distributions and the standard Python distribution from python.org , and which is better? Answer: Python from python.org is Open Source Software developed under OSI compatible license. Bunch of Python Developers are working on fixing bugs and releasing next version of python on various platforms. ActiveState provides a commertial distribution of same python with support options. They have a custom built installer, which will install extra modules like Python Windows Extensions and Documentation like regex tutorials and Mark Pilgrim's excellent work "Dive Into Python". All these are available for download from web however. I dont think there is a question of which is better. Both are better, check with your requirements. If you willing to contribute back to python community and raise bugs against Python software, download and use the latest from python.org Also, what IDE will give a user the ability to view HTML designs of a web application as well as the code view (like Dreamweaver does with PHP pages)? Answer: PyDev for Eclipse turns Eclipse into a pretty good IDE for Python. You may figure out similar extension for Eclipse for HTML development as well. That would satisfy your need. As it said, Eclipse is an IDE for any thing in general and nothing in particular. HTH. Senthil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/6bd3c0fb/attachment.html From Senthil_OR at Dell.com Mon May 14 15:31:16 2007 From: Senthil_OR at Dell.com (Senthil_OR at Dell.com) Date: Mon, 14 May 2007 19:01:16 +0530 Subject: [Tutor] Adding a (Python) Command Button in Maya In-Reply-To: <30c6012b0705140254h277ae079ne3a682b63201c034@mail.gmail.com> References: <30c6012b0705140254h277ae079ne3a682b63201c034@mail.gmail.com> Message-ID: From: Preecha Bundrikwong Sent: Monday, May 14, 2007 3:24 PM To: tutor at python.org Subject: [Tutor] Adding a (Python) Command Button in Maya I'm pretty new to Python. I want to add a command button in Maya. Once clicked, it runs Python's script/program. I'm not sure where I should write to ask Python or Maya; Answer: Design it in Maya and call it via Python. Thats what I understand in this tutorial on Python Maya Package. All the solutions for your questions should be here: http://cgkit.sourceforge.net/mayadoc/module-maya.gui.html -- Senthil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/5006f37f/attachment.html From alan.gauld at btinternet.com Mon May 14 16:20:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 May 2007 15:20:16 +0100 Subject: [Tutor] ActivePython and CPython References: Message-ID: "OkaMthembo" wrote > What are the difference between ActiveState's Python > distributions and the standard Python distribution from > python.org, and which is better? I prefer the ActiveState version for windows, I haven't tried their Luinux/Mac versions. Basically the Windows version comes with a bunch of extras targetting windows users. You get most of it by adding the winall package linked from python.org but ActiveState package it all up nicely. The help system is much better too and includes some extra material. > Also, what IDE will give a user the ability to view HTML > designs of a web application as well as the code view > (like Dreamweaver does with PHP pages)? Dreamweaver, I believe, will work with Python too. But you don't generally embed python into HTML as you do with PHP or ASP (although some solutions do) Modern thinking on web design suggests you should separate the code and HTML as much as possible and most web frameworks use a templating system like Cheetah/Kid to do that. Any XML/HTML editor should give you a web preview of any of the templating languages. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon May 14 16:22:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 May 2007 15:22:49 +0100 Subject: [Tutor] ActivePython and CPython References: Message-ID: wrote > Answer: PyDev for Eclipse turns Eclipse into a pretty good IDE for > Python. Agreed, I downloaded pydev over the weekend and have been playing. The editor isn't exactly vim/emacs but its as good as IDLE/Pythonwin However I think the OP wants an HTML preview and I don't see that facility in Eclipse anywhere. Alan G. From pthanos at gmail.com Mon May 14 16:29:38 2007 From: pthanos at gmail.com (Thanos Panousis) Date: Mon, 14 May 2007 16:29:38 +0200 Subject: [Tutor] Web GUI for a network management tool In-Reply-To: <4644450E.7060300@tds.net> References: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> <46435DE8.8070904@ericwalstad.com> <4dcb3660705110113v6a0e44d3l39984e572437bc52@mail.gmail.com> <4644450E.7060300@tds.net> Message-ID: <4dcb3660705140729g1637dcf1p160bc81483c4d52@mail.gmail.com> I know jfreechart is java only. It looks quite capable but the colleagues here say its not the easiest tool to use. I was about to start with a JSP solution for my web interface. But a short tutorial convinced me that writing this thing in java/jsp is simply crazy!!!! My god, coming from everyday python development it just shocked me to see how much code these guys are actually writing.... Just to do the most obvious of tasks. I am now seriously considering a matplotlib/python web framework solution. I think that the single advantage of rapid development will be so overwhelming compared to the J2EE monstrosities that it will compensate for any other dissadvantages. I just hope that matplotlib plays well with the web, and that I can integrate it to play with an MVC architecture that is employed by turbogears for example. On 5/11/07, Kent Johnson wrote: > Thanos Panousis wrote: > > I 'm going to need some hardcore graphing functionalities. And for > > that reason alone, I think jfreechart is the only thing that provides > > free and decent solution, also designed with the web in mind. > > jfreechart is a Java library so it will not integrate easily into a > Python web framework. > > Did you look at matplotlib? It is a very capable graphing library. You > can see examples of its output here: > http://matplotlib.sourceforge.net/screenshots.html > > > So everybody seems to prefer some framework even for not complicated > > (business) logic. I 'll try to go for something lightweight. > > web.py is pretty light, I think: > http://webpy.org/ > > Kent > From kent37 at tds.net Mon May 14 16:48:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 May 2007 10:48:13 -0400 Subject: [Tutor] Web GUI for a network management tool In-Reply-To: <4dcb3660705140729g1637dcf1p160bc81483c4d52@mail.gmail.com> References: <4dcb3660705100618w30d07f87rdff2b5f6d0f27d61@mail.gmail.com> <46435DE8.8070904@ericwalstad.com> <4dcb3660705110113v6a0e44d3l39984e572437bc52@mail.gmail.com> <4644450E.7060300@tds.net> <4dcb3660705140729g1637dcf1p160bc81483c4d52@mail.gmail.com> Message-ID: <464876AD.5050802@tds.net> Thanos Panousis wrote: > I was about to start with a JSP solution for my web interface. But a > short tutorial convinced me that writing this thing in java/jsp is > simply crazy!!!! My god, coming from everyday python development it > just shocked me to see how much code these guys are actually > writing.... Just to do the most obvious of tasks. Yes. And then they look at you crazy if you suggest there might be a better way. I'm a refugee from Java myself. > > I am now seriously considering a matplotlib/python web framework > solution. I just hope that matplotlib > plays well with the web, and that I can integrate it to play with an > MVC architecture that is employed by turbogears for example. I am using matplotlib and Django to create dynamic charts, it works fine. Maybe you missed my earlier pointer to a recipe for this: http://www.scipy.org/Cookbook/Matplotlib/Django The recipe creates a chart in memory and returns it as a string. Something very similar should work with other web frameworks. > > On 5/11/07, Kent Johnson wrote: >> Thanos Panousis wrote: >> > I 'm going to need some hardcore graphing functionalities. And for >> > that reason alone, I think jfreechart is the only thing that provides >> > free and decent solution, also designed with the web in mind. >> >> jfreechart is a Java library so it will not integrate easily into a >> Python web framework. >> >> Did you look at matplotlib? It is a very capable graphing library. You >> can see examples of its output here: >> http://matplotlib.sourceforge.net/screenshots.html >> >> > So everybody seems to prefer some framework even for not complicated >> > (business) logic. I 'll try to go for something lightweight. >> >> web.py is pretty light, I think: >> http://webpy.org/ >> >> Kent >> > From Michiel.Duvekot at autodesk.com Mon May 14 15:56:18 2007 From: Michiel.Duvekot at autodesk.com (Michiel Duvekot) Date: Mon, 14 May 2007 09:56:18 -0400 Subject: [Tutor] Adding a (Python) Command Button in Maya Message-ID: > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Senthil_OR at Dell.com > Sent: Monday, May 14, 2007 9:31 AM > To: preecha88 at gmail.com; tutor at python.org > Subject: Re: [Tutor] Adding a (Python) Command Button in Maya > > > From: Preecha Bundrikwong > Sent: Monday, May 14, 2007 3:24 PM > To: tutor at python.org > Subject: [Tutor] Adding a (Python) Command Button in Maya > > I'm pretty new to Python. I want to add a command button in > Maya. Once clicked, it runs Python's script/program. I'm not > sure where I should write to ask Python or Maya; > > Answer: Design it in Maya and call it via Python. Thats what > I understand in this tutorial on Python Maya Package. > All the solutions for your questions should be here: > > http://cgkit.sourceforge.net/mayadoc/module-maya.gui.html Not quite. The site you're referring to is a different project. You should refer to the Maya manuals for information on how to create menu items in Python. If you have questions about Maya and Python, a good place to ask is the Maya forum on the Area http://discussion.autodesk.com/adskcsp/forum.jspa?forumID=201 (free registration) or Ask Autodesk at http://forums.alias.com/WebX?14@@.3bb21e03 (requires Subscription) To create a button on the shelf, you would MMB-drag a command from the ScriptEditor's Python tab to the shelf. Here is an example that will make a button that will open the help docs for the button command. import maya.cmds as cmds cmds.help ('button',doc=True) -- Michiel From dkuhlman at rexx.com Mon May 14 20:16:19 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 14 May 2007 11:16:19 -0700 Subject: [Tutor] Parsing text file In-Reply-To: <46478B74.1090705@wardroper.org> References: <46478B74.1090705@wardroper.org> Message-ID: <20070514181619.GA186@cutter.rexx.com> On Sun, May 13, 2007 at 03:04:36PM -0700, Alan wrote: > I'm looking for a more elegant way to parse sections of text files that > are bordered by BEGIN/END delimiting phrases, like this: > > some text > some more text > BEGIN_INTERESTING_BIT > someline1 > someline2 > someline3 > END_INTERESTING_BIT > more text > more text > > What I have been doing is clumsy, involving converting to a string and > slicing out the required section using split('DELIMITER'): > > import sys > infile = open(sys.argv[1], 'r') > #join list elements with @ character into a string > fileStr = '@'.join(infile.readlines()) > #Slice out the interesting section with split, then split again into > lines using @ > resultLine = > fileStr.split('BEGIN_INTERESTING_BIT')[1].split('END_INTERESTING_BIT')[0].split('@') > for line in resultLine: > do things > > Can anyone point me at a better way to do this? > Possibly over-kill, but ... How much fun are you interested in having? Others have given you the "low fun" easy way. Now ask yourself whether this task is likely to become more complex (the interesting parts more hidden in a more complex grammar) and perhaps you also can't wait to have some fun. Is so, consider this suggestion: 1. Write grammar rules that describe your input text. In your case, those rules might look something like the following: Seq ::= {InterestingChunk | UninterestingChunk}* InterestingChunk ::= BeginToken InterestingSeq EndToken InterestingSeq ::= InterestingChunk* 2. For each rule, write a Python function that tries to recognize what the rule describes. To do its job, each function might call other functions that implement other grammar rules and might call a tokenizer function (see below) when it needs another token from the input stream. Example: def InterestingChunk_reco(self): if self.token_type == Tok_Begin: self.get_token() if self.InterestingSeq_reco(): if self.token_type == Tok_End: self.get_token() return True else: self.Error('bad interesting sequence') 3. Write a tokenizer function. Each time this function is called, it returns the next "token" (probably a word) from the input stream and a code that indicates the token type. Recognizer functions call this tokenizer function each time another token is needed. In your case there might be 3 token types: (1) plain word, (2) BeginTok, and (3) EndTok. If you do the above, you have just written your first recursive descent parser. Then, the next time you are at a party, beer bar, or wedding, any time the conversation comes even remotely close to the subject of parsing text, you say, "Well, for that kind of problem I usually write a recursive descent parser. It's the most powerful way and the only way to go. ..." Now, that's how to impress your friends and relations. But, seriously, recursive descent parsers are quite easy and are a useful technique to have in your tool bag. And, like I said above: It's fun. Besides, if your problem becomes more complex, and, for example, the input is not quite so line oriented, you will need a more powerful approach. Wikipedia has a better explanation than mine plus an example and links: http://en.wikipedia.org/wiki/Recursive_descent_parser I've attached a sample solution and sample input. Also, be aware that there are parse generators for Python. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman -------------- next part -------------- A non-text attachment was scrubbed... Name: recursive_descent_parser.py Type: text/x-python Size: 3385 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070514/ea5a84b3/attachment.py -------------- next part -------------- aaa bbb ccc ddd eee BEGIN_INTERESTING_BIT fff ggg hhh iii END_INTERESTING_BIT jjj kkk BEGIN_INTERESTING_BIT ppp qqq rrr sss ttt END_INTERESTING_BIT lll mmm From matt at mattanddawn.orangehome.co.uk Mon May 14 22:59:17 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Mon, 14 May 2007 21:59:17 +0100 Subject: [Tutor] How to test for a remainder from division Message-ID: <1179176357.13736.13.camel@computer> Hi there, I'm trying to write a short function to test whether a year is a leap year or not. To do this I need to check whether the year divides exactly by 4, 100 and 400. I can't think of an easy way to test whether there is a remainder or not. The best I can come up with so far is: if (year / 4.0) - (year // 4.0) <> 0: This doesn't seem to work, it is always True, is there a problem with the comparison? The arithmetic seems to be the correct way to isolate the remainder of the division. Can anyone suggest a better way of performing this test or alternately, how can I get the line above to work. Thanks, Matt From rabidpoobear at gmail.com Mon May 14 23:31:55 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 May 2007 16:31:55 -0500 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <1179176357.13736.13.camel@computer> References: <1179176357.13736.13.camel@computer> Message-ID: <4648D54B.6060207@gmail.com> Matt Smith wrote: > Hi there, > > I'm trying to write a short function to test whether a year is a leap > year or not. To do this I need to check whether the year divides exactly > by 4, 100 and 400. I can't think of an easy way to test whether there is > a remainder or not. The best I can come up with so far is: > > if (year / 4.0) - (year // 4.0) <> 0: > > This doesn't seem to work, it is always True, is there a problem with > the comparison? The arithmetic seems to be the correct way to isolate > the remainder of the division. > > Can anyone suggest a better way of performing this test or alternately, > how can I get the line above to work. > Matt > Matt: I'm not sure about your pseudocode, but have you tried to accomplish this with the modulus operator? It provides the remainder of integer division (i.e. a remainder of 0 indicates a perfect divisor.) so you could do: if year % 4 or year % 100 or year % 400: #then it's divisible perfectly by any of [4,100,400] for example. HTH, -Luke From nephish at gmail.com Mon May 14 20:48:00 2007 From: nephish at gmail.com (shawn bright) Date: Mon, 14 May 2007 13:48:00 -0500 Subject: [Tutor] easiest way to get true/false of odd/even number In-Reply-To: <384c93600705140829u6937312foaad4e2c329de07c8@mail.gmail.com> References: <384c93600705140829u6937312foaad4e2c329de07c8@mail.gmail.com> Message-ID: <384c93600705141148q4e0adda7lb993701fe83f4287@mail.gmail.com> nevermind, i found it. 4 %2 = 0 (even) 5 %2 = 1 (odd) pretty simple shawn On 5/14/07, shawn bright wrote: > > Hey there all, > i know this sounds kinda easy, but i was wanting the least verbose way to > get a True / False of a number being odd (not even) > thanks > shawn > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/8a181e8c/attachment.htm From eric at ericwalstad.com Mon May 14 23:45:14 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Mon, 14 May 2007 14:45:14 -0700 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <1179176357.13736.13.camel@computer> References: <1179176357.13736.13.camel@computer> Message-ID: <4648D86A.1040104@ericwalstad.com> Hey Matt, Skirting your question that looks like a modulo issue[1]... Maybe isleapyear[2] will work for you: import calendar calendar.isleap(2007) -> False calendar.isleap(2008) -> True I hope that helps, Eric. [1] http://docs.python.org/ref/binary.html [2] http://docs.python.org/lib/module-calendar.html Matt Smith wrote: > Hi there, > > I'm trying to write a short function to test whether a year is a leap > year or not. To do this I need to check whether the year divides exactly > by 4, 100 and 400. I can't think of an easy way to test whether there is > a remainder or not. The best I can come up with so far is: > > if (year / 4.0) - (year // 4.0) <> 0: > > This doesn't seem to work, it is always True, is there a problem with > the comparison? The arithmetic seems to be the correct way to isolate > the remainder of the division. > > Can anyone suggest a better way of performing this test or alternately, > how can I get the line above to work. > > Thanks, > > Matt > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- -- _________________________ Eric Walstad 2856 Diamond Street San Francisco, CA 94131 eric at ericwalstad.com 415-864-4224 _________________________ From bill at celestial.net Mon May 14 23:49:55 2007 From: bill at celestial.net (Bill Campbell) Date: Mon, 14 May 2007 14:49:55 -0700 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <4648D54B.6060207@gmail.com> References: <1179176357.13736.13.camel@computer> <4648D54B.6060207@gmail.com> Message-ID: <20070514214954.GA23161@ayn.mi.celestial.com> On Mon, May 14, 2007, Luke Paireepinart wrote: >Matt Smith wrote: >> Hi there, >> >> I'm trying to write a short function to test whether a year is a leap >> year or not. To do this I need to check whether the year divides exactly >> by 4, 100 and 400. I can't think of an easy way to test whether there is >> a remainder or not. The best I can come up with so far is: >> >> if (year / 4.0) - (year // 4.0) <> 0: >> >> This doesn't seem to work, it is always True, is there a problem with >> the comparison? The arithmetic seems to be the correct way to isolate >> the remainder of the division. >> >> Can anyone suggest a better way of performing this test or alternately, >> how can I get the line above to work. >> Matt >> >Matt: I'm not sure about your pseudocode, but have you tried to >accomplish this with the modulus operator? >It provides the remainder of integer division (i.e. a remainder of 0 >indicates a perfect divisor.) >so you could do: >if year % 4 or year % 100 or year % 400: #then it's divisible perfectly >by any of [4,100,400] While the modulus operator is generally useful for things like this, one might want to use the calendar module for this if it's smarter about some of the subtle quirks of leapyear: import calendar if calendar.isleap(year): ... Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software, LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 We contend that for a nation to try to tax itself into prosperity is like a man standing in a bucket and trying to lift himself up by the handle. -- Winston Churchill From arthur at nowsol.com Mon May 14 23:44:27 2007 From: arthur at nowsol.com (Arthur Coleman) Date: Mon, 14 May 2007 14:44:27 -0700 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <4648D54B.6060207@gmail.com> References: <1179176357.13736.13.camel@computer> <4648D54B.6060207@gmail.com> Message-ID: <009b01c79671$0bc095f0$1fa8a8c0@nowsol.com> Hi, I believe it should be if !(year % 4) or !(year % 100) or !(year % 400) Since 4*n % 4 = 0 for n integer Arthur -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Luke Paireepinart Sent: Monday, May 14, 2007 2:32 PM To: Matt Smith Cc: Python Tutor Subject: Re: [Tutor] How to test for a remainder from division Matt Smith wrote: > Hi there, > > I'm trying to write a short function to test whether a year is a leap > year or not. To do this I need to check whether the year divides exactly > by 4, 100 and 400. I can't think of an easy way to test whether there is > a remainder or not. The best I can come up with so far is: > > if (year / 4.0) - (year // 4.0) <> 0: > > This doesn't seem to work, it is always True, is there a problem with > the comparison? The arithmetic seems to be the correct way to isolate > the remainder of the division. > > Can anyone suggest a better way of performing this test or alternately, > how can I get the line above to work. > Matt > Matt: I'm not sure about your pseudocode, but have you tried to accomplish this with the modulus operator? It provides the remainder of integer division (i.e. a remainder of 0 indicates a perfect divisor.) so you could do: if year % 4 or year % 100 or year % 400: #then it's divisible perfectly by any of [4,100,400] for example. HTH, -Luke _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From john at fouhy.net Tue May 15 00:17:35 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 15 May 2007 10:17:35 +1200 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <009b01c79671$0bc095f0$1fa8a8c0@nowsol.com> References: <1179176357.13736.13.camel@computer> <4648D54B.6060207@gmail.com> <009b01c79671$0bc095f0$1fa8a8c0@nowsol.com> Message-ID: <5e58f2e40705141517l380cd0cbldaa05ed717073ca5@mail.gmail.com> On 15/05/07, Arthur Coleman wrote: > Hi, > > I believe it should be if !(year % 4) or !(year % 100) or !(year % 400) FWIW, the correct leapyear test is: if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): # then year is a leap year Year 2100 will not be a leap year, despite being divisible by 4. But y2k was a leap year, because it was a multiple of 400. -- John. From bgailer at alum.rpi.edu Tue May 15 00:44:01 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 14 May 2007 15:44:01 -0700 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <4648D54B.6060207@gmail.com> References: <1179176357.13736.13.camel@computer> <4648D54B.6060207@gmail.com> Message-ID: <4648E631.5020201@alum.rpi.edu> Luke Paireepinart wrote: > Matt Smith wrote: > >> Hi there, >> >> I'm trying to write a short function to test whether a year is a leap >> year or not. To do this I need to check whether the year divides exactly >> by 4, 100 and 400. I can't think of an easy way to test whether there is >> a remainder or not. The best I can come up with so far is: >> >> if (year / 4.0) - (year // 4.0) <> 0: >> >> This doesn't seem to work, it is always True, is there a problem with >> the comparison? The arithmetic seems to be the correct way to isolate >> the remainder of the division. >> >> Can anyone suggest a better way of performing this test or alternately, >> how can I get the line above to work. >> Matt >> >> > Matt: I'm not sure about your pseudocode, but have you tried to > accomplish this with the modulus operator? > It provides the remainder of integer division No, it provides the modulus, and applies to float not just integer!. For positive left argument that happens to = the remainder, but not for negative! See http://en.wikipedia.org/wiki/Modular_arithmetic which is how it works in python. -- Bob Gailer 510-978-4454 From samrobertsmith at gmail.com Tue May 15 01:07:55 2007 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 14 May 2007 16:07:55 -0700 Subject: [Tutor] version and path In-Reply-To: <1d987df30705051211w54d92bd3wffe678735c87aeef@mail.gmail.com> References: <1d987df30705051211w54d92bd3wffe678735c87aeef@mail.gmail.com> Message-ID: <1d987df30705141607w3d675fe0sfdfaddfe2a672596@mail.gmail.com> how to check how many versions of Python i have in my mac machine? also, how to put the path to the version I desire? Thanks a lot! From alan.gauld at btinternet.com Tue May 15 01:11:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 May 2007 00:11:54 +0100 Subject: [Tutor] How to test for a remainder from division References: <1179176357.13736.13.camel@computer> <4648D54B.6060207@gmail.com> <4648E631.5020201@alum.rpi.edu> Message-ID: "Bob Gailer" wrote >> Matt: I'm not sure about your pseudocode, but have you tried to >> accomplish this with the modulus operator? >> It provides the remainder of integer division > No, it provides the modulus, and applies to float not just integer!. While modulus is technically correct I prefer to use the term modulo since modulus can also be used to mean the magnitude or absolute value of a number. i.e. its true to say that abs(-7) provides the modulus of -7 (i.e. 7) which is different to the modulo - which is a binary operator... But one of the nice things about Python is that, whatever we call it, Python does it correctly! :-) Alan G. From nephish at gmail.com Mon May 14 17:29:06 2007 From: nephish at gmail.com (shawn bright) Date: Mon, 14 May 2007 10:29:06 -0500 Subject: [Tutor] easiest way to get true/false of odd/even number Message-ID: <384c93600705140829u6937312foaad4e2c329de07c8@mail.gmail.com> Hey there all, i know this sounds kinda easy, but i was wanting the least verbose way to get a True / False of a number being odd (not even) thanks shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/58e8cf63/attachment.html From atpridgen at mail.utexas.edu Tue May 15 01:57:03 2007 From: atpridgen at mail.utexas.edu (Adam Pridgen) Date: Mon, 14 May 2007 18:57:03 -0500 Subject: [Tutor] ctypes typedef Message-ID: Hey everyone, I am messing around with the ctypes package, and I wasn wondering how I go about defining a new type, where I essentially call an int foo. For example in C, I would use the following statement: typedef int foo; Is there an equivalent statement using ctypes, or is there another way of performing this task? Thanks in advance, Adam From llenard_twem at yahoo.com Tue May 15 02:37:55 2007 From: llenard_twem at yahoo.com (Jeff Molinari) Date: Mon, 14 May 2007 17:37:55 -0700 (PDT) Subject: [Tutor] Web Message-ID: <293886.18186.qm@web53207.mail.re2.yahoo.com> How exacly can you use python to create a web site? I have a small program I'm working on that I would like to create available via internet but I dont know how to make python work through internet. --------------------------------- Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/f9481d9a/attachment.html From kent37 at tds.net Tue May 15 03:14:56 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 May 2007 21:14:56 -0400 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <4648D86A.1040104@ericwalstad.com> References: <1179176357.13736.13.camel@computer> <4648D86A.1040104@ericwalstad.com> Message-ID: <46490990.1090708@tds.net> Eric Walstad wrote: > Hey Matt, > > Skirting your question that looks like a modulo issue[1]... > > Maybe isleapyear[2] will work for you: > > import calendar > > calendar.isleap(2007) -> False > calendar.isleap(2008) -> True And one of the nice things about Python, as well as having lots of useful stuff built in, much of the useful stuff is itself written in Python making it very easy to look under the hood and see what is going on. Here is the implementation of calendar.isleap(): def isleap(year): """Return 1 for leap years, 0 for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) Kent From tktucker at gmail.com Tue May 15 03:57:07 2007 From: tktucker at gmail.com (Tom Tucker) Date: Mon, 14 May 2007 21:57:07 -0400 Subject: [Tutor] version and path In-Reply-To: <1d987df30705141607w3d675fe0sfdfaddfe2a672596@mail.gmail.com> References: <1d987df30705051211w54d92bd3wffe678735c87aeef@mail.gmail.com> <1d987df30705141607w3d675fe0sfdfaddfe2a672596@mail.gmail.com> Message-ID: <2a278ffe0705141857s2dfd6ab4gd89b1bb942c6051f@mail.gmail.com> I would use the traditional Unix find command to find the various versions installed. find / -name "python*" On 5/14/07, linda.s wrote: > how to check how many versions of Python i have in my mac machine? > also, how to put the path to the version I desire? > Thanks a lot! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tktucker at gmail.com Tue May 15 03:57:50 2007 From: tktucker at gmail.com (Tom Tucker) Date: Mon, 14 May 2007 21:57:50 -0400 Subject: [Tutor] Web In-Reply-To: <293886.18186.qm@web53207.mail.re2.yahoo.com> References: <293886.18186.qm@web53207.mail.re2.yahoo.com> Message-ID: <2a278ffe0705141857n7395fd6cy3df099af8174039f@mail.gmail.com> Jeff, Can you clarify what you are looking to do. You have a small program that you want to distribute via Internet (allow users to view, download, etc)? You want to use Python to create a website? Integrate your program into a web page (modpython for example). On 5/14/07, Jeff Molinari wrote: > How exacly can you use python to create a web site? I have a small program > I'm working on that I would like to create available via internet but I dont > know how to make python work through internet. > > ________________________________ > Be a better Globetrotter. Get better travel answers from someone who knows. > Yahoo! Answers - Check it out. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From samrobertsmith at gmail.com Tue May 15 04:03:03 2007 From: samrobertsmith at gmail.com (linda.s) Date: Mon, 14 May 2007 19:03:03 -0700 Subject: [Tutor] version and path In-Reply-To: <2a278ffe0705141857s2dfd6ab4gd89b1bb942c6051f@mail.gmail.com> References: <1d987df30705051211w54d92bd3wffe678735c87aeef@mail.gmail.com> <1d987df30705141607w3d675fe0sfdfaddfe2a672596@mail.gmail.com> <2a278ffe0705141857s2dfd6ab4gd89b1bb942c6051f@mail.gmail.com> Message-ID: <1d987df30705141903k9a4d2dbw1d646672879a1519@mail.gmail.com> On 5/14/07, Tom Tucker wrote: > I would use the traditional Unix find command to find the various > versions installed. > > find / -name "python*" > > > > On 5/14/07, linda.s wrote: > > how to check how many versions of Python i have in my mac machine? > > also, how to put the path to the version I desire? > > Thanks a lot! That is what I got: find: /.Spotlight-V100: Permission denied find: /.Trashes: Permission denied From tktucker at gmail.com Tue May 15 04:23:12 2007 From: tktucker at gmail.com (Tom Tucker) Date: Mon, 14 May 2007 22:23:12 -0400 Subject: [Tutor] version and path In-Reply-To: <1d987df30705141902j1f10ac7at968fb9b7ad520598@mail.gmail.com> References: <1d987df30705051211w54d92bd3wffe678735c87aeef@mail.gmail.com> <1d987df30705141607w3d675fe0sfdfaddfe2a672596@mail.gmail.com> <2a278ffe0705141857s2dfd6ab4gd89b1bb942c6051f@mail.gmail.com> <1d987df30705141902j1f10ac7at968fb9b7ad520598@mail.gmail.com> Message-ID: <2a278ffe0705141923u131e0327y3c4093138604820a@mail.gmail.com> If you let the command finish, you should have seen the following or something equivalent below. Running the find command I sent you works, however you will see some noise (Permission Denied message). These are common messages because your general user account is trying to access restricted parts of the filesystem. This is normal behavior. Here are some example files on my Mac system. /usr/bin/python /usr/bin/python2.3 /usr/bin/pythonw /usr/bin/pythonw2.3 /usr/lib/python2.3 I'm assuming you are running a stock version of OS X and you have NOT installed Python manually. The typical Python path on my version OS X (11.4) is /usr/bin/python. /usr/bin/python is a link to the actual Python binary installed at /usr/bin/python2.3 For example... >which python /usr/bin/python >ls -l /usr/bin/python lrwxr-xr-x 1 root wheel 9 Jan 17 2006 /usr/bin/python -> python2.3 Does this help? On 5/14/07, linda. s wrote: > On 5/14/07, Tom Tucker wrote: > > I would use the traditional Unix find command to find the various > > versions installed. > > > > find / -name "python*" > > > > > > > > On 5/14/07, linda.s wrote: > > > how to check how many versions of Python i have in my mac machine? > > > also, how to put the path to the version I desire? > > > Thanks a lot! > > That is what I got: > find: /.Spotlight-V100: Permission denied > find: /.Trashes: Permission denied > From dos.fool at gmail.com Tue May 15 04:27:15 2007 From: dos.fool at gmail.com (max .) Date: Mon, 14 May 2007 20:27:15 -0600 Subject: [Tutor] html links Message-ID: <857e4c3d0705141927hf3abc09t40ddac1e9f9a79ec@mail.gmail.com> does anyone know of a tutorial for finding links in a web site with python. or creating files and asking ware to create a file. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070514/4d8dfcd1/attachment.htm From rabidpoobear at gmail.com Tue May 15 05:40:20 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 May 2007 22:40:20 -0500 Subject: [Tutor] html links In-Reply-To: <857e4c3d0705141927hf3abc09t40ddac1e9f9a79ec@mail.gmail.com> References: <857e4c3d0705141927hf3abc09t40ddac1e9f9a79ec@mail.gmail.com> Message-ID: <46492BA4.9080600@gmail.com> max . wrote: > does anyone know of a tutorial for finding links in a web site with > python. I believe BeautifulSoup could help with this, but am uncertain. > > or creating files and asking ware to create a file. There are many ways to do this. The simplest would be: filepath = raw_input("Where would you like to create the file? ") And this can vary in difficulty; if you wanted, for example, a GUI that lets them browse their directory tree graphically for the file they want, you could do that too. > > thanks yw -Luke From matt at mattanddawn.orangehome.co.uk Tue May 15 08:30:40 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Tue, 15 May 2007 07:30:40 +0100 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <1179176357.13736.13.camel@computer> References: <1179176357.13736.13.camel@computer> Message-ID: <1179210640.5947.5.camel@computer> Hi, Thanks for all the help, I guessed that there would be a module out there providing a function to do this but wanted to go through the process as a learning exercise. The modulus operator was just what I was looking for, I had been trying to check for a difference between the division and the floor division - a bit of a long winded way of doing things. Here is the final code I have come up with, any comments? # A program to determine whether a year is a leap year or not def is_leap_year(year): # Function that accepts a year as input and returns true if it is a leap year, false if it is not if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): return True else: return False # Main program logic year = raw_input("What year? ") year = int(year) if is_leap_year(year): print year, "is a leap year." else: print year, "is not a leap year" Thanks, Matt From sonmez at lavabit.com Tue May 15 08:57:42 2007 From: sonmez at lavabit.com (=?ISO-8859-1?Q?S=F6nmez_Kartal?=) Date: Tue, 15 May 2007 09:57:42 +0300 Subject: [Tutor] html links In-Reply-To: <857e4c3d0705141927hf3abc09t40ddac1e9f9a79ec@mail.gmail.com> References: <857e4c3d0705141927hf3abc09t40ddac1e9f9a79ec@mail.gmail.com> Message-ID: <464959E6.6050602@lavabit.com> Hi, import urllib from BeautifulSoup import BeautifulSoup page = urllib.urlopen(url) # url is the page address, if you are reading a file in your hard drive you could use just open(filename) too, and no needing to urllib soup = BeautifulSoup(page) #links = [str(link) for link in soup.findAll('a')] links = soup.findAll('a') I have used list compherension, comment outed line, because findAll function returns a different type specific to BeautifulSoup. First line, list compherension used converts every link to string. Happy coding... -- S?nmez Kartal From lohithreddym at gmail.com Tue May 15 09:07:19 2007 From: lohithreddym at gmail.com (lohith madireddy) Date: Tue, 15 May 2007 00:07:19 -0700 Subject: [Tutor] File access by os.system Message-ID: <905ffcb00705150007x3428084p1664b1c9c36c1a5b@mail.gmail.com> Hello, I am kind of stuck with this problem for many days. I would really appreciate the person who helps me in solving this problem. Here is how I am stuck.. I have files named 'x.pdb', 'y.pdb',..... in one directory. I am using python to read the files in that directory and do a system operation on each of the file using os.system. When I use this, it always gives an error saying 'could not read the file'. I use a for loop to pass each file to the executable. The problem comes in the identification of this file by system. To make you clear here is the rough code I was trying to use. import sys,os,tempfile,shutil Pdbs = os.listdir(os.getcwd()) temp1=tempfile.TemporaryFile() for Pdb in Pdbs: print(type(Pdb)) os.system("dsspcmbi -v Pdb temp1") I will have to process that temp1 file after I get the output from the executable 'dsspcmbi'. The system is not recognising file name Pdb. Please tell me how can I obviate this problem. Thanks in advance..... Lohith. From alan.gauld at btinternet.com Tue May 15 09:32:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 May 2007 08:32:55 +0100 Subject: [Tutor] Web References: <293886.18186.qm@web53207.mail.re2.yahoo.com> Message-ID: "Jeff Molinari" wrote > How exacly can you use python to create a web site? Short question, lots of answers! Have a look at the WebProgramming Topic Guide on python.org. http://wiki.python.org/moin/WebProgramming And check out the CgiScripts topic then the Web Frameworks topic. > I have a small program I'm working on that I would like > to create available via internet but I dont know how to > make python work through internet. At a very basic level you just need to get the python program to spit out html on stdout and set it up as a cgi program. But in practice there is more to consider and the topic guides should give you a feel for things. I'm actually writing a couple of new topics for my tutorial that covers web programming but at the current rate of progress they won't be finished till the end of the year! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 15 09:37:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 May 2007 08:37:40 +0100 Subject: [Tutor] html links References: <857e4c3d0705141927hf3abc09t40ddac1e9f9a79ec@mail.gmail.com> Message-ID: "max ." wrote > does anyone know of a tutorial for finding links in a web site with > python. > Beautifulsuop has been mentioned but its not part of standard python. Her is an example of the standard library parser: html = ''' Test page

Here is the first heading

A short paragraph

A second heading

A paragraph containing a hyperlink to python ''' from HTMLParser import HTMLParser class H1Parser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.h1_count = 0 self.isHeading = False def handle_starttag(self,tag,attributes=None): if tag == 'h1': self.h1_count += 1 self.isHeading = True def handle_endtag(self,tag): if tag == 'h1': self.isHeading = False def handle_data(self,data): if self.isHeading and self.h1_count == 2: print "Second Header contained: ", data parser = H1Parser() parser.feed(html) parser.close() > or creating files and asking ware to create a file. I'm not sure what you mean here? Do you mean fetching a file from a remote server? There is an ftp module if its from an ftp site... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From Dean.Gardner at barco.com Tue May 15 09:42:31 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Tue, 15 May 2007 09:42:31 +0200 Subject: [Tutor] Text matching In-Reply-To: <463B0A42.6040100@tds.net> References: <4639D972.20709@tds.net> <4639E605.6040809@tds.net> <463B0A42.6040100@tds.net> Message-ID: So I took Kents advice and refactored but I have uncovered another problem which I am hoping people may be able to help with. I realized that the string I was using to identify the end of a record can in some cases not be found (i.e. if a commit wasn't reviewed). This can lead to additional records being returned. Can anyone suggest how I can get round this? Text file example ( in this case looking for commit 1 would give details of commit two also): ---- SomeSpec 0000-0001 ---- > some commit 1 Reviewed By: someone ---- SomeSpec 0000-0002 ---- > some commit 2 ---- SomeSpec 0000-0003 ---- >some commit 1 Reviewed By: Someone Code: def searchChangeLog(self,filename): uid = self.item.Uid() record=[] logList=[] displayList=[] f = open(filename) logTextFile="temp.txt" """ searched through the changelog 'breaking' it up into individual entries""" for line in f: if ("Reviewed: 000" in line): logList.append(record) record = [] else: record.append(line) """ searches to determine if we can find entries for a particualr item""" for record in logList: for item in record: if uid in item: displayList.append(record) """ creates a temporary file to write our find results to """ removeFile = os.path.normpath( os.path.join(os.getcwd(), logTextFile)) # if the file exists, get rid of it before writing our new findings if Shared.config.Exists(removeFile): os.remove(removeFile) recordLog = open(logTextFile,"a") for record in range(len(displayList)): for item in displayList[record]: recordLog.write(item) recordLog.close() #display our results commandline = "start cmd /C " + logTextFile os.system(commandline) Dean Gardner Test Engineer Barco Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 www.barco.com dean.gardner at barco.com -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: 04 May 2007 11:26 To: Gardner, Dean Cc: tutor at python.org Subject: Re: [Tutor] Text matching Gardner, Dean wrote: > > So here it is....it might not be pretty (it seems a bit un-python like > to me) but it works exactly as required. If anyone can give any tips > for possible optimisation or refactor I would be delighted to hear > from them. > > Thanks > > uid = self.item.Uid() > record=[] > logList=[] > displayList=[] > f = open(filename) > logTextFile="temp.txt" > """ searched through the changelog 'breaking' it up into > individual entries""" > try: > while 1: > endofRecord=0 > l = f.next() > if l.startswith("----"): > record.append(l) > l=f.next() > while endofRecord==0: > if "Reviewed: 000" not in l: > record.append(l) > l=f.next() > else: > logList.append(record) > record=[] > endofRecord=1 > except StopIteration: > pass I don't think you need endofRecord and the nested loops here. In fact I think you could use a plain for loop here. AFAICT all you are doing is accumulating records with no special handling for anything except the end records. What about this: record = [] for line in f: if "Reviewed: 000" in line: logList.append(record) record = [] else: record.append(line) > """ searches to determine if we can find entries for > a particualr item""" > for record in logList: > currRec = record > for item in currRec: > if uid in item: > displayList.append(currRec) The currRec variable is not needed, just use record directly. If uid can only be in a specific line of the record you can test that directly, e.g. for record in logList: if uid in record[1]: > """ creates a temporary file to write our find results to """ > removeFile = os.path.normpath( os.path.join(os.getcwd(), > logTextFile)) > > # if the file exists, get rid of it before writing our new > findings > if Shared.config.Exists(removeFile): > os.remove(removeFile) > recordLog = open(logTextFile,"a") > > for record in range(len(displayList)): > for item in displayList[record]: > recordLog.write(item) for record in displayList: recordLog.writelines(record) > recordLog.close() > #display our results > commandline = "start cmd /C " + logTextFile > os.system(commandline) > Kent DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. From alan.gauld at btinternet.com Tue May 15 09:44:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 May 2007 08:44:11 +0100 Subject: [Tutor] File access by os.system References: <905ffcb00705150007x3428084p1664b1c9c36c1a5b@mail.gmail.com> Message-ID: "lohith madireddy" > I have files named 'x.pdb', 'y.pdb',..... in one directory. I am > using python to read the files in that directory and do a system > operation on each of the file using os.system. When I use this, it > always gives an error saying 'could not read the file'. There are several likely problems. The first is that the files might not have security pernissions set for you to manipulate - can you do the system() command from the OS prompt oK? Second, you are only passing the name of the file not the full path so the system command can't find the file. Third you could be passing something other than a file - eg another directory - to the command. > import sys,os,tempfile,shutil > Pdbs = os.listdir(os.getcwd()) > temp1=tempfile.TemporaryFile() > for Pdb in Pdbs: You probably need to use stat here to check that the item really is a file and that it has permissions. Alternatively use a try except clause and if an exception is raised simply use continue to start the next loop iteration. (possibly after printing an error message with the pdb name in it so you can check why it failed later) > print(type(Pdb)) > os.system("dsspcmbi -v Pdb temp1") You can get more about doing stat checks in the OS topic of my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From shiv_mbm at hotmail.com Tue May 15 12:18:11 2007 From: shiv_mbm at hotmail.com (ShivKumar Anand) Date: Tue, 15 May 2007 15:48:11 +0530 Subject: [Tutor] ImportError: No module named _apache Message-ID: dear all, I am trying to implement a text from mod_python manual. the code is: from mod_python import apache def handler(req): req.content_type ="text/plain\n\n" req.send_http_header() req.write("Hello World!!!") return apache.ok and the conf file of apache is having AddHandler mod_python .py PythonHandler SoapTest PythonDebug On I am getting this error message: Traceback (most recent call last): File "C:\Python24\exp\Web\SoapTest.py", line 1, in ? from mod_python import apache File "C:\Python24\lib\site-packages\mod_python\apache.py", line 28, in ? import _apacheImportError: No module named _apache where as i have mod_python installed and there is apache.py file also in the mod -python dir. Pls give me solution. Thanks Shiv _________________________________________________________________ Sign in and get updated with all the action! http://content.msn.co.in/Sports/FormulaOne/Default -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070515/fb51cb0c/attachment.html From kent37 at tds.net Tue May 15 12:26:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 May 2007 06:26:53 -0400 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <1179210640.5947.5.camel@computer> References: <1179176357.13736.13.camel@computer> <1179210640.5947.5.camel@computer> Message-ID: <46498AED.3060505@tds.net> Matt Smith wrote: > ere is the final code I have come up with, any comments? > > # A program to determine whether a year is a leap year or not > > def is_leap_year(year): > # Function that accepts a year as input and returns true if it is a leap > year, false if it is not > if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): > return True > else: > return False There is no need for the if statement, you can return the result directly: return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) Kent > > # Main program logic > year = raw_input("What year? ") > year = int(year) > if is_leap_year(year): > print year, "is a leap year." > else: > print year, "is not a leap year" > > Thanks, > > Matt > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue May 15 13:42:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 May 2007 07:42:45 -0400 Subject: [Tutor] Text matching In-Reply-To: References: <4639D972.20709@tds.net> <4639E605.6040809@tds.net> <463B0A42.6040100@tds.net> Message-ID: <46499CB5.9060602@tds.net> Gardner, Dean wrote: > So I took Kents advice and refactored but I have uncovered another > problem which I am hoping people may be able to help with. I realized > that the string I was using to identify the end of a record can in some > cases not be found (i.e. if a commit wasn't reviewed). This can lead to > additional records being returned. > > Can anyone suggest how I can get round this? Your sample data doesn't seem to match either the problem you describe or the code. I suggest looking for the start of a record rather than the end. At the end of the record-finding loop you will have one last record still to process in the record list. Kent > > Text file example ( in this case looking for commit 1 would give details > of commit two also): > > ---- SomeSpec 0000-0001 ---- > >> some commit 1 > > Reviewed By: someone > ---- SomeSpec 0000-0002 ---- >> some commit 2 > > ---- SomeSpec 0000-0003 ---- >> some commit 1 > Reviewed By: Someone > > > Code: > > def searchChangeLog(self,filename): > uid = self.item.Uid() > record=[] > logList=[] > displayList=[] > f = open(filename) > logTextFile="temp.txt" > """ searched through the changelog 'breaking' it up into > individual entries""" > > for line in f: > if ("Reviewed: 000" in line): > logList.append(record) > record = [] > else: > record.append(line) > > """ searches to determine if we can find entries for > a particualr item""" > for record in logList: > for item in record: > if uid in item: > displayList.append(record) > """ creates a temporary file to write our find results to """ > removeFile = os.path.normpath( os.path.join(os.getcwd(), > logTextFile)) > > # if the file exists, get rid of it before writing our new > findings > if Shared.config.Exists(removeFile): > os.remove(removeFile) > recordLog = open(logTextFile,"a") > > for record in range(len(displayList)): > for item in displayList[record]: > recordLog.write(item) > recordLog.close() > #display our results > commandline = "start cmd /C " + logTextFile > os.system(commandline) > > Dean Gardner > Test Engineer > Barco > Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK > Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 > www.barco.com > dean.gardner at barco.com > > > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: 04 May 2007 11:26 > To: Gardner, Dean > Cc: tutor at python.org > Subject: Re: [Tutor] Text matching > > Gardner, Dean wrote: >> >> So here it is....it might not be pretty (it seems a bit un-python like > >> to me) but it works exactly as required. If anyone can give any tips >> for possible optimisation or refactor I would be delighted to hear >> from them. >> >> Thanks >> >> uid = self.item.Uid() >> record=[] >> logList=[] >> displayList=[] >> f = open(filename) >> logTextFile="temp.txt" >> """ searched through the changelog 'breaking' it up into >> individual entries""" >> try: >> while 1: >> endofRecord=0 >> l = f.next() >> if l.startswith("----"): >> record.append(l) >> l=f.next() >> while endofRecord==0: >> if "Reviewed: 000" not in l: >> record.append(l) >> l=f.next() >> else: >> logList.append(record) >> record=[] >> endofRecord=1 >> except StopIteration: >> pass > > I don't think you need endofRecord and the nested loops here. In fact I > think you could use a plain for loop here. AFAICT all you are doing is > accumulating records with no special handling for anything except the > end records. What about this: > record = [] > for line in f: > if "Reviewed: 000" in line: > logList.append(record) > record = [] > else: > record.append(line) > >> """ searches to determine if we can find entries for >> a particualr item""" >> for record in logList: >> currRec = record >> for item in currRec: >> if uid in item: >> displayList.append(currRec) > > The currRec variable is not needed, just use record directly. > If uid can only be in a specific line of the record you can test that > directly, e.g. > for record in logList: > if uid in record[1]: > >> """ creates a temporary file to write our find results to """ >> removeFile = os.path.normpath( os.path.join(os.getcwd(), >> logTextFile)) >> >> # if the file exists, get rid of it before writing our new >> findings >> if Shared.config.Exists(removeFile): >> os.remove(removeFile) >> recordLog = open(logTextFile,"a") >> >> for record in range(len(displayList)): >> for item in displayList[record]: >> recordLog.write(item) > > for record in displayList: > recordLog.writelines(record) > >> recordLog.close() >> #display our results >> commandline = "start cmd /C " + logTextFile >> os.system(commandline) >> > > Kent > > > DISCLAIMER: > Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jason.massey at gmail.com Tue May 15 13:54:19 2007 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 15 May 2007 06:54:19 -0500 Subject: [Tutor] Text matching In-Reply-To: <7e3eab2c0705150451p70e7385fs46c0d71d605aae69@mail.gmail.com> References: <4639D972.20709@tds.net> <4639E605.6040809@tds.net> <463B0A42.6040100@tds.net> <7e3eab2c0705150451p70e7385fs46c0d71d605aae69@mail.gmail.com> Message-ID: <7e3eab2c0705150454g583ffee8t5b6f41d0966f7c4e@mail.gmail.com> heh... forwarding to the list, too. ---------- Forwarded message ---------- From: Jason Massey Date: May 15, 2007 6:51 AM Subject: Re: [Tutor] Text matching To: "Gardner, Dean" Look at it a different way. If the one thing that is sure to be there is the SomeSpec portion, then how about making a listing of where they occur and slicing everything up. Concretely, as Mr. Yoo would say: f = open(r"c:\python24\test.txt",'r').readlines() logList = [] indices = [x for x,line in enumerate(f) if 'SomeSpec' in line] for x in range(len(indices)-1): logList.append(f[indices[x]:indices[x+1]]) #tack on the last record logList.append(f[indices[-1]:]) for count,x in enumerate(logList): print count,':',x C:\Python24>test.py 0 : ['---- SomeSpec 0000-0001 ----\n', '\n', '> some commit 1\n', '\n', 'Reviewed By: someone\n'] 1 : ['---- SomeSpec 0000-0002 ----\n', '> some commit 2\n', '\n'] 2 : ['---- SomeSpec 0000-0003 ----\n', '>some commit 1\n', 'Reviewed By: Someone'] On 5/15/07, Gardner, Dean wrote: > > So I took Kents advice and refactored but I have uncovered another > problem which I am hoping people may be able to help with. I realized > that the string I was using to identify the end of a record can in some > cases not be found ( i.e. if a commit wasn't reviewed). This can lead to > additional records being returned. > > Can anyone suggest how I can get round this? > > Text file example ( in this case looking for commit 1 would give details > of commit two also): > > ---- SomeSpec 0000-0001 ---- > > > some commit 1 > > Reviewed By: someone > ---- SomeSpec 0000-0002 ---- > > some commit 2 > > ---- SomeSpec 0000-0003 ---- > >some commit 1 > Reviewed By: Someone > > > Code: > > def searchChangeLog(self,filename): > uid = self.item.Uid() > record=[] > logList=[] > displayList=[] > f = open(filename) > logTextFile="temp.txt" > """ searched through the changelog 'breaking' it up into > individual entries""" > > for line in f: > if ("Reviewed: 000" in line): > logList.append(record) > record = [] > else: > record.append(line) > > """ searches to determine if we can find entries for > a particualr item""" > for record in logList: > for item in record: > if uid in item: > displayList.append(record) > """ creates a temporary file to write our find results to """ > removeFile = os.path.normpath( os.path.join(os.getcwd(), > logTextFile)) > > # if the file exists, get rid of it before writing our new > findings > if Shared.config.Exists(removeFile): > os.remove(removeFile) > recordLog = open(logTextFile,"a") > > for record in range(len(displayList)): > for item in displayList[record]: > recordLog.write (item) > recordLog.close() > #display our results > commandline = "start cmd /C " + logTextFile > os.system(commandline) > > Dean Gardner > Test Engineer > Barco > Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK > Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799 > www.barco.com > dean.gardner at barco.com > > > -----Original Message----- > From: Kent Johnson [mailto: kent37 at tds.net] > Sent: 04 May 2007 11:26 > To: Gardner, Dean > Cc: tutor at python.org > Subject: Re: [Tutor] Text matching > > Gardner, Dean wrote: > > > > So here it is....it might not be pretty (it seems a bit un-python like > > > to me) but it works exactly as required. If anyone can give any tips > > for possible optimisation or refactor I would be delighted to hear > > from them. > > > > Thanks > > > > uid = self.item.Uid() > > record=[] > > logList=[] > > displayList=[] > > f = open(filename) > > logTextFile=" temp.txt" > > """ searched through the changelog 'breaking' it up into > > individual entries""" > > try: > > while 1: > > endofRecord=0 > > l = f.next() > > if l.startswith("----"): > > record.append(l) > > l=f.next() > > while endofRecord==0: > > if "Reviewed: 000" not in l: > > record.append(l) > > l=f.next() > > else: > > logList.append(record) > > record=[] > > endofRecord=1 > > except StopIteration: > > pass > > I don't think you need endofRecord and the nested loops here. In fact I > think you could use a plain for loop here. AFAICT all you are doing is > accumulating records with no special handling for anything except the > end records. What about this: > record = [] > for line in f: > if "Reviewed: 000" in line: > logList.append(record) > record = [] > else: > record.append(line) > > > """ searches to determine if we can find entries for > > a particualr item""" > > for record in logList: > > currRec = record > > for item in currRec: > > if uid in item: > > displayList.append(currRec) > > The currRec variable is not needed, just use record directly. > If uid can only be in a specific line of the record you can test that > directly, e.g. > for record in logList: > if uid in record[1]: > > > """ creates a temporary file to write our find results to """ > > removeFile = os.path.normpath( os.path.join(os.getcwd(), > > logTextFile)) > > > > # if the file exists, get rid of it before writing our new > > findings > > if Shared.config.Exists (removeFile): > > os.remove(removeFile) > > recordLog = open(logTextFile,"a") > > > > for record in range(len(displayList)): > > for item in displayList[record]: > > recordLog.write(item) > > for record in displayList: > recordLog.writelines(record) > > > recordLog.close() > > #display our results > > commandline = "start cmd /C " + logTextFile > > os.system(commandline) > > > > Kent > > > DISCLAIMER: > Unless indicated otherwise, the information contained in this message is > privileged and confidential, and is intended only for the use of the > addressee(s) named above and others who have been specifically authorized to > receive it. If you are not the intended recipient, you are hereby notified > that any dissemination, distribution or copying of this message and/or > attachments is strictly prohibited. The company accepts no liability for any > damage caused by any virus transmitted by this email. Furthermore, the > company does not warrant a proper and complete transmission of this > information, nor does it accept liability for any delays. If you have > received this message in error, please contact the sender and delete the > message. Thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070515/32f498d5/attachment-0001.html From ktenney at gmail.com Tue May 15 15:25:55 2007 From: ktenney at gmail.com (Kent Tenney) Date: Tue, 15 May 2007 13:25:55 +0000 (UTC) Subject: [Tutor] object design question Message-ID: Howdy, I would be interested in some discussion of which of the following approaches is preferred and why. class RstManager: def __init__(self, text): self.text = text self.parseRst() def parseRst(self): parsed = self.parsed = parsed class RstManager: def __init__(self, text): self.parsed = parseRst(text) def parseRst(self, text): parsed = return parsed Thanks, Kent From Mike.Hansen at atmel.com Tue May 15 16:01:25 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 15 May 2007 08:01:25 -0600 Subject: [Tutor] File access by os.system In-Reply-To: References: <905ffcb00705150007x3428084p1664b1c9c36c1a5b@mail.gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E7D4909@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld > Sent: Tuesday, May 15, 2007 1:44 AM > To: tutor at python.org > Subject: Re: [Tutor] File access by os.system > > > "lohith madireddy" > > > I have files named 'x.pdb', 'y.pdb',..... in one directory. I am > > using python to read the files in that directory and do a system > > operation on each of the file using os.system. When I use this, it > > always gives an error saying 'could not read the file'. > > There are several likely problems. > The first is that the files might not have security pernissions set > for you to manipulate - can you do the system() command from > the OS prompt oK? > > Second, you are only passing the name of the file not the full > path so the system command can't find the file. > > Third you could be passing something other than a > file - eg another directory - to the command. > > > import sys,os,tempfile,shutil > > Pdbs = os.listdir(os.getcwd()) > > temp1=tempfile.TemporaryFile() > > for Pdb in Pdbs: > > You probably need to use stat here to check that the item > really is a file and that it has permissions. > > Alternatively use a try except clause and if an exception > is raised simply use continue to start the next loop iteration. > (possibly after printing an error message with the pdb name > in it so you can check why it failed later) > > > print(type(Pdb)) > > os.system("dsspcmbi -v Pdb temp1") Should the os.system command be something like command = "dsspcmbi -v %s %s" %(Pdb, temp1) os.system(command) ? Mike From kent37 at tds.net Tue May 15 16:14:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 May 2007 10:14:59 -0400 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <1179231926.20531.7.camel@computer> References: <1179176357.13736.13.camel@computer> <4648D86A.1040104@ericwalstad.com> <46490990.1090708@tds.net> <1179231926.20531.7.camel@computer> Message-ID: <4649C063.1070107@tds.net> Matt Smith wrote: >> Here is the implementation of calendar.isleap(): >> >> def isleap(year): >> """Return 1 for leap years, 0 for non-leap years.""" >> return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) > > Hi Kent, > > Thanks for the help. For future reference how do I go look at the > implementation of a particular function (the ones coded in Python, I > don't know C)? Look in the lib directory that was installed with Python. The location varies. On Windows look for C:\Python2.x\Lib. My Mac has it at /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 In the python interpreter, try >>> import sys >>> sys.path The lib directory will be listed as one element of sys.path. Kent From kent37 at tds.net Tue May 15 16:17:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 May 2007 10:17:34 -0400 Subject: [Tutor] object design question In-Reply-To: References: Message-ID: <4649C0FE.6090607@tds.net> Kent Tenney wrote: > Howdy, > > I would be interested in some discussion of > which of the following approaches is preferred and why. > > class RstManager: > > def __init__(self, text): > self.text = text > self.parseRst() > > def parseRst(self): > parsed = > self.parsed = parsed > > > class RstManager: > > def __init__(self, text): > self.parsed = parseRst(text) > > def parseRst(self, text): > parsed = > return parsed If you have no further need of text, I prefer the second. If you need to keep text around then use the first one or possibly class RstManager: def __init__(self, text): self.text = text self.parsed = parseRst(text) def parseRst(self, text): parsed = return parsed which makes the assignment to self.parsed more explicit. Kent > > > Thanks, > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rikard.bosnjakovic at gmail.com Tue May 15 17:25:24 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Tue, 15 May 2007 17:25:24 +0200 Subject: [Tutor] File access by os.system In-Reply-To: <57B026980605A64F9B23484C5659E32E7D4909@poccso.US.ad.atmel.com> References: <905ffcb00705150007x3428084p1664b1c9c36c1a5b@mail.gmail.com> <57B026980605A64F9B23484C5659E32E7D4909@poccso.US.ad.atmel.com> Message-ID: On 5/15/07, Mike Hansen wrote: > Should the os.system command be something like > command = "dsspcmbi -v %s %s" %(Pdb, temp1) > os.system(command) > > ? Yes. -- - Rikard - http://bos.hack.org/cv/ From eric at ericwalstad.com Tue May 15 17:40:16 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 15 May 2007 08:40:16 -0700 Subject: [Tutor] How to test for a remainder from division In-Reply-To: <1179210640.5947.5.camel@computer> References: <1179176357.13736.13.camel@computer> <1179210640.5947.5.camel@computer> Message-ID: <4649D460.1080307@ericwalstad.com> Hey Matt, Matt Smith wrote: > I guessed that there would be a module out > there providing a function to do this but wanted to go through the > process as a learning exercise. Good form, old boy. > Here is the final code I have come up with, any comments? I think your code looks fine. I like to do the following, just to be a little more concise: def is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) That is, the 'if' in your code is evaluating the statement into a boolean. Why not just return the results of that evaluation? From eric at ericwalstad.com Tue May 15 17:53:53 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 15 May 2007 08:53:53 -0700 Subject: [Tutor] ImportError: No module named _apache In-Reply-To: References: Message-ID: <4649D791.2000201@ericwalstad.com> Hey ShivKumar, ShivKumar Anand wrote: > *I am getting this error message:* > > Traceback (most recent call last): > File "C:\Python24\exp\Web\SoapTest.py", line 1, in ? > from mod_python import apache > File "C:\Python24\lib\site-packages\mod_python\apache.py", line 28, in ? > import _apache > ImportError: No module named _apache Are you trying to call your mod_python code from the command line? If so: "you can't import mod_python into scripts that are run from the command line or any other context outside a running apache server." From alan.gauld at btinternet.com Tue May 15 18:25:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 May 2007 17:25:20 +0100 Subject: [Tutor] object design question References: <4649C0FE.6090607@tds.net> Message-ID: "Kent Johnson" wrote >> Howdy, >> >> I would be interested in some discussion of >> which of the following approaches is preferred and why. >> >> class RstManager: >> def __init__(self, text): >> self.parsed = parseRst(text) >> def parseRst(self, text): >> parsed = >> return parsed > > If you have no further need of text, I prefer the second. If you > need to > keep text around then use the first one or possibly I agree with Kent J. It depends a lot on what else your class is doing. If it needs text or if it will parse reguilarly. However I'm also always suspicious of a class called xxxManager. Classes are by definition there to manage some data by providing some behaviour. Usually the Manager bit can be left off the name. Then the class is just Rst. I don't know what an Rst is, but my guess is that you will want one of them as an object rather than some kind of manager object. To use a more mundane example: class FileManager: def open(self, name): .... def close(self):.... fm = FileManager('foo.txt') Do I really want a file manager object or do I want a file? Which is the object? Often when we thinkmof objects as managers we are really thinking in terms of some data that we want to apply functions to. Really we should be thinking of the class as representing the objects themselves. If you do have a real manager object it is usual for it to contain one or more of the things it manages, thius you'd expect the definition to look something like: class FooManager: def __init__(self, aFoo): self.Foos.append(aFoo) def sort(self):.... def find(self,aFooRef):.... ie The init takes a Foo as an argument and manages a collection of Foos. But I don't know your domain and you may well really mean an RstManager. But its worth considering, it may well make your code more intuitive to read. If you want to read much more on this theme try and find a copy of the book OOP by Coad and Nicola. They discuss the problems that can arise in an OOP program with Manager objects. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From foxandxss at gmail.com Wed May 16 00:50:02 2007 From: foxandxss at gmail.com (Jesus Rodriguez) Date: Wed, 16 May 2007 00:50:02 +0200 Subject: [Tutor] python project books/webs from scratch? and python OOP Message-ID: <2a1edb210705151550i15dde437m673a73ba97ceaded@mail.gmail.com> Hi! I have good python knowledge but I don't know how to face a project.Yes, i can do some small projects, but i'm scared of big projects....I don't know how to start!! Then, I'm looking for a book or web with projects, like console text games or console programs explained from scratch to finish. On the other hand, I'm looking for book or tutorial of OO{P, D, A} (programming, analisys and design) with python. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070516/1e7ffd08/attachment.htm From carroll at tjc.com Wed May 16 01:30:19 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 15 May 2007 16:30:19 -0700 (PDT) Subject: [Tutor] How to test for a remainder from division In-Reply-To: <4649C063.1070107@tds.net> Message-ID: On Tue, 15 May 2007, Kent Johnson wrote: > Matt Smith wrote: > > > > Thanks for the help. For future reference how do I go look at the > > implementation of a particular function (the ones coded in Python, I > > don't know C)? > > Look in the lib directory that was installed with Python. The location > varies. On Windows look for C:\Python2.x\Lib. My Mac has it at > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 > > In the python interpreter, try > >>> import sys > >>> sys.path > > The lib directory will be listed as one element of sys.path. Will the following approach always work? It's what I start with. >>> import calendar >>> print calendar.__file__ C:\Python25\lib\calendar.py From rabidpoobear at gmail.com Wed May 16 07:28:04 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 16 May 2007 00:28:04 -0500 Subject: [Tutor] File access by os.system In-Reply-To: References: <905ffcb00705150007x3428084p1664b1c9c36c1a5b@mail.gmail.com> <57B026980605A64F9B23484C5659E32E7D4909@poccso.US.ad.atmel.com> Message-ID: <464A9664.9090205@gmail.com> Rikard Bosnjakovic wrote: > On 5/15/07, Mike Hansen wrote: > > >> Should the os.system command be something like >> command = "dsspcmbi -v %s %s" %(Pdb, temp1) >> os.system(command) >> >> ? >> > > Yes. > Not Quite, I think. >>> import tempfile >>> help(tempfile.TemporaryFile) Help on function NamedTemporaryFile in module tempfile: NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. 'mode' -- the mode argument to os.fdopen (default "w+b"). 'bufsize' -- the buffer size argument to os.fdopen (default -1). The file is created as mkstemp() would do it. Returns an object with a file-like interface; the name of the file is accessible as file.name. The file will be automatically deleted when it is closed. So I'd expect to use command = "dsspcmbi -v %s %s" %(Pdb, temp1.name) That is, unless __str__ and/or __repr__ return the file name also. -Luke From ktenney at gmail.com Wed May 16 13:55:16 2007 From: ktenney at gmail.com (Kent Tenney) Date: Wed, 16 May 2007 11:55:16 +0000 (UTC) Subject: [Tutor] object design question References: <4649C0FE.6090607@tds.net> Message-ID: Alan Gauld btinternet.com> writes: > > "Kent Johnson" tds.net> wrote > >> Howdy, > >> > >> I would be interested in some discussion of > >> which of the following approaches is preferred and why. > >> > >> class RstManager: > >> def __init__(self, text): > >> self.parsed = parseRst(text) > >> def parseRst(self, text): > >> parsed = > >> return parsed > > > > If you have no further need of text, I prefer the second. If you > > need to > > keep text around then use the first one or possibly > > I agree with Kent J. It depends a lot on what else your class is > doing. OK, so there's not "one right way" to handle this. Assigning via the method return is more explicit, I thought class design guidelines might frown on passing values back and forth. > If it needs text or if it will parse reguilarly. > > However I'm also always suspicious of a class called xxxManager. OK, very generous response. I'll expand on what I'm doing. The class I'm working on does conversion between ReStructuredText and the Leo (http://leo.sf.net)file format. It also wraps rst->html rst->xml etc. The class is currently name ``Sections``. The interface consists primarily of properties for the different types. s = Sections() s.rst = 'document.txt' leo_version = s.leo html_version = s.html s.leo = 'document.leo' rst_version = s.rst xml_html = s.html The implementation involves lots of choices like the original post, do the variables get returned by conversion methods, or do the methods set the class variables? I'm not sure if 'Manager' is the correct term here. Thanks, Kent > > Classes are by definition there to manage some data by > providing some behaviour. Usually the Manager bit can > be left off the name. Then the class is just Rst. > > I don't know what an Rst is, but my guess is that you will > want one of them as an object rather than some kind of > manager object. To use a more mundane example: > > class FileManager: > def open(self, name): .... > def close(self):.... > > fm = FileManager('foo.txt') > > Do I really want a file manager object or do I want a file? > Which is the object? Often when we thinkmof objects as > managers we are really thinking in terms of some data > that we want to apply functions to. Really we should be > thinking of the class as representing the objects themselves. > > If you do have a real manager object it is usual for it to contain > one or more of the things it manages, thius you'd expect > the definition to look something like: > > class FooManager: > def __init__(self, aFoo): > self.Foos.append(aFoo) > > def sort(self):.... > def find(self,aFooRef):.... > > ie The init takes a Foo as an argument and manages a > collection of Foos. > > But I don't know your domain and you may well really mean > an RstManager. But its worth considering, it may well make > your code more intuitive to read. > > If you want to read much more on this theme try and find > a copy of the book OOP by Coad and Nicola. They discuss > the problems that can arise in an OOP program with Manager > objects. > > HTH, > From dsh0105 at comcast.net Wed May 16 17:23:23 2007 From: dsh0105 at comcast.net (dsh0105 at comcast.net) Date: Wed, 16 May 2007 15:23:23 +0000 Subject: [Tutor] Learning to Debug? Message-ID: <051620071523.23105.464B21EB000EAA7B00005A412207021633CACFCECF089C0B@comcast.net> I'm moving forward with my learning of Python, but I've decided it's finally time to address a problem that has haunted me in every language I've every tried to learn: debugging. I'm just not very good at it. Does anyone have recommendations for Python-centric books/online tutorials that teach you techniques for good debugging? Thanks, David Hamilton From emadnawfal at gmail.com Wed May 16 17:40:16 2007 From: emadnawfal at gmail.com (Emad Nawfal) Date: Wed, 16 May 2007 08:40:16 -0700 Subject: [Tutor] words and lengths Message-ID: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> Hi All, I'm beginning to learn Python for linguistic research using the Natural Language Toolkit. I want to write a small piece of code to count lengths of words and print them a long with the words. I've tried this but it does not work. What's wrong with it, and how can I fix it? phrase2 = ['colorless', 'green', 'ideas', 'sleep', 'furiously'] lengths = {} for word in phrase2: lengths = lengths[word, len(word)] print lengths Thank you in anticipation -- If everyone is thinking alike, then somebody isn't thinking." George S. Patton ------------------------------------------------------- Emad Soliman Nawfal University of Arizona, Tucson http://emadnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070516/990e3fdd/attachment.html From Mike.Hansen at atmel.com Wed May 16 18:06:10 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 16 May 2007 10:06:10 -0600 Subject: [Tutor] words and lengths In-Reply-To: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> References: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E7D4A96@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Emad Nawfal > Sent: Wednesday, May 16, 2007 9:40 AM > To: Tutor at python.org > Subject: [Tutor] words and lengths > > Hi All, > I'm beginning to learn Python for linguistic research using > the Natural Language Toolkit. I want to write a small piece > of code to count lengths of words and print them a long with > the words. I've tried this but it does not work. What's wrong > with it, and how can I fix it? > > > phrase2 = ['colorless', 'green', 'ideas', 'sleep', 'furiously'] > lengths = {} > for word in phrase2: > lengths = lengths[word, len(word)] > > print lengths > > > Thank you in anticipation Instead of lengths = lengths[word, len(word)] I think it should be lengths[word] = len(word) # dictionary[key] = value Mike From bensherman at gmail.com Wed May 16 19:20:12 2007 From: bensherman at gmail.com (Ben Sherman) Date: Wed, 16 May 2007 13:20:12 -0400 Subject: [Tutor] Learning to Debug? In-Reply-To: <051620071523.23105.464B21EB000EAA7B00005A412207021633CACFCECF089C0B@comcast.net> References: <051620071523.23105.464B21EB000EAA7B00005A412207021633CACFCECF089C0B@comcast.net> Message-ID: <5a56471e0705161020p664bde43ma9e1d4c55d90c189@mail.gmail.com> On 5/16/07, dsh0105 at comcast.net wrote: > > I'm moving forward with my learning of Python, but I've decided it's > finally time to address a problem that has haunted me in every language I've > every tried to learn: debugging. I'm just not very good at it. Does anyone > have recommendations for Python-centric books/online tutorials that teach > you techniques for good debugging? Hi David, welcome to Python! You should look at the pdb module. A good tutorial is at http://www.ferg.org/papers/debugging_in_python.html Good luck! Ben (accidentally replied directly to David the first time) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070516/1c5e3e09/attachment.htm From jcrajan00 at gmail.com Wed May 16 19:50:21 2007 From: jcrajan00 at gmail.com (Chenthil) Date: Wed, 16 May 2007 23:20:21 +0530 Subject: [Tutor] Python for s60 Message-ID: Hi can some one show nd some good tutorials for writing scripts for symbian s60 devices. Thanks is advance. From jason.massey at gmail.com Wed May 16 20:43:23 2007 From: jason.massey at gmail.com (Jason Massey) Date: Wed, 16 May 2007 13:43:23 -0500 Subject: [Tutor] Python for s60 In-Reply-To: References: Message-ID: <7e3eab2c0705161143y773de49cw246225afa6c37dcb@mail.gmail.com> Google is your friend: http://www.google.com/search?sourceid=navclient&ie=UTF-8&rls=GGLR,GGLR:2006-33,GGLR:en&q=python+symbian The first link in particular looks good. On 5/16/07, Chenthil wrote: > > Hi can some one show nd some good tutorials for writing scripts for > symbian s60 devices. > Thanks is advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070516/03a51b4f/attachment.html From sxkorean at gmail.com Wed May 16 22:02:51 2007 From: sxkorean at gmail.com (Dude, WHOA!) Date: Wed, 16 May 2007 16:02:51 -0400 Subject: [Tutor] Socket question. Message-ID: I thought I'd try my hand at sockets, and tried to make a telnet-ish, kinda thing. The problem is that the client I wrote doesn't receive data and display it, and it also only executes single word commands. Thanks in advance. Server side: #!/usr/bin/env python import socket from subprocess import * IP = 'localhost' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((IP, 1234)) sock.listen(5) while True: log = open("log.log", "a") channel, details = sock.accept() command = channel.recv(2048) channel.send(command) log.write(str(details)) log.write("\n") log.close() print "New connection logged." try: echo = Popen(command, stdout=PIPE).stdout.read() channel.send(echo) except: print 'Eh?' channel.send('Eh?') channel.close() Client: #!/usr/bin/env python import socket print ''' ----------------------------- Weak Insecure Shell ----------------------------- ''' IP = raw_input('IP: ') PORT = input('PORT: ') while 1: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((IP,PORT)) send = raw_input('Send: ') sock.send(send) sock.recv(2048) sock.close() From alan.gauld at btinternet.com Wed May 16 22:57:13 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 May 2007 21:57:13 +0100 Subject: [Tutor] object design question References: <4649C0FE.6090607@tds.net> Message-ID: "Kent Tenney" wrote > The class I'm working on does conversion between ReStructuredText > and the Leo (http://leo.sf.net)file format. It also > wraps rst->html rst->xml etc. OK, I still don;t knoew exactly what it is. But I'll take a guess from what you say that that you have an Rst text stored in one file and want to convert it to Leo text, maybe in another file. The way I'd do that is create an RSTFile class that is initialised with a file name and Rst version(defaulted appropriately) I'd probably provide a method called generateLeo(LeoVersion) So it looks like: rst = RstFile('rstfilename.rst') file('Leofilename.leo','w').write(rst.generateLeo('v1.3')) You could of course create a LeoFile class too, in which case the second line might be: LeoFile(text=rst.generateLeo(''v1.3')).write() Where the initialiser is a Leo text - you could have the option of using a leofile to initialise and making both file classes more like a traditional python file... There are, as you observed, no *right* answers when defining classes/objects it depends on how you intend to use them. The above may be missing the point entirely, in which case just ignore me! :-) Alan G. From bgailer at alum.rpi.edu Wed May 16 23:03:49 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 16 May 2007 14:03:49 -0700 Subject: [Tutor] words and lengths In-Reply-To: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> References: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> Message-ID: <464B71B5.6020107@alum.rpi.edu> Please use plain text. Color hurts my eyes, does NOT help me read your program. Emad Nawfal wrote: > Hi All, > I'm beginning to learn Python for linguistic research using the > Natural Language Toolkit. I want to write a small piece of code to > count lengths of words and print them a long with the words. I've > tried this but it does not work. What's wrong with it, and how can I > fix it? > > > phrase2 = ['colorless', 'green', 'ideas', 'sleep', 'furiously'] > lengths = {} > for word in phrase2: > lengths = lengths[word, len(word)] > > print lengths > > Thank you in anticipation > > -- > If everyone is thinking alike, then somebody isn't thinking." George > S. Patton > ------------------------------------------------------- > Emad Soliman Nawfal > University of Arizona, Tucson > http://emadnawfal.googlepages.com > -------------------------------------------------------- > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 510-978-4454 From alan.gauld at btinternet.com Wed May 16 23:04:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 May 2007 22:04:41 +0100 Subject: [Tutor] Learning to Debug? References: <051620071523.23105.464B21EB000EAA7B00005A412207021633CACFCECF089C0B@comcast.net> Message-ID: wrote in message > Does anyone have recommendations for Python-centric > books/online tutorials that teach you techniques for > good debugging? The paper book version of my tutorial has a chapter on debugging techniques and tools - starting with print statements through to pdb. If you know basic python its not worth buying (my publisher hates when I say that!) but maybe your local library has a copy? Or you can get a cheap second hand copy on Amazon? Unfortunately its one of the chapters that isn't on the web site... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed May 16 23:12:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 May 2007 22:12:41 +0100 Subject: [Tutor] Socket question. References: Message-ID: "Dude, WHOA!" wrote > kinda thing. The problem is that the client I wrote doesn't receive > data and display it, and it also only executes single word commands. > Server side: > #!/usr/bin/env python > import socket > from subprocess import * > IP = 'localhost' > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.bind((IP, 1234)) You are using localhost so it will only work with the client on the same PC and using port 1234. > Client: > IP = raw_input('IP: ') > PORT = input('PORT: ') So there is no point in asking the user, it has to be IP = 127.0.0.1 PORT = 1234 Anything else will fail. You can look at the Network programming topic on my tutorial for some similar examples if you like. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Thu May 17 02:51:52 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 16 May 2007 17:51:52 -0700 Subject: [Tutor] words and lengths In-Reply-To: <464B71B5.6020107@alum.rpi.edu> References: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> <464B71B5.6020107@alum.rpi.edu> Message-ID: <464BA728.8030409@alum.rpi.edu> Emad Nawfal wrote: >> Hi All, >> I'm beginning to learn Python for linguistic research using the >> Natural Language Toolkit. I want to write a small piece of code to >> count lengths of words and print them a long with the words. I've >> tried this but it does not work. What's wrong with it, and how can I >> fix it? >> >> >> phrase2 = ['colorless', 'green', 'ideas', 'sleep', 'furiously'] >> lengths = {} >> for word in phrase2: >> lengths = lengths[word, len(word)] >> >> print lengths Try this: for word in phrase2: lengths[word] = len(word) What you have now is an attempt to get a dictionary value using word, len(word) as a key and replace the dictionary with that value. Should fail with KeyError. -- Bob Gailer 510-978-4454 From mwalsh at groktech.org Thu May 17 04:56:21 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Wed, 16 May 2007 21:56:21 -0500 Subject: [Tutor] Socket question. In-Reply-To: References: Message-ID: <464BC455.2070706@groktech.org> Hey Dude :) Dude, WHOA! wrote: > kinda thing. The problem is that the client I wrote doesn't receive > data and display it, and it also only executes single word commands. > Server side: > #!/usr/bin/env python > try: > echo = Popen(command, stdout=PIPE).stdout.read() On a linux system (and perhaps Windows as well), the type of 'command' seems to be important and changes the behavior of Popen -- whether it be string or sequence. If you pass a 'command' as a string that includes arguments (ex. 'ls -l'), the above will raise an exception. I'm not sure if the same applies to Windows. You could try passing command as a list or tuple (ex command.split(), ['ls', '-l'], or similar), or add 'shell=True' to the Popen call. > Client: > #!/usr/bin/env python > send = raw_input('Send: ') > sock.send(send) > sock.recv(2048) Try 'print sock.recv(2048)'. > sock.close() HTH, Marty From rikard.bosnjakovic at gmail.com Thu May 17 09:57:48 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Thu, 17 May 2007 09:57:48 +0200 Subject: [Tutor] words and lengths In-Reply-To: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> References: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> Message-ID: On 5/16/07, Emad Nawfal wrote: > What's wrong with it, and how can I fix it? Alas, we are not mind readers. Instead of letting others guess, it's usually a better idea to write any syntax errors - or whatever - Python complains, or what the result you expect it to be, and what result it actually turns out to. Then we can help you fix it. This particular five lines code was no problem, but for code longer than that it's usually a pain in the backside having to guess everything and still end up with a poster who's not satisfied with the result based on plain guessing and no fact. -- - Rikard - http://bos.hack.org/cv/ From rikard.bosnjakovic at gmail.com Thu May 17 10:00:57 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Thu, 17 May 2007 10:00:57 +0200 Subject: [Tutor] File access by os.system In-Reply-To: <464A9664.9090205@gmail.com> References: <905ffcb00705150007x3428084p1664b1c9c36c1a5b@mail.gmail.com> <57B026980605A64F9B23484C5659E32E7D4909@poccso.US.ad.atmel.com> <464A9664.9090205@gmail.com> Message-ID: On 5/16/07, Luke Paireepinart wrote: > Not Quite, I think. I'm sorry, I missed the fact about using the tempfile. I parsed Mike's post being a sole question about sending a var-args string to os.command(). -- - Rikard - http://bos.hack.org/cv/ From agilfoy at frontiernet.net Thu May 17 23:03:18 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Thu, 17 May 2007 21:03:18 +0000 Subject: [Tutor] I want some help with arrays... Message-ID: <20070517210318.ncayqbjlgflcsw0w@webmail.frontiernet.net> What is the best (only?) way to set up an array in Python. I've heard they can be quite good for certain types of data you need to organize... What IS the best reason(s) to be using an array? Apologies, if Python has something similar by a different name. From agilfoy at frontiernet.net Thu May 17 23:51:07 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Thu, 17 May 2007 21:51:07 +0000 Subject: [Tutor] I want some help with arrays... In-Reply-To: <4618763.1179436844245.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> References: <4618763.1179436844245.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> Message-ID: <20070517215107.8oxu2fqs7v7cww4c@webmail.frontiernet.net> Ah, a simple concept. Good. :) I'm already familiar in working with lists. Here's a case of a simple two-dimensional array (the simplest possible), ran in the IDLE interpreter: >>> array = [["1.1", "1.2"], ["2.1", "2.2"]] >>> array[1[2]] Traceback (most recent call last): File "", line 1, in array[1[2]] TypeError: 'int' object is unsubscriptable >>> array[1] ['2.1', '2.2'] >>> second_half = array[1] >>> second_half[1] '2.2' When I nest the slices ( array[1[2]] ) I get that error message. When I define one variable as an index value of the array, and then index-value that, it works fine. What's the deal? From kent37 at tds.net Fri May 18 00:01:42 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 May 2007 18:01:42 -0400 Subject: [Tutor] I want some help with arrays... In-Reply-To: <20070517215107.8oxu2fqs7v7cww4c@webmail.frontiernet.net> References: <4618763.1179436844245.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> <20070517215107.8oxu2fqs7v7cww4c@webmail.frontiernet.net> Message-ID: <464CD0C6.4050108@tds.net> Alan Gilfoy wrote: > Ah, a simple concept. Good. :) > I'm already familiar in working with lists. > > Here's a case of a simple two-dimensional array (the simplest > possible), ran in the IDLE interpreter: > >>>> array = [["1.1", "1.2"], ["2.1", "2.2"]] >>>> array[1[2]] > > Traceback (most recent call last): > File "", line 1, in > array[1[2]] > TypeError: 'int' object is unsubscriptable >>>> array[1] > ['2.1', '2.2'] >>>> second_half = array[1] >>>> second_half[1] > '2.2' > > When I nest the slices ( array[1[2]] ) I get that error message. When > I define one variable as an index value of the array, and then > index-value that, it works fine. Use array[1][2] - the second element of the first element. Kent From alan.gauld at btinternet.com Fri May 18 00:48:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 May 2007 23:48:01 +0100 Subject: [Tutor] I want some help with arrays... References: <4618763.1179436844245.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> <20070517215107.8oxu2fqs7v7cww4c@webmail.frontiernet.net> Message-ID: "Alan Gilfoy" wrote >>>> array = [["1.1", "1.2"], ["2.1", "2.2"]] >>>> array[1[2]] This is trying to get the second element of 1. But one doesn't have a second element, hence the error. Just add an extra bracket: array[1][2] But that won;t work either because the index starts at 0 so it needs to be: array[0][1] > When I nest the slices ( array[1[2]] ) I get that error message. Note that this is not slicing. Slicing is extracting a subsection of an array (or list) using the end points as indices Thus: lst = [1,3,5,7,9] slice = lst[2:4] will put the 3rd and 4th elements into slice(zero indexing) Thats quite different to indexing to select a single value. Finally, you can use layout when defining your multi dimensional data to make it more obvious: table = [ [1,2,3], [4,5,6], [7,8,9] ] print table[1][1] #---> 5 You will get some more on data types including arrays and other classic data structures in my tutorial under the Raw Materials topic. Look for the Collections heading about 40% through and it extends to the Files heading about 80% through... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jjcrump at myuw.net Fri May 18 00:06:11 2007 From: jjcrump at myuw.net (Jon Crump) Date: Thu, 17 May 2007 15:06:11 -0700 (PDT) Subject: [Tutor] urllib.urlencode and unicode strings Message-ID: Dear all, I've got a python list of data pulled via ElementTree from an xml file that contains mixed str and unicode strings, like this: [u'Jumi\xe9ge, Normandie', 'Farringdon, Hampshire', 'Ravensworth, Durham', 'La Suse, Anjou', 'Lions, Normandie', 'Lincoln, Lincolnshire', 'Chelmsford, Essex', u'Ch\xe2telerault, Poitou', 'Bellencombre, Normandie'] etc. trying to use geopy to geocode these placenames I get the following traceback: Traceback (most recent call last): File "", line 2, in File "build/bdist.macosx-10.3-fat/egg/geopy/geocoders.py", line 327, in geocode File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", line 1242, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 2: ordinal not in range(128) It appears that urlencode is choking on the unicode literals. Can anybody tell me how I can translate these strings into something like this: Ch%C3%A2tellerault. No doubt this is obvious, but for a hopeless tyro like me, it is proving to be un-intuitive. Thanks From kent37 at tds.net Fri May 18 01:29:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 May 2007 19:29:54 -0400 Subject: [Tutor] urllib.urlencode and unicode strings In-Reply-To: References: Message-ID: <464CE572.8000602@tds.net> Jon Crump wrote: > Dear all, > > I've got a python list of data pulled via ElementTree from an xml file > that contains mixed str and unicode > strings, like this: > > [u'Jumi\xe9ge, Normandie', 'Farringdon, Hampshire', 'Ravensworth, > Durham', 'La Suse, Anjou', 'Lions, Normandie', 'Lincoln, Lincolnshire', > 'Chelmsford, Essex', u'Ch\xe2telerault, Poitou', 'Bellencombre, > Normandie'] etc. > > trying to use geopy to geocode these placenames I get the following > traceback: > > Traceback (most recent call last): > File "", line 2, in > File "build/bdist.macosx-10.3-fat/egg/geopy/geocoders.py", line 327, in > geocode > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.py", > line 1242, in urlencode > v = quote_plus(str(v)) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in > position 2: ordinal not in range(128) > > It appears that urlencode is choking on the unicode literals. Can anybody > tell me how I can translate these strings into something like this: > Ch%C3%A2tellerault. It's two steps. First convert to utf-8, then urlencode: >>> c = u'\xe2' >>> c u'\xe2' >>> c.encode('utf-8') '\xc3\xa2' >>> import urllib >>> urllib.quote(c.encode('utf-8')) '%C3%A2' Kent From jamesmatt18 at gmail.com Fri May 18 03:28:47 2007 From: jamesmatt18 at gmail.com (James Matthews) Date: Thu, 17 May 2007 21:28:47 -0400 Subject: [Tutor] words and lengths In-Reply-To: References: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> Message-ID: <0B7F01358D1742D4A04C686BCEC315C1@MomsComputer> Please include some code? http://www.goldwatches.com/watches.asp?Brand=39 ----- Original Message ----- From: "Rikard Bosnjakovic" To: "Emad Nawfal" Cc: Sent: Thursday, May 17, 2007 3:57 AM Subject: Re: [Tutor] words and lengths > On 5/16/07, Emad Nawfal wrote: > >> What's wrong with it, and how can I fix it? > > Alas, we are not mind readers. Instead of letting others guess, it's > usually a better idea to write any syntax errors - or whatever - > Python complains, or what the result you expect it to be, and what > result it actually turns out to. > > Then we can help you fix it. > > This particular five lines code was no problem, but for code longer > than that it's usually a pain in the backside having to guess > everything and still end up with a poster who's not satisfied with the > result based on plain guessing and no fact. > > > -- > - Rikard - http://bos.hack.org/cv/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From agilfoy at frontiernet.net Fri May 18 03:39:17 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Fri, 18 May 2007 01:39:17 +0000 Subject: [Tutor] I want some help with arrays... In-Reply-To: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> Message-ID: <20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> Why Python starts counting at [0] instead of at [1] is a whole other issue. :D array = [["0.0", "0.1"], ["1.0", "1.1"]] array[0[1]] seems right, although it isn't, because the index (0) and the subindex(1) are nested in 'array[0[1]]' much like the list and sublist that I'm "calling" from with the indexes. array[0][1] works instead? Gotcha. From rabidpoobear at gmail.com Fri May 18 03:46:10 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 17 May 2007 20:46:10 -0500 Subject: [Tutor] I want some help with arrays... In-Reply-To: <20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> <20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> Message-ID: <464D0562.90604@gmail.com> Alan Gilfoy wrote: > Why Python starts counting at [0] instead of at [1] is a whole other issue. :D > > array = [["0.0", "0.1"], ["1.0", "1.1"]] > > array[0[1]] seems right, although it isn't, because the index (0) and > the subindex(1) are nested in 'array[0[1]]' much like the list and > sublist that I'm "calling" from with the indexes. > > array[0][1] works instead? Gotcha. > Think of this command as being interpreted from left to right. command: array[0[1]] array[ ... now what do we index? 0[1] -> this doesn't work, it raises an error. Whereas this: command: array[0][1] array[ ... what do we index? 0 ] -> we index the first item. so now we have this: command: ["0.0","0.1"][1] ["0.0","0.1"] [ ... what do we index? 1 ] -> we index the 2nd item. so now we have this: "0.1" there are no more commands, so we stop here. Hope that made sense, -Luke From adler at stephenadler.com Fri May 18 04:26:24 2007 From: adler at stephenadler.com (Stephen Adler) Date: Thu, 17 May 2007 22:26:24 -0400 Subject: [Tutor] help with arrays Message-ID: <464D0ED0.7090406@stephenadler.com> Guys, I'm quite new to python and come from a c++/old school math/computing/physics background. My main road block I have right now is that I can't for the life of me figure out how to allocate a 1meg buffer. (or any arbitrary sized buffer) without using something like the range function. It would be nice to do something like a=string(100000) or something like that which would create a string 1000000 characters long. And then use that as input into the array module so that I can build up an array. What's the standard convention to do this? Also, how about pointers? I'm using a c++ wrapped in python package called vtk and there are some function or class "attributes" which return pointers. How do I create a pointer reference? Thanks. Steve. From jamesmatt18 at gmail.com Fri May 18 05:40:48 2007 From: jamesmatt18 at gmail.com (James Matthews) Date: Thu, 17 May 2007 23:40:48 -0400 Subject: [Tutor] I want some help with arrays... In-Reply-To: <464D0562.90604@gmail.com> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net><20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> <464D0562.90604@gmail.com> Message-ID: Also computer start counting from 0 you can change this when you learn the language more but it isn't recommended! http://www.goldwatches.com/watches.asp?Brand=39 ----- Original Message ----- From: "Luke Paireepinart" To: "Alan Gilfoy" Cc: Sent: Thursday, May 17, 2007 9:46 PM Subject: Re: [Tutor] I want some help with arrays... > Alan Gilfoy wrote: >> Why Python starts counting at [0] instead of at [1] is a whole other >> issue. :D >> >> array = [["0.0", "0.1"], ["1.0", "1.1"]] >> >> array[0[1]] seems right, although it isn't, because the index (0) and >> the subindex(1) are nested in 'array[0[1]]' much like the list and >> sublist that I'm "calling" from with the indexes. >> >> array[0][1] works instead? Gotcha. >> > Think of this command as being interpreted from left to right. > command: array[0[1]] > > array[ ... now what do we index? > > 0[1] -> this doesn't work, it raises an error. > > Whereas this: > > command: array[0][1] > > array[ ... what do we index? > 0 ] -> we index the first item. > > so now we have this: > > command: ["0.0","0.1"][1] > > ["0.0","0.1"] [ ... what do we index? > > 1 ] -> we index the 2nd item. > > so now we have this: > > "0.1" > there are no more commands, so we stop here. > > Hope that made sense, > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rikard.bosnjakovic at gmail.com Fri May 18 06:05:40 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Fri, 18 May 2007 06:05:40 +0200 Subject: [Tutor] help with arrays In-Reply-To: <464D0ED0.7090406@stephenadler.com> References: <464D0ED0.7090406@stephenadler.com> Message-ID: On 5/18/07, Stephen Adler wrote: > or something like that which would create a string 1000000 characters > long. And then use that as input into the array module so that I can > build up an array. What's the standard convention to do this? a = " " * 1000000 > How do I create a pointer reference? You don't. 99% in Python is by pass-by-reference. You don't need to think in pointers like C-programmers do. Simply send a list to a function, and a reference (not a copy) to it will be sent. >>> l = [1,2,3] >>> def foo(bar): ... bar[2] = 42 ... >>> foo(l) >>> l [1, 2, 42] -- - Rikard - http://bos.hack.org/cv/ From bgailer at alum.rpi.edu Fri May 18 06:03:23 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 17 May 2007 21:03:23 -0700 Subject: [Tutor] I want some help with arrays... In-Reply-To: References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net><20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> <464D0562.90604@gmail.com> Message-ID: <464D258B.8080909@alum.rpi.edu> James Matthews wrote: > Also computer start counting from 0 No no. Computers don't count. Programs count. And they start whereever you program them to start. Recall that humans count from 1 because of some historic evolution. The introduction of zero into human arithmetic came many centuries after counting. And met with much initial resistance. The origin for array indexes is also varied in its evolution. FORTRAN arrays are indexed starting at 1. In some languages you can specify the range of indexes as in dimension a (1900:2030) if you want to use the year as an index and don't care about years outside the range 1900..2030. > you can change this when you learn the language more but it isn't recommended! > Oh? who disrecommends it? -- Bob Gailer 510-978-4454 From calitar at gmail.com Fri May 18 06:09:57 2007 From: calitar at gmail.com (calitar) Date: Thu, 17 May 2007 21:09:57 -0700 Subject: [Tutor] words and lengths In-Reply-To: <0B7F01358D1742D4A04C686BCEC315C1@MomsComputer> References: <652641e90705160840t73c91ef5t4cd81229e312436a@mail.gmail.com> <0B7F01358D1742D4A04C686BCEC315C1@MomsComputer> Message-ID: <464D2715.5050602@gmail.com> James Matthews wrote: > Please include some code? > > http://www.goldwatches.com/watches.asp?Brand=39 Um...why does that link go to a page with expensive watches? Please no spamming on this mailing list. - Cole Armer From jamesmatt18 at gmail.com Fri May 18 06:12:22 2007 From: jamesmatt18 at gmail.com (James Matthews) Date: Fri, 18 May 2007 00:12:22 -0400 Subject: [Tutor] I want some help with arrays... In-Reply-To: <464D258B.8080909@alum.rpi.edu> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net><20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> <464D0562.90604@gmail.com> <464D258B.8080909@alum.rpi.edu> Message-ID: <73CEB8B8290042A587003E8AA23011AF@MomsComputer> When the CPU writes to the RAM the 0th location can be written to also. When you alter components of a language for example changing the way an list is indexed you have to be careful because you can accidently jump out of bounds! http://www.goldwatches.com/watches.asp?Brand=39 ----- Original Message ----- From: "Bob Gailer" To: "James Matthews" Cc: Sent: Friday, May 18, 2007 12:03 AM Subject: Re: [Tutor] I want some help with arrays... > James Matthews wrote: >> Also computer start counting from 0 > No no. Computers don't count. Programs count. And they start whereever you > program them to start. > Recall that humans count from 1 because of some historic evolution. The > introduction of zero into human arithmetic came many centuries after > counting. And met with much initial resistance. > The origin for array indexes is also varied in its evolution. FORTRAN > arrays are indexed starting at 1. In some languages you can specify the > range of indexes as in dimension a (1900:2030) if you want to use the > year as an index and don't care about years outside the range 1900..2030. >> you can change this when you learn the language more but it isn't >> recommended! >> > Oh? who disrecommends it? > > -- > Bob Gailer > 510-978-4454 > From rabidpoobear at gmail.com Fri May 18 07:03:51 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 18 May 2007 00:03:51 -0500 Subject: [Tutor] I want some help with arrays... In-Reply-To: <73CEB8B8290042A587003E8AA23011AF@MomsComputer> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net><20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> <464D0562.90604@gmail.com> <464D258B.8080909@alum.rpi.edu> <73CEB8B8290042A587003E8AA23011AF@MomsComputer> Message-ID: <464D33B7.6060303@gmail.com> James Matthews wrote: > When the CPU writes to the RAM the 0th location can be written to also. When > you alter components of a language for example changing the way an list is > indexed you have to be careful because you can accidently jump out of > bounds! def indexOneBased(somelist,index): return somelist[index-1] now you can do indexOneBased([1,2,3,4,5], 5) and you will get 5. Obviously the verbosity of this example seems to imply its uselessness, but what Bob was getting at is that there are situations where you can create a list that you index into based upon some arbitrary starting point. For example, say you had a calendar program that kept track of my schedule for days 1 through 31 of this month. You'd store the schedule of each day in a list starting with the 0th element and ending at the 30th element. Then, whenever I asked you for the 1st element, for example, you'd retrieve the 0th element for me, and so on. The indexing itself isn't changed, merely the interface to it. Note that you don't actually index the list starting at the 1th element (the 2nd one) you index it starting at the 0th element, but use indexes that begin at 1. HTH, -Luke From rabidpoobear at gmail.com Fri May 18 07:05:48 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 18 May 2007 00:05:48 -0500 Subject: [Tutor] I want some help with arrays... In-Reply-To: <73CEB8B8290042A587003E8AA23011AF@MomsComputer> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net><20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> <464D0562.90604@gmail.com> <464D258B.8080909@alum.rpi.edu> <73CEB8B8290042A587003E8AA23011AF@MomsComputer> Message-ID: <464D342C.3070704@gmail.com> James Matthews wrote: > http://www.goldwatches.com/watches.asp?Brand=39 Also, please stop spamming us with this link. You have a gmail account, so there's no reason for us to believe that you are required to put it there by a company you work for or otherwise. It's annoying. -Luke From alan.gauld at btinternet.com Fri May 18 09:52:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 May 2007 08:52:27 +0100 Subject: [Tutor] help with arrays References: <464D0ED0.7090406@stephenadler.com> Message-ID: "Stephen Adler" wrote > I'm quite new to python and come from a c++/old school > math/computing/physics background. Thats OK, many of us came from there too. Its not permanently damaging! :-) > is that I can't for the life of me figure out how to allocate a 1meg > buffer. (or any arbitrary sized buffer) without using something like > the > range function. First I have to ask why you need to? Thats an fairly unusual requirement in Python where storage is nearly always dynamically allocated. > It would be nice to do something like > > a=string(100000) > > or something like that which would create a string 1000000 > characters > long. And then use that as input into the array module so that I can > build up an array. What's the standard convention to do this? And again why do you need to use an array, thats also fairly uncommon. Can you not just allocate a dynamically created string to a normal Python list? Thee are valid cases in Python where you do need to preallocate a block of storage and where the array module is the best choice but before going there lets be sure we need to! > Also, how about pointers? Most things in Python are effectively pointers in that all variables in Python are effectively references in C++ terms. There are no static variables. Everything is passed by reference. > I'm using a c++ wrapped in python package > called vtk and there are some function or class "attributes" which > return pointers. How do I create a pointer reference? Its just a name in Python myName = returnMyPointer() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tms43 at clearwire.net Fri May 18 18:06:08 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Fri, 18 May 2007 09:06:08 -0700 Subject: [Tutor] (no subject) Message-ID: <000401c79966$798bafa0$6ca30ee0$@net> Hi all: Remember when I was having problems moving my .gif around my Tkinter maze? Well, I was going about it all wrong (as some pointed out). What REALLY works is a graph. I used a dictionary, the keys are main coordinates that are a path that the .gif follows using a greedy algorithm that finds all the paths to a determined location. The definition of the keys are all the possible directions the .gif can go. Not all paths are covered on purpose. In any case, here is the updated code, for those who asked me to post it. I'm hoping to have it completed next week, without the gif of my dog (lol) and a bad guy or two to follow the gif that will be used in the maze. The next thing I have to do is bind an event to the arrow keys that will update the current x and y position.. I haven't quite worked that out yet. Right now the gif moves through the maze based on the path. Now the event (an keyboard arrow) should tell it to go to that direction at the next turn. The function that defines the move is called move_gif(). I could use some ideas because I keep getting stuck on the details. How does the event effect the current course through the maze? Does it somehow update the current call to find_all_paths? Or some sort of Helper function that interrupts the current path at a vertex giving it a new path? That one seems most likely, but I'm still stuck on how to stop at the vertex and move to the new location. Any help would be appreciated. TYIA T -------------- next part -------------- A non-text attachment was scrubbed... Name: DustY.gif Type: image/gif Size: 6733 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070518/fe3d66f6/attachment.gif -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: mazeRev.pyw Url: http://mail.python.org/pipermail/tutor/attachments/20070518/fe3d66f6/attachment.pot From rhenderson1965 at yahoo.com Fri May 18 20:57:21 2007 From: rhenderson1965 at yahoo.com (Richard Henderson) Date: Fri, 18 May 2007 11:57:21 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <55949.90647.qm@web54307.mail.re2.yahoo.com> Hello, I am a rank beginner, as I'm sure my question will show. After I enter and save a script using Notepad, it is not recognized by DOS and will not run. What might I be doing wrong. I am using PythonWin and Windows XP. Thanks, Richard ____________________________________________________________________________________ Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. http://autos.yahoo.com/green_center/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070518/9d849311/attachment.htm From nuin at genedrift.org Fri May 18 21:10:45 2007 From: nuin at genedrift.org (Paulo Nuin) Date: Fri, 18 May 2007 15:10:45 -0400 Subject: [Tutor] (no subject) In-Reply-To: <55949.90647.qm@web54307.mail.re2.yahoo.com> References: <55949.90647.qm@web54307.mail.re2.yahoo.com> Message-ID: <464DFA35.5090401@genedrift.org> Hi Richard Have you try running it with Python in front of the script name? Such as: python my_script.py Usually on Windows command prompt, if Python is not on your path you have to enter the whole path to it, something like C:\Python25\python. HTH Paulo Richard Henderson wrote: > Hello, > I am a rank beginner, as I'm sure my question will show. After I enter > and save a script using Notepad, it is not recognized by DOS and will > not run. What might I be doing wrong. I am using PythonWin and > Windows XP. > Thanks, > Richard > > ------------------------------------------------------------------------ > Moody friends. Drama queens. Your life? Nope! - their life, your story. > Play Sims Stories at Yahoo! Games. > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mail at timgolden.me.uk Fri May 18 21:11:20 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 18 May 2007 20:11:20 +0100 Subject: [Tutor] (no subject) In-Reply-To: <55949.90647.qm@web54307.mail.re2.yahoo.com> References: <55949.90647.qm@web54307.mail.re2.yahoo.com> Message-ID: <464DFA58.4040301@timgolden.me.uk> Richard Henderson wrote: > Hello, > I am a rank beginner, as I'm sure my question will show. After I enter > and save a script using Notepad, it is not recognized by DOS and will > not run. What might I be doing wrong. I am using PythonWin and Windows XP. Often the case that Notepad will (silently) add a ".txt" to whatever filename you offer, unless you quote the whole thing. This confusion can be compounded if you have set the (default) setting: Hide extensions for known file types. TJG From jjcrump at myuw.net Fri May 18 21:13:43 2007 From: jjcrump at myuw.net (Jon Crump) Date: Fri, 18 May 2007 12:13:43 -0700 (PDT) Subject: [Tutor] urllib.urlencode and unicode strings In-Reply-To: <464CE572.8000602@tds.net> References: <464CE572.8000602@tds.net> Message-ID: Kent, Thanks so much. It's easy when you know how. Now that I know, I only need the encode('utf-8') step since geopy does the urlencode step. On Thu, 17 May 2007, Kent Johnson wrote: > It's two steps. First convert to utf-8, then urlencode: >>>> c = u'\xe2' >>>> c > u'\xe2' >>>> c.encode('utf-8') > '\xc3\xa2' >>>> import urllib >>>> urllib.quote(c.encode('utf-8')) > '%C3%A2' > > Kent From rabidpoobear at gmail.com Fri May 18 21:36:33 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 18 May 2007 14:36:33 -0500 Subject: [Tutor] (no subject) In-Reply-To: <55949.90647.qm@web54307.mail.re2.yahoo.com> References: <55949.90647.qm@web54307.mail.re2.yahoo.com> Message-ID: <464E0041.70209@gmail.com> Richard Henderson wrote: > Hello, > I am a rank beginner, as I'm sure my question will show. After I enter > and save a script using Notepad, it is not recognized by DOS and will > not run. What might I be doing wrong. I am using PythonWin and > Windows XP. > Thanks, > Richard Please never again write a message to this mailing list without a subject. For those of us who have threads turned on, it becomes quite cumbersome. (for me, you essentially revived a thread from 7/6/2005 because my thunderbird can't tell that this message isn't part of the thread because it has the same subject line.) Thanks, -Luke From rikard.bosnjakovic at gmail.com Fri May 18 23:26:35 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Fri, 18 May 2007 23:26:35 +0200 Subject: [Tutor] (no subject) In-Reply-To: <000401c79966$798bafa0$6ca30ee0$@net> References: <000401c79966$798bafa0$6ca30ee0$@net> Message-ID: On 5/18/07, Teresa Stanton wrote: > Remember when I was having problems moving my .gif around my Tkinter maze? No, but we will all hereby remember you forever for posting a new thread without a proper subject on this list. Perhaps at the same time as our eyes will start peering. -- - Rikard - http://bos.hack.org/cv/ From matt at mattanddawn.orangehome.co.uk Fri May 18 23:37:07 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Fri, 18 May 2007 22:37:07 +0100 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please Message-ID: <1179524228.12384.16.camel@computer> Hi, I am trying to write a simple program to display Conway's Game Of Life. I have the bones of the program together but I'm struggling with the function that tests for and applies the rules of the game (the important bit). I have the current state of the game stored in a 2d matrix with each cell represented by a 1 or 0 (alive or dead) i.e: [[0, 1, 0], [1, 0, 0], [0, 0, 0]]. I'm using a 15 * 15 matrix for testing purposes. I have come up with the following function to update the matrix so far: def update_matrix(matrix): matrix_updated = [matrix] # Perform check for each value in the matrix for x in range(len(matrix[0])): for y in range(len(matrix)): neighbour_count = 0 if matrix[x-1][y+1]: neighbour_count = neighbour_count + 1 if matrix[x][y+1]: neighbour_count = neighbour_count + 1 if matrix[x+1][y+1]: neighbour_count = neighbour_count + 1 if matrix[x+1][y]: neighbour_count = neighbour_count + 1 if matrix[x+1][y-1]: neighbour_count = neighbour_count + 1 if matrix[x][y-1]: neighbour_count = neighbour_count + 1 if matrix[x-1][y-1]: neighbour_count = neighbour_count + 1 if matrix[x-1][y]: neighbour_count = neighbour_count + 1 # Apply game of life rules to each item in the matrix if 2 < neighbour_count > 3: matrix_updated[x][y] = 0 elif neighbour_count == 3: matrix_updated[x][y] = 1 # No need to change values if neighbour count == 2 return matrix_updated I have two problems with this code: Firstly, when testing cells on the edges of the matrix, I get an IndexError because I am testing an item in the list that does not exist. I want the program to assume that cells outside the bounds of the board are automatically dead. I am not sure how to suppress or avoid this error so that neighbour_count is not incremented for indexes outside the matrix. My second problem is that this function seems to be very clunky to me (even if it did work...). I cannot think of a way of checking each of the 8 cells surrounding the one being tested without doing it this way. Is there a better way of doing this? Thanks in advance, Matt. From rikard.bosnjakovic at gmail.com Fri May 18 23:49:52 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Fri, 18 May 2007 23:49:52 +0200 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: <1179524228.12384.16.camel@computer> References: <1179524228.12384.16.camel@computer> Message-ID: On 5/18/07, Matt Smith wrote: > I am not sure > how to suppress or avoid this error so that neighbour_count is not > incremented for indexes outside the matrix. Something like this: try: the_index_outside_matrix_test() except IndexError: suppress_the_error() > Is there a better way of doing this? Perhaps something like this: for n in (x, x+1, x-1): for m in (y, y+1, y-1): if matrix[n, m]: neighbour_count = neighbour_count + 1 -- - Rikard - http://bos.hack.org/cv/ From matt at mattanddawn.orangehome.co.uk Fri May 18 23:57:28 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Fri, 18 May 2007 22:57:28 +0100 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: References: <1179524228.12384.16.camel@computer> Message-ID: <1179525448.12384.23.camel@computer> On Fri, 2007-05-18 at 23:49 +0200, Rikard Bosnjakovic wrote: > Something like this: > > try: > the_index_outside_matrix_test() > except IndexError: > suppress_the_error() Thanks Rikard, I'm not sure how I would go about actually suppressing the error - what would suppress_the_error() actually call? Cheers, Matt From matt at mattanddawn.orangehome.co.uk Sat May 19 00:02:34 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Fri, 18 May 2007 23:02:34 +0100 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: References: <1179524228.12384.16.camel@computer> Message-ID: <1179525754.12384.28.camel@computer> > > Is there a better way of doing this? > > Perhaps something like this: > > for n in (x, x+1, x-1): > for m in (y, y+1, y-1): > if matrix[n, m]: > neighbour_count = neighbour_count + 1 > I need to not text matrix[x][y] is there a simple way to exclude this from the possible combinations of values from the two tuples? From rabidpoobear at gmail.com Sat May 19 00:03:16 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 18 May 2007 17:03:16 -0500 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: <1179525448.12384.23.camel@computer> References: <1179524228.12384.16.camel@computer> <1179525448.12384.23.camel@computer> Message-ID: <464E22A4.2090601@gmail.com> Matt Smith wrote: > On Fri, 2007-05-18 at 23:49 +0200, Rikard Bosnjakovic wrote: > >> Something like this: >> >> try: >> the_index_outside_matrix_test() >> except IndexError: >> suppress_the_error() >> > > Thanks Rikard, > > I'm not sure how I would go about actually suppressing the error - what > would suppress_the_error() actually call? > In this case, you don't need to do anything to the error. You're expecting an IndexError, and if one occurs, you're assuming that that neighbor doesn't count. So just put the code Rikard sent you in the try block and in the except block, put 'pass' (i.e. "Do Nothing"). Another note: I think (x-1, x, x+1) is more clear than (x, x+1, x-1), and also: note that Rikard's code will always check x,y which will always be 1 (assuming you don't do checks on whether they should stay alive for already dead squares!) You can add an if statement to remove this case, or, easier (and probably more efficient) just subtract 1 from your result. HTH, -Luke From rabidpoobear at gmail.com Sat May 19 00:03:43 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 18 May 2007 17:03:43 -0500 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: <1179525754.12384.28.camel@computer> References: <1179524228.12384.16.camel@computer> <1179525754.12384.28.camel@computer> Message-ID: <464E22BF.8090203@gmail.com> Matt Smith wrote: >>> Is there a better way of doing this? >>> >> Perhaps something like this: >> >> for n in (x, x+1, x-1): >> for m in (y, y+1, y-1): >> if matrix[n, m]: >> neighbour_count = neighbour_count + 1 >> >> > > I need to not text matrix[x][y] is there a simple way to exclude this from the possible combinations of values from the two tuples? see my other reply, Matt. -Luke From Mike.Hansen at atmel.com Fri May 18 23:58:39 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 18 May 2007 15:58:39 -0600 Subject: [Tutor] GRUMPY? In-Reply-To: References: <000401c79966$798bafa0$6ca30ee0$@net> Message-ID: <57B026980605A64F9B23484C5659E32E7D4D1A@poccso.US.ad.atmel.com> > No, but we will all hereby remember you forever for posting a new > thread without a proper subject on this list. Perhaps at the same time > as our eyes will start peering. > I would imagine that the original poster didn't have any remnants of the previous thread. Yes, the poster should have put a subject. On the other hand, we need to be nicer too. More like... "Glad you figured it out. Hey, could you do us a favor next time and put a subject on your message?" Mike From kent37 at tds.net Sat May 19 00:13:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 May 2007 18:13:53 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <000401c79966$798bafa0$6ca30ee0$@net> Message-ID: <464E2521.3020500@tds.net> Rikard Bosnjakovic wrote: > On 5/18/07, Teresa Stanton wrote: > >> Remember when I was having problems moving my .gif around my Tkinter maze? > > No, but we will all hereby remember you forever for posting a new > thread without a proper subject on this list. Perhaps at the same time > as our eyes will start peering. Let's remember that this is a list for beginners, with a well-earned reputation for friendliness. Please be gentle and forgiving of mistakes so beginners feel welcome as they learn. Thanks, Kent From jkrishna at uhnresearch.ca Fri May 18 22:17:48 2007 From: jkrishna at uhnresearch.ca (Janani Krishnaswamy) Date: Fri, 18 May 2007 16:17:48 -0400 Subject: [Tutor] question re: executing exe files with arguments Message-ID: <1179519468.11328.8.camel@carrow23.uhnres.utoronto.ca> Hi! I am having trouble executing an exe file with 3 arguments within a python script. Right now I have something like this: os.system(r'"1/2/3/program 1/2/3/argument1 1/2/3/argument2"') I was trying it with a raw string because of the /'s within it. I'm not sure of any other approaches. Any advice would be greatly appreciated! Thanks! Janani From rabidpoobear at gmail.com Sat May 19 00:21:47 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 18 May 2007 17:21:47 -0500 Subject: [Tutor] question re: executing exe files with arguments In-Reply-To: <1179519468.11328.8.camel@carrow23.uhnres.utoronto.ca> References: <1179519468.11328.8.camel@carrow23.uhnres.utoronto.ca> Message-ID: <464E26FB.9000105@gmail.com> Janani Krishnaswamy wrote: > Hi! > I am having trouble executing an exe file with 3 arguments within a > python script. Right now I have something like this: > > os.system(r'"1/2/3/program 1/2/3/argument1 1/2/3/argument2"') > > I was trying it with a raw string because of the /'s within it. I'm not > sure of any other approaches. > '\' is the only reason you'd need to use a raw string, not '/'. This is because backslash is used for special character sequences. For example, a new line is '\n'. Other than that, what is the problem you're having, exactly? HTH, -Luke From tktucker at gmail.com Sat May 19 00:27:13 2007 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 18 May 2007 18:27:13 -0400 Subject: [Tutor] (no subject) In-Reply-To: <000401c79966$798bafa0$6ca30ee0$@net> References: <000401c79966$798bafa0$6ca30ee0$@net> Message-ID: <2a278ffe0705181527k3db5fc6cw4fe43caf6f72e755@mail.gmail.com> Very cool! Where is Inky, Blinky, Pinky, and Clyde? ;-) Maybe dog catchers would be better foes for Dusty. On 5/18/07, Teresa Stanton wrote: > > Hi all: > > Remember when I was having problems moving my .gif around my Tkinter maze? > Well, I was going about it all wrong (as some pointed out). What REALLY > works is a graph. I used a dictionary, the keys are main coordinates that > are a path that the .gif follows using a greedy algorithm that finds all > the > paths to a determined location. The definition of the keys are all the > possible directions the .gif can go. Not all paths are covered on > purpose. > In any case, here is the updated code, for those who asked me to post it. > I'm hoping to have it completed next week, without the gif of my dog (lol) > and a bad guy or two to follow the gif that will be used in the maze. > > The next thing I have to do is bind an event to the arrow keys that will > update the current x and y position.. I haven't quite worked that out yet. > Right now the gif moves through the maze based on the path. Now the event > (an keyboard arrow) should tell it to go to that direction at the next > turn. > The function that defines the move is called move_gif(). I could use some > ideas because I keep getting stuck on the details. How does the event > effect > the current course through the maze? Does it somehow update the current > call > to find_all_paths? > Or some sort of Helper function that interrupts the current path at a > vertex > giving it a new path? That one seems most likely, but I'm still stuck on > how to stop at the vertex and move to the new location. Any help would be > appreciated. > > TYIA > > T > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070518/f846175c/attachment.htm From tms43 at clearwire.net Sat May 19 00:53:40 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Fri, 18 May 2007 15:53:40 -0700 Subject: [Tutor] subject changed to Tkinter arrow event In-Reply-To: <2a278ffe0705181527k3db5fc6cw4fe43caf6f72e755@mail.gmail.com> References: <000401c79966$798bafa0$6ca30ee0$@net> <2a278ffe0705181527k3db5fc6cw4fe43caf6f72e755@mail.gmail.com> Message-ID: <000b01c7999f$62c05490$2840fdb0$@net> Thanks. Eventually, one will be able to take a picture of oneself and that will be the gif that chases around the maze. I'm trying to avoid any 'copy write' infringement. I have a little alien that I am trying to incorporate into the maze that will try to find the gif. But as it stands, it's not very interactive which is why I'm hoping someone has the ability to guide me in the direction I need to finish the interactive part with the keyboard event. I am sorry for not putting a subject line the first time. I suppose I was a little hasty when sending the first post. T From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Tom Tucker Sent: Friday, May 18, 2007 3:27 PM To: tutor at python.org Subject: Re: [Tutor] (no subject) Very cool! Where is Inky, Blinky, Pinky, and Clyde? ;-) Maybe dog catchers would be better foes for Dusty. On 5/18/07, Teresa Stanton wrote: Hi all: Remember when I was having problems moving my .gif around my Tkinter maze? Well, I was going about it all wrong (as some pointed out). What REALLY works is a graph. I used a dictionary, the keys are main coordinates that are a path that the .gif follows using a greedy algorithm that finds all the paths to a determined location. The definition of the keys are all the possible directions the .gif can go. Not all paths are covered on purpose. In any case, here is the updated code, for those who asked me to post it. I'm hoping to have it completed next week, without the gif of my dog (lol) and a bad guy or two to follow the gif that will be used in the maze. The next thing I have to do is bind an event to the arrow keys that will update the current x and y position.. I haven't quite worked that out yet. Right now the gif moves through the maze based on the path. Now the event (an keyboard arrow) should tell it to go to that direction at the next turn. The function that defines the move is called move_gif(). I could use some ideas because I keep getting stuck on the details. How does the event effect the current course through the maze? Does it somehow update the current call to find_all_paths? Or some sort of Helper function that interrupts the current path at a vertex giving it a new path? That one seems most likely, but I'm still stuck on how to stop at the vertex and move to the new location. Any help would be appreciated. TYIA T _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070518/5e16a319/attachment.html From alan.gauld at btinternet.com Sat May 19 01:44:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 00:44:08 +0100 Subject: [Tutor] Help with excetion handing and making my codemore efficient needed please References: <1179524228.12384.16.camel@computer> <1179525754.12384.28.camel@computer> Message-ID: "Matt Smith" wrote in message news:1179525754.12384.28.camel at computer... >> > Is there a better way of doing this? >> >> Perhaps something like this: >> >> for n in (x, x+1, x-1): >> for m in (y, y+1, y-1): >> if matrix[n, m]: >> neighbour_count = neighbour_count + 1 >> > > I need to not text matrix[x][y] is there a simple way to > exclude this from the possible combinations of values > from the two tuples? As Luke said you don;t need to exclude it because you know that it is always True so you can adjust the final count to take that into consideration. The cost of testing one extra cell is much less than testing for an exception for each of the other 8! The lesson? Sometimes algorithms can be adjusted slightly to make life a lot simpler. Alan G. From alan.gauld at btinternet.com Sat May 19 01:49:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 00:49:51 +0100 Subject: [Tutor] (no subject) References: <55949.90647.qm@web54307.mail.re2.yahoo.com> <464E0041.70209@gmail.com> Message-ID: "Luke Paireepinart" wrote > Please never again write a message to this mailing list without a > subject. > For those of us who have threads turned on, it becomes quite > cumbersome. FWIW I have the same problem reading via gmane. It was telling me there were unread messages but I couldn't see them till I scrolled waaaaayyyyy back in the history to find the old thread. Its not a killer but it is inconvenient in a threaded reader. Alan G. From finalyugi at sapo.pt Sat May 19 02:47:51 2007 From: finalyugi at sapo.pt (Rolando Pereira) Date: Sat, 19 May 2007 01:47:51 +0100 Subject: [Tutor] two input acceptions In-Reply-To: References: Message-ID: <464E4937.2090201@sapo.pt> adam urbas escreveu: > Thanks for the help. I've made quite some progress since I first posted this email. I have a question though, what did you mean when you were talking about the raw_input( )? How can the regular input( ) be used evilly? If you could explain in depth, I would be very grateful. I have a new question related to my program area.py., I guess it's the same one as before. When I run the program and input the rectangle option, it asks me for a radius, unless I input 1, instead of rectangle. How do I program it to accept both 1 and rectangle?> Date: Sat, 12 May 2007 18:55:20 +0100> From: finalyugi at sapo.pt> To: adamurbas at hotmail.com> CC: tutor at python.org> Subject: Re: [Tutor] (no subject)> > adam urbas escreveu:> > Hi,I just started python today and I would like a few pointers, if you don't mind. I tried using a tutorial, but was only able to get the correct results for the most basic problems. # Area calculation programprint ?Welcome to the Area calculation program?print ??? ????????????print# Print out the menu:print ?Please select a shape:?print ?1 Rectangle?print ?2 Circle?# Get the user?s choice:shape = input(?> ?)# Calculate the area:if shape == 1: height = input(?Please enter the height: ?) width = input(?Please enter the width: ?) area = height*width print ?The area is?, areaelse: radius = input(?Please enter the radius: ?) area = 3.14*(radius**2) print ?The area is?, areaI've been trying to get this to work. I was on a forum on Google and they said to put:input("press ENTER to continue")at the end. I did, but it didn't work. It runs the program but just shuts itself off when its done and i don't even get to select any of the option things that i'm s> upposed to be able to select. It just turns on then back off and I don't even get to see anything. Could someone help me out.ThanksAdam> > _________________________________________________________________> > Create the ultimate e-mail address book. Import your cont acts to Windows Live Hotmail.> > www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507> > > > > > ------------------------------------------------------------------------> > > > _______________________________________________> > Tutor maillist - Tutor at python.org> > http://mail.python.org/mailman/listinfo/tutor> > First, welcome to the world of Python. :D> Second. please give a title when you start a new thread on a mailing list.> Third, format your posts and code. Since Python uses indented code, it's > kinda hard to read it when it's all in one line (Don't worry, I'll paste > it indented in a file attached to this email :D )> > Now for the code.> > After arranging the code, the first thing I noticed were this characters ? ?> > I tried running the code, and if gave me a error there, so I just > replace then with " ", and voil?, the code worked :D . So the lesson > here is always use either " " or ' ' in the code.> > Oh, a lso another thing. Don't use input() to get the user input, because > that command can run code and it may be evilly used. Always use > raw_input() instead :D .> > Anyway, I hope I helped you,> > > -- > _> ASCII ribbon campaign ( )> - against HTML email X> & vCards / \ > _________________________________________________________________ > Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. > www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 First of all, what email client are you using? Because the text is getting all weird and difficult to read (it's all in one line, with no paragraphs and things like that). Now, the thing about input() and why it's not a good policy to use is that, unlike raw_input(), what type in a input() is executed by Python (in raw_input() is stored as a string). Example: var = raw_input() >> list("LOL") Now we have a variable called var which contains the string that says 'list("LOL")' You can confirm that by typing: print var >> 'list("LOL") There, no harm done. Now let's try the same thing using the input() command: var = input() >> list("LOL") Now let's type "print var" again as we did before. print var >> ['L', 'O'. 'L'] Now what happened? Because you used the input() command, what you type was interpreted by Python, instead of being stored in a string and since the list() command is used to create a list, Python did just that. He created a list. Now, in this example, no harm was done. But image someone typing the command os.system("command to delete some file or run some file"). That would send a delete command to the terminal, or install some file (it could even be a virus). Ok, it's a little harder to explain, but the thing you should is that usually raw_input() = GOOD, input() = BAD. Now, I couldn't quite understand the second problem. Please explain a little better. PS: Now I know why I see all posts messed up. It's because you're sending your emails as a HTML, and I deactivated that on my email client. I don't know if Hotmail (I believe you send you emails from there) as an option to turn off HTML. If it was please use it :D (Besides being nice, you can get more responses if you do that. Not everyone has an HTML capable email client.) PS2 (no, not the console): I just noticed you didn't send the email back to the mailing list. You should select reply to all (or a similar option) when replying to mailing list, so that other people can learn too. -- _ ASCII ribbon campaign ( ) - against HTML email X & vCards / \ From tktucker at gmail.com Sat May 19 02:58:21 2007 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 18 May 2007 20:58:21 -0400 Subject: [Tutor] Continue Matching after First Match Message-ID: <2a278ffe0705181758v29b8229ice736c5b5eade1c9@mail.gmail.com> Please forgive the colors, just trying to help illustrate my question. The below code snipet works as designed, however the regex matches once and exits. I want it to continue matching and printing until EOF. Any suggestions? Why the cStringIO stuff? The input data shown below is collected from os.popen. I was trying to find an easy way of matching my regex. Matching with a string seemed easier than looping through the ouput collected. Hmm. Come to think of it, I guess I could match on the first "^dn" catpure that output and then keep looping until "^cn:" is seen. Then repeat. Anyways, any suggestions to fix the below code? Thanks for the help, Code Snipet ########### multi_regex = re.compile(r'dn: uid=(\w+)..*cn: ((\w+ \w+)|(\w+ \w+\. \w+))..*(?=dn:)', re.MULTILINE| re.DOTALL) output = os.popen(command).readlines() voutput = cStringIO.StringIO() for line in output: voutput.write(line) contents = voutput.getvalue() #<-- contents is match = re.search(multi_regex, contents) if match: print match.group(1) print match.group(2) Blue = is what the regex matches Red = regex groups # match.group(#) Green = next regex groups not being captured INPUT Data ########### version: 1 dn: uid=jtucker,ou=people,dc=companyA,dc=com host: hostA host: hostB host: hostC description: other gecos: John Tucker gidNumber: 1 uidNumber: 1157 sn: Tucker cn: John Tucker uid: jtucker objectClass: top objectClass: account objectClass: person objectClass: posixAccount objectClass: shadowAccount objectClass: inetorgperson objectClass: organizationalPerson loginShell: /usr/bin/ksh homeDirectory: /home/jtucker dn: uid=ttucker,ou=people,dc=companyA,dc=com loginShell: /usr/bin/zsh host: hostZ host: hostC uid: ttucker cn: Tom Tucker sn: Tucker objectClass: top objectClass: account objectClass: person objectClass: posixAccount objectClass: shadowAccount objectClass: inetorgperson objectClass: organizationalPerson uidNumber: 108 gidNumber: 102 gecos: Tom Tucker homeDirectory: /home/ttucker description: system Current OUTPUT ################# jtucker John Tucker Desired OUTPUT ################ jtucker John Tucker ttucker Tom Tucker -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070518/bdeec5a6/attachment.html From tktucker at gmail.com Sat May 19 03:15:25 2007 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 18 May 2007 21:15:25 -0400 Subject: [Tutor] Continue Matching after First Match In-Reply-To: <2a278ffe0705181758v29b8229ice736c5b5eade1c9@mail.gmail.com> References: <2a278ffe0705181758v29b8229ice736c5b5eade1c9@mail.gmail.com> Message-ID: <2a278ffe0705181815n767b87eeoea724f0617db6a6@mail.gmail.com> Disregard! Looks like part of my problem is the regex string. On 5/18/07, Tom Tucker wrote: > > Please forgive the colors, just trying to help illustrate my question. > > The below code snipet works as designed, however the regex matches once > and exits. I want it to continue matching and printing until EOF. Any > suggestions? > > Why the cStringIO stuff? The input data shown below is collected from > os.popen. I was trying to find an easy way of matching my regex. > Matching with a string seemed easier than looping through the ouput > collected. Hmm. Come to think of it, I guess I could match on the first > "^dn" catpure that output and then keep looping until "^cn:" is seen. Then > repeat. > > Anyways, any suggestions to fix the below code? > > Thanks for the help, > > > > Code Snipet > ########### > multi_regex = re.compile(r'dn: uid=(\w+)..*cn: ((\w+ \w+)|(\w+ \w+\. > \w+))..*(?=dn:)', re.MULTILINE| re.DOTALL) > output = os.popen(command).readlines() > voutput = cStringIO.StringIO() > for line in output: > voutput.write(line) > contents = voutput.getvalue() #<-- contents is > match = re.search(multi_regex, contents) > if match: > print match.group(1) > print match.group(2) > > > > Blue = is what the regex matches > Red = regex groups # match.group(#) > Green = next regex groups not being captured > > INPUT Data > ########### > version: 1 > dn: uid= jtucker,ou=people,dc=companyA,dc=com > host: hostA > host: hostB > host: hostC > description: other > gecos: John Tucker > gidNumber: 1 > uidNumber: 1157 > sn: Tucker > cn: John Tucker > uid: jtucker > objectClass: top > objectClass: account > objectClass: person > objectClass: posixAccount > objectClass: shadowAccount > objectClass: inetorgperson > objectClass: organizationalPerson > loginShell: /usr/bin/ksh > homeDirectory: /home/jtucker > dn: uid=ttucker ,ou=people,dc=companyA,dc=com > loginShell: /usr/bin/zsh > host: hostZ > host: hostC > uid: ttucker > cn: Tom Tucker > sn: Tucker > objectClass: top > objectClass: account > objectClass: person > objectClass: posixAccount > objectClass: shadowAccount > objectClass: inetorgperson > objectClass: organizationalPerson > uidNumber: 108 > gidNumber: 102 > gecos: Tom Tucker > homeDirectory: /home/ttucker > description: system > > > Current OUTPUT > ################# > jtucker > John Tucker > > > Desired OUTPUT > ################ > jtucker > John Tucker > ttucker > Tom Tucker > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070518/342c01a4/attachment.html From rabidpoobear at gmail.com Sat May 19 03:34:32 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 18 May 2007 20:34:32 -0500 Subject: [Tutor] two input acceptions In-Reply-To: <464E4937.2090201@sapo.pt> References: <464E4937.2090201@sapo.pt> Message-ID: <464E5428.5020200@gmail.com> > [snip] > > PS: Now I know why I see all posts messed up. It's because you're > sending your emails as a HTML, and I deactivated that on my email > client. I don't know if Hotmail (I believe you send you emails from > there) as an option to turn off HTML. If it was please use it :D > (Besides being nice, you can get more responses if you do that. Not > everyone has an HTML capable email client.) > > PS2 (no, not the console): I just noticed you didn't send the email back > to the mailing list. You should select reply to all (or a similar > option) when replying to mailing list, so that other people can learn too. > Yeah, you should probably turn off HTML. I don't know what the problem is, but I can't read your e-mails at all. You'll get _much_ more help if people don't have to copy-paste your emails into another program and reformat them just so they can read them. Also, if your code is more than a few lines, sending it as an attachment keeps it from getting all weird from e-mail client formatting. HTH, -Luke From pythontutoraccount at gmail.com Sat May 19 04:05:40 2007 From: pythontutoraccount at gmail.com (John) Date: Fri, 18 May 2007 22:05:40 -0400 Subject: [Tutor] pywinauto for OS X and Linux? Message-ID: <464E5B74.4010004@gmail.com> I have been playing with pywinauto http://pywinauto.pbwiki.com/ for a few hours. Pywinauto allows you to use python to automate the GUI of Windows using Python in very intuitive ways. What are the closest analogs for this under OS X and Linux? John From rohan.deshpande at gmail.com Sat May 19 05:50:42 2007 From: rohan.deshpande at gmail.com (Rohan Deshpande) Date: Fri, 18 May 2007 23:50:42 -0400 Subject: [Tutor] encryption for files/passwords Message-ID: Hey all, I am writing a small python script to maintain some passwords and identity info. All the data is in an external file. what is the best way to encrypt/decrypt this file's data using a key? I am new to encryption methods let alone how to do it in python. I had a look at python-crypto, ezPyCrypto and yawPyCrypto but they seemed overkill? Thanks, Rohan From bensherman at gmail.com Sat May 19 06:48:47 2007 From: bensherman at gmail.com (Ben Sherman) Date: Sat, 19 May 2007 00:48:47 -0400 Subject: [Tutor] encryption for files/passwords In-Reply-To: References: Message-ID: <5a56471e0705182148l4f326fe5h612af05ab03e60ad@mail.gmail.com> On 5/18/07, Rohan Deshpande wrote: > > Hey all, > > I am writing a small python script to maintain some passwords and > identity info. All the data is in an external file. what is the best > way to encrypt/decrypt this file's data using a key? I am new to > encryption methods let alone how to do it in python. I had a look at > python-crypto, ezPyCrypto and yawPyCrypto but they seemed overkill? If you only need to encrypt passwords, look at the crypt module - it does one way password hashing. Good luck! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070519/e4731189/attachment.htm From alan.gauld at btinternet.com Sat May 19 09:28:19 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 08:28:19 +0100 Subject: [Tutor] two input acceptions References: <464E4937.2090201@sapo.pt> Message-ID: "Rolando Pereira" wrote > what did you mean when you were talking about the raw_input( )? > How can the regular input( ) be used evilly? raw_input() is the preferred way to read input from a user. It only reads the raw input as typed by the user so it always returns a string which you then need to convert to another type (like an int) if you need to. This gives you more controil over what kind of data your program receives. input() by contrast reads the string input by the user and tries to evaluate it as a Python expression. Thus if the user typed import os;os.system('format c:\') Python would try to evaluate that as a python string and it could format your C drive. (In practice it would throw up a prompt and hopefully you would say no!) It might not be something as obvious as that, it could simply deactivate your firewall, or add a new user account to your PC, anything that enables a subsequent attack to do more damage. The attack might not be deliberate, sometimes accidentally typed errors can result in code being executed that you didn't want. But thats why input() is best used in very strictly controlled environments - like at the >>> prompt when you are testing/developing code. But use raw_input plus a conversion function for finished code. > When I run the program and input the rectangle option, > it asks me for a radius, Your code is unreadable and I don't have the time or inclination to try to unpick it. Can you send as plain text or as an attachment please? Alan G From alan.gauld at btinternet.com Sat May 19 09:30:50 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 08:30:50 +0100 Subject: [Tutor] Continue Matching after First Match References: <2a278ffe0705181758v29b8229ice736c5b5eade1c9@mail.gmail.com> Message-ID: "Tom Tucker" wrote > The below code snipet works as designed, however the regex matches > once and > exits. I want it to continue matching and printing until EOF. Any > suggestions? Does re.findall() help? Alan G. From alan.gauld at btinternet.com Sat May 19 09:37:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 08:37:29 +0100 Subject: [Tutor] pywinauto for OS X and Linux? References: <464E5B74.4010004@gmail.com> Message-ID: "John" wrote > few hours. Pywinauto allows you to use python to automate the GUI of > Windows using Python in very intuitive ways. What are the closest > analogs for this under OS X and Linux? Applescript on MacOS could be used. You can call Python from within Applescript (and vice versa I think?) ISTR there is a module in the MacPython download for doing this. Alan G. From rikard.bosnjakovic at gmail.com Sat May 19 11:45:01 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Sat, 19 May 2007 11:45:01 +0200 Subject: [Tutor] (no subject) In-Reply-To: <464E2521.3020500@tds.net> References: <000401c79966$798bafa0$6ca30ee0$@net> <464E2521.3020500@tds.net> Message-ID: On 5/19/07, Kent Johnson wrote: > Please be gentle and forgiving of mistakes > so beginners feel welcome as they learn. My intention was not to be harsh or rude in any manner, I was just trying to hint to encourage the use of subjects for posts. Should Teresa feel hurt, my humble apologies. -- - Rikard - http://bos.hack.org/cv/ From kent37 at tds.net Sat May 19 14:21:41 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 May 2007 08:21:41 -0400 Subject: [Tutor] pywinauto for OS X and Linux? In-Reply-To: References: <464E5B74.4010004@gmail.com> Message-ID: <464EEBD5.4080105@tds.net> Alan Gauld wrote: > "John" wrote > >> few hours. Pywinauto allows you to use python to automate the GUI of >> Windows using Python in very intuitive ways. What are the closest >> analogs for this under OS X and Linux? > > Applescript on MacOS could be used. > You can call Python from within Applescript (and vice versa I think?) > ISTR there is a module in the MacPython download for doing this. I wasn't aware that AppleScript could be used for general UI scripting but apparently since MacOS 10.3 it can. Here is an article about it: http://www.macgeekery.com/development/gui_automation_with_applescript Googling 'python applescript' is also rewarding. Kent From matt at mattanddawn.orangehome.co.uk Sat May 19 14:54:50 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Sat, 19 May 2007 13:54:50 +0100 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: <464E22BF.8090203@gmail.com> References: <1179524228.12384.16.camel@computer> <1179525754.12384.28.camel@computer> <464E22BF.8090203@gmail.com> Message-ID: <1179579290.5425.0.camel@computer> > the possible combinations of values from the two tuples? > see my other reply, Matt. > -Luke Hi Luke, Sorry if I'm missing something but which other reply? Matt From rohan.deshpande at gmail.com Sat May 19 16:07:13 2007 From: rohan.deshpande at gmail.com (Rohan Deshpande) Date: Sat, 19 May 2007 10:07:13 -0400 Subject: [Tutor] encryption for files/passwords In-Reply-To: <5a56471e0705182148l4f326fe5h612af05ab03e60ad@mail.gmail.com> References: <5a56471e0705182148l4f326fe5h612af05ab03e60ad@mail.gmail.com> Message-ID: Thanks, but I want to be able to encrypt *files* with passwords in them.. the passwords being the sensitive data :) Any other ideas? On 5/19/07, Ben Sherman wrote: > On 5/18/07, Rohan Deshpande wrote: > > > Hey all, > > > > I am writing a small python script to maintain some passwords and > > identity info. All the data is in an external file. what is the best > > way to encrypt/decrypt this file's data using a key? I am new to > > encryption methods let alone how to do it in python. I had a look at > > python-crypto, ezPyCrypto and yawPyCrypto but they seemed overkill? > > If you only need to encrypt passwords, look at the crypt module - it does > one way password hashing. > > Good luck! > > From bgailer at alum.rpi.edu Sat May 19 16:41:43 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 19 May 2007 07:41:43 -0700 Subject: [Tutor] two input acceptions In-Reply-To: References: <464E4937.2090201@sapo.pt> Message-ID: <464F0CA7.7020800@alum.rpi.edu> Alan Gauld wrote: > "Rolando Pereira" wrote > >> what did you mean when you were talking about the raw_input( )? >> How can the regular input( ) be used evilly? >> > > raw_input() is the preferred way to read input from a user. > It only reads the raw input as typed by the user so it always > returns a string which you then need to convert to another > type (like an int) if you need to. This gives you more controil > over what kind of data your program receives. > > input() by contrast reads the string input by the user and tries > to evaluate it as a Python expression. Thus if the user typed > > import os;os.system('format c:\') > Err... are you confusing eval with exec? input( [prompt]) Equivalent to eval(raw_input(prompt)). > Python would try to evaluate that as a python string > and it could format your C drive. (In practice it would > throw up a prompt and hopefully you would say no!) > It might not be something as obvious as that, it > could simply deactivate your firewall, or add a new > user account to your PC, anything that enables a > subsequent attack to do more damage. > > The attack might not be deliberate, sometimes > accidentally typed errors can result in code being > executed that you didn't want. > > But thats why input() is best used in very strictly > controlled environments - like at the >>> prompt when > you are testing/developing code. But use raw_input plus > a conversion function for finished code. > > >> When I run the program and input the rectangle option, >> it asks me for a radius, >> > > Your code is unreadable and I don't have the time > or inclination to try to unpick it. Can you send as plain > text or as an attachment please? > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From emilia12 at mail.bg Sat May 19 18:03:16 2007 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Sat, 19 May 2007 19:03:16 +0300 Subject: [Tutor] how to seed up? In-Reply-To: References: Message-ID: <1179590596.14d7f97a7632d@mail.bg> hi list when i have many modules in my script (eg. 'import pylab, os, sys'), python loads them very slow ... so is there a way to run same script many times (with small changes in the code), without reloading/parsing all modules each time ? and 2nd question - in case of CGI script - is there a way to recall faster already loaded/called script? Regards, e. ----------------------------- SCENA - ???????????? ????????? ???????? ?? ??????? ??????????? ? ??????????. http://www.bgscena.com/ From alan.gauld at btinternet.com Sat May 19 19:43:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 18:43:26 +0100 Subject: [Tutor] pywinauto for OS X and Linux? References: <464E5B74.4010004@gmail.com> <464EEBD5.4080105@tds.net> Message-ID: "Kent Johnson" wrote > I wasn't aware that AppleScript could be used for general UI > scripting Its all I was aware it could do! What else does it have up its sleeve? I keep meaning to dig into Aopplescript properly. I downloaded the applescript development IDE from Apples site but I've never really used it. Alan G. From alan.gauld at btinternet.com Sat May 19 19:50:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 18:50:02 +0100 Subject: [Tutor] how to seed up? References: <1179590596.14d7f97a7632d@mail.bg> Message-ID: wrote > when i have many modules in my script (eg. 'import pylab, > os, sys'), python loads them very slow ... You could try putting all the imports into a single module and them importing that module. The new imported module should be compiled into Python byte code the first time you import it which might be faster on subsequent runs - I've never tried this so I'm interested in the results! > so is there a way to run same script many times (with small > changes in the code), without reloading/parsing all modules > each time ? If you split your code into modules and import them at the Python prompt you can sometimes develop code in one module while avoiding imports of the rest, but its not 100% effective. > and 2nd question - in case of CGI script - is there a way to > recall faster already loaded/called script? There are lots of ways around this, including FastCGI, mod_python, one of the many Python web frameworks. Look at this page for lots of options: http://wiki.python.org/moin/WebFrameworks HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From shiv_mbm at hotmail.com Sat May 19 19:53:53 2007 From: shiv_mbm at hotmail.com (ShivKumar Anand) Date: Sat, 19 May 2007 23:23:53 +0530 Subject: [Tutor] PythonHandler mpcp: AttributeError: 'module' object has no attribute 'argv' Message-ID: dear all, I am trying to run turbogears application using Apache on windows and the start_prj.py is from os.path import *import sys #if len(sys.argv) > 1:# update_config(configfile=sys.argv[1], modulename="wiki30.config") sys.argv[0]="d:/web/Wiki-30"sys.argv[1]="d:/web/Wiki-30/dev.conf" if exists(join(dirname(__file__), "setup.py")): cherrypy.config.update(file=join(dirname(__file__),"d:/web/Wiki-30/dev.cfg"))else: cherrypy.config.update(file=join(dirname(__file__),"d:/web/Wiki-30/prod.cfg")) from wiki30.controllers import Rootcherrypy.root =Root()if __name__ == "__main__": cherrypy.server.start() def mp_setup(): pass if __name__!="__main__": #ie imported this from apache import kid kid.path.insert(dirname(__file__)) #or: #kid.path.insert("D:\\") # or whatever===================================================== The Apache httpd.conf settings are like this: ServerName 'localhost' PythonPath "['D:/web/wiki-30/'] +sys.path" SetHandler mod_python PythonHandler mpcp PythonOption cherrysetup startwiki30::mp_setup and when I am trying to access the page from http://localhost it is giving PythonHandler mpcp: AttributeError: 'module' object has no attribute 'argv' pls help to come out of this. Thanks Shiv Kumar _________________________________________________________________ The idiot box is no longer passe! http://content.msn.co.in/Entertainment/TV/Default.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070519/a053cc4d/attachment.html From alej0varas at gmail.com Sat May 19 19:55:00 2007 From: alej0varas at gmail.com (alejandro varas) Date: Sat, 19 May 2007 13:55:00 -0400 Subject: [Tutor] how to seed up? In-Reply-To: <1179590596.14d7f97a7632d@mail.bg> References: <1179590596.14d7f97a7632d@mail.bg> Message-ID: <84391c2a0705191054p61ac7050md922bbfa95bf9d03@mail.gmail.com> hi list this is an answer to your first question I put two attachments, both python code main.py is the file you have to run and script.py is the file that must contain your code Howto: 1.- run main.py and your code will be executed 2.- then you will be answered to do it again, don't answer right now 3.- modify your code, save it 4.- answer in any Pythonic way of True or False( obviously True to run again and False to stop) HTH 2007/5/19, emilia12 at mail.bg : > > hi list > > when i have many modules in my script (eg. 'import pylab, > os, sys'), python loads them very slow ... > > so is there a way to run same script many times (with small > changes in the code), without reloading/parsing all modules > each time ? > > and 2nd question - in case of CGI script - is there a way to > recall faster already loaded/called script? > > Regards, > e. > > ----------------------------- > > SCENA - ???????????? ????????? ???????? ?? ??????? ??????????? ? > ??????????. > http://www.bgscena.com/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Alejandro Varas G. T.N.S. en Redes de Computadores.(estudiante) http://alej0varas.googlepages.com +56998330920 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070519/83a10d9e/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: main.py Type: text/x-python Size: 285 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070519/83a10d9e/attachment-0002.py -------------- next part -------------- A non-text attachment was scrubbed... Name: script.py Type: text/x-python Size: 177 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070519/83a10d9e/attachment-0003.py From alan.gauld at btinternet.com Sat May 19 20:02:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 19:02:52 +0100 Subject: [Tutor] encryption for files/passwords References: <5a56471e0705182148l4f326fe5h612af05ab03e60ad@mail.gmail.com> Message-ID: "Rohan Deshpande" wrote in message news:e5a6f5430705190707h305d2e22p84e4ffaa868e5178 at mail.gmail.com... > Thanks, but I want to be able to encrypt *files* with passwords in > them.. the passwords being the sensitive data :) > > Any other ideas? Have you any more specific requirements that prevents the use of the modules you have already mentioned? They seem to be the norms for Python encryption. What exactly are you hoping to find? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alej0varas at gmail.com Sat May 19 20:05:38 2007 From: alej0varas at gmail.com (alejandro varas) Date: Sat, 19 May 2007 14:05:38 -0400 Subject: [Tutor] I want some help with arrays... In-Reply-To: <464D33B7.6060303@gmail.com> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> <20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> <464D0562.90604@gmail.com> <464D258B.8080909@alum.rpi.edu> <73CEB8B8290042A587003E8AA23011AF@MomsComputer> <464D33B7.6060303@gmail.com> Message-ID: <84391c2a0705191105u4d10cd38l6f108fc4a280c763@mail.gmail.com> 2007/5/18, Luke Paireepinart : > > James Matthews wrote: > > When the CPU writes to the RAM the 0th location can be written to also. > When > > you alter components of a language for example changing the way an list > is > > indexed you have to be careful because you can accidently jump out of > > bounds! > def indexOneBased(somelist,index): > return somelist[index-1] > > now you can do > indexOneBased([1,2,3,4,5], 5) > and you will get 5. > > Obviously the verbosity of this example seems to imply its uselessness, > but what Bob was getting at is that there are situations where you can > create a list that you index into based upon some arbitrary starting > point. > For example, say you had a calendar program that kept track of my > schedule for days 1 through 31 of this month. > You'd store the schedule of each day in a list starting with the 0th > element and ending at the 30th element. > Then, whenever I asked you for the 1st element, for example, you'd > retrieve the 0th element for me, and so on. > The indexing itself isn't changed, merely the interface to it. > Note that you don't actually index the list starting at the 1th element > (the 2nd one) > you index it starting at the 0th element, but use indexes that begin at 1. if you want something like a calendar i thin is beter to use adictionary where you can do this agenda = { 'month' : { 'day': { ... }, }, } so you don't have to deal whit indexes you jut wet what you want by doing month = "month" day = "day" agenda[month][day] HTH, > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Alejandro Varas G. T.N.S. en Redes de Computadores.(estudiante) http://alej0varas.googlepages.com +56998330920 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070519/0fdfe905/attachment.html From andreas at kostyrka.org Sat May 19 20:53:14 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sat, 19 May 2007 20:53:14 +0200 Subject: [Tutor] how to seed up? Message-ID: Check the permissions, python does not emit any warnings if it cannot write the pyc files Andreas -- Urspr?ngl. Mitteil. -- Betreff: Re: [Tutor] how to seed up? Von: "Alan Gauld" Datum: 19.05.2007 17:53 wrote > when i have many modules in my script (eg. 'import pylab, > os, sys'), python loads them very slow ... You could try putting all the imports into a single module and them importing that module. The new imported module should be compiled into Python byte code the first time you import it which might be faster on subsequent runs - I've never tried this so I'm interested in the results! > so is there a way to run same script many times (with small > changes in the code), without reloading/parsing all modules > each time ? If you split your code into modules and import them at the Python prompt you can sometimes develop code in one module while avoiding imports of the rest, but its not 100% effective. > and 2nd question - in case of CGI script - is there a way to > recall faster already loaded/called script? There are lots of ways around this, including FastCGI, mod_python, one of the many Python web frameworks. Look at this page for lots of options: http://wiki.python.org/moin/WebFrameworks HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Sat May 19 21:04:15 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 19 May 2007 14:04:15 -0500 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: <1179579290.5425.0.camel@computer> References: <1179524228.12384.16.camel@computer> <1179525754.12384.28.camel@computer> <464E22BF.8090203@gmail.com> <1179579290.5425.0.camel@computer> Message-ID: <464F4A2F.90606@gmail.com> Matt Smith wrote: >> the possible combinations of values from the two tuples? >> see my other reply, Matt. >> -Luke >> > > Hi Luke, > > Sorry if I'm missing something but which other reply? > All the info in my other reply Alan reiterated, I believe. You can just subtract 1 from the total at the end. Your ISP believes I'm spamming you and won't let my e-mails get through, but the Tutor has you listed as a recipient of the mail, so it didn't send you a copy of that particular e-mail. SO, for you, there was no other reply, I guess. Basically what i said was: You're expecting an IndexError, and if one occurs, you're assuming that that neighbor doesn't count, So just put the code Rikard sent you in the try block and in the except block, put 'pass' (i.e. "Do Nothing"). And: You can add an if statement to remove this case [of counting the square that you're currently checking], or, easier (and probably more efficient) just subtract 1 from your end result. -Luke From matt at mattanddawn.orangehome.co.uk Sat May 19 21:07:40 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Sat, 19 May 2007 20:07:40 +0100 Subject: [Tutor] Help with excetion handing and making my code more efficient needed please In-Reply-To: <464E22BF.8090203@gmail.com> References: <1179524228.12384.16.camel@computer> <1179525754.12384.28.camel@computer> <464E22BF.8090203@gmail.com> Message-ID: <1179601660.5231.1.camel@computer> On Fri, 2007-05-18 at 17:03 -0500, Luke Paireepinart wrote: > see my other reply, Matt. > -Luke Apologies Luke, I have found your earlier post in the tutor archives - I don't seem to have received it from the list yet. Thanks for the help. Matt From rabidpoobear at gmail.com Sat May 19 21:20:12 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 19 May 2007 14:20:12 -0500 Subject: [Tutor] I want some help with arrays... In-Reply-To: <84391c2a0705191105u4d10cd38l6f108fc4a280c763@mail.gmail.com> References: <7822513.1179439717619.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> <20070518013917.xqwol2x95lfq8kos@webmail.frontiernet.net> <464D0562.90604@gmail.com> <464D258B.8080909@alum.rpi.edu> <73CEB8B8290042A587003E8AA23011AF@MomsComputer> <464D33B7.6060303@gmail.com> <84391c2a0705191105u4d10cd38l6f108fc4a280c763@mail.gmail.com> Message-ID: <464F4DEC.7000003@gmail.com> [snip my calendar example about fake 1-based indexing] > > if you want something like a calendar i thin is beter to use > adictionary where you can do this > agenda = > { > 'month' : > { > 'day': > { ... > }, > }, > } > > so you don't have to deal whit indexes you jut wet what you want by doing > > month = "month" > day = "day" And what is day? Is it, perhaps, a number, such as 1-31? That sounds like an index to me. Your example's better in the sense that you save a bit of storage if you don't have a schedule for every day. But it's not conducive to the example I was trying to give. My original example was for the schedule for a particular month, not for a particular year. The purpose of the example was to show a situation where you could use 1-based indexing into a 0-based array. And if I made the example use a dictionary, the purpose of the example would have been lost. I never said that my method of solving this particular problem was the best. It's like, how in school, they teach you recursion using factorial and summing sequences, when, really, factorial can be done linear and iterative, and sequences can even be done in constant time, depending on the sequence. It's not that that's the best solution. It's that it's a solution that uses the tool you're trying to give people experience with. The intent is that they extrapolate from that the general usefulness of the technique (be it recursion or munging with indexes) so that, later, they will hopefully be able to recognize the situation where it's better to do it a different way. Giving them more tools on their belt so they're more versatile and thus, hopefully, better programmers in the end. Hope That's Clear, -Luke From alan.gauld at btinternet.com Sat May 19 21:23:50 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2007 20:23:50 +0100 Subject: [Tutor] PythonHandler mpcp: AttributeError: 'module' object has no attribute 'argv' References: Message-ID: "ShivKumar Anand" wrote > I am trying to run turbogears application using Apache > on windows and the start_prj.py is Have you tried the TurboGears forums? I suspect you'll get an answer there faster and more reliably than here. I use TurboGears but not with Apache on XP. Alan G. From kent37 at tds.net Sun May 20 00:06:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 May 2007 18:06:02 -0400 Subject: [Tutor] two input acceptions In-Reply-To: <464F0CA7.7020800@alum.rpi.edu> References: <464E4937.2090201@sapo.pt> <464F0CA7.7020800@alum.rpi.edu> Message-ID: <464F74CA.3000600@tds.net> Bob Gailer wrote: > Alan Gauld wrote: >> input() by contrast reads the string input by the user and tries >> to evaluate it as a Python expression. Thus if the user typed >> >> import os;os.system('format c:\') >> > Err... are you confusing eval with exec? > > input( [prompt]) > > Equivalent to eval(raw_input(prompt)). Yes he is but it doesn't matter; how about __import__('os').system('format c:\') ? See the many discussions about safe eval on comp.lang.python for more examples of evil things you can do with eval. Kent From kent37 at tds.net Sun May 20 00:10:42 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 May 2007 18:10:42 -0400 Subject: [Tutor] pywinauto for OS X and Linux? In-Reply-To: References: <464E5B74.4010004@gmail.com> <464EEBD5.4080105@tds.net> Message-ID: <464F75E2.5060605@tds.net> Alan Gauld wrote: > "Kent Johnson" wrote > >> I wasn't aware that AppleScript could be used for general UI >> scripting > > Its all I was aware it could do! > > What else does it have up its sleeve? Originally AppleScript could only perform actions that were intentionally exposed by the authors of an application. IOW AppleScript has access to an API that is explicitly exposed by the authors. If you open Script Editor, then open the dictionary of an application, that is what you will see. AFAIK this is still the way AppleScript is usually used. IIUC What happened in 10.3 is that the accessibility hooks were exposed to AppleScript allowing control of an app by manipulating its GUI elements. Kent From kent37 at tds.net Sun May 20 00:14:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 May 2007 18:14:36 -0400 Subject: [Tutor] PythonHandler mpcp: AttributeError: 'module' object has no attribute 'argv' In-Reply-To: References: Message-ID: <464F76CC.2070703@tds.net> ShivKumar Anand wrote: > dear all, > > I am trying to run turbogears application using Apache on windows and > the start_prj.py is > > from os.path import * > import sys > PythonHandler mpcp: AttributeError: 'module' object has no attribute 'argv' Do you have a module somewhere called sys.py? Perhaps you are shadowing the builtin sys module. Kent From alan.gauld at btinternet.com Sun May 20 01:09:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 May 2007 00:09:53 +0100 Subject: [Tutor] pywinauto for OS X and Linux? References: <464E5B74.4010004@gmail.com> <464EEBD5.4080105@tds.net> <464F75E2.5060605@tds.net> Message-ID: "Kent Johnson" wrote > Originally AppleScript could only perform actions that were > intentionally exposed by the authors of an application. OK, Like a COM interface in Windoze? > IIUC What happened in 10.3 is that the accessibility hooks were > exposed > to AppleScript allowing control of an app by manipulating its GUI > elements. Yes I see. after reading the link you posted I noticed that it was responding to events which I admit I didn't realise it could do. I have only used it to control GUI apps via the usual hooks. I've also linked it with shell commands (using do shell script) which are easier to use in scripting than trying to drive finder IMHO! Thanks for the clarification Kent, Alan G. From simplebob at gmail.com Sun May 20 10:31:07 2007 From: simplebob at gmail.com (Daniel McQuay) Date: Sun, 20 May 2007 04:31:07 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <55949.90647.qm@web54307.mail.re2.yahoo.com> <464E0041.70209@gmail.com> Message-ID: <6d87ecf40705200131h1aa0c350g93572b54b84f252a@mail.gmail.com> You may also need to add it to your system environmental list. Under System variables you will want to add the directory where python is. Mine looks like this: c:\ruby\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\QuickTime\QTSystem\;C:\Python25\ Just my two cents. HTH, On 5/18/07, Alan Gauld wrote: > > "Luke Paireepinart" wrote > > > Please never again write a message to this mailing list without a > > subject. > > For those of us who have threads turned on, it becomes quite > > cumbersome. > > FWIW I have the same problem reading via gmane. It was > telling me there were unread messages but I couldn't see > them till I scrolled waaaaayyyyy back in the history to find > the old thread. > > Its not a killer but it is inconvenient in a threaded reader. > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Daniel McQuay boxster.homelinux.org H: 814.825.0847 M: 814-341-9013 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070520/9677d159/attachment.htm From mwalsh at groktech.org Sun May 20 21:04:31 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 20 May 2007 14:04:31 -0500 Subject: [Tutor] Continue Matching after First Match In-Reply-To: <2a278ffe0705181758v29b8229ice736c5b5eade1c9@mail.gmail.com> References: <2a278ffe0705181758v29b8229ice736c5b5eade1c9@mail.gmail.com> Message-ID: <46509BBF.40800@groktech.org> Hi Tom, Tom Tucker wrote: > Why the cStringIO stuff? The input data shown below is collected from > os.popen. I was trying to find an easy way of matching my regex. Ah, ldap... > Matching with a string seemed easier than looping through the ouput > collected. Hmm. Come to think of it, I guess I could match on the > first "^dn" catpure that output and then keep looping until "^cn:" is > seen. Then repeat. Honestly, I'm not very good with regular expressions -- and try to avoid them when possible. But in cases where they seem to be the best option, I have formed a heavy dependence on regex debuggers like kodos. http://kodos.sourceforge.net/ > Anyways, any suggestions to fix the below code? Have you had a look at the python-ldap package? http://python-ldap.sourceforge.net/ You could probably access ldap directly with python, if that's an option. Or, you could roll your own ldif parser (but make sure your data contains a newline between each dn, or the parser will choke with a 'ValueError: Two lines starting with dn: in one record.'): import ldif from cStringIO import StringIO class MyLDIF(ldif.LDIFParser): def __init__(self, inputfile): ldif.LDIFParser.__init__(self, inputfile) self.users = [] def handle(self, dn, entry): self.users.append((entry['uid'], entry['cn'])) raw = """\ """ if __name__ == '__main__': io = StringIO(raw) lp = MyLDIF(io) lp.parse() for user in lp.users: uid = user[0][0] cn = user[1][0] print uid print cn ... or ... You could also use ldif.LDIFRecordList directly without creating a custom parser class which would return a list of (dn, entry) tuples. The module author warns that 'It can be a memory hog!', and I can imagine this is true if you are working with a particularly large ldap directory. io = StringIO(raw) directory = ldif.LDIFRecordList(io) directory.parse() for dn, entry in directory.all_records: print entry['uid'][0] print entry['cn'][0] From mwalsh at groktech.org Mon May 21 00:06:39 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 20 May 2007 17:06:39 -0500 Subject: [Tutor] question re: executing exe files with arguments In-Reply-To: <1179519468.11328.8.camel@carrow23.uhnres.utoronto.ca> References: <1179519468.11328.8.camel@carrow23.uhnres.utoronto.ca> Message-ID: <4650C66F.2040503@groktech.org> Hey Janani, Janani Krishnaswamy wrote: > Hi! > I am having trouble executing an exe file with 3 arguments within a > python script. Right now I have something like this: > > os.system(r'"1/2/3/program 1/2/3/argument1 1/2/3/argument2"') Without an error message, or traceback, this is difficult to diagnose. But, my guess is your use of quotes is causing the issue. Can you successfully run the hypothetical command as used above (with the same double-quote placement) in a shell? as in: user at host:~$ "1/2/3/program 1/2/3/argument1 1/2/3/argument2" ... or, if you are a windows user ... c:\> "1/2/3/program 1/2/3/argument1 1/2/3/argument2" I think the command string would be treated as one long path, in this case. If your paths contain whitespace or other special characters, you probably want something like this: "1/2/3/program" "1/2/3/argument1" "1/2/3/argument2" HTH, Marty From mwalsh at groktech.org Mon May 21 00:46:37 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 20 May 2007 17:46:37 -0500 Subject: [Tutor] ActivePython and CPython In-Reply-To: References: Message-ID: <4650CFCD.90306@groktech.org> Alan Gauld wrote: > wrote >> Answer: PyDev for Eclipse turns Eclipse into a pretty good IDE for >> Python. > > Agreed, I downloaded pydev over the weekend and have been > playing. The editor isn't exactly vim/emacs but its as good as > IDLE/Pythonwin > > However I think the OP wants an HTML preview and I don't see that > facility in Eclipse anywhere. Not with a default install, but there are a few html editor plugins with preview mode that can be installed separately. Aptana (http://www.aptana.com) is one such, that seems promising. The easiest way to get aptana would be through the eclipse update mechanism, described here: http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration I have not used Aptana regularly for editing html, but I really appreciate it's code-completion for css and js. I tend to prefer the eclipse web tools platform html editor, but I don't think any recent release has html preview, or if it's even planned -- I'd be happy to be proven wrong. HTH, Marty From mailchansek at yahoo.com Mon May 21 09:56:59 2007 From: mailchansek at yahoo.com (Chandrashekar) Date: Mon, 21 May 2007 00:56:59 -0700 (PDT) Subject: [Tutor] string replacement Message-ID: <797656.92788.qm@web58714.mail.re1.yahoo.com> Hi, I am trying to do something like this in python. Can you please help? handle= open('test.txt','a') handle.write(''' Testsomething$i something$i-test ''' ) when i write into the file, i would like to have the output like this. Testsomething1 something1-test Testsomething2 something2-test Testsomething3 something3-test ....... I can perform the same using a loop. But how do i append i (1,2,......n) while i am writing into the file.(I mean inside the handle.write) Thanks, Chandru --------------------------------- Pinpoint customers who are looking for what you sell. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070521/d576a5df/attachment.html From andreas at kostyrka.org Mon May 21 10:10:21 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 21 May 2007 10:10:21 +0200 Subject: [Tutor] string replacement In-Reply-To: <797656.92788.qm@web58714.mail.re1.yahoo.com> References: <797656.92788.qm@web58714.mail.re1.yahoo.com> Message-ID: <465153ED.40201@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Well, there are a number of ways to achieve this, but the classical one would be: """abc%(i)s def%(i)s """ % dict(i=1) Andreas Chandrashekar wrote: > Hi, > > I am trying to do something like this in python. Can you please help? > > handle= open('test.txt','a') > > handle.write(''' > > Testsomething$i > > something$i-test > > ''' > ) > > when i write into the file, i would like to have the output like this. > > Testsomething1 > something1-test > Testsomething2 > something2-test > Testsomething3 > something3-test > ....... > > I can perform the same using a loop. But how do i append i (1,2,......n) > while i am writing into the file.(I mean inside the handle.write) > > Thanks, > Chandru > > ------------------------------------------------------------------------ > Pinpoint customers > who > are looking for what you sell. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGUVPtHJdudm4KnO0RAgZwAJ9XOamfWZHd1CXYGuLIlOP11p7PWwCgxPD7 UILsdZNbknZz4zq71EuvxSs= =0y02 -----END PGP SIGNATURE----- From tktucker at gmail.com Mon May 21 19:52:21 2007 From: tktucker at gmail.com (Tom Tucker) Date: Mon, 21 May 2007 13:52:21 -0400 Subject: [Tutor] Continue Matching after First Match In-Reply-To: <46509BBF.40800@groktech.org> References: <2a278ffe0705181758v29b8229ice736c5b5eade1c9@mail.gmail.com> <46509BBF.40800@groktech.org> Message-ID: <2a278ffe0705211052q76386871k7ca4415977419ee1@mail.gmail.com> Alan & Martin, Thanks for the feedback and suggestions. Kodos is a great tool. I use it regularly to debug my regex mistakes. It can also be a excellent learning tool to those unfamiliar with regular expressions. Thanks for the Python-LDAP link and ldif example code. On 5/20/07, Martin Walsh wrote: > > Hi Tom, > > Tom Tucker wrote: > > Why the cStringIO stuff? The input data shown below is collected from > > os.popen. I was trying to find an easy way of matching my regex. > > Ah, ldap... Oh yes, > Matching with a string seemed easier than looping through the ouput > > collected. Hmm. Come to think of it, I guess I could match on the > > first "^dn" catpure that output and then keep looping until "^cn:" is > > seen. Then repeat. > > Honestly, I'm not very good with regular expressions -- and try to avoid > them when possible. But in cases where they seem to be the best option, > I have formed a heavy dependence on regex debuggers like kodos. > http://kodos.sourceforge.net/ Kodos is an excellent regex tool. I use it regularly to verify regex strings. > Anyways, any suggestions to fix the below code? > > > Have you had a look at the python-ldap package? > > http://python-ldap.sourceforge.net/ Thanks. I checked the Python module index page and You could probably access ldap directly with python, if that's an > option. Or, you could roll your own ldif parser (but make sure your data > contains a newline between each dn, or the parser will choke with a > 'ValueError: Two lines starting with dn: in one record.'): > > import ldif > from cStringIO import StringIO > > class MyLDIF(ldif.LDIFParser): > def __init__(self, inputfile): > ldif.LDIFParser.__init__(self, inputfile) > self.users = [] > > def handle(self, dn, entry): > self.users.append((entry['uid'], entry['cn'])) > > raw = """\ > > """ > > if __name__ == '__main__': > io = StringIO(raw) > lp = MyLDIF(io) > lp.parse() > for user in lp.users: > uid = user[0][0] > cn = user[1][0] > print uid > print cn > > ... or ... > > You could also use ldif.LDIFRecordList directly without creating a > custom parser class which would return a list of (dn, entry) tuples. The > module author warns that 'It can be a memory hog!', and I can imagine > this is true if you are working with a particularly large ldap directory. > > io = StringIO(raw) > directory = ldif.LDIFRecordList(io) > directory.parse() > for dn, entry in directory.all_records: > print entry['uid'][0] > print entry['cn'][0] > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070521/ac0b755e/attachment.htm From tktucker at gmail.com Mon May 21 20:43:08 2007 From: tktucker at gmail.com (Tom Tucker) Date: Mon, 21 May 2007 14:43:08 -0400 Subject: [Tutor] string replacement In-Reply-To: <465153ED.40201@kostyrka.org> References: <797656.92788.qm@web58714.mail.re1.yahoo.com> <465153ED.40201@kostyrka.org> Message-ID: <2a278ffe0705211143o63b8eb3s7cb101219ec321f@mail.gmail.com> One way is... CODE ############ #!/usr/bin/python handle = file("test.txt",'a') number = 1 for num in range(1,5): handle.write("TestingSome%s\n" % (number)) handle.write("something%s-test\n" % (number)) number += 1 handle.close() OUTPUT ############ TestingSome1 something1-test TestingSome2 something2-test TestingSome3 something3-test TestingSome4 something4-test On 5/21/07, Andreas Kostyrka wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Well, there are a number of ways to achieve this, but the classical one > would be: > > """abc%(i)s > def%(i)s > """ % dict(i=1) > > Andreas > > Chandrashekar wrote: > > Hi, > > > > I am trying to do something like this in python. Can you please help? > > > > handle= open('test.txt','a') > > > > handle.write(''' > > > > Testsomething$i > > > > something$i-test > > > > ''' > > ) > > > > when i write into the file, i would like to have the output like this. > > > > Testsomething1 > > something1-test > > Testsomething2 > > something2-test > > Testsomething3 > > something3-test > > ....... > > > > I can perform the same using a loop. But how do i append i (1,2,......n) > > while i am writing into the file.(I mean inside the handle.write) > > > > Thanks, > > Chandru > > > > ------------------------------------------------------------------------ > > Pinpoint customers > > < > http://us.rd.yahoo.com/evt=48250/*http://searchmarketing.yahoo.com/arp/sponsoredsearch_v9.php?o=US2226&cmp=Yahoo&ctv=AprNI&s=Y&s2=EM&b=50 > >who > > are looking for what you sell. > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.2 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org > > iD8DBQFGUVPtHJdudm4KnO0RAgZwAJ9XOamfWZHd1CXYGuLIlOP11p7PWwCgxPD7 > UILsdZNbknZz4zq71EuvxSs= > =0y02 > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070521/ce7597ea/attachment.html From rabidpoobear at gmail.com Mon May 21 22:04:53 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 21 May 2007 15:04:53 -0500 Subject: [Tutor] string replacement In-Reply-To: <797656.92788.qm@web58714.mail.re1.yahoo.com> References: <797656.92788.qm@web58714.mail.re1.yahoo.com> Message-ID: <4651FB65.4000806@gmail.com> Chandrashekar wrote: > Hi, > > I am trying to do something like this in python. Can you please help? > > handle= open('test.txt','a') > > handle.write(''' > > Testsomething$i > > something$i-test > > ''' > ) > > when i write into the file, i would like to have the output like this. > > Testsomething1 > something1-test > Testsomething2 > something2-test > Testsomething3 > something3-test > ....... If you want multiple lines like this, you could use list comprehensions and use writelines instead. f = open("test.txt","a") string = "Testsomething%s\nsomething%s-test\n" n = 5 f.writelines([string % (i,i) for i in range(1,n+1)]) f.close() Note that this code produces n *2 lines of output, from 1 to n, as per your example output, which is why the range goes from 1 to n+1 rather than the more common range(n). This saves you from having to shift each i one further in your string substitution. string % (i+1, i+1) would work for range(n), but should be slightly less efficient. Of course you'd have to profile it to be sure. > > I can perform the same using a loop. But how do i append i > (1,2,......n) while i am writing into the file.(I mean inside the > handle.write) For each write you use a string substitution, and you do the write in a loop. Or you use writelines like my above example. Also note you're not "appending" i to the string. You're placing it inside the string at an arbitrary position you designate. appending means to add to the end. HTH, -Luke From ethics at gmail.com Mon May 21 23:51:59 2007 From: ethics at gmail.com (Leon Keylin) Date: Mon, 21 May 2007 17:51:59 -0400 Subject: [Tutor] MS SQL Connection Message-ID: Been trying to do a very small and simple select via Python. First I tried a module that looked clean but it couldn't truncate tables. Then I started sifting through docs at python.org and couldn't find a simple way of communicating with a MS SQL via Python program. Do I have to use ODBC? Any examples would be awesome. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070521/0e52c04a/attachment.htm From washakie at gmail.com Mon May 21 23:53:17 2007 From: washakie at gmail.com (John Washakie) Date: Mon, 21 May 2007 14:53:17 -0700 Subject: [Tutor] for k,v in d: ValueError: too many values to unpack Message-ID: I have a Dictionary, that is made up of keys which are email addresses, and values which are a list of firstname, lastnamet, address, etc... If I run the following: #! /bin/python import csv last = {} rdr = csv.DictReader(file("reg-data.csv")) for row in rdr: #print row last[row["reg-email"]] = [row["reg-last"],row["reg-first"],row["reg-country"],row["reg-address"],row["reg-institution"],row["reg-phone"],row["reg-subject"],row["reg-abstract"],row["reg-category"],row["reg-speaking"],row["reg-travel"],row["reg-abstract-upload"],row["reg-rec"]] print last['jfb at nilu.no'][0] # print records for k,v in last: print "Email: %s , has the Last name: %s" % (k,v[0]) I get the error indicated in the subject: ValueError: too many values to unpack Any ideas? Thanks! From Mike.Hansen at atmel.com Tue May 22 00:06:11 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Mon, 21 May 2007 16:06:11 -0600 Subject: [Tutor] MS SQL Connection In-Reply-To: References: Message-ID: <57B026980605A64F9B23484C5659E32E7D4E15@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Leon Keylin > Sent: Monday, May 21, 2007 3:52 PM > To: tutor at python.org > Subject: [Tutor] MS SQL Connection > > Been trying to do a very small and simple select via Python. > First I tried a module that looked clean but it couldn't > truncate tables. > > Then I started sifting through docs at python.org and > couldn't find a simple > way of communicating with a MS SQL via Python program. > > Do I have to use ODBC? > > Any examples would be awesome. Thanks! > I did a quick search on Google for MS SQL Python, and this came up. It looks like it will do the trick. http://pymssql.sourceforge.net/ Mike From john at fouhy.net Tue May 22 00:50:14 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 22 May 2007 10:50:14 +1200 Subject: [Tutor] for k,v in d: ValueError: too many values to unpack In-Reply-To: References: Message-ID: <5e58f2e40705211550q2e1315f0g98ec394562d1a0be@mail.gmail.com> On 22/05/07, John Washakie wrote: > I have a Dictionary, that is made up of keys which are email > addresses, and values which are a list of firstname, lastnamet, > address, etc... > > If I run the following: > > last = {} [...] > for k,v in last: > print "Email: %s , has the Last name: %s" % (k,v[0]) > > I get the error indicated in the subject: > ValueError: too many values to unpack The "implicit" iteration that dictionaries support only iterates over keys. i.e. you could have done this: for k in last: print "Key is %s, value is %s" % (k, last[k]) Alternatively, you can use the iteritems() method; for k, v in last.iteritems(): print "Key is %s, value is %s" % (k, v) See http://www.python.org/doc/current/lib/typesmapping.html for details. -- John. From ethics at gmail.com Tue May 22 01:21:21 2007 From: ethics at gmail.com (Leon Keylin) Date: Mon, 21 May 2007 19:21:21 -0400 Subject: [Tutor] MS SQL Connection Message-ID: Thanks Mike, unfortunately that's the mod I had problems with before. The one that can't do truncate. I've written about it before here and it was easier to look for another solution. Is there any other way? Should I be looking for a different language to do it in? > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Leon Keylin > Sent: Monday, May 21, 2007 3:52 PM > To: tutor at python.org > Subject: [Tutor] MS SQL Connection > > Been trying to do a very small and simple select via Python. > First I tried a module that looked clean but it couldn't > truncate tables. > > Then I started sifting through docs at python.org and > couldn't find a simple > way of communicating with a MS SQL via Python program. > > Do I have to use ODBC? > > Any examples would be awesome. Thanks! > I did a quick search on Google for MS SQL Python, and this came up. It looks like it will do the trick. http://pymssql.sourceforge.net/ Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070521/e7d170a7/attachment.html From bill at celestial.net Tue May 22 02:02:14 2007 From: bill at celestial.net (Bill Campbell) Date: Mon, 21 May 2007 17:02:14 -0700 Subject: [Tutor] Behaviour of dictionaries and others when deleting? Message-ID: <20070522000213.GA13493@ayn.mi.celestial.com> Is the behaviour defined if one is processing a dictionary using iteritems, and delete items? for k, v in d.iteritems(): if somecondition(k, v): del d[k] Would this process all the original members of the dictionary? How about doing something similar with bsddb files? I've always been leary of deleting items while processing things like this, keeping a list of keys to be deleted, then processing that list upon completion of the mail loop to delete the items from the original dictionary or database file. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software, LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``there is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things. Because the innovator has for enemies all those who have done well under the old conditions, and lukewarm defenders in those who may do well under the new.'' -- Machiavelli From jfabiani at yolo.com Tue May 22 01:28:02 2007 From: jfabiani at yolo.com (johnf) Date: Mon, 21 May 2007 16:28:02 -0700 Subject: [Tutor] MS SQL Connection In-Reply-To: References: Message-ID: <200705211628.02105.jfabiani@yolo.com> On Monday 21 May 2007 16:21, Leon Keylin wrote: > Thanks Mike, unfortunately that's the mod I had problems with before. The > one that > can't do truncate. I've written about it before here and it was easier to > look for > another solution. > > Is there any other way? Should I be looking for a different language to do > it in? > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Leon Keylin > > Sent: Monday, May 21, 2007 3:52 PM > > To: tutor at python.org > > Subject: [Tutor] MS SQL Connection > > > > Been trying to do a very small and simple select via Python. > > First I tried a module that looked clean but it couldn't > > truncate tables. > > > > Then I started sifting through docs at python.org and > > couldn't find a simple > > way of communicating with a MS SQL via Python program. > > > > Do I have to use ODBC? > > > > Any examples would be awesome. Thanks! > > I did a quick search on Google for MS SQL Python, and this came up. It > looks like it will do the trick. > > http://pymssql.sourceforge.net/ > > Mike Mike I just tried it and it worked using pymssql-0.8.0. Could you post the code you are using to truncate? Also is it possible you don't have permission to truncate? -- John Fabiani From kent37 at tds.net Tue May 22 03:09:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 May 2007 21:09:24 -0400 Subject: [Tutor] MS SQL Connection In-Reply-To: References: Message-ID: <465242C4.2060805@tds.net> Leon Keylin wrote: > Thanks Mike, unfortunately that's the mod I had problems with before. > The one that > can't do truncate. I've written about it before here and it was easier > to look for > another solution. You could try adodbapi http://adodbapi.sourceforge.net/ Kent > Is there any other way? Should I be looking for a different language to > do it in? > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto: tutor-bounces at python.org ] > On Behalf Of Leon Keylin > > Sent: Monday, May 21, 2007 3:52 PM > > To: tutor at python.org > > Subject: [Tutor] MS SQL Connection > > > > Been trying to do a very small and simple select via Python. > > First I tried a module that looked clean but it couldn't > > truncate tables. > > > > Then I started sifting through docs at python.org > and > > couldn't find a simple > > way of communicating with a MS SQL via Python program. > > > > Do I have to use ODBC? > > > > Any examples would be awesome. Thanks! > > > > I did a quick search on Google for MS SQL Python, and this came up. It > looks like it will do the trick. > > http://pymssql.sourceforge.net/ > > Mike > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue May 22 03:17:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 May 2007 21:17:19 -0400 Subject: [Tutor] Behaviour of dictionaries and others when deleting? In-Reply-To: <20070522000213.GA13493@ayn.mi.celestial.com> References: <20070522000213.GA13493@ayn.mi.celestial.com> Message-ID: <4652449F.7080708@tds.net> Bill Campbell wrote: > Is the behaviour defined if one is processing a dictionary using > iteritems, and delete items? > > for k, v in d.iteritems(): > if somecondition(k, v): del d[k] > > Would this process all the original members of the dictionary? This is not well-defined. You can use for k, v in d.items(): which creates a new list to hold the items and iterates that. > I've always been leary of deleting items while processing things > like this, keeping a list of keys to be deleted, then processing > that list upon completion of the mail loop to delete the items > from the original dictionary or database file. I don't know about bsddb but for lists and dicts that is the right approach. You can also use a list comprehension to filter a list or dict. Kent From maseriyer at yahoo.com Tue May 22 03:25:43 2007 From: maseriyer at yahoo.com (Iyer) Date: Mon, 21 May 2007 18:25:43 -0700 (PDT) Subject: [Tutor] creating a buffer object from a file ? In-Reply-To: <465242C4.2060805@tds.net> Message-ID: <24512.1857.qm@web50707.mail.re2.yahoo.com> How do I go about creating a buffer object from a file containing binary data ? I have a function that accepts only buffer objects for it's parameters and would like to pass on the contents of a file to that function. thanks, iyer --------------------------------- You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070521/44e24b69/attachment.html From mwalsh at groktech.org Tue May 22 05:33:12 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Mon, 21 May 2007 22:33:12 -0500 Subject: [Tutor] MS SQL Connection In-Reply-To: <465242C4.2060805@tds.net> References: <465242C4.2060805@tds.net> Message-ID: <46526478.2030602@groktech.org> Kent Johnson wrote: > Leon Keylin wrote: >> Thanks Mike, unfortunately that's the mod I had problems with before. >> The one that >> can't do truncate. I've written about it before here and it was easier >> to look for >> another solution. > > You could try adodbapi > http://adodbapi.sourceforge.net/ > > Kent Could be a long shot -- but you might also have a look at python-sybase. A few years ago I used Sybase (with freetds) to access ms sql server 2000 from linux -- which I found very satisfying. However, I suspect adodbapi is a lot easier to install on a windows system. http://python-sybase.sourceforge.net/ Good luck! Marty > >> Is there any other way? Should I be looking for a different language to >> do it in? >> >> >> > -----Original Message----- >> > From: tutor-bounces at python.org >> > [mailto: tutor-bounces at python.org ] >> On Behalf Of Leon Keylin >> > Sent: Monday, May 21, 2007 3:52 PM >> > To: tutor at python.org >> > Subject: [Tutor] MS SQL Connection >> > >> > Been trying to do a very small and simple select via Python. >> > First I tried a module that looked clean but it couldn't >> > truncate tables. >> > >> > Then I started sifting through docs at python.org >> and >> > couldn't find a simple >> > way of communicating with a MS SQL via Python program. >> > >> > Do I have to use ODBC? >> > >> > Any examples would be awesome. Thanks! >> > >> >> I did a quick search on Google for MS SQL Python, and this came up. It >> looks like it will do the trick. >> >> http://pymssql.sourceforge.net/ >> >> Mike >> From alan.gauld at btinternet.com Tue May 22 09:32:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2007 08:32:11 +0100 Subject: [Tutor] creating a buffer object from a file ? References: <465242C4.2060805@tds.net> <24512.1857.qm@web50707.mail.re2.yahoo.com> Message-ID: "Iyer" wrote > How do I go about creating a buffer object from > a file containing binary data ? I have a function > that accepts only buffer objects for it's parameters Can you define what you mean by a buffer object? Python uses duck typing so, unless the function has been badly coded with an explicit type check, it should accept any object that supports the methods used. If you really do need a buffer the docs say: ----- Buffer objects are not directly supported by Python syntax, but can be created by calling the builtin function buffer(). They don't support concatenation or repetition. ----- Which was new to me. But some experimentation with the interpreter shows: ---- class buffer(object) | buffer(object [, offset[, size]]) | | Create a new buffer object which references the given object. | The buffer will reference a slice of the target object from the | start of the object (or at the specified offset). The slice will | extend to the end of the target object (or with the specified size). --- and ---- >>> b = buffer('fredrica', 2,4) >>> b[:] 'edri' ---- So we can see how to create a buffer object. You want to do it with a binary file. You can read the content of a binary file using the struct module. But you need to know what kind of data is in your file. To create a buffer you need a string. So do you want your buffer to process the raw binary bytes as if they were a string? Or do you want to convert the binary data and then convert it again into a string representation? Either is possible but you need to decide which you need. BTW Please don't post new subjects to the list by replying to an existing subject. For those using threaded readers it buries your post insife another thread, in this case 3 levels deep in one about MSSQL! I only just noticed it. Its better to start a fresh message. After all its not exactly difficult to type tutor at python.org in the to line! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eiwot at hotmail.com Tue May 22 10:41:57 2007 From: eiwot at hotmail.com (Eiwot) Date: Tue, 22 May 2007 08:41:57 +0000 Subject: [Tutor] Python Articles Message-ID: Hi all, I found this blog interesting http://pyarticles.blogspot.com .Let's check it out :) _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 From jbrink at npsd.k12.wi.us Tue May 22 15:08:27 2007 From: jbrink at npsd.k12.wi.us (Jessica Brink) Date: Tue, 22 May 2007 08:08:27 -0500 Subject: [Tutor] Rounding to nearest cent Message-ID: <4652A4FB.CB8D.003F.0@npsd.k12.wi.us> How would I round to the nearest cent when doing calculations with dollar amounts? -Jess -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070522/b036e34d/attachment.htm From ethics at gmail.com Tue May 22 15:35:26 2007 From: ethics at gmail.com (Leon Keylin) Date: Tue, 22 May 2007 09:35:26 -0400 Subject: [Tutor] Tutor Digest, Vol 39, Issue 57 In-Reply-To: References: Message-ID: Hi John, Here's the code (I do have permissions to truncate, works manually under the same user. import pymssql con = pymssql.connect (host='server',user='user',password='pwd',database='DB_QA') cur = con.cursor() query="truncate TABLE bbConsolidatedMessageAcks" cur.execute(query) print "Deleted Records: %d" % cur.rowcount On Monday 21 May 2007 16:21, Leon Keylin wrote: > Thanks Mike, unfortunately that's the mod I had problems with before. The > one that > can't do truncate. I've written about it before here and it was easier to > look for > another solution. > > Is there any other way? Should I be looking for a different language to do > it in? > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Leon Keylin > > Sent: Monday, May 21, 2007 3:52 PM > > To: tutor at python.org > > Subject: [Tutor] MS SQL Connection > > > > Been trying to do a very small and simple select via Python. > > First I tried a module that looked clean but it couldn't > > truncate tables. > > > > Then I started sifting through docs at python.org and > > couldn't find a simple > > way of communicating with a MS SQL via Python program. > > > > Do I have to use ODBC? > > > > Any examples would be awesome. Thanks! > > I did a quick search on Google for MS SQL Python, and this came up. It > looks like it will do the trick. > > http://pymssql.sourceforge.net/ > > Mike >Mike I just tried it and it worked using pymssql-0.8.0. Could you post the >code you are using to truncate? Also is it possible you don't have > permission to truncate? > John Fabiani On Monday 21 May 2007 16:21, Leon Keylin wrote: > Thanks Mike, unfortunately that's the mod I had problems with before. The > one that > can't do truncate. I've written about it before here and it was easier to > look for > another solution. > > Is there any other way? Should I be looking for a different language to do > it in? > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Leon Keylin > > Sent: Monday, May 21, 2007 3:52 PM > > To: tutor at python.org > > Subject: [Tutor] MS SQL Connection > > > > Been trying to do a very small and simple select via Python. > > First I tried a module that looked clean but it couldn't > > truncate tables. > > > > Then I started sifting through docs at python.org and > > couldn't find a simple > > way of communicating with a MS SQL via Python program. > > > > Do I have to use ODBC? > > > > Any examples would be awesome. Thanks! > > I did a quick search on Google for MS SQL Python, and this came up. It > looks like it will do the trick. > > http://pymssql.sourceforge.net/ > > Mike Mike I just tried it and it worked using pymssql-0.8.0. Could you post the code you are using to truncate? Also is it possible you don't have permission to truncate? -- John Fabiani -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070522/983fcb18/attachment.html From broek at cc.umanitoba.ca Tue May 22 15:40:04 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 22 May 2007 09:40:04 -0400 Subject: [Tutor] Rounding to nearest cent In-Reply-To: <4652A4FB.CB8D.003F.0@npsd.k12.wi.us> References: <4652A4FB.CB8D.003F.0@npsd.k12.wi.us> Message-ID: <4652F2B4.3050607@cc.umanitoba.ca> Jessica Brink said unto the world upon 05/22/2007 09:08 AM: > How would I round to the nearest cent when doing calculations with dollar amounts? > > -Jess > Hi Jess, The decimal module was introduced in large part to facilitate financial calculations. Have a look at and see if you can get what you need from the docs. If not, ask for more help. Best, Brian vdB From jfabiani at yolo.com Tue May 22 16:19:15 2007 From: jfabiani at yolo.com (johnf) Date: Tue, 22 May 2007 07:19:15 -0700 Subject: [Tutor] MSSQL Connection In-Reply-To: References: Message-ID: <200705220719.15809.jfabiani@yolo.com> On Tuesday 22 May 2007 06:35, Leon Keylin wrote: > Hi John, > > Here's the code (I do have permissions to truncate, works manually under > the same user. > > > import pymssql > > con = pymssql.connect > (host='server',user='user',password='pwd',database='DB_QA') > cur = con.cursor() > > > query="truncate TABLE bbConsolidatedMessageAcks" > cur.execute(query) > print "Deleted Records: %d" % cur.rowcount > I see from the other postings that you are running windows. I am on SUSE 10.2 using FreeTDS and pymssql. In my case my "cur.execute" is passed to FreeTDS and FreeTDS is what really interfaces with the SQL server. I'm also running a patch from www.dabodev.com but I doubt that would stop you from passing the truncate. Are you using pymssql-0.8.0.win32-py2.5.exe and ODBC ? Can you see the trace provided by MS SQL? -- John Fabiani From jsmith at medplus.com Tue May 22 17:13:33 2007 From: jsmith at medplus.com (Smith, Jeff) Date: Tue, 22 May 2007 11:13:33 -0400 Subject: [Tutor] SMS to Python Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A0201A70147@EXCHMAIL01.corp.medplus.com> I would like to be able to send an SMS message from my phone which is then picked up by a Python script and acted on. I'm fairly proficient in Python and networking, but don't know much about SMS messaging. Where's the best place to start? Thanks, Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070522/92c88a85/attachment.htm From alan.gauld at btinternet.com Tue May 22 18:44:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2007 17:44:27 +0100 Subject: [Tutor] SMS to Python References: <288A3B43F7B2224D9C8441C9FC5D6A0201A70147@EXCHMAIL01.corp.medplus.com> Message-ID: "Smith, Jeff" wrote i > don't know much about SMS messaging. > Where's the best place to start? There are some web sites that you could acvcess via Python. Or there is BT's Web21C SDK which includes the ability to do SMS and is available in Python: http://sdk.bt.com It's free but you have to register. And I think there are usage limits. But it might help. Disclaimer: I work for BT. But I'm not involved with the SDK! :-) Alan G. From alan.gauld at btinternet.com Tue May 22 18:49:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2007 17:49:17 +0100 Subject: [Tutor] SMS to Python References: <288A3B43F7B2224D9C8441C9FC5D6A0201A70147@EXCHMAIL01.corp.medplus.com> Message-ID: "Smith, Jeff" wrote FWIW. Here's the BT SDK sample SMS code... from datetime import datetime import sys import btsdk def send_sms(sender, messageText, recipients): server = btsdk.services.Messaging() resp = server.sendMessage(recipients, sender, sender, messageText) return resp if __name__ == "__main__": if len(sys.argv) < 2: print "Usage %s sender recipient" % sys.argv[0] sys.exit(-1) messageText = "The time is %s." % datetime.now().strftime("%Y-%m-%dT%H:%M:%S") print sys.argv[1:] send_sms(sys.argv[1], messageText, sys.argv[2:]) HTHAlan G. From agilfoy at frontiernet.net Tue May 22 19:10:30 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Tue, 22 May 2007 17:10:30 +0000 Subject: [Tutor] Starting with wxPython Message-ID: <20070522171030.1208czw2x52c48og@webmail.frontiernet.net> I'm not quite there yet, but I want to get into using GUIs in Python soon, and I plan to use wxPython to do so. What, do you think, is the best tutorial out there for wxPython? Also, what happens when you code for some GUI feature and run the script in your IDE, such as IDLE? Will the graphical features properly appear? From andreas at kostyrka.org Tue May 22 19:10:58 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 22 May 2007 19:10:58 +0200 Subject: [Tutor] SMS to Python In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A0201A70147@EXCHMAIL01.corp.medplus.com> References: <288A3B43F7B2224D9C8441C9FC5D6A0201A70147@EXCHMAIL01.corp.medplus.com> Message-ID: <46532422.1090101@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Well, how do plan to receive the SMS? The range is from special contracts with mobile carriers, over using some webservice, to using a GSM module (a special "mobile" designed not to be mobile *g*), or just some mobile via datacable, ... So what are your requirements? But anyway, that is not really a Python question, it's a mobile messaging question :) Andreas Smith, Jeff wrote: > I would like to be able to send an SMS message from my phone which is > then picked up by a Python script and acted on. I'm fairly proficient > in Python and networking, but don't know much about SMS messaging. > Where's the best place to start? > > Thanks, > Jeff > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGUyQiHJdudm4KnO0RAm2lAJ4tptIVGtZ5ZA0PUucN0zeOlhQBaACdEjxk lOgo8Dg+eyO8L3nlwHZ8lj4= =rFbT -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Tue May 22 19:25:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2007 18:25:02 +0100 Subject: [Tutor] Starting with wxPython References: <20070522171030.1208czw2x52c48og@webmail.frontiernet.net> Message-ID: "Alan Gilfoy" wrote > soon, and I plan to use wxPython to do so. What, do you think, is > the > best tutorial out there for wxPython? I'm working through the new wxPython book and highly recommend it. It's one of the best GUI books I've read - and I've read a few in my time! And given the iffy standard of the online wxPython documentation I'd also recommend it as a reference. > Also, what happens when you code for some GUI feature and run the > script in your IDE, such as IDLE? Will the graphical features > properly > appear? IMHO The best thing is to use PyCrust (part of wxPython) instead of IDLE or Pythonwin. Its fully integrated and gives a very good interactive prompt too. The book gives instructions on how to run your app from within pyCrust so you can use PyCrust to inspect values etc while the app is running. Its powerful stuff. (In fact I'm now using PyCrust as my standard shell. Or use PyAlaMode as an IDE. Features the PyCrust shell and tabbed edit windows. The Py toolset is found in {PYTHON}\Lib\site-packages\wx-2.8-msw-ansi\wx\py HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue May 22 20:13:46 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 22 May 2007 18:13:46 +0000 (GMT) Subject: [Tutor] Starting with wxPython Message-ID: <641164.93488.qm@web86113.mail.ird.yahoo.com> > Could you please give the title and author of that book. Oops, sorry. Its "wxPython in Action", published by Manning. Authors: Noel Rappin, Robin Dunn Dunn is of course the author of wxPython. Alan G ___________________________________________________________ Yahoo! Mail is the world's favourite email. Don't settle for less, sign up for your free account today http://uk.rd.yahoo.com/evt=44106/*http://uk.docs.yahoo.com/mail/winter07.html From wescpy at gmail.com Tue May 22 20:26:19 2007 From: wescpy at gmail.com (wesley chun) Date: Tue, 22 May 2007 11:26:19 -0700 Subject: [Tutor] SMS to Python In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A0201A70147@EXCHMAIL01.corp.medplus.com> References: <288A3B43F7B2224D9C8441C9FC5D6A0201A70147@EXCHMAIL01.corp.medplus.com> Message-ID: <78b3a9580705221126r5c999029s6bf418bafa8ab79b@mail.gmail.com> > I would like to be able to send an SMS message from my phone which is then > picked up by a Python script and acted on. I'm fairly proficient in Python > and networking, but don't know much about SMS messaging. Where's the best > place to start? it depends on your application. at my current job here in the US, we deal with mBlox (http://www.mblox.com) who connects our app to carriers which then exchanges SMS/txt msgs with phones. they provide us an API (java SDK or XML) -- we use the latter plus ElementTree -- and you just call theirs directly to send msgs to phones (MTs). we also provide them an API so they can call our app for incoming msgs (MOs). the bottom line is that you need some sort of interface with carriers in order to communicate to/from phones with. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From minyie at hotmail.com Tue May 22 20:39:19 2007 From: minyie at hotmail.com (Antonio Diaz) Date: Tue, 22 May 2007 18:39:19 +0000 Subject: [Tutor] Glade + python dialogs Message-ID: hello, i have a problem, i created a main window on Glade. now second i created a dialog window.how do i use the input data on the dialog to affect things on the main window?class edit rotate is the problem. :( oh btw i am using PIL library, sometimes img object doesnt want to change. oh i almost forgot to the person that responded me some time ago i asked about making a basic image editing program thank you :) sorry for the time it took haven't checked my email :P# -*- coding: utf-8 -*-import gtkimport gtk.gladeimport Imageimport ImageDrawimport osclass wndBase: "Clase base para manejar todas las ventanas, contiene las caracter?icas principales" windowname = '' def __init__(self): "Constructor base de las ventanas" #Obtiene el nombre de la ventana del nombre de la clase que se est?tilizando self.windowname = str(self.__class__).split(".")[1] if self.windowname: self.wTree = gtk.glade.XML("proyecto1.glade", self.windowname) self.win = self.wTree.get_widget(self.windowname) self.wTree.signal_autoconnect(self) self.win.connect("destroy", self.destroy) self.post_init() def init(self): "Funci?irtual que debe ser sobreescrita para especificar los valores de arranque del formulario" pass def post_init(self): "Funci?ue se ejecuta luego de haber creado el formulario base y conectado las se?s" pass def show(self): "Llama al m?do show del widget correspondiente a la ventana" if self.win: self.win.show() def hide(self): if self.win: self.win.hide() def set_modal(self, bool = False): self.win.set_modal(bool) def destroy(self, *args): self.win.destroy() def set_parent(self, parent): "Establece la clase padre y la ventana padre para el objeto actual" if parent: self.parent = parent self.win.set_transient_for(parent.win) def maximize(self, *args): self.win.maximize() def set_modal(self, bool = False): self.win.set_modal(bool)class Main(wndBase): def destroy(self, *args): gtk.main_quit() def on_button_open_activate(self, widget, *args): def respuesta(widget, response): if response == gtk.RESPONSE_OK: self.archivo = widget.get_filename() archivo_temporal = "/tmp/" + os.path.basename(self.archivo) self.img=Image.open(self.archivo) self.img.save(archivo_temporal) self.wTree.get_widget('imagen_principal').set_from_file(archivo_temporal) widget.destroy() else: widget.destroy() abrir = gtk.FileSelection() abrir.connect("response", respuesta) abrir.run() def on_rotate_activate(self, widget, *args): window_rotate=edit_rotate() def on_button_font_clicked(self, widget, *args): font_vent=fontselectiondialog1() font_vent.show() class fontselectiondialog1(wndBase): passclass edit_rotate(wndBase): def my_response(self, widget, respuesta): if respuesta == gtk.RESPONSE_OK: #print self.wTree.get_widget("entry_rotate").get_text() rotate_value=int(self.wTree.get_widget("entry_rotate").get_text()) archivo_temporal = "/tmp/" + os.path.basename(Main.archivo) print archivo_temporal self.img=Image.open(archivo_temporal) self.img.rotate(rotate_value) self.img.save(archivo_temporal) self.wTree.get_widget('imagen_principal').set_from_file(archivo_temporal) widget.destroy() else: widget.destroy() ventana1=Main()ventana1.maximize()ventana1.show()gtk.main() _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070522/d5a45ca1/attachment.htm From alan.gauld at btinternet.com Tue May 22 21:58:50 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2007 20:58:50 +0100 Subject: [Tutor] Glade + python dialogs References: Message-ID: "Antonio Diaz" wrote > hello, i have a problem, i created a main window on Glade. You might get better results asking on the wxPython mailing list. There could well be Glade experts here but its more by luck than good reason, tutor is really aimed at learning Python itself. Also it would help if you can avoid HTML email, I know that's not always possible but the mess below is barely decipherable in my version of Outlook Express... Alan G. # -*- coding: utf-8 -*-import gtkimport gtk.gladeimport Imageimport ImageDrawimport osclass wndBase: "Clase base para manejar todas las ventanas, contiene las caracter?icas principales" windowname = '' def __init__(self): "Constructor base de las ventanas" #Obtiene el nombre de la ventana del nombre de la clase que se est?tilizando self.windowname = str(self.__class__).split(".")[1] if self.windowname: self.wTree = gtk.glade.XML("proyecto1.glade", self.windowname) self.win = self.wTree.get_widget(self.windowname) self.wTree.signal_autoconnect(self) self.win.connect("destroy", self.destroy) self.post_init() def init(self): "Funci?irtual que debe ser sobreescrita para especificar los valores de arranque del formulario" pass def post_init(self): "Funci?ue se ejecuta luego de haber creado el formulario base y conectado las se?s" pass def show(self): "Llama al m?do show del widget correspondiente a la ventana" if self.win: self.win.show() def hide(self): if self.win: self.win.hide() def set_modal(self, bool = False): self.win.set_modal(bool) def destroy(self, *args): self.win.destroy() def set_parent(self, parent): "Establece la clase padre y la ventana padre para el objeto actual" if parent: self.parent = parent self.win.set_transient_for(parent.win) def maximize(self, *args): self.win.maximize() def set_modal(self, bool = False): self.win.set_modal(bool)class Main(wndBase): def destroy(self, *args): gtk.main_quit() def on_button_open_activate(self, widget, *args): def respuesta(widget, response): if response == gtk.RESPONSE_OK: self.archivo = widget.get_filename() archivo_temporal = "/tmp/" + os.path.basename(self.archivo) self.img=Image.open(self.archivo) self.img.save(archivo_temporal) self.wTree.get_widget('imagen_principal').set_from_file(archivo_temporal) widget.destroy() else: widget.destroy() abrir = gtk.FileSelection() abrir.connect("response", respuesta) abrir.run() def on_rotate_activate(self, widget, *args): window_rotate=edit_rotate() def on_button_font_clicked(self, widget, *args): font_vent=fontselectiondialog1() font_vent.show() class fontselectiondialog1(wndBase): passclass edit_rotate(wndBase): def my_response(self, widget, respuesta): if respuesta == gtk.RESPONSE_OK: #print self.wTree.get_widget("entry_rotate").get_text() rotate_value=int(self.wTree.get_widget("entry_rotate").get_text()) archivo_temporal = "/tmp/" + os.path.basename(Main.archivo) print archivo_temporal self.img=Image.open(archivo_temporal) self.img.rotate(rotate_value) self.img.save(archivo_temporal) self.wTree.get_widget('imagen_principal').set_from_file(archivo_temporal) widget.destroy() else: widget.destroy() ventana1=Main()ventana1.maximize()ventana1.show()gtk.main() > _________________________________________________________________ > Create the ultimate e-mail address book. Import your contacts to > Windows Live Hotmail. > www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From minyie at hotmail.com Tue May 22 22:36:16 2007 From: minyie at hotmail.com (Antonio Diaz) Date: Tue, 22 May 2007 20:36:16 +0000 Subject: [Tutor] sending data between classes Message-ID: oh ok :)but how do i manage to use a variable on one class in another? exclass main () :.....def on_rotate_activate(self, widget, *args): window_rotate=edit_rotate() print window_rotate.value......class edit_rotate(wndBase): def my_response(self, widget, respuesta): if respuesta == gtk.RESPONSE_OK: #print self.wTree.get_widget("entry_rotate").get_text() value=int(self.wTree.get_widget("entry_rotate").get_text() else: widget.destroy()that doesnt work for me :S i want to show the value of "value" in the main class _________________________________________________________________ Add some color. Personalize your inbox with your favorite colors. www.windowslive-hotmail.com/learnmore/personalize.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_addcolor_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070522/1f86c86d/attachment.htm From bill at celestial.net Tue May 22 23:38:46 2007 From: bill at celestial.net (Bill Campbell) Date: Tue, 22 May 2007 14:38:46 -0700 Subject: [Tutor] Behaviour of dictionaries and others when deleting? In-Reply-To: <4652449F.7080708@tds.net> References: <20070522000213.GA13493@ayn.mi.celestial.com> <4652449F.7080708@tds.net> Message-ID: <20070522213846.GA5469@ayn.mi.celestial.com> On Mon, May 21, 2007, Kent Johnson wrote: >Bill Campbell wrote: >> Is the behaviour defined if one is processing a dictionary using >> iteritems, and delete items? >> >> for k, v in d.iteritems(): >> if somecondition(k, v): del d[k] >> >> Would this process all the original members of the dictionary? > >This is not well-defined. You can use > for k, v in d.items(): > >which creates a new list to hold the items and iterates that. Thanks for the feeback Kent. It confirms my thoughts. Using the 2nd method, d.items(), can be an issue with very large dictionaries (although I tend use the Berkeley databases for these when dealing with very large data sets). >> I've always been leary of deleting items while processing things >> like this, keeping a list of keys to be deleted, then processing >> that list upon completion of the mail loop to delete the items >> from the original dictionary or database file. > >I don't know about bsddb but for lists and dicts that is the right >approach. You can also use a list comprehension to filter a list or dict. The places where I'm really concerned with this is dealing with large databases, say a few million records with info on all data storage on a server. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software, LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 If you think health care is expensive now, wait until you see what it coses when it's free -- P.J. O'Rourke From ps_python at yahoo.com Tue May 22 23:42:42 2007 From: ps_python at yahoo.com (kumar s) Date: Tue, 22 May 2007 14:42:42 -0700 (PDT) Subject: [Tutor] please help formating Message-ID: <5524.31872.qm@web35801.mail.mud.yahoo.com> hi group, i have a data obtained from other student(over 100K) lines that looks like this: (39577484, 39577692) [['NM_003750']] (107906, 108011) [['NM_002443']] (113426, 113750) [['NM_138634', 'NM_002443']] (106886, 106991) [['NM_138634', 'NM_002443']] (100708, 100742) [['NM_138634', 'NM_002443']] (35055935, 35056061) [['NM_002313', 'NM_001003407', 'NM_001003408']] I know that first two items in () are tuples, and the next [[]] a list of list. I was told that the tuples were keys and the list was its value in a dictionary. how can I parse this into a neat structure that looks like this: 39577484, 39577692 \t NM_003750 107906, 108011 \t NM_002443 113426, 113750 \t NM_138634,NM_002443 106886, 106991 \t NM_138634,NM_002443 100708, 100742 \t NM_138634,NM_002443 35055935, 35056061 \t NM_002313,NM_001003407,NM_001003408 I treid substituting in vim editor but it is not effective. Thank you kum ____________________________________________________________________________________Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ From andreas at kostyrka.org Tue May 22 23:53:42 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 22 May 2007 23:53:42 +0200 Subject: [Tutor] please help formating In-Reply-To: <5524.31872.qm@web35801.mail.mud.yahoo.com> References: <5524.31872.qm@web35801.mail.mud.yahoo.com> Message-ID: <46536666.8030809@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Why does my "homework-alert" ring with this post? Andreas kumar s wrote: > hi group, > > i have a data obtained from other student(over 100K) > lines that looks like this: > (39577484, 39577692) [['NM_003750']] > (107906, 108011) [['NM_002443']] > (113426, 113750) [['NM_138634', 'NM_002443']] > (106886, 106991) [['NM_138634', 'NM_002443']] > (100708, 100742) [['NM_138634', 'NM_002443']] > (35055935, 35056061) [['NM_002313', 'NM_001003407', > 'NM_001003408']] > > I know that first two items in () are tuples, and the > next [[]] a list of list. I was told that the tuples > were keys and the list was its value in a dictionary. > > how can I parse this into a neat structure that looks > like this: > 39577484, 39577692 \t NM_003750 > 107906, 108011 \t NM_002443 > 113426, 113750 \t NM_138634,NM_002443 > 106886, 106991 \t NM_138634,NM_002443 > 100708, 100742 \t NM_138634,NM_002443 > 35055935, 35056061 \t > NM_002313,NM_001003407,NM_001003408 > > > I treid substituting in vim editor but it is not > effective. > > Thank you > > kum > > > > ____________________________________________________________________________________Pinpoint customers who are looking for what you sell. > http://searchmarketing.yahoo.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGU2ZmHJdudm4KnO0RAnIgAJ4oHRPSfYFId7C7TzeWYXPobf9l+QCg34Ja bRtlufQ7K/TKPsLOOBNEmJI= =QeIu -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Wed May 23 00:26:12 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2007 23:26:12 +0100 Subject: [Tutor] sending data between classes References: Message-ID: "Antonio Diaz" wrote in message news:BAY144-W1848572F28691C44257747D0360 at phx.gbl... oh ok :)but how do i manage to use a variable on one class in another? exclass main () :.....def on_rotate_activate(self, widget, *args): window_rotate=edit_rotate() print window_rotate.value......class edit_rotate(wndBase): def my_response(self, widget, respuesta): if respuesta == gtk.RESPONSE_OK: #print self.wTree.get_widget("entry_rotate").get_text() value=int(self.wTree.get_widget("entry_rotate").get_text() else: widget.destroy()that doesnt work for me :S i want to show the value of "value" in the main class So create a showValue method in main that has a widget as a parameter and displays the value on that widget. If value is an attribite of main then its mains responsibility to display it. Or if main is a model class then create a view that pairs with it to display the attribute. But its not clear what your objects are - they look more like functions. Alan G. From janos.juhasz at VELUX.com Wed May 23 08:07:35 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 23 May 2007 08:07:35 +0200 Subject: [Tutor] MSSQL Connection In-Reply-To: Message-ID: Hi Leon, > > Hi John, > > > > Here's the code (I do have permissions to truncate, works manually under > > the same user. > > > > > > import pymssql > > > > con = pymssql.connect > > (host='server',user='user',password='pwd',database='DB_QA') > > cur = con.cursor() > > > > > > query="truncate TABLE bbConsolidatedMessageAcks" > > cur.execute(query) > > print "Deleted Records: %d" % cur.rowcount > > I use two alternatives to connect to mssql server. ADODB connection via win32com.client ------------------ import win32com.client cn =win32com.client.Dispatch('ADODB.connection') cn.Provider='sqloledb' cn.Open('Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=production;Data Source=036fefersqls001') # The argument of cn.Open(), the connection string can be created very easy on windows. # Create a conn.udl on your desktop # Open it with double click, and build a new connection string, test it, save it # Copy and paste from your .udl stockcode = '100701-06' sql = "select * from stocks where stock = '%s'" % stockcode print sql rs = win32com.client.Dispatch('ADODB.recordset') rs.Open(sql, cn) print rs.Fields[0].Value rs.Close() cn.Close() ----------------- But I usually use ODBC with this kind of class. import dbi, odbc class myDB: def __init__(self): """Open a new connection.""" self.cn = odbc.odbc('DSN=myDB;UID=query;PWD=query;DATABASE=myDB') def closeDB(self): """Close the connection.""" self.cn.close() def Execute(self, sql): cr = self.cn.cursor() cr.execute(sql) cr.close() def Query(self, sql): try: cr = self.cn.cursor() cr.execute(sql) self.colnames = [field_prop[0] for field_prop in cr.description] self.result = cr.fetchall() self.rownum = len(self.result) return self.result except: self.colnames = [None] self.result = [[None]] self.rownum = 0 return [[None]] test = myDB() print(test.Query('Select * from testtable') ) Best regards, Janos From ethics at gmail.com Wed May 23 17:48:49 2007 From: ethics at gmail.com (Leon Keylin) Date: Wed, 23 May 2007 11:48:49 -0400 Subject: [Tutor] Tutor Digest, Vol 39, Issue 60 In-Reply-To: References: Message-ID: Janos, I tried the ODBC way and it worked! I was about to give up and do it in C# or some other language but I love Python so much I wanted it to work. Thank you SO MUCH! And thanks to all of you who helped as well! You folks are the best. > > Message: 6 > Date: Wed, 23 May 2007 08:07:35 +0200 > From: J?nos Juh?sz > Subject: Re: [Tutor] MSSQL Connection > To: tutor at python.org > Message-ID: > < > OFD30D5C16.F0DCE181-ONC12572E4.001F1BB3-C12572E4.0021A6AC at velux.com> > Content-Type: text/plain; charset="US-ASCII" > > Hi Leon, > > > > > Hi John, > > > > > > Here's the code (I do have permissions to truncate, works manually > under > > > the same user. > > > > > > > > > import pymssql > > > > > > con = pymssql.connect > > > (host='server',user='user',password='pwd',database='DB_QA') > > > cur = con.cursor() > > > > > > > > > query="truncate TABLE bbConsolidatedMessageAcks" > > > cur.execute(query) > > > print "Deleted Records: %d" % cur.rowcount > > > > > I use two alternatives to connect to mssql server. > > ADODB connection via win32com.client > ------------------ > import win32com.client > > cn =win32com.client.Dispatch('ADODB.connection') > cn.Provider='sqloledb' > cn.Open('Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security > Info=False;Initial Catalog=production;Data Source=036fefersqls001') > # The argument of cn.Open(), the connection string can be created very > easy on windows. > # Create a conn.udl on your desktop > # Open it with double click, and build a new connection string, test it, > save it > # Copy and paste from your .udl > > stockcode = '100701-06' > sql = "select * from stocks where stock = '%s'" % stockcode > > print sql > rs = win32com.client.Dispatch('ADODB.recordset') > rs.Open(sql, cn) > print rs.Fields[0].Value > rs.Close() > > cn.Close() > ----------------- > > But I usually use ODBC with this kind of class. > > import dbi, odbc > > class myDB: > def __init__(self): > """Open a new connection.""" > self.cn = > odbc.odbc('DSN=myDB;UID=query;PWD=query;DATABASE=myDB') > > def closeDB(self): > """Close the connection.""" > self.cn.close() > > def Execute(self, sql): > cr = self.cn.cursor() > cr.execute(sql) > cr.close() > > def Query(self, sql): > try: > cr = self.cn.cursor() > cr.execute(sql) > self.colnames = [field_prop[0] for field_prop in > cr.description] > self.result = cr.fetchall() > self.rownum = len(self.result) > return self.result > except: > self.colnames = [None] > self.result = [[None]] > self.rownum = 0 > return [[None]] > > test = myDB() > print(test.Query('Select * from testtable') ) > > > Best regards, > Janos > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 39, Issue 60 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/ccfae532/attachment.html From maseriyer at yahoo.com Wed May 23 17:50:10 2007 From: maseriyer at yahoo.com (Iyer) Date: Wed, 23 May 2007 08:50:10 -0700 (PDT) Subject: [Tutor] creating a buffer object from a file ? In-Reply-To: Message-ID: <932708.54250.qm@web50704.mail.re2.yahoo.com> thanks, alan for your helpful response. in reality what is a buffer object used for ? reading a file itself creates a string as in itself, file_handle = file ("path_to_file") file_data = file_handle.read() # file_data is a string, so why is a buffer object is needed ? the data in the binary file is just raw binary. I apologize for replying to the existing subject. Thanks for letting me know. I shall make sure this doesn't happen again. thanks iyer --- Alan Gauld wrote: > "Iyer" wrote > > > How do I go about creating a buffer object from > > a file containing binary data ? I have a function > > that accepts only buffer objects for it's > parameters > > Can you define what you mean by a buffer object? > Python uses duck typing so, unless the function has > been badly coded with an explicit type check, it > should accept any object that supports the methods > used. > > If you really do need a buffer the docs say: > > ----- > Buffer objects are not directly supported by Python > syntax, but can be created by calling the builtin > function buffer(). They don't support concatenation > or repetition. > ----- > > Which was new to me. But some experimentation > with the interpreter shows: > ---- > class buffer(object) > | buffer(object [, offset[, size]]) > | > | Create a new buffer object which references the > given object. > | The buffer will reference a slice of the target > object from the > | start of the object (or at the specified > offset). The slice will > | extend to the end of the target object (or with > the specified > size). > --- > and > ---- > >>> b = buffer('fredrica', 2,4) > >>> b[:] > 'edri' > ---- > > So we can see how to create a buffer object. > You want to do it with a binary file. You can read > the content > of a binary file using the struct module. But you > need to know > what kind of data is in your file. To create a > buffer you need > a string. So do you want your buffer to process the > raw binary > bytes as if they were a string? Or do you want to > convert the > binary data and then convert it again into a string > representation? > > Either is possible but you need to decide which you > need. > > BTW Please don't post new subjects to the list by > replying > to an existing subject. For those using threaded > readers it > buries your post insife another thread, in this case > 3 levels > deep in one about MSSQL! I only just noticed it. Its > better > to start a fresh message. After all its not exactly > difficult to > type tutor at python.org in the to line! :-) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From adamurbas at hotmail.com Wed May 23 17:57:24 2007 From: adamurbas at hotmail.com (adam urbas) Date: Wed, 23 May 2007 10:57:24 -0500 Subject: [Tutor] trouble with "if" Message-ID: Hi all,I've been working with this new program that I wrote. I started out with it on a Ti-83, which is much easier to program than python. Now I'm trying to transfer the program to python but its proving to be quite difficult. I'm not sure what the whole indentation thing is for. And now I'm having trouble with the if statement things. #"Circle Data Calculation Program:"print "Welcome to the Circle Data Calcuation Program."print #"Menu 1:"print "Pick a shape:"print "(NOTE: You must select the number of the shape and not the shape itself)"print "1 Circle"print "2 Square"print "3 Triangle" #"User's Choice:"shape=raw_input("> ") #"Select Given:"if shape == 1: print "Choose the given value:" print "1 radius" print "2 diameter" print "3 circumference" print "4 area"#"User's Choice:"given=raw_input("> ")if given == 1: radius=raw_input("Enter Radius:") diameter=(radius*2) circumference=(diameter*3.14) area=(radius**2*3.14) print "Diameter:", diameter print "Circumference:", circumference print "Area:", areaif given == 2: diameter=raw_input("Enter Diameter:") radius=(diameter/2) circumference=(diameter*3.14) area=(radius**2*3.14) print "Radius:", radius print "Circumference:", circumference print "Area:", areaif given == 3: circumference=raw_input("Enter Circumference:") radius=(circumference/3.14/2) diameter=(radius*2) area=(radius**2*3.14) print "Radius:", radius print "Diameter:", diameter print "Area:", areaif given == 4: area=raw_input("Enter Area:") radius=(area/3.14) This is the whole program so far, because I haven't quite finished it yet. But I tried to get it to display another list of options after you select a shape but it just does this.Pick a shape:1 Circle2 Square3 Triangle>1>1>>>I'm not sure why it does that but I do know that it is skipping the second list of options.Another of my problems is that I can't figure out how to get it to accept two different inputs for a selection. Like I want it to accept both the number 1 and circle as circle then list the options for circle. It won't even accept words. I can only get it to accept numbers. It's quite frustrating actually.Any advice would be greatly appreciated.Thanks in advance,AdamI tried to get it to display ano _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/71bd7de4/attachment.htm From andreengels at gmail.com Wed May 23 18:08:20 2007 From: andreengels at gmail.com (Andre Engels) Date: Wed, 23 May 2007 18:08:20 +0200 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <6faf39c90705230908x3ceebe3bhf9667e022ced13b8@mail.gmail.com> The problem is with types. The outcome of raw_input is a string. But if you give the line: if shape == 1: you are comparing it with a number. The text "1" is not equal to the number 1, so this evaluates to False. Instead you should do: if shape == "1": To also be able to type 'circle' instead of '1', you can do: if shape == "1" or shape == "circle": or alternatively: if shape in ["1","circle"]: Andre Engels 2007/5/23, adam urbas : > > Hi all, > > I've been working with this new program that I wrote. I started out with it > on a Ti-83, which is much easier to program than python. Now I'm trying to > transfer the program to python but its proving to be quite difficult. I'm > not sure what the whole indentation thing is for. And now I'm having > trouble with the if statement things. > > #"Circle Data Calculation Program:" > print "Welcome to the Circle Data Calcuation Program." > print > > #"Menu 1:" > print "Pick a shape:" > print "(NOTE: You must select the number of the shape and not the shape > itself)" > print "1 Circle" > print "2 Square" > print "3 Triangle" > > #"User's Choice:" > shape=raw_input("> ") > > #"Select Given:" > if shape == 1: > print "Choose the given value:" > print "1 radius" > print "2 diameter" > print "3 circumference" > print "4 area" > > #"User's Choice:" > given=raw_input("> ") > > if given == 1: > radius=raw_input("Enter Radius:") > diameter=(radius*2) > circumference=(diameter*3.14) > area=(radius**2*3.14) > print "Diameter:", diameter > print "Circumference:", circumference > print "Area:", area > > if given == 2: > diameter=raw_input("Enter Diameter:") > radius=(diameter/2) > circumference=(diameter*3.14) > area=(radius**2*3.14) > print "Radius:", radius > print "Circumference:", circumference > print "Area:", area > > if given == 3: > circumference=raw_input("Enter Circumference:") > radius=(circumference/3.14/2) > diameter=(radius*2) > area=(radius**2*3.14) > print "Radius:", radius > print "Diameter:", diameter > print "Area:", area > > if given == 4: > area=raw_input("Enter Area:") > radius=(area/3.14) > > This is the whole program so far, because I haven't quite finished it yet. > But I tried to get it to display another list of options after you select a > shape but it just does this. > > Pick a shape: > 1 Circle > 2 Square > 3 Triangle > >1 > >1 > >>> > > I'm not sure why it does that but I do know that it is skipping the second > list of options. > > Another of my problems is that I can't figure out how to get it to accept > two different inputs for a selection. Like I want it to accept both the > number 1 and circle as circle then list the options for circle. It won't > even accept words. I can only get it to accept numbers. It's quite > frustrating actually. > > Any advice would be greatly appreciated. > Thanks in advance, > Adam > > > > > > I tried to get it to display ano > > ________________________________ > Add some color. Personalize your inbox with your favorite colors. Try it! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From broek at cc.umanitoba.ca Wed May 23 18:12:16 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 23 May 2007 12:12:16 -0400 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <465467E0.5080609@cc.umanitoba.ca> adam urbas said unto the world upon 05/23/2007 11:57 AM: > > Hi all, > > I've been working with this new program that I wrote. I started out > with it on a Ti-83, which is much easier to program than python. Now > I'm trying to transfer the program to python but its proving to be quite > difficult. I'm not sure what the whole indentation thing is for. And > now I'm having trouble with the if statement things. > > #"Circle Data Calculation Program:" > print "Welcome to the Circle Data Calcuation Program." > print > > #"Menu 1:" > print "Pick a shape:" > print "(NOTE: You must select the number of the shape and not the shape > itself)" > print "1 Circle" > print "2 Square" > print "3 Triangle" > > #"User's Choice:" > shape=raw_input("> ") > > #"Select Given:" > if shape == 1: > print "Choose the given value:" > print "1 radius" > print "2 diameter" > print "3 circumference" > print "4 area" > > #"User's Choice:" > given=raw_input("> ") > > if given == 1: > radius=raw_input("Enter Radius:") > diameter=(radius*2) > circumference=(diameter*3.14) > area=(radius**2*3.14) > print "Diameter:", diameter > print "Circumference:", circumference > print "Area:", area > > if given == 2: > diameter=raw_input("Enter Diameter:") > radius=(diameter/2) > circumference=(diameter*3.14) > area=(radius**2*3.14) > print "Radius:", radius > print "Circumference:", circumference > print "Area:", area > > if given == 3: > circumference=raw_input("Enter Circumference:") > radius=(circumference/3.14/2) > diameter=(radius*2) > area=(radius**2*3.14) > print "Radius:", radius > print "Diameter:", diameter > print "Area:", area > > if given == 4: > area=raw_input("Enter Area:") > radius=(area/3.14) > > This is the whole program so far, because I haven't quite finished it > yet. But I tried to get it to display another list of options after you > select a shape but it just does this. > > Pick a shape: > 1 Circle > 2 Square > 3 Triangle > >1 > >1 > >>> > > I'm not sure why it does that but I do know that it is skipping the > second list of options. > > Another of my problems is that I can't figure out how to get it to > accept two different inputs for a selection. Like I want it to accept > both the number 1 and circle as circle then list the options for > circle. It won't even accept words. I can only get it to accept > numbers. It's quite frustrating actually. > > Any advice would be greatly appreciated. > Thanks in advance, > Adam > > Adam, Could you send plain text email rather than html, please? At least for me, your code's indentation is all messed up unless I take some steps to rectify it. The problem is that raw_input returns a string, and you are testing whether given is equal to integers. See if this helps make things clear: >>> data = raw_input('Feed me!') Feed me!42 >>> type(data) >>> data == 42 False >>> int(data) == 42 True >>> Best, Brian vdB From eric at ericwalstad.com Wed May 23 18:14:53 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 23 May 2007 09:14:53 -0700 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <4654687D.3040709@ericwalstad.com> adam urbas wrote: > Hi all, > > I've been working with this new program that I wrote. ... > #"User's Choice:" > shape=raw_input("> ") > > #"Select Given:" > if shape == 1: ... ewalstad at uluwatu:~$ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> shape = raw_input('>') >1 >>> type(shape) >>> shape == 1 False >>> HTH, Eric. From adamurbas at hotmail.com Wed May 23 18:26:23 2007 From: adamurbas at hotmail.com (adam urbas) Date: Wed, 23 May 2007 11:26:23 -0500 Subject: [Tutor] two input acceptions Message-ID: Sorry, Hotmail doesn't have a turn of HTML feature or if it does, I couldn't find it. I think I'm just going to take your word for it that raw_input is better because I find the entire concept quite confusing. I tried typing in your example in IDLE and it didn't do anything, except:>>>>>>And then it told me that it didn't know what the >>("LOL") was. It really disliked the >> bit. I understand the concept though, I think. I have been using the raw_input though. If I change it from var=raw_input()>>("LOL")to var=raw_input("LOL")then it displays>>>LOL>>>Not sure what that means, but yeah. Well thanks anyway.Adam> Date: Sat, 19 May 2007 01:47:51 +0100> From: finalyugi at sapo.pt> To: adamurbas at hotmail.com; tutor at python.org> Subject: Re: [Tutor] two input acceptions> > adam urbas escreveu:> > Thanks for the help. I've made quite some progress since I first posted this email. I have a question though, what did you mean when you were talking about the raw_input( )? How can the regular input( ) be used evilly? If you could explain in depth, I would be very grateful. I have a new question related to my program area.py., I guess it's the same one as before. When I run the program and input the rectangle option, it asks me for a radius, unless I input 1, instead of rectangle. How do I program it to accept both 1 and rectangle?> Date: Sat, 12 May 2007 18:55:20 +0100> From: finalyugi at sapo.pt> To: adamurbas at hotmail.com> CC: tutor at python.org> Subject: Re: [Tutor] (no subject)> > adam urbas escreveu:> > Hi,I just started python today and I would like a few pointers, if you don't mind. I tried using a tutorial, but was only able to get the correct results for the most basic problems. # Area calculation programprint ?Welcome to the Area calculation program?print ???> ????????????print# Print out the menu:print ?Please select a shape:?print ?1 Rectangle?print ?2 Circle?# Get the user?s choice:shape = input(?> ?)# Calculate the area:if shape == 1: height = input(?Please enter the height: ?) width = input(?Please enter the width: ?) area = height*width print ?The area is?, areaelse: radius = input(?Please enter the radius: ?) area = 3.14*(radius**2) print ?The area is?, areaI've been trying to get this to work. I was on a forum on Google and they said to put:input("press ENTER to continue")at the end. I did, but it didn't work. It runs the program but just shuts itself off when its done and i don't even get to select any of the option things that i'm s> upposed to be able to select. It just turns on then back off and I don't even get to see anything. Could someone help me out.ThanksAdam> > _________________________________________________________________> > Create the ultimate e-mail address book. Import your cont> acts to Windows Live Hotmail.> > www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507> > > > > > ------------------------------------------------------------------------> > > > _______________________________________________> > Tutor maillist - Tutor at python.org> > http://mail.python.org/mailman/listinfo/tutor> > First, welcome to the world of Python. :D> Second. please give a title when you start a new thread on a mailing list.> Third, format your posts and code. Since Python uses indented code, it's > kinda hard to read it when it's all in one line (Don't worry, I'll paste > it indented in a file attached to this email :D )> > Now for the code.> > After arranging the code, the first thing I noticed were this characters ? ?> > I tried running the code, and if gave me a error there, so I just > replace then with " ", and voil?, the code worked :D . So the lesson > here is always use either " " or ' ' in the code.> > Oh, a> lso another thing. Don't use input() to get the user input, because > that command can run code and it may be evilly used. Always use > raw_input() instead :D .> > Anyway, I hope I helped you,> > > -- > _> ASCII ribbon campaign ( )> - against HTML email X> & vCards / \> > _________________________________________________________________> > Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail.> > www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507> > First of all, what email client are you using?> Because the text is getting all weird and difficult to read (it's all in > one line, with no paragraphs and things like that).> > Now, the thing about input() and why it's not a good policy to use is > that, unlike raw_input(), what type in a input() is executed by Python > (in raw_input() is stored as a string).> > Example:> > var = raw_input()> >> list("LOL")> > Now we have a variable called var which contains the string that says > 'list("LOL")'> You can confirm that by typing:> print var> >> 'list("LOL")> > There, no harm done. Now let's try the same thing using the input() command:> > var = input()> >> list("LOL")> > Now let's type "print var" again as we did before.> > print var> >> ['L', 'O'. 'L']> > Now what happened? Because you used the input() command, what you type > was interpreted by Python, instead of being stored in a string and since > the list() command is used to create a list, Python did just that. He > created a list. Now, in this example, no harm was done. But image > someone typing the command os.system("command to delete some file or run > some file"). That would send a delete command to the terminal, or > install some file (it could even be a virus).> > Ok, it's a little harder to explain, but the thing you should is that > usually raw_input() = GOOD, input() = BAD.> > > > > Now, I couldn't quite understand the second problem.> Please explain a little better.> > PS: Now I know why I see all posts messed up. It's because you're > sending your emails as a HTML, and I deactivated that on my email > client. I don't know if Hotmail (I believe you send you emails from > there) as an option to turn off HTML. If it was please use it :D> (Besides being nice, you can get more responses if you do that. Not > everyone has an HTML capable email client.)> > PS2 (no, not the console): I just noticed you didn't send the email back > to the mailing list. You should select reply to all (or a similar > option) when replying to mailing list, so that other people can learn too.> > > > -- > _> ASCII ribbon campaign ( )> - against HTML email X> & vCards / \ _________________________________________________________________ Change is good. See what?s different about Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_changegood_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/6042a68d/attachment.html From adamurbas at hotmail.com Wed May 23 18:33:29 2007 From: adamurbas at hotmail.com (adam urbas) Date: Wed, 23 May 2007 11:33:29 -0500 Subject: [Tutor] two input acceptions Message-ID: I figured out why it was asking for the radius of a square. It was because I had the if shape==1: thing on there. I was typing in rectangle and that was an else: function. How do i get it to accept both 1 and circle? I learned not to use else: unless I was completely sure that I could use it, to avoid problems like this.I put both the .py and .txt files on there, so which ever you prefer.Thanks,Adam> To: tutor at python.org> From: alan.gauld at btinternet.com> Date: Sat, 19 May 2007 08:28:19 +0100> Subject: Re: [Tutor] two input acceptions> > > "Rolando Pereira" wrote> > what did you mean when you were talking about the raw_input( )? > > How can the regular input( ) be used evilly? > > raw_input() is the preferred way to read input from a user.> It only reads the raw input as typed by the user so it always > returns a string which you then need to convert to another > type (like an int) if you need to. This gives you more controil > over what kind of data your program receives.> > input() by contrast reads the string input by the user and tries > to evaluate it as a Python expression. Thus if the user typed> > import os;os.system('format c:\')> > Python would try to evaluate that as a python string > and it could format your C drive. (In practice it would > throw up a prompt and hopefully you would say no!)> It might not be something as obvious as that, it > could simply deactivate your firewall, or add a new > user account to your PC, anything that enables a > subsequent attack to do more damage.> > The attack might not be deliberate, sometimes > accidentally typed errors can result in code being > executed that you didn't want.> > But thats why input() is best used in very strictly > controlled environments - like at the >>> prompt when > you are testing/developing code. But use raw_input plus > a conversion function for finished code.> > > When I run the program and input the rectangle option, > > it asks me for a radius, > > Your code is unreadable and I don't have the time > or inclination to try to unpick it. Can you send as plain > text or as an attachment please?> > Alan G> > _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/e28fae72/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: area.py Url: http://mail.python.org/pipermail/tutor/attachments/20070523/e28fae72/attachment.asc -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: area.txt Url: http://mail.python.org/pipermail/tutor/attachments/20070523/e28fae72/attachment-0001.txt From adamurbas at hotmail.com Wed May 23 18:46:32 2007 From: adamurbas at hotmail.com (adam urbas) Date: Wed, 23 May 2007 11:46:32 -0500 Subject: [Tutor] trouble with "if" Message-ID: Thanks Andre. That solved most of the problems. Now all the lists will run correctly, but when I input a radius, it says:can't multiply sequence by non-int of type 'float'When it displays that, it is talking about circumference=(radius*2*3.14). I'm guessing it doesn't want me to multiply by pi. PLEASE HELP!!!thanks in advance,Adam> Date: Wed, 23 May 2007 18:08:20 +0200> From: andreengels at gmail.com> To: adamurbas at hotmail.com> Subject: Re: [Tutor] trouble with "if"> CC: tutor at python.org> > The problem is with types. The outcome of raw_input is a string. But> if you give the line:> > if shape == 1:> > you are comparing it with a number. The text "1" is not equal to the> number 1, so this evaluates to False.> > Instead you should do:> > if shape == "1":> > To also be able to type 'circle' instead of '1', you can do:> > if shape == "1" or shape == "circle":> > or alternatively:> > if shape in ["1","circle"]:> > > > Andre Engels> > 2007/5/23, adam urbas :> >> > Hi all,> >> > I've been working with this new program that I wrote. I started out with it> > on a Ti-83, which is much easier to program than python. Now I'm trying to> > transfer the program to python but its proving to be quite difficult. I'm> > not sure what the whole indentation thing is for. And now I'm having> > trouble with the if statement things.> >> > #"Circle Data Calculation Program:"> > print "Welcome to the Circle Data Calcuation Program."> > print> >> > #"Menu 1:"> > print "Pick a shape:"> > print "(NOTE: You must select the number of the shape and not the shape> > itself)"> > print "1 Circle"> > print "2 Square"> > print "3 Triangle"> >> > #"User's Choice:"> > shape=raw_input("> ")> >> > #"Select Given:"> > if shape == 1:> > print "Choose the given value:"> > print "1 radius"> > print "2 diameter"> > print "3 circumference"> > print "4 area"> >> > #"User's Choice:"> > given=raw_input("> ")> >> > if given == 1:> > radius=raw_input("Enter Radius:")> > diameter=(radius*2)> > circumference=(diameter*3.14)> > area=(radius**2*3.14)> > print "Diameter:", diameter> > print "Circumference:", circumference> > print "Area:", area> >> > if given == 2:> > diameter=raw_input("Enter Diameter:")> > radius=(diameter/2)> > circumference=(diameter*3.14)> > area=(radius**2*3.14)> > print "Radius:", radius> > print "Circumference:", circumference> > print "Area:", area> >> > if given == 3:> > circumference=raw_input("Enter Circumference:")> > radius=(circumference/3.14/2)> > diameter=(radius*2)> > area=(radius**2*3.14)> > print "Radius:", radius> > print "Diameter:", diameter> > print "Area:", area> >> > if given == 4:> > area=raw_input("Enter Area:")> > radius=(area/3.14)> >> > This is the whole program so far, because I haven't quite finished it yet.> > But I tried to get it to display another list of options after you select a> > shape but it just does this.> >> > Pick a shape:> > 1 Circle> > 2 Square> > 3 Triangle> > >1> > >1> > >>>> >> > I'm not sure why it does that but I do know that it is skipping the second> > list of options.> >> > Another of my problems is that I can't figure out how to get it to accept> > two different inputs for a selection. Like I want it to accept both the> > number 1 and circle as circle then list the options for circle. It won't> > even accept words. I can only get it to accept numbers. It's quite> > frustrating actually.> >> > Any advice would be greatly appreciated.> > Thanks in advance,> > Adam> >> >> >> >> >> > I tried to get it to display ano> >> > ________________________________> > Add some color. Personalize your inbox with your favorite colors. Try it!> > _______________________________________________> > Tutor maillist - Tutor at python.org> > http://mail.python.org/mailman/listinfo/tutor> >> >> > > -- > Andre Engels, andreengels at gmail.com> ICQ: 6260644 -- Skype: a_engels _________________________________________________________________ Add some color. Personalize your inbox with your favorite colors. www.windowslive-hotmail.com/learnmore/personalize.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_addcolor_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/9352e0f2/attachment.html From adamurbas at hotmail.com Wed May 23 18:48:45 2007 From: adamurbas at hotmail.com (adam urbas) Date: Wed, 23 May 2007 11:48:45 -0500 Subject: [Tutor] trouble with "if" Message-ID: Sorry, I forgot to attach the files. Don't critique too much. If you find a mistake in the program, then I probably haven't gotten that far, since it isn't complete yet. I'm pretty much on the editing phase now.> Date: Wed, 23 May 2007 18:08:20 +0200> From: andreengels at gmail.com> To: adamurbas at hotmail.com> Subject: Re: [Tutor] trouble with "if"> CC: tutor at python.org> > The problem is with types. The outcome of raw_input is a string. But> if you give the line:> > if shape == 1:> > you are comparing it with a number. The text "1" is not equal to the> number 1, so this evaluates to False.> > Instead you should do:> > if shape == "1":> > To also be able to type 'circle' instead of '1', you can do:> > if shape == "1" or shape == "circle":> > or alternatively:> > if shape in ["1","circle"]:> > > > Andre Engels> > 2007/5/23, adam urbas :> >> > Hi all,> >> > I've been working with this new program that I wrote. I started out with it> > on a Ti-83, which is much easier to program than python. Now I'm trying to> > transfer the program to python but its proving to be quite difficult. I'm> > not sure what the whole indentation thing is for. And now I'm having> > trouble with the if statement things.> >> > #"Circle Data Calculation Program:"> > print "Welcome to the Circle Data Calcuation Program."> > print> >> > #"Menu 1:"> > print "Pick a shape:"> > print "(NOTE: You must select the number of the shape and not the shape> > itself)"> > print "1 Circle"> > print "2 Square"> > print "3 Triangle"> >> > #"User's Choice:"> > shape=raw_input("> ")> >> > #"Select Given:"> > if shape == 1:> > print "Choose the given value:"> > print "1 radius"> > print "2 diameter"> > print "3 circumference"> > print "4 area"> >> > #"User's Choice:"> > given=raw_input("> ")> >> > if given == 1:> > radius=raw_input("Enter Radius:")> > diameter=(radius*2)> > circumference=(diameter*3.14)> > area=(radius**2*3.14)> > print "Diameter:", diameter> > print "Circumference:", circumference> > print "Area:", area> >> > if given == 2:> > diameter=raw_input("Enter Diameter:")> > radius=(diameter/2)> > circumference=(diameter*3.14)> > area=(radius**2*3.14)> > print "Radius:", radius> > print "Circumference:", circumference> > print "Area:", area> >> > if given == 3:> > circumference=raw_input("Enter Circumference:")> > radius=(circumference/3.14/2)> > diameter=(radius*2)> > area=(radius**2*3.14)> > print "Radius:", radius> > print "Diameter:", diameter> > print "Area:", area> >> > if given == 4:> > area=raw_input("Enter Area:")> > radius=(area/3.14)> >> > This is the whole program so far, because I haven't quite finished it yet.> > But I tried to get it to display another list of options after you select a> > shape but it just does this.> >> > Pick a shape:> > 1 Circle> > 2 Square> > 3 Triangle> > >1> > >1> > >>>> >> > I'm not sure why it does that but I do know that it is skipping the second> > list of options.> >> > Another of my problems is that I can't figure out how to get it to accept> > two different inputs for a selection. Like I want it to accept both the> > number 1 and circle as circle then list the options for circle. It won't> > even accept words. I can only get it to accept numbers. It's quite> > frustrating actually.> >> > Any advice would be greatly appreciated.> > Thanks in advance,> > Adam> >> >> >> >> >> > I tried to get it to display ano> >> > ________________________________> > Add some color. Personalize your inbox with your favorite colors. Try it!> > _______________________________________________> > Tutor maillist - Tutor at python.org> > http://mail.python.org/mailman/listinfo/tutor> >> >> > > -- > Andre Engels, andreengels at gmail.com> ICQ: 6260644 -- Skype: a_engels _________________________________________________________________ Add some color. Personalize your inbox with your favorite colors. www.windowslive-hotmail.com/learnmore/personalize.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_addcolor_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/7614fea0/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: radiacir.py Url: http://mail.python.org/pipermail/tutor/attachments/20070523/7614fea0/attachment.asc From tms43 at clearwire.net Wed May 23 19:00:34 2007 From: tms43 at clearwire.net (Teresa Stanton) Date: Wed, 23 May 2007 10:00:34 -0700 Subject: [Tutor] tkinter arrow event location Message-ID: <001901c79d5b$e4b59a40$ae20cec0$@net> Using a mouse I could use event.x to find the current location of the mouse. But if I have a canvas with a gif and I need the current location of the gif, could I bind the gif to an arrow event to get the feedback of where the gif is at any given time? If so, can someone show me how? T From adamurbas at hotmail.com Wed May 23 19:04:10 2007 From: adamurbas at hotmail.com (adam urbas) Date: Wed, 23 May 2007 12:04:10 -0500 Subject: [Tutor] trouble with "if" Message-ID: Sorry, I don't think Hotmail has turn off HTML. If it does I havn't been able to find it. I think you're going to have to explain your little bit of text stuff down there at the bottom. I have no idea what most of that means. All my choice things are working now though. I think that is what you were trying to help me with. What I used wasif shape in["1","circle"]:and if shape == "1" or shape =="circle":It works perfectly fine now.Ya that little bit o' code is really puzzling. I wish I knew more about this python deal. I understand the concept, but not the rules or the techniques and things of that sort. OK... I've got it... the data=raw_input('Feed Me!'). Ok I now understand that bit. Then it says Feed Me! and you put 42 (the ultimate answer to life the universe, everything). OK, it won't accept the bit. it doesn't like the "<". Well, I just removed that bit and it said:Feed Me! and I put 42, and it said >>> (I guess it's satisfied now, with the whole feeding). Well if I understood what 'str' meant, then I could probably figure the rest out. Well I have to go do other things so I'll save the rest of this figuring out till later.I shall return,Adam> Date: Wed, 23 May 2007 12:12:16 -0400> From: broek at cc.umanitoba.ca> To: adamurbas at hotmail.com> CC: tutor at python.org> Subject: Re: [Tutor] trouble with "if"> > adam urbas said unto the world upon 05/23/2007 11:57 AM:> > > > Hi all,> > > > I've been working with this new program that I wrote. I started out > > with it on a Ti-83, which is much easier to program than python. Now > > I'm trying to transfer the program to python but its proving to be quite > > difficult. I'm not sure what the whole indentation thing is for. And > > now I'm having trouble with the if statement things. > > > > #"Circle Data Calculation Program:"> > print "Welcome to the Circle Data Calcuation Program."> > print> > > > #"Menu 1:"> > print "Pick a shape:"> > print "(NOTE: You must select the number of the shape and not the shape > > itself)"> > print "1 Circle"> > print "2 Square"> > print "3 Triangle"> > > > #"User's Choice:"> > shape=raw_input("> ")> > > > #"Select Given:"> > if shape == 1:> > print "Choose the given value:"> > print "1 radius"> > print "2 diameter"> > print "3 circumference"> > print "4 area"> > > > #"User's Choice:"> > given=raw_input("> ")> > > > if given == 1:> > radius=raw_input("Enter Radius:")> > diameter=(radius*2)> > circumference=(diameter*3.14)> > area=(radius**2*3.14)> > print "Diameter:", diameter> > print "Circumference:", circumference> > print "Area:", area> > > > if given == 2:> > diameter=raw_input("Enter Diameter:")> > radius=(diameter/2)> > circumference=(diameter*3.14)> > area=(radius**2*3.14)> > print "Radius:", radius> > print "Circumference:", circumference> > print "Area:", area> > > > if given == 3:> > circumference=raw_input("Enter Circumference:")> > radius=(circumference/3.14/2)> > diameter=(radius*2)> > area=(radius**2*3.14)> > print "Radius:", radius> > print "Diameter:", diameter> > print "Area:", area> > > > if given == 4:> > area=raw_input("Enter Area:")> > radius=(area/3.14)> > > > This is the whole program so far, because I haven't quite finished it > > yet. But I tried to get it to display another list of options after you > > select a shape but it just does this.> > > > Pick a shape:> > 1 Circle> > 2 Square> > 3 Triangle> > >1> > >1> > >>>> > > > I'm not sure why it does that but I do know that it is skipping the > > second list of options.> > > > Another of my problems is that I can't figure out how to get it to > > accept two different inputs for a selection. Like I want it to accept > > both the number 1 and circle as circle then list the options for > > circle. It won't even accept words. I can only get it to accept > > numbers. It's quite frustrating actually.> > > > Any advice would be greatly appreciated.> > Thanks in advance,> > Adam> > > > > > > Adam,> > Could you send plain text email rather than html, please? At least for > me, your code's indentation is all messed up unless I take some steps > to rectify it.> > The problem is that raw_input returns a string, and you are testing > whether given is equal to integers. See if this helps make things clear:> > >>> data = raw_input('Feed me!')> Feed me!42> >>> type(data)> > >>> data == 42> False> >>> int(data) == 42> True> >>>> > Best,> > Brian vdB _________________________________________________________________ Change is good. See what?s different about Windows Live Hotmail. http://www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=RMT_TAGLM_HMWL_reten_changegood_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/c42b07e3/attachment.htm From broek at cc.umanitoba.ca Wed May 23 19:40:09 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 23 May 2007 13:40:09 -0400 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <46547C79.1080605@cc.umanitoba.ca> adam urbas said unto the world upon 05/23/2007 01:04 PM: > Sorry, I don't think Hotmail has turn off HTML. If it does I > havn't been able to find it. I think you're going to have to > explain your little bit of text stuff down there at the bottom. I > have no idea what most of that means. All my choice things are > working now though. I think that is what you were trying to help > me with. What I used wasif shape in["1","circle"]:and if shape == > "1" or shape =="circle":It works perfectly fine now.Ya that little > bit o' code is really puzzling. I wish I knew more about this > python deal. I understand the concept, but not the rules or the > techniques and things of that sort. OK... I've got it... the > data=raw_input('Feed Me!'). Ok I now understand that bit. Then it > says Feed Me! and you put 42 (the ultimate answer to life the > universe, everything). OK, it won't accept the bit. > it doesn't like the "<". Well, I just removed that bit and it > said:Feed Me! and I put 42, and it said >>> (I guess it's > satisfied now, with the whole feeding). Well if I understood what > 'str' meant, then I could probably figure the rest out. Well I > have to go do other things so I'll save the rest of this figuring > out till later.I shall return,Adam> Date: Wed, 23 May 2007 12:12:16 > -0400> From: broek at cc.umanitoba.ca> To: adamurbas at hotmail.com> CC: > tutor at python.org> Subject: Re: [Tutor] trouble with "if"> > adam > urbas said unto the world upon 05/23/2007 11:57 AM:> > > > Hi all,> > > > > I've been working with this new program that I wrote. I > started out > > with it on a Ti-83, which is much easier to program > than python. Now > > I'm trying to transfer the program to python > but its proving to be quite > > difficult. I'm not sure what the > whole indentation thing is for. And > > now I'm having trouble > with the if statement things. > > > > #"Circle Data Calculation > Program:"> > print "Welcome to the Circle Data Calcuation > Program."> > print> > > > #"Menu 1:"> > print "Pick a shape:"> > > print "(NOTE: You must select the number of the shape and not the > shape > > itself)"> > print "1 Circle"> > print "2 Square"> > print > "3 Triangle"> > > > #"User's Choice:"> > shape=raw_input("> ")> > > > > #"Select Given:"> > if shape == 1:> > print > "Choose the given value:"> > print "1 radius"> > > print "2 diameter"> > print "3 circumference"> > > print "4 area"> > > > #"User's Choice:"> > given=raw_input("> ")> > > > > if given == 1:> > radius=raw_input("Enter Radius:")> > > diameter=(radius*2)> > circumference=(diameter*3.14)> > > area=(radius**2*3.14)> > print "Diameter:", diameter> > > print "Circumference:", circumference> > print "Area:", > area> > > > if given == 2:> > diameter=raw_input("Enter > Diameter:")> > radius=(diameter/2)> > > circumference=(diameter*3.14)> > area=(radius**2*3.14)> > > print "Radius:", radius> > print "Circumference:", > circumference> > print "Area:", area> > > > if given == 3:> > > circumference=raw_input("Enter Circumference:")> > > radius=(circumference/3.14/2)> > diameter=(radius*2)> > > area=(radius**2*3.14)> > print "Radius:", radius> > > print "Diameter:", diameter> > print "Area:", area> > > > > if given == 4:> > area=raw_input("Enter Area:")> > > radius=(area/3.14)> > > > This is the whole program so > far, because I haven't quite finished it > > yet. But I tried to > get it to display another list of options after you > > select a > shape but it just does this.> > > > Pick a shape:> > 1 Circle> > 2 > Square> > 3 Triangle> > >1> > >1> > >>>> > > > I'm not sure why > it does that but I do know that it is skipping the > > second list > of options.> > > > Another of my problems is that I can't figure > out how to get it to > > accept two different inputs for a > selection. Like I want it to accept > > both the number 1 and > circle as circle then list the options for > > circle. It won't > even accept words. I can only get it to accept > > numbers. It's > quite frustrating actually.> > > > Any advice would be greatly > appreciated.> > Thanks in advance,> > Adam> > > > > > > Adam,> > > Could you send plain text email rather than html, please? At least > for > me, your code's indentation is all messed up unless I take > some steps > to rectify it.> > The problem is that raw_input > returns a string, and you are testing > whether given is equal to > integers. See if this helps make things clear:> > >>> data = > raw_input('Feed me!')> Feed me!42> >>> type(data)> > > >>> data == 42> False> >>> int(data) == 42> True> >>>> > Best,> > > Brian vdB Adam, As you can see from the above, the way hotmail is formatting things makes the conversation a bit tricky :-) I'm only willing to spend so much time trying to sort through it, so I hope what follows helps. >>> data = raw_input("Feed me!") Feed me!42 This calls the builtin function raw_input with a parameter setting the prompt to "Feed me!" and assigns the result to data. Since I hit 42 and then enter, >>> data '42' Notice the quotes around 42. They indicate that the value of data is a string. That's what this tells us: >>> type(data) The string '42' is not the same as the integer 42: >>> type(42) >>> '42' == 42 False So, when you had an if test that was something like: if given == 1: # Do stuff here the equality comparison was never going to work---given was a string returned by raw_input and no string is ever equal to an integer. What I suggested was taking the string returned by raw_input and feeding it to int() to transform it from a string to an integer, and allow your if test to stand a chance: >>> data = raw_input("Feed me!") Feed me!42 >>> if data == 42: ... print "Matches!" ... >>> data = int(raw_input("Feed me!")) Feed me!42 >>> if data == 42: ... print "Matches!" ... Matches! >>> There are other ways, for instance: >>> data = raw_input("Feed me!") Feed me!42 >>> if data == '42': ... print "Matches!" ... Matches! >>> Here, instead of transforming data to an int and then testing for equality with 42, I left data as a string and tested for equality with the string '42'. The way calling int() is a bit better, I think. If the user enters a few spaces, then 42 then a few more spaces, that way will still work: >>> data = int(raw_input("Feed me!")) Feed me! 42 >>> if data == 42: ... print "Matches!" ... Matches! >>> because >>> int(' 42 ') 42 >>> whereas >>> ' 42 ' == '42' False I hope there is some help in there somewhere :-) Brian vdB From eric at ericwalstad.com Wed May 23 19:42:53 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 23 May 2007 10:42:53 -0700 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <46547D1D.9050900@ericwalstad.com> Hi Adam, adam urbas wrote: > when I input a radius, it says: > > can't multiply sequence by non-int of type 'float' ... > > radius=raw_input("Enter Radius:") > > diameter=(radius*2) After you collect the raw_input for the radius, the radius variable contains a string, not a number (that's what '' means). Python is calling the string a sequence in your error message. Try converting your radius to a float type first: radius=float(raw_input("Enter Radius:")) As side notes: those '>>>' characters in previous responses are what the python interactive terminal displays as its command prompt. The 'type()' function tells you the data type of a variable. Here's an example of using the Python interactive terminal to debug your issue (give it a try yourself, but don't enter the '>>>' in the terminal): ewalstad at sawarna:~$ python Python 2.5.1 (r251:54863, May 3 2007, 12:27:48) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> radius=raw_input("Enter Radius:") Enter Radius:5 >>> radius '5' >>> type(radius) >>> diameter=(radius*2) >>> diameter '55' # That is, it is giving you the string '5', two times >>> type(diameter) >>> >>> >>> radius=float(raw_input("Enter Radius:")) Enter Radius:5 >>> radius # radius now contains a float type 5.0 >>> type(radius) >>> diameter=(radius*2) >>> diameter 10.0 >>> type(diameter) >>> From simplebob at gmail.com Wed May 23 21:49:21 2007 From: simplebob at gmail.com (Daniel McQuay) Date: Wed, 23 May 2007 15:49:21 -0400 Subject: [Tutor] smtplib howto send with a subject line Message-ID: <6d87ecf40705231249u9181084nfde92863701fd5d0@mail.gmail.com> Hey Guys, I'm having a problem with my script that sends out an email using smtplib. Whats happening now is when it is send I get a (no subject) where the subject line should be. I checked a few places such as effbot and some other online doc but couldn't find any thing about the subject line. Any help would be much appreciated. ################################### #Created by: Daniel McQuay #This script will send and email #to verify if the backup was #successful or not. ################################### import smtplib import sys emmssg = "/tmp/backup.log" smtpserver = 'localhost' AUTHREQUIRED = 0 smtpuser = '' smtppass = '' #Recipients who will be getting the emails RECIPIENTS = ['simplebob at gmail.com'] SENDER = 'Saint_Richards' #This does not work? SUBJECT = 'Backup_Log' emmssg = open('/tmp/backup.log','r').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, SUBJECT, emmssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr Thanks in advance, -- Daniel McQuay Jaluno.com H: 814.825.0847 M: 814-341-9013 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/312df417/attachment.htm From Mike.Hansen at atmel.com Wed May 23 22:14:35 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 23 May 2007 14:14:35 -0600 Subject: [Tutor] smtplib howto send with a subject line In-Reply-To: <6d87ecf40705231249u9181084nfde92863701fd5d0@mail.gmail.com> References: <6d87ecf40705231249u9181084nfde92863701fd5d0@mail.gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E7D4FAB@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Daniel McQuay > Sent: Wednesday, May 23, 2007 1:49 PM > To: tutor at python.org > Subject: [Tutor] smtplib howto send with a subject line > > Hey Guys, I'm having a problem with my script that sends out > an email using smtplib. Whats happening now is when it is > send I get a (no subject) where the subject line should be. I > checked a few places such as effbot and some other online doc > but couldn't find any thing about the subject line. > > Any help would be much appreciated. > > ################################### > #Created by: Daniel McQuay > #This script will send and email > #to verify if the backup was > #successful or not. > ################################### > > import smtplib > import sys > > emmssg = "/tmp/backup.log" > smtpserver = 'localhost' > AUTHREQUIRED = 0 > smtpuser = '' > smtppass = '' > > #Recipients who will be getting the emails > RECIPIENTS = ['simplebob at gmail.com'] > > SENDER = 'Saint_Richards' > > #This does not work? > SUBJECT = 'Backup_Log' > > emmssg = open('/tmp/backup.log','r').read() > > session = smtplib.SMTP(smtpserver) > if AUTHREQUIRED: > session.login(smtpuser, smtppass) > smtpresult = session.sendmail(SENDER, RECIPIENTS, SUBJECT, emmssg) > > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > Thanks in advance, > > -- > Daniel McQuay > Jaluno.com > H: 814.825.0847 > M: 814-341-9013 > It seems a little easier to use the email module along with the smtp module to create and send a message. http://docs.python.org/lib/node162.html Mike From simplebob at gmail.com Wed May 23 23:52:28 2007 From: simplebob at gmail.com (Daniel McQuay) Date: Wed, 23 May 2007 17:52:28 -0400 Subject: [Tutor] smtplib howto send with a subject line In-Reply-To: <57B026980605A64F9B23484C5659E32E7D4FAB@poccso.US.ad.atmel.com> References: <6d87ecf40705231249u9181084nfde92863701fd5d0@mail.gmail.com> <57B026980605A64F9B23484C5659E32E7D4FAB@poccso.US.ad.atmel.com> Message-ID: <6d87ecf40705231452u3ad2e4e5u9808269c0bb436f2@mail.gmail.com> Thanks Mike, it seems that I'll be easy to incorporate that into my script as well. I'll give it a try. I'm still open to other suggestions, though. On 5/23/07, Mike Hansen wrote: > > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Daniel McQuay > > Sent: Wednesday, May 23, 2007 1:49 PM > > To: tutor at python.org > > Subject: [Tutor] smtplib howto send with a subject line > > > > Hey Guys, I'm having a problem with my script that sends out > > an email using smtplib. Whats happening now is when it is > > send I get a (no subject) where the subject line should be. I > > checked a few places such as effbot and some other online doc > > but couldn't find any thing about the subject line. > > > > Any help would be much appreciated. > > > > ################################### > > #Created by: Daniel McQuay > > #This script will send and email > > #to verify if the backup was > > #successful or not. > > ################################### > > > > import smtplib > > import sys > > > > emmssg = "/tmp/backup.log" > > smtpserver = 'localhost' > > AUTHREQUIRED = 0 > > smtpuser = '' > > smtppass = '' > > > > #Recipients who will be getting the emails > > RECIPIENTS = ['simplebob at gmail.com'] > > > > SENDER = 'Saint_Richards' > > > > #This does not work? > > SUBJECT = 'Backup_Log' > > > > emmssg = open('/tmp/backup.log','r').read() > > > > session = smtplib.SMTP(smtpserver) > > if AUTHREQUIRED: > > session.login(smtpuser, smtppass) > > smtpresult = session.sendmail(SENDER, RECIPIENTS, SUBJECT, emmssg) > > > > if smtpresult: > > errstr = "" > > for recip in smtpresult.keys(): > > errstr = """Could not delivery mail to: %s > > > > Server said: %s > > %s > > > > %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) > > raise smtplib.SMTPException, errstr > > > > Thanks in advance, > > > > -- > > Daniel McQuay > > Jaluno.com > > H: 814.825.0847 > > M: 814-341-9013 > > > > It seems a little easier to use the email module along with the smtp > module to create and send a message. > > http://docs.python.org/lib/node162.html > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Daniel McQuay Linux Jedi Jaluno.com H: 814.825.0847 M: 814-341-9013 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/3974d657/attachment.html From Mike.Hansen at atmel.com Thu May 24 00:06:25 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 23 May 2007 16:06:25 -0600 Subject: [Tutor] smtplib howto send with a subject line In-Reply-To: <6d87ecf40705231452u3ad2e4e5u9808269c0bb436f2@mail.gmail.com> References: <6d87ecf40705231249u9181084nfde92863701fd5d0@mail.gmail.com><57B026980605A64F9B23484C5659E32E7D4FAB@poccso.US.ad.atmel.com> <6d87ecf40705231452u3ad2e4e5u9808269c0bb436f2@mail.gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E7D4FD5@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Daniel McQuay > Sent: Wednesday, May 23, 2007 3:52 PM > Cc: tutor at python.org > Subject: Re: [Tutor] smtplib howto send with a subject line > > Thanks Mike, it seems that I'll be easy to incorporate that > into my script as well. > > I'll give it a try. I'm still open to other suggestions, though. > Take a look at this link again(I think you said you looked at it.) http://effbot.org/librarybook/smtplib.htm Notice that the body string has From:, To:, Subject: followed by the from, to, and subject. body = string.join(( "From: %s" % FROM, "To: %s" % TO, "Subject: %s" % SUBJECT, "", BODY), "\r\n") You might need to do something similar to get your subject line although without the string module since the string methods are built in. I'm no expert on how to construct e-mail messages, so take this with a grain of salt. I'm but a simple caveman programmer(*). Mike * - Phil Hartman "I'm but a simple caveman lawyer" SNL From simplebob at gmail.com Thu May 24 03:39:44 2007 From: simplebob at gmail.com (Daniel McQuay) Date: Wed, 23 May 2007 21:39:44 -0400 Subject: [Tutor] smtplib howto send with a subject line In-Reply-To: <57B026980605A64F9B23484C5659E32E7D4FD5@poccso.US.ad.atmel.com> References: <6d87ecf40705231249u9181084nfde92863701fd5d0@mail.gmail.com> <57B026980605A64F9B23484C5659E32E7D4FAB@poccso.US.ad.atmel.com> <6d87ecf40705231452u3ad2e4e5u9808269c0bb436f2@mail.gmail.com> <57B026980605A64F9B23484C5659E32E7D4FD5@poccso.US.ad.atmel.com> Message-ID: <6d87ecf40705231839h1eb7d84dg7111e05a8c2416f6@mail.gmail.com> Thanks a lot Mike you have been very helpful. I gave that a try in a few different ways but, with the same results. I'm going to try your first example. Best Regards, On 5/23/07, Mike Hansen wrote: > > > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Daniel McQuay > > Sent: Wednesday, May 23, 2007 3:52 PM > > Cc: tutor at python.org > > Subject: Re: [Tutor] smtplib howto send with a subject line > > > > Thanks Mike, it seems that I'll be easy to incorporate that > > into my script as well. > > > > I'll give it a try. I'm still open to other suggestions, though. > > > > Take a look at this link again(I think you said you looked at it.) > > http://effbot.org/librarybook/smtplib.htm > > Notice that the body string has From:, To:, Subject: followed by the > from, to, and subject. > > body = string.join(( > "From: %s" % FROM, > "To: %s" % TO, > "Subject: %s" % SUBJECT, > "", > BODY), "\r\n") > > You might need to do something similar to get your subject line although > without the string module since the string methods are built in. > > I'm no expert on how to construct e-mail messages, so take this with a > grain of salt. I'm but a simple caveman programmer(*). > > Mike > > * - Phil Hartman "I'm but a simple caveman lawyer" SNL > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Daniel McQuay Jaluno.com H: 814.825.0847 M: 814-341-9013 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070523/c278b32b/attachment.html From pine508 at hotmail.com Thu May 24 21:30:34 2007 From: pine508 at hotmail.com (Che M) Date: Thu, 24 May 2007 15:30:34 -0400 Subject: [Tutor] trouble with if Message-ID: >I'm not sure what the whole indentation thing is for. And now I'm having >trouble with the if statement things. Maybe your if statement troubles have been solved by others by now, but I'll just add that "the indentation thing" is a vital feature of Python, it is the way to separate code blocks. Other languages uses other means, like curly braces, etc. I get the sense those who like Python enjoy indentation because it forces the code to be quite readable, and I agree. See this: http://www.diveintopython.org/getting_to_know_python/indenting_code.html Also, as mentioned previously, keep in mind that 2 is not the same as "2" and "=" is not the same as "==". The single "=" is used to assign names to objects, whereas the == is for evaluating something, so for if statements use == and not =. Also note you can put "and" along with if, so you can say if x == "mom" and y == "dad": print "my parents" and lots of other stuff. -Che _________________________________________________________________ PC Magazine?s 2007 editors? choice for best Web mail?award-winning Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_pcmag_0507 From alan.gauld at btinternet.com Fri May 25 00:34:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 May 2007 23:34:05 +0100 Subject: [Tutor] trouble with "if" References: Message-ID: "adam urbas" wrote > It won't even accept words. > I can only get it to accept numbers. try this(untested code!): number = None data = raw_input('Type something: ') try: number = int(data) except: data = data.split() # assume a string if number: # user entered a number if number == 1: print 'circle' elif number == 2: print 'another' else: # user entered words if data[0].lower() == 'circle': print 'circle' else: print 'user entered ', data[0] Notice that to use ithe input as a number you have to convert the raw input characters to a number (using int) To get the individual words we can use split() which by default splits a string into the individual words. Is that the kind of thing you mean? I've no idea what a Ti83 is BTW. :-) Alan G. From alan.gauld at btinternet.com Fri May 25 00:39:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 May 2007 23:39:41 +0100 Subject: [Tutor] trouble with "if" References: Message-ID: Hi adam. With the aid of Google it seems a Ti83 is a programmable calculator. I'm not sure what python tutor you are using but it looks like you need to cover some very basic stuff around data types. You may find the Raw Materials topic in my tutor useful to give you a feel for the different types of data in Python. The Talking to the User topic will cover the use of raw_input. And the Branching topic has an examplre very similar to what you are trying to do. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri May 25 00:42:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 May 2007 23:42:53 +0100 Subject: [Tutor] tkinter arrow event location References: <001901c79d5b$e4b59a40$ae20cec0$@net> Message-ID: "Teresa Stanton" wrote > Using a mouse I could use event.x to find the current location of > the mouse. > But if I have a canvas with a gif and I need the current location of > the > gif, could I bind the gif to an arrow event to get the feedback of > where the > gif is at any given time? If so, can someone show me how? If you mean an arrow key then yes you can trap keystrokes and the event driven programming topic of my tutor shows how to do that in Tkinter. Once you've detected the keys that you want you should be able to ask the canvas where the gif currently is located. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ps_python at yahoo.com Fri May 25 04:31:45 2007 From: ps_python at yahoo.com (kumar s) Date: Thu, 24 May 2007 19:31:45 -0700 (PDT) Subject: [Tutor] dealing with nested list values in a dictionary Message-ID: <922119.62088.qm@web35808.mail.mud.yahoo.com> Dear group, unfortunately my previous post got tagged as 'homework' mail and got no responses. In short, I have a dictionary structure as depicted below. I want to go over every key and print the key,value pairs in a more sensible way. I have written a small piece of code. May I request tutors to go through it and comment if it is correct or prone to bugs. Thank you. kum >>>md = {(21597133, 21597325): [['NM_032457']], (21399193, 21399334): [['NM_032456'], ['NM_002589']], (21397395, 21399192): [['NM_032457'], ['NM_032456'], ['NM_002589']], (21407733, 21408196): [['NM_002589']], (21401577, 21402315): [['NM_032456']], (21819453, 21820111): [['NM_032457']], (21399335, 21401576): [['NM_032457'], ['NM_032456'], ['NM_002589']]} >>> for item in md.keys(): mlst = [] for frnd in md[item]: for srnd in frnd: mlst.append(srnd) mystr = ','.join(mlst) print(('%d\t%d\t%s')%(item[0],item[1],mystr)) 21597133 21597325 NM_032457 21399193 21399334 NM_032456,NM_002589 21397395 21399192 NM_032457,NM_032456,NM_002589 21407733 21408196 NM_002589 21401577 21402315 NM_032456 21819453 21820111 NM_032457 21399335 21401576 NM_032457,NM_032456,NM_002589 ____________________________________________________________________________________Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From kent37 at tds.net Fri May 25 12:35:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 May 2007 06:35:46 -0400 Subject: [Tutor] dealing with nested list values in a dictionary In-Reply-To: <922119.62088.qm@web35808.mail.mud.yahoo.com> References: <922119.62088.qm@web35808.mail.mud.yahoo.com> Message-ID: <4656BC02.2020107@tds.net> kumar s wrote: > Dear group, > > unfortunately my previous post got tagged as > 'homework' mail and got no responses. > > In short, I have a dictionary structure as depicted > below. > > I want to go over every key and print the key,value > pairs in a more sensible way. > > I have written a small piece of code. May I request > tutors to go through it and comment if it is correct > or prone to bugs. > > Thank you. > kum > >>>> md = {(21597133, 21597325): [['NM_032457']], > (21399193, 21399334): [['NM_032456'], ['NM_002589']], > (21397395, 21399192): [['NM_032457'], ['NM_032456'], > ['NM_002589']], > (21407733, 21408196): [['NM_002589']], > (21401577, 21402315): [['NM_032456']], > (21819453, 21820111): [['NM_032457']], > (21399335, 21401576): [['NM_032457'], ['NM_032456'], > ['NM_002589']]} > >>>> for item in md.keys(): > mlst = [] > for frnd in md[item]: > for srnd in frnd: > mlst.append(srnd) > mystr = ','.join(mlst) > print(('%d\t%d\t%s')%(item[0],item[1],mystr)) This is OK but it could be shorter. I usually use dict.items() when I need both the keys and values of a dictionary. The nested lists seem to always have one item in them so maybe you could pull that out directly instead of with a for loop. Then a list comprehension would make the code more concise. So I would write this more this way: for key, value in md.items(): mlst = [ frnd[0] for frnd in value ] mystr = ','.join(mlst) print(('%d\t%d\t%s')%(key[0],key[1],mystr)) This is not more correct, just more concise. Also if you care about the order of the output you could easily sort it using for key, value in sorted(md.items()): Kent > > > 21597133 21597325 NM_032457 > 21399193 21399334 NM_032456,NM_002589 > 21397395 21399192 NM_032457,NM_032456,NM_002589 > 21407733 21408196 NM_002589 > 21401577 21402315 NM_032456 > 21819453 21820111 NM_032457 > 21399335 21401576 NM_032457,NM_032456,NM_002589 > > > ____________________________________________________________________________________Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri May 25 12:45:31 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 May 2007 06:45:31 -0400 Subject: [Tutor] please help formating In-Reply-To: <5524.31872.qm@web35801.mail.mud.yahoo.com> References: <5524.31872.qm@web35801.mail.mud.yahoo.com> Message-ID: <4656BE4B.6050606@tds.net> kumar s wrote: > hi group, > > i have a data obtained from other student(over 100K) > lines that looks like this: > (39577484, 39577692) [['NM_003750']] > (107906, 108011) [['NM_002443']] > (113426, 113750) [['NM_138634', 'NM_002443']] > (106886, 106991) [['NM_138634', 'NM_002443']] > (100708, 100742) [['NM_138634', 'NM_002443']] > (35055935, 35056061) [['NM_002313', 'NM_001003407', > 'NM_001003408']] > > I know that first two items in () are tuples, and the > next [[]] a list of list. I was told that the tuples > were keys and the list was its value in a dictionary. > > how can I parse this into a neat structure that looks > like this: > 39577484, 39577692 \t NM_003750 > 107906, 108011 \t NM_002443 > 113426, 113750 \t NM_138634,NM_002443 > 106886, 106991 \t NM_138634,NM_002443 > 100708, 100742 \t NM_138634,NM_002443 > 35055935, 35056061 \t > NM_002313,NM_001003407,NM_001003408 How about this (assuming the line wrap at the end was done by mail; if it is in the data it is a little harder to parse it): data = '''(39577484, 39577692) [['NM_003750']] (107906, 108011) [['NM_002443']] (113426, 113750) [['NM_138634', 'NM_002443']] (106886, 106991) [['NM_138634', 'NM_002443']] (100708, 100742) [['NM_138634', 'NM_002443']] (35055935, 35056061) [['NM_002313', 'NM_001003407', 'NM_001003408']] '''.splitlines() import re for line in data: match = re.match(r'\((\d*), (\d*)\) \[\[(.*)\]\]', line) if match: t1, t2, data = match.group(1, 2, 3) data = data.replace("'", "").replace(' ', '') print '%s %s\t%s' % (t1, t2, data) else: print 'no match:', line Note the format of the data here is different from what you showed in your post last night... Kent From kent37 at tds.net Fri May 25 13:11:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 May 2007 07:11:00 -0400 Subject: [Tutor] please help formating In-Reply-To: <4656BE4B.6050606@tds.net> References: <5524.31872.qm@web35801.mail.mud.yahoo.com> <4656BE4B.6050606@tds.net> Message-ID: <4656C444.4030106@tds.net> Just for fun, here is a parser written with pyparsing. It treats newlines as whitespace so it will work with the split data you posted. http://pyparsing.wikispaces.com/ data = '''(39577484, 39577692) [['NM_003750']] (107906, 108011) [['NM_002443']] (113426, 113750) [['NM_138634', 'NM_002443']] (106886, 106991) [['NM_138634', 'NM_002443']] (100708, 100742) [['NM_138634', 'NM_002443']] (35055935, 35056061) [['NM_002313', 'NM_001003407', 'NM_001003408']] ''' from pyparsing import * keys = Suppress('(') + Word(nums) + Suppress(',') + Word(nums) + Suppress(')') values = Group(Suppress('[[') + delimitedList(sglQuotedString.setParseAction(removeQuotes)) + Suppress(']]')) expr = keys + values for result, start, end in expr.scanString(data): print '%s %s\t%s' % (result[0], result[1], ','.join(result[2])) Kent From kent37 at tds.net Fri May 25 13:33:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 May 2007 07:33:21 -0400 Subject: [Tutor] Hands-On Python Message-ID: <4656C981.3090207@tds.net> Here is a tutorial I wasn't aware of. It includes videos for some sections and claims that exercises will be coming soon: http://www.cs.luc.edu/~anh/python/hands-on/handsonHtml/handson.html Does anyone know how to get this added to this page? http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From pgreisen at gmail.com Fri May 25 15:47:55 2007 From: pgreisen at gmail.com (Per Jr. Greisen) Date: Fri, 25 May 2007 15:47:55 +0200 Subject: [Tutor] Replacing characters Message-ID: Hi, I am replacing 4 characters with a number and I would like to make the whitespace dynamic so for fx. 1 it uses 3 whitespace and for 10 two and for 100 one etc. I am using the replace() method. Any help or advice appreciated Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070525/3cebaf11/attachment.htm From thorsten at thorstenkampe.de Fri May 25 16:05:36 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 25 May 2007 15:05:36 +0100 Subject: [Tutor] html links References: <857e4c3d0705141927hf3abc09t40ddac1e9f9a79ec@mail.gmail.com> Message-ID: * max . (Mon, 14 May 2007 20:27:15 -0600) > does anyone know of a tutorial for finding links in a web site with python. import formatter, \ htmllib, \ urllib url = 'http://python.org' htmlp = htmllib.HTMLParser(formatter.NullFormatter()) htmlp.feed(urllib.urlopen(url).read()) htmlp.close() print htmlp.anchorlist From kent37 at tds.net Fri May 25 16:20:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 May 2007 10:20:44 -0400 Subject: [Tutor] Replacing characters In-Reply-To: References: Message-ID: <4656F0BC.4030909@tds.net> Per Jr. Greisen wrote: > Hi, > > I am replacing 4 characters with a number and I would like to make the > whitespace dynamic so > for fx. 1 it uses 3 whitespace and for 10 two and for 100 one etc. I am > using the replace() method. I'm not too sure what you want to do but probably str.rjust() or a format string with a width parameter will do what you want: In [16]: nums = [1, 10, 100, 1000] In [17]: for num in nums: ....: print str(num).rjust(4) ....: ....: 1 10 100 1000 In [18]: for num in nums: ....: print '%4d' % num ....: ....: 1 10 100 1000 Details here: http://docs.python.org/lib/string-methods.html http://docs.python.org/lib/typesseq-strings.html Kent From maseriyer at yahoo.com Fri May 25 16:47:45 2007 From: maseriyer at yahoo.com (Iyer) Date: Fri, 25 May 2007 07:47:45 -0700 (PDT) Subject: [Tutor] creating a buffer object from a file ? Message-ID: <123790.88738.qm@web50708.mail.re2.yahoo.com> I think this got lost among the threads: thanks, alan for your helpful response. in reality what is a buffer object used for ? reading a file itself creates a string as in itself, file_handle = file ("path_to_file") file_data = file_handle.read() # file_data is a string, so why is a buffer object is needed ? the data in the binary file is just raw binary. I apologize for replying to the existing subject. Thanks for letting me know. I shall make sure this doesn't happen again. thanks iyer --- Alan Gauld wrote: > "Iyer" wrote > > > How do I go about creating a buffer object from > > a file containing binary data ? I have a function > > that accepts only buffer objects for it's > parameters > > Can you define what you mean by a buffer object? > Python uses duck typing so, unless the function has > been badly coded with an explicit type check, it > should accept any object that supports the methods > used. > > If you really do need a buffer the docs say: > > ----- > Buffer objects are not directly supported by Python > syntax, but can be created by calling the builtin > function buffer(). They don't support concatenation > or repetition. > ----- > > Which was new to me. But some experimentation > with the interpreter shows: > ---- > class buffer(object) > | buffer(object [, offset[, size]]) > | > | Create a new buffer object which references the > given object. > | The buffer will reference a slice of the target > object from the > | start of the object (or at the specified > offset). The slice will > | extend to the end of the target object (or with > the specified > size). > --- > and > ---- > >>> b = buffer('fredrica', 2,4) > >>> b[:] > 'edri' > ---- > > So we can see how to create a buffer object. > You want to do it with a binary file. You can read > the content > of a binary file using the struct module. But you > need to know > what kind of data is in your file. To create a > buffer you need > a string. So do you want your buffer to process the > raw binary > bytes as if they were a string? Or do you want to > convert the > binary data and then convert it again into a string > representation? > > Either is possible but you need to decide which you > need. > > BTW Please don't post new subjects to the list by > replying > to an existing subject. For those using threaded > readers it > buries your post insife another thread, in this case > 3 levels > deep in one about MSSQL! I only just noticed it. Its > better > to start a fresh message. After all its not exactly > difficult to > type tutor at python.org in the to line! :-) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ________________________________________ ____________________________________________________________________________________ Food fight? Enjoy some healthy debate in the Yahoo! Answers Food & Drink Q&A. http://answers.yahoo.com/dir/?link=list&sid=396545367 From pythontutoraccount at gmail.com Fri May 25 18:07:38 2007 From: pythontutoraccount at gmail.com (John) Date: Fri, 25 May 2007 12:07:38 -0400 Subject: [Tutor] I'm clearly not getting an important pygtk concept Message-ID: <465709CA.50309@gmail.com> I created the following script to test my understanding of creating simple pygtk GUIs. #!/usr/bin/python2.5 import gtk, urllib def pinger_shotgun(): """This function stores an object that pings Peter's writerscafe.org pages.""" open_page = urllib.urlopen(web) def plink(widget, web): print "I just pinged", web pinger_shotgun() web = "http://www.mywebsite.com/" window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", gtk.main_quit) ping_button = gtk.Button("ping me") window.add(ping_button) ping_button.connect("clicked", plink, web) window.show_all() gtk.main() I am not sure what's wrong with the script as I've typed it above. I expected this script to generate a button with the label "ping me". I expected that when I press this button that my webserver log would show that someone with the user-agent python-urllb just tried to access my site. This is not happening unfortunately. Sometimes pressing the button registers in my logs and sometimes it does not. Pressing the button twice in rapid succession may cause a hit to register if a single click did not. Pressing the button 5 or 6 times will cause 4 or 5 hits. What is it I am not understanding? John From alan.gauld at btinternet.com Fri May 25 20:14:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 May 2007 19:14:36 +0100 Subject: [Tutor] Hands-On Python References: <4656C981.3090207@tds.net> Message-ID: "Kent Johnson" wrote > Does anyone know how to get this added to this page? > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > An email to Fred Drake I think. Alan G From matt at mattanddawn.orangehome.co.uk Fri May 25 22:31:45 2007 From: matt at mattanddawn.orangehome.co.uk (Matt Smith) Date: Fri, 25 May 2007 21:31:45 +0100 Subject: [Tutor] Still having trouble with my game of life algorithm Message-ID: <1180125105.5470.10.camel@computer> Hi, First of all, thanks to everyone who helped with my last post (http://mail.python.org/pipermail/tutor/2007-May/054360.html). I have re-written the function that applies the rules but it still doesn't return the expected result. I have been through it and corrected a couple of bugs bet as far as I can tell it should return a matrix that has had the rules of Conway's game of life (http://en.wikipedia.org/wiki/Conway%27s_game_of_life) applied. Here is my function: def update_matrix(matrix): matrix_updated = matrix # Perform check for each value in the matrix for x in range(len(matrix[0])): for y in range(len(matrix)): neighbour_count = 0 for n in (x-1, x, x+1): for m in (y-1, y, y+1): try: if matrix[m][n]: if (n,m) != (x,y): neighbour_count = neighbour_count + 1 except IndexError: pass # Apply game of life rules to each item in the matrix if neighbour_count < 2: matrix_updated[y][x] = 0 elif neighbour_count > 3: matrix_updated[y][x] = 0 elif neighbour_count == 3: matrix_updated[y][x] = 1 # No need to change value if neighbour count == 2 return matrix_updated I have also attached the full program and the input file that I am using for testing in case anyone is interested. The program does use curses to display the board so I guess it won't be any good for Windows users. I hope someone can see where I am going wrong here. Thanks, Matt -------------- next part -------------- A non-text attachment was scrubbed... Name: life.py Type: text/x-python Size: 2444 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070525/db07ca9b/attachment.py -------------- next part -------------- 000000000000000 000000000000000 000000000000000 000000000000000 000000000000000 000000000000000 000000011000000 000000110000000 000000010000000 000000000000000 000000000000000 000000000000000 000000000000000 000000000000000 000000000000000 From ksterling at mindspring.com Sat May 26 00:23:54 2007 From: ksterling at mindspring.com (Ken Oliver) Date: Fri, 25 May 2007 18:23:54 -0400 (EDT) Subject: [Tutor] Still having trouble with my game of life algorithm Message-ID: <2181695.1180131834952.JavaMail.root@mswamui-chipeau.atl.sa.earthlink.net> -----Original Message----- >From: Matt Smith >Sent: May 25, 2007 4:31 PM >To: Python Tutor >Subject: [Tutor] Still having trouble with my game of life algorithm > >Hi, > >First of all, thanks to everyone who helped with my last post >(http://mail.python.org/pipermail/tutor/2007-May/054360.html). I have >re-written the function that applies the rules but it still doesn't >return the expected result. I have been through it and corrected a >couple of bugs bet as far as I can tell it should return a matrix that >has had the rules of Conway's game of life >(http://en.wikipedia.org/wiki/Conway%27s_game_of_life) applied. Here is >my function: > >def update_matrix(matrix): > matrix_updated = matrix ># Perform check for each value in the matrix > for x in range(len(matrix[0])): > for y in range(len(matrix)): > neighbour_count = 0 > for n in (x-1, x, x+1): > for m in (y-1, y, y+1): > try: > if matrix[m][n]: > if (n,m) != (x,y): > neighbour_count = neighbour_count + 1 > except IndexError: > pass ># Apply game of life rules to each item in the matrix > if neighbour_count < 2: > matrix_updated[y][x] = 0 > elif neighbour_count > 3: > matrix_updated[y][x] = 0 > elif neighbour_count == 3: > matrix_updated[y][x] = 1 ># No need to change value if neighbour count == 2 > return matrix_updated > >I have also attached the full program and the input file that I am using >for testing in case anyone is interested. The program does use curses to >display the board so I guess it won't be any good for Windows users. > >I hope someone can see where I am going wrong here. > >Thanks, > >Matt I am NOT an expert, and I have not studied your code very carefully, but I had a thought. If I understand Conway's rules, if an empty cell has exactly two neighbors, a new "live" cell is spawned. I don't see that you have done this, but it may be something subtle that I missed. ken oliver From alan.gauld at btinternet.com Sat May 26 01:57:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 May 2007 00:57:36 +0100 Subject: [Tutor] Still having trouble with my game of life algorithm References: <1180125105.5470.10.camel@computer> Message-ID: "Matt Smith" wrote in > re-written the function that applies the rules but it still doesn't > return the expected result. Care to tell us what you think it's doing wrong? Some sample data maybe? A casual glance at the code looks OK, but I haven't studied all the boundary poossibilities - and it's usually the corners and edges where the problems llie... Do you have any known error conditions? Alan G. From malaclypse2 at gmail.com Sat May 26 02:07:53 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 25 May 2007 20:07:53 -0400 Subject: [Tutor] Still having trouble with my game of life algorithm In-Reply-To: <1180125105.5470.10.camel@computer> References: <1180125105.5470.10.camel@computer> Message-ID: <16651e80705251707k6dadf0ecnb4eb46fa1fa6f2a0@mail.gmail.com> On 5/25/07, Matt Smith wrote: > def update_matrix(matrix): > matrix_updated = matrix That line assigns the name matrix_updated to the same list-of-lists as matrix. Since lists are mutable objects, changing matrix_updated is also changing matrix. What you need is to bind matrix_updated to a new copy of matrix instead. At the top of your code add: from copy import deepcopy and replace the first line of update_matrix() with: matrix_updated = deepcopy(matrix) After making that change, your code appears to run beautifully! -- Jerry From agilfoy at frontiernet.net Sat May 26 14:30:25 2007 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sat, 26 May 2007 12:30:25 +0000 Subject: [Tutor] file(), open() Message-ID: <20070526123025.und2tp6hy1wkgko4@webmail.frontiernet.net> I want to work with simple ASCII text files, here.. I know you get them loaded into Python with file() or open() The arguments for file() and open() are: (filename, mode, buffering). How do you refer to the filename? Do you put it in quotes? Do you put in the file's full directory path? Or do file() and open() refer to the same directory as the one the script is in? Are the mode and buffering things always necessary arguments? For now, I just want to read/manipulate files, not write to them. What do file() and open() create? Do you need to set them equal to some variable? Is one better than the other? I want to create a list, where each list item is a line in the file. (The, my program would do stuff with the list.) From rikard.bosnjakovic at gmail.com Sat May 26 15:00:58 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Sat, 26 May 2007 15:00:58 +0200 Subject: [Tutor] file(), open() In-Reply-To: <20070526123025.und2tp6hy1wkgko4@webmail.frontiernet.net> References: <20070526123025.und2tp6hy1wkgko4@webmail.frontiernet.net> Message-ID: On 5/26/07, Alan Gilfoy wrote: > How do you refer to the filename? Do you put it in quotes? Yes. open("foo") > Do you put > in the file's full directory path? Or do file() and open() refer to > the same directory as the one the script is in? Yes, and yes. If you dont supply the absolute path, the script will read the file from the cwd (current working dir). This is _usually_ the same as the script, but not necessarily. If the cwd is /foo/bar and the script is launched using /bar/foo/foo/foo/script.py, then open("file") will refer too /foo/bar/file, while open("/bar/foo/foo/foo/file") will get the file from the same dir as the script itself. This is handled by the OS. > Are the mode and buffering things always necessary arguments? Both mode and buffering are optional. I have during my 7 years of Python-coding never used the buffering-flag. > What do file() and open() create? Do you need to set them equal to > some variable? Is one better than the other? open() and file() are the same functions. Try "print open.__doc__" in your Python interpreter, and you will see this: Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. Add a 'U' to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a '\n' in Python. Also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\r', '\n', '\r\n' or a tuple containing all the newline types seen. > I want to create a list, where each list item is a line in the file. > (The, my program would do stuff with the list.) mylist = open("listfile").readlines() -- - Rikard - http://bos.hack.org/cv/ From alan.gauld at btinternet.com Sat May 26 15:50:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 May 2007 14:50:00 +0100 Subject: [Tutor] file(), open() References: <20070526123025.und2tp6hy1wkgko4@webmail.frontiernet.net> Message-ID: "Alan Gilfoy" wrote in >I want to work with simple ASCII text files, here.. You may find it worth reading the relevant section in one of the tutorials. The official python one is good or you could try the Handling files topic in mine. Most tutorials will answer all of the questions you ask and give examples. > I know you get them loaded into Python with file() or open() You get access to the file objects, you don;t load anything until you call one of the read methods (or use the file as an iterator) > The arguments for file() and open() are: (filename, mode, > buffering). > How do you refer to the filename? As a string > Do you put it in quotes? Yes, or store it in a variable and use that. > Do you put in the file's full directory path? Yes, or it will use the current working directory as shown by os.getcwd() and can be changed using os.chdir() > Or do file() and open() refer to the same directory > as the one the script is in? Thats often what the cwd is set to but not always. > Are the mode and buffering things always necessary arguments? the default mode is 'r' - ie read - if you want any other mode then you must supply it. I've never actually used buffering, the default will do in nearly all cases. If you do help(open) or help(file) at the python prompt you will get a lot of info including this sat the top: file(name[, mode[, buffering]]) -> file object That tells you that open/file() take a mandatory name, an optional mode and an optional buffering (the []) and that they return a file object ( the -> symbol) Its worth getting to know this notation because it is compact and accurate and is often diosplayed by IDEs with code introspection capabilities(IDLE, Pythonwin, SPE, PyCrust, Eclipse etc) > For now, I just want to read/manipulate files, not write to them. > > What do file() and open() create? file objects. Those objects expose a bunch of methods. Those methods are alspo described when you do help(file) at the >>> prompt. The >>> prompt is also a great place to try out these things to see for yourself exactly how they work, what kind of values to pass etc. Never underestimate the power of the >>> prompt in building code, especiually when its new features that you are using for the first time or things you only use occasionally... > Do you need to set them equal to > some variable? Is one better than the other? If you just want to slurp up the content of a file you can bypass the file variable with something like: data = file('myfile.dat').read() Or if you only want to do a single pass over the lines of the file use: for line in file('myfile.dat'): processLine(line) Otherwise you are better assigning to a variable. If you do you should really put the open within a try/except and close it in a finally as a metter of best practice: try: myFile = open('myfile.dat') process(myFile) except IOError: processError() finally: myFile.close() Its also good practice to close files as soon as possible to ensure you don;t lock other users out from accessing them. > I want to create a list, where each list item is a > line in the file. If you only want to process the lines once you can use a for loop directly as shown above. Otherwise use the readlines() method. All of this and more is covered in my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pine508 at hotmail.com Sun May 27 02:29:22 2007 From: pine508 at hotmail.com (Che M) Date: Sat, 26 May 2007 20:29:22 -0400 Subject: [Tutor] monitor other running applications with Python? Message-ID: Hi, searched a bit for this but haven't found much. Is it possible to use Python to monitor the use of other applications? (anything...Word, Excel, browsers, etc.) At minimum, I wan't to know that the application was running, but even better would be some sense of the use or content, such as whether the app was idle or the user was using it, or, for a web browser, what URLs were visited and for how long, etc. Ideally I'd like a cross-platforms approach but expect that might be hard. I know utilities like this are out there, but I have no sense how to go about this in Python, or how difficult it might be. Any ideas are appreciated. Thanks, Che _________________________________________________________________ Like the way Microsoft Office Outlook works? You?ll love Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_outlook_0507 From alan.gauld at btinternet.com Sun May 27 16:54:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 May 2007 15:54:11 +0100 Subject: [Tutor] monitor other running applications with Python? References: Message-ID: "Che M" wrote > Hi, searched a bit for this but haven't found much. > Is it possible to use Python to monitor the use of > other applications? Yes, definitely. > At minimum, I wan't to know that the application was running Thats fairly easy using OS tools such as ps on Unix. You can dig a little deeper and use the system APIs such as the proc fiilesystem or the equivalent in the windows registry. > better would be some sense of the use or content, such > as whether the app was idle or the user was using it, > or, for a web browser, what URLs were visited and for > how long, etc. Thats possible but gets very OS specific and very low level too. On Windows you can catch Windows events and messages using some of the raw Win32 API calls from the ctypes module. (I've never used ctypes for anything this low level but it should be possible, I''ve certainly done it in C++ and Delphi on Win 9X). But its messy and fairly deep Windows magic and you will need to spend a fair bit of time experimenting and reading the docs on MSDN as well as the Win32 API help file. > Ideally I'd like a cross-platforms approach I doubt if that's possible except at the process monitoring level. For the kind of detail you want the bgestb you can do is have a common UI and pluggable modules based on the OS. Also beware legal implications. There are issues around personal privacy, data proptection etc and these vary between countries (and even states in the US). People are increasingly wary of Big Brother style monitoring. Detecting inappropriate use of the internet across a corporate firwall is generally considered OK but silently monitoring individuals brings you into murky legal waters. Finally, take a look at the stuff in the os package and the syslog module for Unix. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From adamurbas at hotmail.com Sun May 27 19:25:17 2007 From: adamurbas at hotmail.com (adam urbas) Date: Sun, 27 May 2007 12:25:17 -0500 Subject: [Tutor] error message questions Message-ID: Hello all,I was wondering if there would be someone who would be able to give me a list of error messages and their meanings. I've attached this test.py to illustrate my problem. When I run the program, I am able to enter all the data, yet it will not calculate.It says:can't multiply sequence by non-int of type 'str'I really would like to know how to fix this.I get a similar message with my other one, radiacir.py:can't multiply sequence by non-int of type 'float'Please help!Thanks in advance,Adam _________________________________________________________________ Change is good. See what?s different about Windows Live Hotmail. http://www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=RMT_TAGLM_HMWL_reten_changegood_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070527/167120aa/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.py Url: http://mail.python.org/pipermail/tutor/attachments/20070527/167120aa/attachment.asc -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: radiacir.py Url: http://mail.python.org/pipermail/tutor/attachments/20070527/167120aa/attachment.pot From adamurbas at hotmail.com Sun May 27 19:49:04 2007 From: adamurbas at hotmail.com (adam urbas) Date: Sun, 27 May 2007 12:49:04 -0500 Subject: [Tutor] trouble with "if" Message-ID: Thank you for the help Brian. I would like to ask you about these things. Which one of the examples you gave would be most fool proof.> Date: Wed, 23 May 2007 13:40:09 -0400> From: broek at cc.umanitoba.ca> To: adamurbas at hotmail.com> CC: tutor at python.org> Subject: Re: [Tutor] trouble with "if"> > adam urbas said unto the world upon 05/23/2007 01:04 PM:> > Sorry, I don't think Hotmail has turn off HTML. If it does I> > havn't been able to find it. I think you're going to have to> > explain your little bit of text stuff down there at the bottom. I> > have no idea what most of that means. All my choice things are> > working now though. I think that is what you were trying to help> > me with. What I used wasif shape in["1","circle"]:and if shape ==> > "1" or shape =="circle":It works perfectly fine now.Ya that little> > bit o' code is really puzzling. I wish I knew more about this> > python deal. I understand the concept, but not the rules or the> > techniques and things of that sort. OK... I've got it... the> > data=raw_input('Feed Me!'). Ok I now understand that bit. Then it> > says Feed Me! and you put 42 (the ultimate answer to life the> > universe, everything). OK, it won't accept the bit.> > it doesn't like the "<". Well, I just removed that bit and it> > said:Feed Me! and I put 42, and it said >>> (I guess it's> > satisfied now, with the whole feeding). Well if I understood what> > 'str' meant, then I could probably figure the rest out. Well I> > have to go do other things so I'll save the rest of this figuring> > out till later.I shall return,Adam> Date: Wed, 23 May 2007 12:12:16> > -0400> From: broek at cc.umanitoba.ca> To: adamurbas at hotmail.com> CC:> > tutor at python.org> Subject: Re: [Tutor] trouble with "if"> > adam> > urbas said unto the world upon 05/23/2007 11:57 AM:> > > > Hi all,>> > > > > I've been working with this new program that I wrote. I> > started out > > with it on a Ti-83, which is much easier to program> > than python. Now > > I'm trying to transfer the program to python> > but its proving to be quite > > difficult. I'm not sure what the> > whole indentation thing is for. And > > now I'm having trouble> > with the if statement things. > > > > #"Circle Data Calculation> > Program:"> > print "Welcome to the Circle Data Calcuation> > Program."> > print> > > > #"Menu 1:"> > print "Pick a shape:">> > > print "(NOTE: You must select the number of the shape and not the> > shape > > itself)"> > print "1 Circle"> > print "2 Square"> > print> > "3 Triangle"> > > > #"User's Choice:"> > shape=raw_input("> ")>> > > > > #"Select Given:"> > if shape == 1:> > print> > "Choose the given value:"> > print "1 radius"> >> > print "2 diameter"> > print "3 circumference"> >> > print "4 area"> > > > #"User's Choice:"> > given=raw_input("> ")> >> > > > if given == 1:> > radius=raw_input("Enter Radius:")> >> > diameter=(radius*2)> > circumference=(diameter*3.14)> >> > area=(radius**2*3.14)> > print "Diameter:", diameter> >> > print "Circumference:", circumference> > print "Area:",> > area> > > > if given == 2:> > diameter=raw_input("Enter> > Diameter:")> > radius=(diameter/2)> >> > circumference=(diameter*3.14)> > area=(radius**2*3.14)> >> > print "Radius:", radius> > print "Circumference:",> > circumference> > print "Area:", area> > > > if given == 3:>> > > circumference=raw_input("Enter Circumference:")> >> > radius=(circumference/3.14/2)> > diameter=(radius*2)> >> > area=(radius**2*3.14)> > print "Radius:", radius> >> > print "Diameter:", diameter> > print "Area:", area> > > >> > if given == 4:> > area=raw_input("Enter Area:")> >> > radius=(area/3.14)> > > > This is the whole program so> > far, because I haven't quite finished it > > yet. But I tried to> > get it to display another list of options after you > > select a> > shape but it just does this.> > > > Pick a shape:> > 1 Circle> > 2> > Square> > 3 Triangle> > >1> > >1> > >>>> > > > I'm not sure why> > it does that but I do know that it is skipping the > > second list> > of options.> > > > Another of my problems is that I can't figure> > out how to get it to > > accept two different inputs for a> > selection. Like I want it to accept > > both the number 1 and> > circle as circle then list the options for > > circle. It won't> > even accept words. I can only get it to accept > > numbers. It's> > quite frustrating actually.> > > > Any advice would be greatly> > appreciated.> > Thanks in advance,> > Adam> > > > > > > Adam,> >> > Could you send plain text email rather than html, please? At least> > for > me, your code's indentation is all messed up unless I take> > some steps > to rectify it.> > The problem is that raw_input> > returns a string, and you are testing > whether given is equal to> > integers. See if this helps make things clear:> > >>> data => > raw_input('Feed me!')> Feed me!42> >>> type(data)> >> > >>> data == 42> False> >>> int(data) == 42> True> >>>> > Best,> >> > Brian vdB > > > Adam,> > As you can see from the above, the way hotmail is formatting things > makes the conversation a bit tricky :-) I'm only willing to spend so > much time trying to sort through it, so I hope what follows helps.> > >>> data = raw_input("Feed me!")> Feed me!42> > This calls the builtin function raw_input with a parameter setting the > prompt to "Feed me!" and assigns the result to data. Since I hit 42 > and then enter,> > >>> data> '42'> > Notice the quotes around 42. They indicate that the value of data is a > string. That's what this tells us:> > >>> type(data)> > > The string '42' is not the same as the integer 42:> > >>> type(42)> > >>> '42' == 42> False> > So, when you had an if test that was something like:> > if given == 1:> # Do stuff here> > the equality comparison was never going to work---given was a string > returned by raw_input and no string is ever equal to an integer.> > What I suggested was taking the string returned by raw_input and > feeding it to int() to transform it from a string to an integer, and > allow your if test to stand a chance:> > >>> data = raw_input("Feed me!")> Feed me!42> >>> if data == 42:> ... print "Matches!"> ...> >>> data = int(raw_input("Feed me!"))> Feed me!42> >>> if data == 42:> ... print "Matches!"> ...> Matches!> >>>> > There are other ways, for instance:> > >>> data = raw_input("Feed me!")> Feed me!42> >>> if data == '42':> ... print "Matches!"> ...> Matches!> >>>> > Here, instead of transforming data to an int and then testing for > equality with 42, I left data as a string and tested for equality with > the string '42'.> > The way calling int() is a bit better, I think. If the user enters a > few spaces, then 42 then a few more spaces, that way will still work:> > >>> data = int(raw_input("Feed me!"))> Feed me! 42> >>> if data == 42:> ... print "Matches!"> ...> Matches!> >>>> > because> > >>> int(' 42 ')> 42> >>>> > whereas> > >>> ' 42 ' == '42'> False> > > I hope there is some help in there somewhere :-)> > Brian vdB _________________________________________________________________ Change is good. See what?s different about Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_changegood_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070527/81f34a70/attachment.html From rikard.bosnjakovic at gmail.com Sun May 27 19:53:18 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Sun, 27 May 2007 19:53:18 +0200 Subject: [Tutor] error message questions In-Reply-To: References: Message-ID: On 5/27/07, adam urbas wrote: > It says: > > can't multiply sequence by non-int of type 'str' The reason is that raw_input() returns a string. What you are trying to do is multiply a string with a string, which - in Python - is an illegal operation. What you want to do is to convert the read value from raw_input() to an integer, and then multiply. You convert with the function int(). So if you change the two upper lines of your code test.py to height = int(raw_input("enter height:")) width = int(raw_input("enter width:")) then the multiplication will work. It will - however - not work if you don't enter a numerical value, because int() will fail for everything else than numericals. HTH. -- - Rikard - http://bos.hack.org/cv/ From jjcrump at myuw.net Sun May 27 20:01:45 2007 From: jjcrump at myuw.net (Jon Crump) Date: Sun, 27 May 2007 11:01:45 -0700 (PDT) Subject: [Tutor] numbers and ranges Message-ID: Dear all, Here's a puzzle that should be simple, but I'm so used to words that numbers tend to baffle me. I've got fields that look something like this: 1942. Oct. 1,3,5,7,8,9,10 I need to parse them to obtain something like this: The xml representation is incidental, the basic problem is how to test a list of integers to see if they contain a range, and if they do, do something different with them. I'm sure this is the question of a rank tyro, but the denizens of this list seem tolerant and gentle. Many thanks. From alan.gauld at btinternet.com Sun May 27 21:08:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 May 2007 20:08:36 +0100 Subject: [Tutor] error message questions References: Message-ID: "adam urbas" wrote in > Hello all,I was wondering if there would be someone who > would be able to give me a list of error messages and > their meanings. The errors are actually self explanatory - no really! - once you undestandd the basic concepts. But to understand those you will need to go back to basics. I suggested in an earlier post that you read my Raw Materials topic which discusses data and types. Did you do that? Also the Talking to the User illustrates the use of raw_input, you could usefully read that too. it discusses using the Python conversion functions to get the right input values from raw_input.. > It says:can't multiply sequence by non-int of type 'str' Which means Python cannot multiply the two types of data you are giving it. You need to convert those values to the compatible types. > can't multiply sequence by non-int of type 'float' Same thing, you have a sequence type on one side (probably a string but could be a list or tuple?) and a float on the other. You need to turn the sequence into something that a float can multiply - either another float or an int (or a complex or decimal if you feel really picky). -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From broek at cc.umanitoba.ca Sun May 27 21:10:08 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Sun, 27 May 2007 15:10:08 -0400 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <4659D790.4070200@cc.umanitoba.ca> adam urbas said unto the world upon 05/27/2007 01:49 PM: > Thank you for the help Brian. I would like to ask you about these > things. Which one of the examples you gave would be most fool > proof. Hi Adam and all, Adam was asking about how to use raw_input to drive a basic command prompt menu system. I'd tried to explain that raw_input returns strings, so his if tests which were something like: choice = raw_input("Enter an option) if choice == 1: do_option_1_stuff() elif choice == 2: do_option_2_stuff() were not going to work, as choice will never be equal to an int. I'd sketched a few ways to deal with this, chiefly applying int() to choice or comparing choice to '1', etc. That's more of less the gist of the above snippage and takes us more or less up to the point where Adam asked his question above. I'm going to show you a few things that might be new to you, Adam. Let's build up in steps. As a first pass, I would do the following: choice = int(raw_input("Please make your choice ")) if choice == 1: # Option 1 code here print "In option 1" elif choice == 2: # Option 2 code here print "In option 2" # Carry on if-test as needed (or until you get to the point # of learning about dictionary dispatch :-) That will be fine, until your user enters something silly: >>> Please make your choice I like bikes! Traceback (most recent call last): File "/home/brian/docs/jotter/python_scraps/adamcode.py", line 1, in choice = int(raw_input("Please make your choice ")) ValueError: invalid literal for int() with base 10: 'I like bikes!' >>> That's no good! So, we can use Python's exception handling tools to make this a bit better. try: choice = int(raw_input("Please make your choice ")) except ValueError: print "Please make a choice from the options offered." if choice == 1: print "In option 1" elif choice == 2: print "In option 2" There is still a problem, though: >>> # Make sure the previous value assigned to choice is gone. >>> del(choice) >>> Please make your choice I like Bikes Please make a choice from the options offered. Traceback (most recent call last): File "/home/brian/docs/jotter/python_scraps/adamcode.py", line 7, in if choice == 1: NameError: name 'choice' is not defined >>> We've printed the reminder to the user, but then have gone on to compare the non-existent choice value to 1, and that doesn't work so well. It isn't enough to make sure that choice isn't insane---we need to make sure that there is a choice value at all. So, better still: while True: try: choice = int(raw_input("Please make your choice ")) # If the previous line worked, end the while loop. If it did # not work, we won't get here, so the loop will keep looping. break except ValueError: print "Please make a choice from the options offered." if choice == 1: print "In option 1" elif choice == 2: print "In option 2" Now we get the following: Please make your choice I like bikes! Please make a choice from the options offered. Please make your choice Please take this Please make a choice from the options offered. Please make your choice1 In option 1 >>> There is still a problem, though: Please make your choice 42 >>> Our sanity check has only insisted that the user enter a value that can be turned into an int; nothing as yet makes it be one of the ints we are expecting. So, try this: while True: try: choice = int(raw_input("Please make your choice ")) if choice < 1 or choice > 2: # Adjust to suit options raise ValueError break except ValueError: print "Please make a choice from the options offered." if choice == 1: print "In option 1" elif choice == 2: print "In option 2" Please make your choice I like bikes! Please make a choice from the options offered. Please make your choice 42 Please make a choice from the options offered. Please make your choice 2 In option 2 >>> Now, all of this should be formatted to be a bit prettier---and displaying the allowable options up front is a good idea, too---but the essential ideas are there. There might be some parts of this that are new to you, so ask away if you've gotten a bit lost. And, I'm no expert, so if someone else comes along and says `No, don't do it like that', odds are they might be right. (Especially if their name is Alan, Danny, or Kent ;-) Best, Brian vdB From bgailer at alum.rpi.edu Sun May 27 22:18:38 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 27 May 2007 13:18:38 -0700 Subject: [Tutor] numbers and ranges In-Reply-To: References: Message-ID: <4659E79E.5030606@alum.rpi.edu> Jon Crump wrote: > Dear all, > > Here's a puzzle that should be simple, but I'm so used to words that > numbers tend to baffle me. > > I've got fields that look something like this: > 1942. Oct. 1,3,5,7,8,9,10 > > I need to parse them to obtain something like this: > > > > > > The xml representation is incidental, the basic problem is how to test a > list of integers to see if they contain a range, and if they do, do > something different with them. > numList = (1, 3, 5, 7, 8, 9, 10) inSequence = False result = "" priorNumber = numList[0] for number in numList[1:]: if number - priorNumber == 1: if not inSequence: seqStart = priorNumber inSequence = True else: if inSequence: result += '\n' % (seqStart, priorNumber) inSequence = False else: result += '\n' % priorNumber priorNumber = number if inSequence: result += '\n' % (seqStart, priorNumber) print result > I'm sure this is the question of a rank tyro, but the denizens of this > list seem tolerant and gentle. Many thanks. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 510-978-4454 From kent37 at tds.net Sun May 27 22:33:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 27 May 2007 16:33:05 -0400 Subject: [Tutor] numbers and ranges In-Reply-To: References: Message-ID: <4659EB01.5090306@tds.net> Jon Crump wrote: > Dear all, > > Here's a puzzle that should be simple, but I'm so used to words that > numbers tend to baffle me. > > I've got fields that look something like this: > 1942. Oct. 1,3,5,7,8,9,10 > > I need to parse them to obtain something like this: > > > > > > The xml representation is incidental, the basic problem is how to test a > list of integers to see if they contain a range, and if they do, do > something different with them. Here is a solution that uses a generator to create the ranges: def ranges(data): i = iter(data) first = last = i.next() try: while 1: next = i.next() if next > last+1: yield (first, last) first = last = next else: last = next except StopIteration: yield (first, last) print list(ranges((1,))) print list(ranges((1,2,3))) print list(ranges((1,3,5))) print list(ranges((1,3,5,7,8,9,10))) for start, end in ranges((1,3,5,7,8,9,10)): if start == end: print '' % start else: print '' % (start, end) Kent From jjcrump at myuw.net Mon May 28 00:09:20 2007 From: jjcrump at myuw.net (Jon Crump) Date: Sun, 27 May 2007 15:09:20 -0700 (PDT) Subject: [Tutor] numbers and ranges In-Reply-To: <4659EB01.5090306@tds.net> References: <4659EB01.5090306@tds.net> Message-ID: Kent, That's damned clever! Your solution hovers right at the limit of my understanding, but the print statements illustrate very clearly the operation of the function. Many thanks! Jon On Sun, 27 May 2007, Kent Johnson wrote: >> Here's a puzzle that should be simple, but I'm so used to words that >> numbers tend to baffle me. >> >> I've got fields that look something like this: >> 1942. Oct. 1,3,5,7,8,9,10 >> >> I need to parse them to obtain something like this: >> >> >> >> > > Here is a solution that uses a generator to create the ranges: > > def ranges(data): > i = iter(data) > first = last = i.next() > try: > while 1: > next = i.next() > if next > last+1: > yield (first, last) > first = last = next > else: > last = next > except StopIteration: > yield (first, last) > > print list(ranges((1,))) > print list(ranges((1,2,3))) > print list(ranges((1,3,5))) > print list(ranges((1,3,5,7,8,9,10))) > > for start, end in ranges((1,3,5,7,8,9,10)): > if start == end: > print '' % start > else: > print '' % (start, > end) From kent37 at tds.net Mon May 28 01:33:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 27 May 2007 19:33:32 -0400 Subject: [Tutor] numbers and ranges In-Reply-To: References: <4659EB01.5090306@tds.net> Message-ID: <465A154C.7040608@tds.net> Jon Crump wrote: > Kent, > > That's damned clever! Your solution hovers right at the limit of my > understanding, but the print statements illustrate very clearly the > operation of the function. You're welcome! I recently wrote some notes about iterators and generators that might help your understanding: http://personalpages.tds.net/~kent37/kk/00004.html Kent From adamurbas at hotmail.com Mon May 28 06:24:03 2007 From: adamurbas at hotmail.com (adam urbas) Date: Sun, 27 May 2007 23:24:03 -0500 Subject: [Tutor] trouble with indents Message-ID: Thanks for the clarification, but I'm still a tad confused. I'm not sure when to indent. I understand that it has to be done. That link was really confusing. Very newb non-friendly. Arrg... That site is doom. So confusing. I need somewhere to start from the beginning. This site uses all kinds of big words and doesn't explain things in a clear manner. Oh well. Thanks for the help, though.Au> From: pine508 at hotmail.com> To: tutor at python.org> Date: Thu, 24 May 2007 15:30:34 -0400> Subject: Re: [Tutor] trouble with if> > >I'm not sure what the whole indentation thing is for. And now I'm having > >trouble with the if statement things.> > Maybe your if statement troubles have been solved by others by now, but I'll > just add that "the indentation thing" is a vital feature of Python, it is > the way to separate code blocks. Other languages uses other means, like > curly braces, etc. I get the sense those who like Python enjoy indentation > because it forces the code to be quite readable, and I agree. See this:> > http://www.diveintopython.org/getting_to_know_python/indenting_code.html> > Also, as mentioned previously, keep in mind that 2 is not the same as "2" > and "=" is not the same as "==". The single "=" is used to assign names to > objects, whereas the == is for evaluating something, so for if statements > use == and not =. Also note you can put "and" along with if, so you can say> > if x == "mom" and y == "dad":> print "my parents"> > and lots of other stuff.> -Che> > _________________________________________________________________> PC Magazine?s 2007 editors? choice for best Web mail?award-winning Windows > Live Hotmail. > http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_pcmag_0507> _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070527/3d9776c6/attachment.htm From broek at cc.umanitoba.ca Mon May 28 06:37:01 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 28 May 2007 00:37:01 -0400 Subject: [Tutor] trouble with indents In-Reply-To: References: Message-ID: <465A5C6D.9030501@cc.umanitoba.ca> adam urbas said unto the world upon 05/28/2007 12:24 AM: > Thanks for the clarification, but I'm still a tad confused. I'm > not sure when to indent. I understand that it has to be done. > That link was really confusing. Very newb non-friendly. Arrg... > That site is doom. So confusing. I need somewhere to start from > the beginning. This site uses all kinds of big words and doesn't > explain things in a clear manner. Oh well. Thanks for the help, > though.Au> From: pine508 at hotmail.com> To: tutor at python.org> Date: > Thu, 24 May 2007 15:30:34 -0400> Subject: Re: [Tutor] trouble with > if> > >I'm not sure what the whole indentation thing is for. And > now I'm having > >trouble with the if statement things.> > Maybe > your if statement troubles have been solved by others by now, but > I'll > just add that "the indentation thing" is a vital feature of > Python, it is > the way to separate code blocks. Other languages > uses other means, like > curly braces, etc. I get the sense those > who like Python enjoy indentation > because it forces the code to > be quite readable, and I agree. See this:> > > http://www.diveintopython.org/getting_to_know_python/indenting_code.html> Adam, I think Dive Into Python is quite good, but as a second book or a first book for someone with a bit more experience of other languages than it seems like you might have. The first think I read was which is aimed at high school students. It might move a bit slowly for some tastes, but it sounds like DIP is moving a bit too fast. The full text is free; give it a look. Best, Brian vdB From adamurbas at hotmail.com Mon May 28 06:42:01 2007 From: adamurbas at hotmail.com (adam urbas) Date: Sun, 27 May 2007 23:42:01 -0500 Subject: [Tutor] trouble with "if" Message-ID: You don't know what a Ti 83 is. Calculator. The most basic programming available. It already has so many functions built into it that it is much easier to tell it to do things. You don't have to do all this integer conversion and such whatnot. Wow... I'm really unsure of how this thing is supposed to work. It seems the more I learn about Python, the more confused I become. It's enough to bring tears to your eyes. Not really but ya.Someone else helped me with the problem of accepting numbers and words. I used:if shape in["1","circle"]:something like that. It works wonderfully. I'm not sure why, but I know that it does and that is enough. Someone else also said that I had to convert to int, and I did. That was another problem, which is now fixed.But, as usual, it is just one problem after another. Now I have run into this error message: Traceback (most recent call last): File "C:\Documents and Settings\HP_Owner\Python0\area.py", line 23, in area = 3.14*(radius**2)TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'>>> and others like this:Traceback (most recent call last): File "C:\Documents and Settings\HP_Owner\Python0\area.py", line 19, in area = height*widthTypeError: can't multiply sequence by non-int of type 'str'>>> Very frustrating. What is a non-int and what is 'str'? Why can't it multiply the sequence? I guess I should include the program I'm using for these things.I'm having this problem with both of these attached. The messages above are from area.py. area.py is sort of a prototype of radiacir.py, a test version. You know, I should probably try that int trick, which I seem to have forgotten. And guess what that did it. It's amazing when you apply the things that you learn. Apparently I am quite absent minded. Well It seems I don't need any of this help anymore. Oh well. Thanks anyway.Au > To: tutor at python.org> From: alan.gauld at btinternet.com> Date: Thu, 24 May 2007 23:34:05 +0100> Subject: Re: [Tutor] trouble with "if"> > "adam urbas" wrote > > > It won't even accept words. > > I can only get it to accept numbers. > > try this(untested code!):> > number = None> data = raw_input('Type something: ')> try: number = int(data)> except: data = data.split() # assume a string> > if number: # user entered a number> if number == 1: print 'circle'> elif number == 2: print 'another'> else: # user entered words> if data[0].lower() == 'circle': print 'circle'> else: print 'user entered ', data[0]> > Notice that to use ithe input as a number you have to > convert the raw input characters to a number (using int)> To get the individual words we can use split() which by > default splits a string into the individual words.> > Is that the kind of thing you mean?> > I've no idea what a Ti83 is BTW. :-)> > Alan G.> > _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070527/a522dade/attachment.html -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: area.py Url: http://mail.python.org/pipermail/tutor/attachments/20070527/a522dade/attachment.pot -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: radiacir.py Url: http://mail.python.org/pipermail/tutor/attachments/20070527/a522dade/attachment.asc From bgailer at alum.rpi.edu Mon May 28 06:42:48 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 27 May 2007 21:42:48 -0700 Subject: [Tutor] trouble with indents In-Reply-To: References: Message-ID: <465A5DC8.9060904@alum.rpi.edu> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070527/f90a2895/attachment.htm From adamurbas at hotmail.com Mon May 28 07:07:13 2007 From: adamurbas at hotmail.com (adam urbas) Date: Mon, 28 May 2007 00:07:13 -0500 Subject: [Tutor] trouble with "if" Message-ID: I thank you much Alan. This has been very helpful already and I'm only on page 2. The world needs more newb-friendly people like you.> To: tutor at python.org> From: alan.gauld at btinternet.com> Date: Thu, 24 May 2007 23:39:41 +0100> Subject: Re: [Tutor] trouble with "if"> > Hi adam. > > With the aid of Google it seems a Ti83 is a programmable calculator.> > I'm not sure what python tutor you are using but it looks like > you need to cover some very basic stuff around data types.> > You may find the Raw Materials topic in my tutor useful to give > you a feel for the different types of data in Python.> > The Talking to the User topic will cover the use of raw_input.> > And the Branching topic has an examplre very similar to what > you are trying to do.> > HTH,> > -- > Alan Gauld> Author of the Learn to Program web site> http://www.freenetpages.co.uk/hp/alan.gauld> > _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Download Messenger. Start an i?m conversation. Support a cause. Join now. http://im.live.com/messenger/im/home/?source=TAGWL_MAY07 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070528/878d97d6/attachment.html From adamurbas at hotmail.com Mon May 28 07:35:55 2007 From: adamurbas at hotmail.com (adam urbas) Date: Mon, 28 May 2007 00:35:55 -0500 Subject: [Tutor] square root Message-ID: Hi all,I was just wondering how I would go about performing a square root thing, for my radiacir.py program. _________________________________________________________________ Change is good. See what?s different about Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_changegood_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070528/f2f03c69/attachment.htm From john at fouhy.net Mon May 28 07:41:30 2007 From: john at fouhy.net (John Fouhy) Date: Mon, 28 May 2007 17:41:30 +1200 Subject: [Tutor] square root In-Reply-To: References: Message-ID: <5e58f2e40705272241t7360b8bfnfc51cb0caf4c64d0@mail.gmail.com> Check out the math module. On 28/05/07, adam urbas wrote: > > Hi all, > > I was just wondering how I would go about performing a square root thing, > for my radiacir.py program. > > ________________________________ > Create the ultimate e-mail address book. Import your contacts to Windows > Live Hotmail. Try it! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From norman at khine.net Mon May 28 07:43:51 2007 From: norman at khine.net (Norman Khine) Date: Mon, 28 May 2007 07:43:51 +0200 Subject: [Tutor] square root In-Reply-To: References: Message-ID: <465A6C17.7050002@khine.net> Hello, I have not seen your radiacir.py programme so I am not sure what you want, but for square root, try this http://mail.python.org/pipermail/tutor/2001-February/003411.html HTH adam urbas wrote: > Hi all, > > I was just wondering how I would go about performing a square root > thing, for my radiacir.py program. > > ------------------------------------------------------------------------ > Create the ultimate e-mail address book. Import your contacts to Windows > Live Hotmail. Try it! > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Norman From alan.gauld at btinternet.com Mon May 28 10:36:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 May 2007 09:36:31 +0100 Subject: [Tutor] trouble with indents References: Message-ID: "adam urbas" wrote in > I'm not sure when to indent. I understand that it has to be done. Ok, But you need to understand *why* it has to be done. To do that you need to understand the basic constructs of programming: sequences, branches, loops and modules. (these are described in the concepts section of my tutorial) Basically each construct is defined by indenting in python. Thus if you have a loop in your code the set of instructions to be repeated is indented. This makes it visually clear what gets repeated. More importantly it tells the Python interpreter what it should repeat! Thus, simplistically, you need to indent anything following a colon. That is after a branch instruction: if/elif/else or a loop: for/while or a function(module) definition: def or inside a class: class The next trick is to determine when to stop indenting and that's actually harder to describe! Its basically when you want Python to stop treating your code as special - eg no longer part of the code to be repeated in a loop. > I need somewhere to start from the beginning. There are several non-programmers tutorials (including mine :-). Try one of them. http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Dive Into python is an excellent book for experienced programmers or after you have gone through one of those listed above. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon May 28 10:41:38 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 May 2007 09:41:38 +0100 Subject: [Tutor] square root References: Message-ID: "adam urbas" wrote > Hi all,I was just wondering how I would go about > performing a square root thing, for my radiacir.py program. There is a sqrt function in the math module. import math print math.sqrt(9) Math has a lot of other common mathematical functions in it too - logs, trigonometry etc Or you can use the builtin pow() function to raise the value to the power 0.5 print pow(9,0.5) or use exponentiation: print 9 ** 0.5 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From thorsten at thorstenkampe.de Mon May 28 11:45:36 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 28 May 2007 10:45:36 +0100 Subject: [Tutor] trouble with "if" References: Message-ID: * adam urbas (Sun, 27 May 2007 23:42:01 -0500) > You don't know what a Ti 83 is. Calculator. The most basic programming available. It already has so many functions built into it that it is much easier to tell it to do things. You don't have to do all this integer conversion and such whatnot. Wow... I'm really unsure of how this thing is supposed to work. It seems the more I learn about Python, the more confused I become. It's enough to bring tears to your eyes. Not really but ya.Someone else helped me with the problem of accepting numbers and words. I used:if shape in["1","circle"]:something like that. It works wonderfully. I'm not sure why, but I know that it does and that is enough. Someone else also said that I had to convert to int, and I did. That was another problem, which is now fixed.But, as usual, it is just one problem after another. Now I have run into this error message: Traceback (most recent call last): File "C:\Documents and Settings\HP_Owner\Python0\area.py", line 23, in area = 3.14*(radius**2)TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'>>> and others like this:Traceback (most recent call last): File "C:\Documents and Settings\HP_Owner\Python0\area.py", line 19, in area = height*widthTypeError: can't multiply sequence by non-int of type 'str'>>> Very frustrating. What is a non-int and what is 'str'? Why can't it multiply the sequence? I guess I should include the program I'm using for these things.I'm having this problem with both of these attached. The messages above are from area.py. area.py is sort of a prototype of radiacir.py, a test version. You know, I should probably try that int trick, which I seem to have forgotten. And guess what that did it. It's amazing when you apply the things that you learn. Apparently I am quite absent minded. Well It seems I don't need any of this help anymore. Oh well. Thanks anyway.Au > To: tutor at python.org> From: alan.gauld at btinternet.com> Date: Thu, 24 May 2007 23:34:05 +0100> Subject: Re: [Tutor] trouble with "if"> > "adam urbas" wrote > > > It won't even accept words. > > I can only get it to accept numbers. > > try this(untested code!):> > number = None> data = raw_input('Type something: ')> try: number = int(data)> except: data = data.split() # assume a string> > if number: # user entered a number> if number == 1: print 'circle'> elif number == 2: print 'another'> else: # user entered words> if data[0].lower() == 'circle': print 'circle'> else: print 'user entered ', data[0]> > Notice that to use ithe input as a number you have to > convert the raw input characters to a number (using int)> To get the individual words we can use split() which by > default splits a string into the individual words.> > Is that the kind of thing you mean?> > I've no idea what a Ti83 is BTW. :-)> > Alan G.> > _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor Do you really think someone can or will read what you wrote? I've never seen something so horribly formatted like you emails - and I've seen lots of awful formatted emails... From kent37 at tds.net Mon May 28 14:06:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 28 May 2007 08:06:02 -0400 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <465AC5AA.2080605@tds.net> adam urbas wrote: > Very frustrating. What is a non-int and what is 'str'? Why can't it > multiply the sequence? I guess I should include the program I'm using > for these things. These are more examples of the same kinds of errors you have been having. Values in Python have a type. Some examples of types are int (integer), float (floating point number) and str (string). Each type supports different operations, for example you can't add 5 to 'this is a string' or multiply 'a' * 'b' or even '5' * '6', both are strings. > I'm having this problem with both of these attached. The messages above > are from area.py. area.py is sort of a prototype of radiacir.py, a test > version. You know, I should probably try that int trick, which I seem > to have forgotten. And guess what that did it. It's amazing when you > apply the things that you learn. Apparently I am quite absent minded. > Well It seems I don't need any of this help anymore. Oh well. Thanks > anyway. You really should take the time to understand what is going on here. int() is not a 'trick'. If you approach programming as trying a bunch of tricks until you get something that seems to work, your programs will be build on sand. If you take the time to understand and work with the model that the programming language presents, you will have a much easier time of it. There are many good books and tutorials available. I recommend the book "Python Programming for the absolute beginner" for someone with no previous programming experience: http://premierpressbooks.com/ptr_detail.cfm?group=Programming&subcat=Other%20Programming&isbn=1%2D59863%2D112%2D8 Quite a few beginners' tutorials are listed here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Please, pick one of these resources, read it, write small programs that use what you learn, come back here to ask questions when you get stuck. Kent From powerpython at googlemail.com Mon May 28 10:56:45 2007 From: powerpython at googlemail.com (Sophie Marston) Date: Mon, 28 May 2007 09:56:45 +0100 Subject: [Tutor] Creating a closed source application in Python? Message-ID: <465A994D.4030206@gmail.com> Is it possible to create a closed source project in Python? Like in C++ or something, where they can't view your code? From thorsten at thorstenkampe.de Mon May 28 14:41:36 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 28 May 2007 13:41:36 +0100 Subject: [Tutor] Creating a closed source application in Python? References: <465A994D.4030206@gmail.com> Message-ID: * Sophie Marston (Mon, 28 May 2007 09:56:45 +0100) > Is it possible to create a closed source project in Python? Like in C++ > or something, where they can't view your code? Google for "Python code obfuscation" (web and comp.lang.python) Thorsten From rikard.bosnjakovic at gmail.com Mon May 28 17:55:42 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Mon, 28 May 2007 17:55:42 +0200 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: On 5/28/07, Thorsten Kampe wrote: > Do you really think someone can or will read what you wrote? I've > never seen something so horribly formatted like you emails - and I've > seen lots of awful formatted emails... Looks fine at my end. -- - Rikard - http://bos.hack.org/cv/ From thorsten at thorstenkampe.de Mon May 28 19:07:59 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 28 May 2007 18:07:59 +0100 Subject: [Tutor] trouble with "if" References: Message-ID: * Rikard Bosnjakovic (Mon, 28 May 2007 17:55:42 +0200) > On 5/28/07, Thorsten Kampe wrote: > > Do you really think someone can or will read what you wrote? I've > > never seen something so horribly formatted like you emails - and I've > > seen lots of awful formatted emails... > > Looks fine at my end. As Brian van den Broek said[1] to the "Hotmail" guy: "". Maybe because he's posting HTML and the text part is complete crap. *Hotmail* *gnarrf*. Thorsten [1] http://permalink.gmane.org/gmane.comp.python.tutor/40742 From alan.gauld at btinternet.com Mon May 28 19:21:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 May 2007 18:21:29 +0100 Subject: [Tutor] Creating a closed source application in Python? References: <465A994D.4030206@gmail.com> Message-ID: "Sophie Marston" wrote > Is it possible to create a closed source project in Python? Like in > C++ > or something, where they can't view your code? Partially. It is usually possible to reverse engineer the code but it won''t look as pretty as the original nor will it necessarily have all the comments etc. But it will be readable. Of course you can reverse engineer C++ programs too but less successfully and usually with expensive tools. However closed source doesn't mean you don't distribute the source, it means you can't (legally) change the source. Most commercial mainframe programs are 'closed source' but they include a source code listing so that the operations teams can figfure out whats going wrong in the event of an abend (ABnormal END - mainframe speak for a crash!) So in a legal sense closde source is just as easy to distribute as open source. If what you want is hidden source then you need to distribute either the .pyc compiled files or use something like py2exe to convert to an executable bundle. You could also use Jython and compile to JVM code which is easily reverse engineered into Jaba, but not so easily into Python! HTH, From bgailer at alum.rpi.edu Mon May 28 19:32:31 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 28 May 2007 10:32:31 -0700 Subject: [Tutor] Creating a closed source application in Python? In-Reply-To: References: <465A994D.4030206@gmail.com> Message-ID: <465B122F.7040802@alum.rpi.edu> Alan Gauld wrote: > Most commercial mainframe programs are 'closed source' > but they include a source code listing so that the > operations teams can figfure out whats going wrong in > the event of an abend (ABnormal END - mainframe speak > for a crash!) > Ah that brings back fond memories. In November 1974 I learned APL and began using it frevently. 3 months later I was 1 of 2 men responsible for the installation maintenance and enhancement of IBM's CMS\APL interpreter program. In order to do this job I also had to learn 370 assembler and be able to wade thru a several inch thick stack of assembler listings finding the code relevant to a particular problem, find the bug, and report it to the IBMers in Philadelphia. They were always accessible and responsive. BTW my mainframe terminal ran at 120 cps and printed on paper! -- Bob Gailer 510-978-4454 From simplebob at gmail.com Mon May 28 20:44:48 2007 From: simplebob at gmail.com (Daniel McQuay) Date: Mon, 28 May 2007 14:44:48 -0400 Subject: [Tutor] trouble with indents In-Reply-To: References: Message-ID: <6d87ecf40705281144v4a02ec7fsf5b6d3d700db5d88@mail.gmail.com> I would recomend you take a look at Alan Gauld's tutor. That is what got me started and I was able to catch on fairly quick even with little to no programming experience. http://www.freenetpages.co.uk/hp/alan.gauld On 5/28/07, Alan Gauld wrote: > > > "adam urbas" wrote in > > > I'm not sure when to indent. I understand that it has to be done. > > Ok, But you need to understand *why* it has to be done. > To do that you need to understand the basic constructs > of programming: sequences, branches, loops and modules. > (these are described in the concepts section of my tutorial) > Basically each construct is defined by indenting in python. > Thus if you have a loop in your code the set of instructions > to be repeated is indented. This makes it visually clear what > gets repeated. More importantly it tells the Python interpreter > what it should repeat! > > Thus, simplistically, you need to indent anything following > a colon. > That is after a branch instruction: if/elif/else > or a loop: for/while > or a function(module) definition: def > or inside a class: class > > The next trick is to determine when to stop indenting and > that's actually harder to describe! Its basically when you > want Python to stop treating your code as special - eg no > longer part of the code to be repeated in a loop. > > > I need somewhere to start from the beginning. > > There are several non-programmers tutorials > (including mine :-). Try one of them. > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Dive Into python is an excellent book for experienced > programmers or after you have gone through one of those > listed above. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Daniel McQuay Linux Padawan Jaluno.com H: 814.825.0847 M: 814-341-9013 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070528/89aaaa16/attachment.htm From p_grandmaison at hotmail.com Mon May 28 21:09:26 2007 From: p_grandmaison at hotmail.com (Philippe Grand'Maison) Date: Mon, 28 May 2007 15:09:26 -0400 Subject: [Tutor] Beginners In-Reply-To: <6d87ecf40705281144v4a02ec7fsf5b6d3d700db5d88@mail.gmail.com> Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070528/b6374351/attachment.htm From alan.gauld at btinternet.com Mon May 28 23:11:12 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 May 2007 22:11:12 +0100 Subject: [Tutor] Creating a closed source application in Python? References: <465A994D.4030206@gmail.com> Message-ID: "Alan Gauld" wrote > use Jython and compile to JVM code which is easily reverse > engineered into Jaba, but not so easily into Python! Erm, that would of course be Java and nothing to do with Star Wars, no matter how much I may dislike Java! :-) Alan G. From jped.aru at gmail.com Tue May 29 18:24:58 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Tue, 29 May 2007 11:24:58 -0500 Subject: [Tutor] gmail Message-ID: Hey, I have gmail now, but I'm not sure how to turn off HTML. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070529/110358fd/attachment.htm From rfquerin at gmail.com Tue May 29 18:31:21 2007 From: rfquerin at gmail.com (Richard Querin) Date: Tue, 29 May 2007 12:31:21 -0400 Subject: [Tutor] gmail In-Reply-To: References: Message-ID: <7d81675b0705290931v687604c2i98c7711bc7b44947@mail.gmail.com> On 5/29/07, Adam Urbas wrote: > Hey, > > I have gmail now, but I'm not sure how to turn off HTML. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > When you're typing in your email, you should see a '<< Plain text' button link on the upper left. This will put you in plain text mode. Likewise you'll see a similar button to switch back to 'Rich Formatting>>' mode from there. RQ From adamurbas at hotmail.com Tue May 29 18:39:56 2007 From: adamurbas at hotmail.com (adam urbas) Date: Tue, 29 May 2007 11:39:56 -0500 Subject: [Tutor] trouble with "if" Message-ID: The scary part is, I think I understand this. I copied your last example and put it in IDLE and it doesn't like you code. Never mind. I figured it out. So that is so it will notify you if your choice is invalid. Nice lil tidbit of information there. I'll be sure to use this. Oh and while your here, I'd like to ask about loops I guess they are. I want to have the program go back to the part where it asks for the user to select an option after it has run one of its if statements.Like, when the user tells it, "circle," then "radius," then enters the radius: here I would like the program to go back and ask the user if they want to do anything else, like find the area of a square, instead of the circle. Would I have to tell python to print all those selections again, or would there be a way to just return to the beginning?Thanks,Au> Date: Sun, 27 May 2007 15:10:08 -0400> From: broek at cc.umanitoba.ca> To: adamurbas at hotmail.com> CC: tutor at python.org> Subject: Re: [Tutor] trouble with "if"> > adam urbas said unto the world upon 05/27/2007 01:49 PM:> > Thank you for the help Brian. I would like to ask you about these> > things. Which one of the examples you gave would be most fool> > proof.> > readable>> > > Hi Adam and all,> > Adam was asking about how to use raw_input to drive a basic command > prompt menu system. I'd tried to explain that raw_input returns > strings, so his if tests which were something like:> > choice = raw_input("Enter an option)> if choice == 1:> do_option_1_stuff()> elif choice == 2:> do_option_2_stuff()> > were not going to work, as choice will never be equal to an int.> > I'd sketched a few ways to deal with this, chiefly applying int() to > choice or comparing choice to '1', etc.> > That's more of less the gist of the above snippage and takes us more > or less up to the point where Adam asked his question above.> > I'm going to show you a few things that might be new to you, Adam. > Let's build up in steps.> > As a first pass, I would do the following:> > choice = int(raw_input("Please make your choice "))> > if choice == 1:> # Option 1 code here> print "In option 1"> > elif choice == 2:> # Option 2 code here> print "In option 2"> > # Carry on if-test as needed (or until you get to the point> # of learning about dictionary dispatch :-)> > That will be fine, until your user enters something silly:> > >>>> Please make your choice I like bikes!> Traceback (most recent call last):> File "/home/brian/docs/jotter/python_scraps/adamcode.py", line 1, > in > choice = int(raw_input("Please make your choice "))> ValueError: invalid literal for int() with base 10: 'I like bikes!'> >>>> > That's no good!> > So, we can use Python's exception handling tools to make this a bit > better.> > > try:> choice = int(raw_input("Please make your choice "))> except ValueError:> print "Please make a choice from the options offered."> > > if choice == 1:> print "In option 1"> > elif choice == 2:> print "In option 2"> > > There is still a problem, though:> > >>> # Make sure the previous value assigned to choice is gone.> >>> del(choice)> >>>> Please make your choice I like Bikes> Please make a choice from the options offered.> Traceback (most recent call last):> File "/home/brian/docs/jotter/python_scraps/adamcode.py", line 7, > in > if choice == 1:> NameError: name 'choice' is not defined> >>>> > We've printed the reminder to the user, but then have gone on to > compare the non-existent choice value to 1, and that doesn't work so > well. It isn't enough to make sure that choice isn't insane---we need > to make sure that there is a choice value at all.> > So, better still:> > > while True:> try:> choice = int(raw_input("Please make your choice "))> # If the previous line worked, end the while loop. If it did> # not work, we won't get here, so the loop will keep looping.> break> except ValueError:> print "Please make a choice from the options offered."> > if choice == 1:> print "In option 1"> > elif choice == 2:> print "In option 2"> > > Now we get the following:> > Please make your choice I like bikes!> Please make a choice from the options offered.> Please make your choice Please take this> Please make a choice from the options offered.> Please make your choice1> In option 1> >>>> > > There is still a problem, though:> > Please make your choice 42> >>>> > Our sanity check has only insisted that the user enter a value that > can be turned into an int; nothing as yet makes it be one of the ints > we are expecting.> > So, try this:> > while True:> try:> choice = int(raw_input("Please make your choice "))> if choice < 1 or choice > 2: # Adjust to suit options> raise ValueError> break> except ValueError:> print "Please make a choice from the options offered."> > if choice == 1:> print "In option 1"> > elif choice == 2:> print "In option 2"> > > Please make your choice I like bikes!> Please make a choice from the options offered.> Please make your choice 42> Please make a choice from the options offered.> Please make your choice 2> In option 2> >>>> > > Now, all of this should be formatted to be a bit prettier---and > displaying the allowable options up front is a good idea, too---but > the essential ideas are there.> > There might be some parts of this that are new to you, so ask away if > you've gotten a bit lost.> > And, I'm no expert, so if someone else comes along and says `No, don't > do it like that', odds are they might be right. (Especially if their > name is Alan, Danny, or Kent ;-)> > Best,> > Brian vdB> _________________________________________________________________ Create the ultimate e-mail address book. Import your contacts to Windows Live Hotmail. www.windowslive-hotmail.com/learnmore/managemail2.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_impcont_0507 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070529/165e34fa/attachment.html From jim at well.com Tue May 29 18:45:11 2007 From: jim at well.com (jim stockford) Date: Tue, 29 May 2007 09:45:11 -0700 Subject: [Tutor] gmail In-Reply-To: References: Message-ID: i'd be curious to see what happens if you use the

 tag around your (properly)
indented code, e.g.

this = 1
that = 0
if this == 1 :
	that = 1
print that
On May 29, 2007, at 9:24 AM, Adam Urbas wrote: > Hey, > > I have gmail now, but I'm not sure how to turn off HTML. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From broek at cc.umanitoba.ca Tue May 29 19:36:36 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 29 May 2007 13:36:36 -0400 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <465C64A4.60602@cc.umanitoba.ca> adam urbas said unto the world upon 05/29/2007 12:39 PM: > The scary part is, I think I understand this. I copied your last > example and put it in IDLE and it doesn't like you code. Never > mind. I figured it out. So that is so it will notify you if your > choice is invalid. Nice lil tidbit of information there. I'll be > sure to use this. Oh and while your here, I'd like to ask about > loops I guess they are. I want to have the program go back to the > part where it asks for the user to select an option after it has > run one of its if statements.Like, when the user tells it, > "circle," then "radius," then enters the radius: here I would like > the program to go back and ask the user if they want to do anything > else, like find the area of a square, instead of the circle. Would > I have to tell python to print all those selections again, or would > there be a way to just return to the beginning?Thanks,Au> Date: Hi Adam, Again, I cut the mess, but I expect that if you use the gmail account you just posted about here on in, that will be the end of it. I'm glad that you are starting to have the warm glow of understanding :-) What you are asking about here is one reason why functions are so useful. They allow you (more or less) to give a name to a chunk of code, and then you can rerun that chunk at will by invoking the name. Given the problem you want to solve, I'd structure my code something like the following. Most of the details need to be filled in, but this is the skeletal structure. def welcome_message(): # Some actions to invoke when the user starts the program print "Welcome to this program." def display_menu(): # Insert code for showing the user the menu of options pass def circle_area(): # insert code here to ask user for the radius, compute the area, # and display the result. You might well want to divide that up # into other functions that this one calls. pass def square_area(): # Likewise pass # And so on, for each shape that you wish to handle def exit_message(): # Some actions to invoke when the user chooses to terminate # the program. print "Thank you for using this program. Goodbye." def prompt_user(): # Here is where the sort of code I showed you before would go. # I'd include an option, say 0, for exiting, which, when the # user picks it, you call exit_message() while True: try: choice = int(raw_input("Please make your choice ")) if choice < 0 or choice > 2: # Adjust to suit options raise ValueError break except ValueError: print "Please make a choice from the options offered." # sends the choice back to the code that called prompt_user # We won't get here until a good choice has been made return choice def main(): # The main function driving your program. It might look # something like this: welcome_message() while True: # This will loop forever until you break out display_menu() choice = prompt_user() if choice == 0: exit_message() break # Terminate the while loop elif choice == 1: # Assuming 1 was the option for circle circle_area() elif choice == 2: square_area() # And so on print "Please make another choice:" # Go back to top of loop if __name__ == '__main__': # This will run if you run the script, but not if you import it. main() This has not been tested (it is only an outline) but it does pass the only so reliable eyeball check :-) I'd suggest you try filling this sketch out to be useful, and post if you run into troubles. Best, Brian vdB From Nick.Treloar at education.nsw.gov.au Wed May 30 01:56:48 2007 From: Nick.Treloar at education.nsw.gov.au (Treloar, Nick) Date: Wed, 30 May 2007 09:56:48 +1000 Subject: [Tutor] (no subject) Message-ID: <42E18E55C3B8C24FBE1633506D22EC1303833311@DET-MAIL-EVS03.DETISP.LOCAL> how do you import sounds This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/a2fd47ad/attachment.htm From jped.aru at gmail.com Wed May 30 05:57:03 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Tue, 29 May 2007 22:57:03 -0500 Subject: [Tutor] gmail In-Reply-To: References: Message-ID: Ok, I'm not sure if I'm in the right gmail. When I type I don't see any buttons that say rich text or plain text. Only Send, Save Draft, and Discard. And I have no idea what jim is talking about. Please clarify. On 5/29/07, jim stockford wrote: > > i'd be curious to see what happens if you > use the
 tag around your (properly)
> indented code, e.g.
>
> 
> this = 1
> that = 0
> if this == 1 :
> 	that = 1
> print that
> 
> > > > On May 29, 2007, at 9:24 AM, Adam Urbas wrote: > > > Hey, > > > > I have gmail now, but I'm not sure how to turn off HTML. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > From broek at cc.umanitoba.ca Wed May 30 06:08:04 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 30 May 2007 00:08:04 -0400 Subject: [Tutor] gmail In-Reply-To: References: Message-ID: <465CF8A4.1030906@cc.umanitoba.ca> Adam Urbas said unto the world upon 05/29/2007 11:57 PM: > Ok, I'm not sure if I'm in the right gmail. When I type I don't see > any buttons that say rich text or plain text. Only Send, Save Draft, > and Discard. > > And I have no idea what jim is talking about. Please clarify. > > On 5/29/07, jim stockford wrote: >> >> i'd be curious to see what happens if you >> use the
 tag around your (properly)
>> indented code, e.g.
>>
>> 
>> this = 1
>> that = 0
>> if this == 1 :
>>     that = 1
>> print that
>> 
Well, whatever you did when sending this one sent out a plain text email. (And there was much rejoicing.) Jim suggested using an html tag to see if it helped your formatting. See here Best, Brian vdB From broek at cc.umanitoba.ca Wed May 30 06:26:29 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 30 May 2007 00:26:29 -0400 Subject: [Tutor] [Fwd: Re: trouble with "if"] Message-ID: <465CFCF5.80400@cc.umanitoba.ca> Forwarding to the list as I'm out of time on this one for now. Adam, it is better to reply to all so that messages are sent to the list and not just the original sender. That way, more people can help, more people can learn, and you don't have to wait on one person to find the time. Anticipating: when you are displaying a message in gmail, the top right-hand side of the message display window has a clickable `Reply'. Immediately beside that is a down pointing arrow. Click on that, and you will have a menu with an option `Reply to all.' That's the reply mechanism you want to use to reply to the list and the original sender rather than just the sender. Best, Brian vdB -------- Original Message -------- Subject: Re: [Tutor] trouble with "if" Date: Tue, 29 May 2007 23:07:57 -0500 From: Adam Urbas To: Brian van den Broek References: <465C64A4.60602 at cc.umanitoba.ca> In the def welcome(), what do you put in the parentheses? Another question, what code do you use for ending the program. I want the user to be able to cancel the program from the main menu, where it asks you to choose circle, square, etc. Or even perhaps allow the user to go back to a previous menu, well I suppose that would be the def thing() code. But what if they were at the part where the program was asking them to input the radius, how would I give them the option of returning to the list of given measurements of a circle? On 5/29/07, Brian van den Broek wrote: > adam urbas said unto the world upon 05/29/2007 12:39 PM: > > The scary part is, I think I understand this. I copied your last > > example and put it in IDLE and it doesn't like you code. Never > > mind. I figured it out. So that is so it will notify you if your > > choice is invalid. Nice lil tidbit of information there. I'll be > > sure to use this. Oh and while your here, I'd like to ask about > > loops I guess they are. I want to have the program go back to the > > part where it asks for the user to select an option after it has > > run one of its if statements.Like, when the user tells it, > > "circle," then "radius," then enters the radius: here I would like > > the program to go back and ask the user if they want to do anything > > else, like find the area of a square, instead of the circle. Would > > I have to tell python to print all those selections again, or would > > there be a way to just return to the beginning?Thanks,Au> Date: > > > Hi Adam, > > Again, I cut the mess, but I expect that if you use the gmail account > you just posted about here on in, that will be the end of it. > > I'm glad that you are starting to have the warm glow of understanding :-) > > What you are asking about here is one reason why functions are so > useful. They allow you (more or less) to give a name to a chunk of > code, and then you can rerun that chunk at will by invoking the name. > > Given the problem you want to solve, I'd structure my code something > like the following. Most of the details need to be filled in, but this > is the skeletal structure. > > > def welcome_message(): > # Some actions to invoke when the user starts the program > print "Welcome to this program." > > def display_menu(): > # Insert code for showing the user the menu of options > pass > > def circle_area(): > # insert code here to ask user for the radius, compute the area, > # and display the result. You might well want to divide that up > # into other functions that this one calls. > pass > > def square_area(): > # Likewise > pass > > # And so on, for each shape that you wish to handle > > def exit_message(): > # Some actions to invoke when the user chooses to terminate > # the program. > print "Thank you for using this program. Goodbye." > > def prompt_user(): > # Here is where the sort of code I showed you before would go. > # I'd include an option, say 0, for exiting, which, when the > # user picks it, you call exit_message() > > while True: > try: > choice = int(raw_input("Please make your choice ")) > if choice < 0 or choice > 2: # Adjust to suit options > raise ValueError > break > except ValueError: > print "Please make a choice from the options offered." > > # sends the choice back to the code that called prompt_user > # We won't get here until a good choice has been made > return choice > > def main(): > # The main function driving your program. It might look > # something like this: > welcome_message() > > while True: # This will loop forever until you break out > display_menu() > choice = prompt_user() > > if choice == 0: > exit_message() > break # Terminate the while loop > elif choice == 1: # Assuming 1 was the option for circle > circle_area() > elif choice == 2: > square_area() > # And so on > > print "Please make another choice:" # Go back to top of loop > > > if __name__ == '__main__': > # This will run if you run the script, but not if you import it. > main() > > > This has not been tested (it is only an outline) but it does pass the > only so reliable eyeball check :-) > > I'd suggest you try filling this sketch out to be useful, and post if > you run into troubles. > > Best, > > Brian vdB > From broek at cc.umanitoba.ca Wed May 30 06:32:06 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 30 May 2007 00:32:06 -0400 Subject: [Tutor] [Fwd: Re: trouble with "if"] Message-ID: <465CFE46.50900@cc.umanitoba.ca> Another fwd, folks. Brian vdB -------- Original Message -------- Subject: Re: [Tutor] trouble with "if" Date: Tue, 29 May 2007 23:28:46 -0500 From: Adam Urbas To: Brian van den Broek References: <465C64A4.60602 at cc.umanitoba.ca> I'm having trouble with the parentheses after the def thing(). IDLE says that there is something wrong with it. If I type something between them, it says that there is something wrong with the quotation marks. If I just leave it like (), then it says that something is wrong with what is after the parentheses. Unless my code is supposed to go between the parentheses. I'll try that. On 5/29/07, Adam Urbas wrote: > In the def welcome(), what do you put in the parentheses? Another > question, what code do you use for ending the program. I want the > user to be able to cancel the program from the main menu, where it > asks you to choose circle, square, etc. Or even perhaps allow the > user to go back to a previous menu, well I suppose that would be the > def thing() code. But what if they were at the part where the program > was asking them to input the radius, how would I give them the option > of returning to the list of given measurements of a circle? > > On 5/29/07, Brian van den Broek wrote: > > adam urbas said unto the world upon 05/29/2007 12:39 PM: > > > The scary part is, I think I understand this. I copied your last > > > example and put it in IDLE and it doesn't like you code. Never > > > mind. I figured it out. So that is so it will notify you if your > > > choice is invalid. Nice lil tidbit of information there. I'll be > > > sure to use this. Oh and while your here, I'd like to ask about > > > loops I guess they are. I want to have the program go back to the > > > part where it asks for the user to select an option after it has > > > run one of its if statements.Like, when the user tells it, > > > "circle," then "radius," then enters the radius: here I would like > > > the program to go back and ask the user if they want to do anything > > > else, like find the area of a square, instead of the circle. Would > > > I have to tell python to print all those selections again, or would > > > there be a way to just return to the beginning?Thanks,Au> Date: > > > > > > Hi Adam, > > > > Again, I cut the mess, but I expect that if you use the gmail account > > you just posted about here on in, that will be the end of it. > > > > I'm glad that you are starting to have the warm glow of understanding :-) > > > > What you are asking about here is one reason why functions are so > > useful. They allow you (more or less) to give a name to a chunk of > > code, and then you can rerun that chunk at will by invoking the name. > > > > Given the problem you want to solve, I'd structure my code something > > like the following. Most of the details need to be filled in, but this > > is the skeletal structure. > > > > > > def welcome_message(): > > # Some actions to invoke when the user starts the program > > print "Welcome to this program." > > > > def display_menu(): > > # Insert code for showing the user the menu of options > > pass > > > > def circle_area(): > > # insert code here to ask user for the radius, compute the area, > > # and display the result. You might well want to divide that up > > # into other functions that this one calls. > > pass > > > > def square_area(): > > # Likewise > > pass > > > > # And so on, for each shape that you wish to handle > > > > def exit_message(): > > # Some actions to invoke when the user chooses to terminate > > # the program. > > print "Thank you for using this program. Goodbye." > > > > def prompt_user(): > > # Here is where the sort of code I showed you before would go. > > # I'd include an option, say 0, for exiting, which, when the > > # user picks it, you call exit_message() > > > > while True: > > try: > > choice = int(raw_input("Please make your choice ")) > > if choice < 0 or choice > 2: # Adjust to suit options > > raise ValueError > > break > > except ValueError: > > print "Please make a choice from the options offered." > > > > # sends the choice back to the code that called prompt_user > > # We won't get here until a good choice has been made > > return choice > > > > def main(): > > # The main function driving your program. It might look > > # something like this: > > welcome_message() > > > > while True: # This will loop forever until you break out > > display_menu() > > choice = prompt_user() > > > > if choice == 0: > > exit_message() > > break # Terminate the while loop > > elif choice == 1: # Assuming 1 was the option for circle > > circle_area() > > elif choice == 2: > > square_area() > > # And so on > > > > print "Please make another choice:" # Go back to top of loop > > > > > > if __name__ == '__main__': > > # This will run if you run the script, but not if you import it. > > main() > > > > > > This has not been tested (it is only an outline) but it does pass the > > only so reliable eyeball check :-) > > > > I'd suggest you try filling this sketch out to be useful, and post if > > you run into troubles. > > > > Best, > > > > Brian vdB > > > From jped.aru at gmail.com Wed May 30 06:58:12 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Tue, 29 May 2007 23:58:12 -0500 Subject: [Tutor] trouble with "if" In-Reply-To: References: <465C64A4.60602@cc.umanitoba.ca> Message-ID: ok well, I'm testing to see if the CC thing worked. On 5/29/07, Adam Urbas wrote: > I'll try the CC thing. > > On 5/29/07, Adam Urbas wrote: > > Well, Brian, I am now very sure that we have different versions of > > gmail, because on both the Quick Reply and the full reply screens, > > there are no Reply buttons, or downpointing arrows. > > > > On 5/29/07, Adam Urbas wrote: > > > What is the actual command to exit the program. I tried exit, which > > > turned purple, so I know that does something. > > > > > > On 5/29/07, Adam Urbas wrote: > > > > No I don't think that worked either, because now it has a problem with > > > > print. > > > > > > > > Please help. > > > > > > > > Au > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > I'm having trouble with the parentheses after the def thing(). IDLE > > > > > says that there is something wrong with it. If I type something > > > > > between them, it says that there is something wrong with the > quotation > > > > > marks. If I just leave it like (), then it says that something is > > > > > wrong with what is after the parentheses. Unless my code is > supposed > > > > > to go between the parentheses. I'll try that. > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > In the def welcome(), what do you put in the parentheses? Another > > > > > > question, what code do you use for ending the program. I want the > > > > > > user to be able to cancel the program from the main menu, where it > > > > > > asks you to choose circle, square, etc. Or even perhaps allow the > > > > > > user to go back to a previous menu, well I suppose that would be > the > > > > > > def thing() code. But what if they were at the part where the > > program > > > > > > was asking them to input the radius, how would I give them the > > option > > > > > > of returning to the list of given measurements of a circle? > > > > > > > > > > > > On 5/29/07, Brian van den Broek wrote: > > > > > > > adam urbas said unto the world upon 05/29/2007 12:39 PM: > > > > > > > > The scary part is, I think I understand this. I copied your > > last > > > > > > > > example and put it in IDLE and it doesn't like you code. > Never > > > > > > > > mind. I figured it out. So that is so it will notify you if > > your > > > > > > > > choice is invalid. Nice lil tidbit of information there. > I'll > > be > > > > > > > > sure to use this. Oh and while your here, I'd like to ask > about > > > > > > > > loops I guess they are. I want to have the program go back to > > the > > > > > > > > part where it asks for the user to select an option after it > has > > > > > > > > run one of its if statements.Like, when the user tells it, > > > > > > > > "circle," then "radius," then enters the radius: here I would > > like > > > > > > > > the program to go back and ask the user if they want to do > > > anything > > > > > > > > else, like find the area of a square, instead of the circle. > > > Would > > > > > > > > I have to tell python to print all those selections again, or > > > would > > > > > > > > there be a way to just return to the beginning?Thanks,Au> > Date: > > > > > > > > > > > > > > > > > > > > > Hi Adam, > > > > > > > > > > > > > > Again, I cut the mess, but I expect that if you use the gmail > > > account > > > > > > > you just posted about here on in, that will be the end of it. > > > > > > > > > > > > > > I'm glad that you are starting to have the warm glow of > > > understanding > > > > > :-) > > > > > > > > > > > > > > What you are asking about here is one reason why functions are > so > > > > > > > useful. They allow you (more or less) to give a name to a chunk > of > > > > > > > code, and then you can rerun that chunk at will by invoking the > > > name. > > > > > > > > > > > > > > Given the problem you want to solve, I'd structure my code > > something > > > > > > > like the following. Most of the details need to be filled in, > but > > > this > > > > > > > is the skeletal structure. > > > > > > > > > > > > > > > > > > > > > def welcome_message(): > > > > > > > # Some actions to invoke when the user starts the program > > > > > > > print "Welcome to this program." > > > > > > > > > > > > > > def display_menu(): > > > > > > > # Insert code for showing the user the menu of options > > > > > > > pass > > > > > > > > > > > > > > def circle_area(): > > > > > > > # insert code here to ask user for the radius, compute the > > > area, > > > > > > > # and display the result. You might well want to divide > that > > up > > > > > > > # into other functions that this one calls. > > > > > > > pass > > > > > > > > > > > > > > def square_area(): > > > > > > > # Likewise > > > > > > > pass > > > > > > > > > > > > > > # And so on, for each shape that you wish to handle > > > > > > > > > > > > > > def exit_message(): > > > > > > > # Some actions to invoke when the user chooses to terminate > > > > > > > # the program. > > > > > > > print "Thank you for using this program. Goodbye." > > > > > > > > > > > > > > def prompt_user(): > > > > > > > # Here is where the sort of code I showed you before would > > go. > > > > > > > # I'd include an option, say 0, for exiting, which, when > the > > > > > > > # user picks it, you call exit_message() > > > > > > > > > > > > > > while True: > > > > > > > try: > > > > > > > choice = int(raw_input("Please make your choice ")) > > > > > > > if choice < 0 or choice > 2: # Adjust to suit > options > > > > > > > raise ValueError > > > > > > > break > > > > > > > except ValueError: > > > > > > > print "Please make a choice from the options > > offered." > > > > > > > > > > > > > > # sends the choice back to the code that called prompt_user > > > > > > > # We won't get here until a good choice has been made > > > > > > > return choice > > > > > > > > > > > > > > def main(): > > > > > > > # The main function driving your program. It might look > > > > > > > # something like this: > > > > > > > welcome_message() > > > > > > > > > > > > > > while True: # This will loop forever until you break out > > > > > > > display_menu() > > > > > > > choice = prompt_user() > > > > > > > > > > > > > > if choice == 0: > > > > > > > exit_message() > > > > > > > break # Terminate the while loop > > > > > > > elif choice == 1: # Assuming 1 was the option for > circle > > > > > > > circle_area() > > > > > > > elif choice == 2: > > > > > > > square_area() > > > > > > > # And so on > > > > > > > > > > > > > > print "Please make another choice:" # Go back to top > of > > > > loop > > > > > > > > > > > > > > > > > > > > > if __name__ == '__main__': > > > > > > > # This will run if you run the script, but not if you > import > > > it. > > > > > > > main() > > > > > > > > > > > > > > > > > > > > > This has not been tested (it is only an outline) but it does > pass > > > the > > > > > > > only so reliable eyeball check :-) > > > > > > > > > > > > > > I'd suggest you try filling this sketch out to be useful, and > post > > > if > > > > > > > you run into troubles. > > > > > > > > > > > > > > Best, > > > > > > > > > > > > > > Brian vdB > > > > > > > > > > > > > > > > > > > > > > > > > > > > From jped.aru at gmail.com Wed May 30 07:06:08 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Wed, 30 May 2007 00:06:08 -0500 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: Dang it... I am really going to have to figure out how to reply all. The cc thing only worked once and now I'm still sending to you. On 5/30/07, Adam Urbas wrote: > I started to read Alan Gauld's tutorial. The problem is, once I get > past the very basics of something, I tend to get impatient and don't > want to go back and have to redo them, but the other problem is, I may > need something that is taught in the basic sections. So ya, I'll try > to keep on a reading Alan's tutorial. > > On 5/30/07, Adam Urbas wrote: > > I have already subscribed. I tried sending a message when I was not > > yet subscribed, and the Moderator or Administrator, or whoever said to > > resubscribe. Sorry about my accident programming. > > > > On 5/29/07, Adam Urbas wrote: > > > ok well, I'm testing to see if the CC thing worked. > > > > > > On 5/29/07, Adam Urbas wrote: > > > > I'll try the CC thing. > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > Well, Brian, I am now very sure that we have different versions of > > > > > gmail, because on both the Quick Reply and the full reply screens, > > > > > there are no Reply buttons, or downpointing arrows. > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > What is the actual command to exit the program. I tried exit, > which > > > > > > turned purple, so I know that does something. > > > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > > No I don't think that worked either, because now it has a > problem > > > with > > > > > > > print. > > > > > > > > > > > > > > Please help. > > > > > > > > > > > > > > Au > > > > > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > > > I'm having trouble with the parentheses after the def thing(). > > > IDLE > > > > > > > > says that there is something wrong with it. If I type > something > > > > > > > > between them, it says that there is something wrong with the > > > > quotation > > > > > > > > marks. If I just leave it like (), then it says that > something > > is > > > > > > > > wrong with what is after the parentheses. Unless my code is > > > > supposed > > > > > > > > to go between the parentheses. I'll try that. > > > > > > > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > > > > In the def welcome(), what do you put in the parentheses? > > > Another > > > > > > > > > question, what code do you use for ending the program. I > want > > > the > > > > > > > > > user to be able to cancel the program from the main menu, > > where > > > it > > > > > > > > > asks you to choose circle, square, etc. Or even perhaps > allow > > > the > > > > > > > > > user to go back to a previous menu, well I suppose that > would > > be > > > > the > > > > > > > > > def thing() code. But what if they were at the part where > the > > > > > program > > > > > > > > > was asking them to input the radius, how would I give them > the > > > > > option > > > > > > > > > of returning to the list of given measurements of a circle? > > > > > > > > > > > > > > > > > > On 5/29/07, Brian van den Broek > wrote: > > > > > > > > > > adam urbas said unto the world upon 05/29/2007 12:39 PM: > > > > > > > > > > > The scary part is, I think I understand this. I copied > > your > > > > > last > > > > > > > > > > > example and put it in IDLE and it doesn't like you code. > > > > Never > > > > > > > > > > > mind. I figured it out. So that is so it will notify > you > > > if > > > > > your > > > > > > > > > > > choice is invalid. Nice lil tidbit of information > there. > > > > I'll > > > > > be > > > > > > > > > > > sure to use this. Oh and while your here, I'd like to > ask > > > > about > > > > > > > > > > > loops I guess they are. I want to have the program go > > back > > > to > > > > > the > > > > > > > > > > > part where it asks for the user to select an option > after > > it > > > > has > > > > > > > > > > > run one of its if statements.Like, when the user tells > it, > > > > > > > > > > > "circle," then "radius," then enters the radius: here I > > > would > > > > > like > > > > > > > > > > > the program to go back and ask the user if they want to > do > > > > > > anything > > > > > > > > > > > else, like find the area of a square, instead of the > > circle. > > > > > > Would > > > > > > > > > > > I have to tell python to print all those selections > again, > > > or > > > > > > would > > > > > > > > > > > there be a way to just return to the > beginning?Thanks,Au> > > > > Date: > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > Hi Adam, > > > > > > > > > > > > > > > > > > > > Again, I cut the mess, but I expect that if you use the > > gmail > > > > > > account > > > > > > > > > > you just posted about here on in, that will be the end of > > it. > > > > > > > > > > > > > > > > > > > > I'm glad that you are starting to have the warm glow of > > > > > > understanding > > > > > > > > :-) > > > > > > > > > > > > > > > > > > > > What you are asking about here is one reason why functions > > are > > > > so > > > > > > > > > > useful. They allow you (more or less) to give a name to a > > > chunk > > > > of > > > > > > > > > > code, and then you can rerun that chunk at will by > invoking > > > the > > > > > > name. > > > > > > > > > > > > > > > > > > > > Given the problem you want to solve, I'd structure my code > > > > > something > > > > > > > > > > like the following. Most of the details need to be filled > > in, > > > > but > > > > > > this > > > > > > > > > > is the skeletal structure. > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > def welcome_message(): > > > > > > > > > > # Some actions to invoke when the user starts the > > program > > > > > > > > > > print "Welcome to this program." > > > > > > > > > > > > > > > > > > > > def display_menu(): > > > > > > > > > > # Insert code for showing the user the menu of > options > > > > > > > > > > pass > > > > > > > > > > > > > > > > > > > > def circle_area(): > > > > > > > > > > # insert code here to ask user for the radius, > compute > > > the > > > > > > area, > > > > > > > > > > # and display the result. You might well want to > divide > > > > that > > > > > up > > > > > > > > > > # into other functions that this one calls. > > > > > > > > > > pass > > > > > > > > > > > > > > > > > > > > def square_area(): > > > > > > > > > > # Likewise > > > > > > > > > > pass > > > > > > > > > > > > > > > > > > > > # And so on, for each shape that you wish to handle > > > > > > > > > > > > > > > > > > > > def exit_message(): > > > > > > > > > > # Some actions to invoke when the user chooses to > > > terminate > > > > > > > > > > # the program. > > > > > > > > > > print "Thank you for using this program. Goodbye." > > > > > > > > > > > > > > > > > > > > def prompt_user(): > > > > > > > > > > # Here is where the sort of code I showed you before > > > would > > > > > go. > > > > > > > > > > # I'd include an option, say 0, for exiting, which, > > when > > > > the > > > > > > > > > > # user picks it, you call exit_message() > > > > > > > > > > > > > > > > > > > > while True: > > > > > > > > > > try: > > > > > > > > > > choice = int(raw_input("Please make your > choice > > > ")) > > > > > > > > > > if choice < 0 or choice > 2: # Adjust to suit > > > > options > > > > > > > > > > raise ValueError > > > > > > > > > > break > > > > > > > > > > except ValueError: > > > > > > > > > > print "Please make a choice from the options > > > > > offered." > > > > > > > > > > > > > > > > > > > > # sends the choice back to the code that called > > > prompt_user > > > > > > > > > > # We won't get here until a good choice has been made > > > > > > > > > > return choice > > > > > > > > > > > > > > > > > > > > def main(): > > > > > > > > > > # The main function driving your program. It might > look > > > > > > > > > > # something like this: > > > > > > > > > > welcome_message() > > > > > > > > > > > > > > > > > > > > while True: # This will loop forever until you > break > > > out > > > > > > > > > > display_menu() > > > > > > > > > > choice = prompt_user() > > > > > > > > > > > > > > > > > > > > if choice == 0: > > > > > > > > > > exit_message() > > > > > > > > > > break # Terminate the while loop > > > > > > > > > > elif choice == 1: # Assuming 1 was the option > for > > > > circle > > > > > > > > > > circle_area() > > > > > > > > > > elif choice == 2: > > > > > > > > > > square_area() > > > > > > > > > > # And so on > > > > > > > > > > > > > > > > > > > > print "Please make another choice:" # Go back > to > > > top > > > > of > > > > > > > loop > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > if __name__ == '__main__': > > > > > > > > > > # This will run if you run the script, but not if you > > > > import > > > > > > it. > > > > > > > > > > main() > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > This has not been tested (it is only an outline) but it > does > > > > pass > > > > > > the > > > > > > > > > > only so reliable eyeball check :-) > > > > > > > > > > > > > > > > > > > > I'd suggest you try filling this sketch out to be useful, > > and > > > > post > > > > > > if > > > > > > > > > > you run into troubles. > > > > > > > > > > > > > > > > > > > > Best, > > > > > > > > > > > > > > > > > > > > Brian vdB > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > From grantahagstrom at gmail.com Wed May 30 07:51:19 2007 From: grantahagstrom at gmail.com (Grant Hagstrom) Date: Wed, 30 May 2007 00:51:19 -0500 Subject: [Tutor] trouble with "if" In-Reply-To: References: Message-ID: <4257d6370705292251g1aa9d521s7ff7cb9c4d41e14f@mail.gmail.com> Right above the empty reply box is a "reply to all" link. Hit it, and you're good to go. On 5/30/07, Adam Urbas wrote: > > Dang it... I am really going to have to figure out how to reply all. > The cc thing only worked once and now I'm still sending to you. > > On 5/30/07, Adam Urbas wrote: > > I started to read Alan Gauld's tutorial. The problem is, once I get > > past the very basics of something, I tend to get impatient and don't > > want to go back and have to redo them, but the other problem is, I may > > need something that is taught in the basic sections. So ya, I'll try > > to keep on a reading Alan's tutorial. > > > > On 5/30/07, Adam Urbas wrote: > > > I have already subscribed. I tried sending a message when I was not > > > yet subscribed, and the Moderator or Administrator, or whoever said to > > > resubscribe. Sorry about my accident programming. > > > > > > On 5/29/07, Adam Urbas wrote: > > > > ok well, I'm testing to see if the CC thing worked. > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > I'll try the CC thing. > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > Well, Brian, I am now very sure that we have different versions > of > > > > > > gmail, because on both the Quick Reply and the full reply > screens, > > > > > > there are no Reply buttons, or downpointing arrows. > > > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > > What is the actual command to exit the program. I tried exit, > > which > > > > > > > turned purple, so I know that does something. > > > > > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > > > No I don't think that worked either, because now it has a > > problem > > > > with > > > > > > > > print. > > > > > > > > > > > > > > > > Please help. > > > > > > > > > > > > > > > > Au > > > > > > > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > > > > I'm having trouble with the parentheses after the def > thing(). > > > > IDLE > > > > > > > > > says that there is something wrong with it. If I type > > something > > > > > > > > > between them, it says that there is something wrong with > the > > > > > quotation > > > > > > > > > marks. If I just leave it like (), then it says that > > something > > > is > > > > > > > > > wrong with what is after the parentheses. Unless my code > is > > > > > supposed > > > > > > > > > to go between the parentheses. I'll try that. > > > > > > > > > > > > > > > > > > On 5/29/07, Adam Urbas wrote: > > > > > > > > > > In the def welcome(), what do you put in the > parentheses? > > > > Another > > > > > > > > > > question, what code do you use for ending the > program. I > > want > > > > the > > > > > > > > > > user to be able to cancel the program from the main > menu, > > > where > > > > it > > > > > > > > > > asks you to choose circle, square, etc. Or even perhaps > > allow > > > > the > > > > > > > > > > user to go back to a previous menu, well I suppose that > > would > > > be > > > > > the > > > > > > > > > > def thing() code. But what if they were at the part > where > > the > > > > > > program > > > > > > > > > > was asking them to input the radius, how would I give > them > > the > > > > > > option > > > > > > > > > > of returning to the list of given measurements of a > circle? > > > > > > > > > > > > > > > > > > > > On 5/29/07, Brian van den Broek > > wrote: > > > > > > > > > > > adam urbas said unto the world upon 05/29/2007 12:39 > PM: > > > > > > > > > > > > The scary part is, I think I understand this. I > copied > > > your > > > > > > last > > > > > > > > > > > > example and put it in IDLE and it doesn't like you > code. > > > > > Never > > > > > > > > > > > > mind. I figured it out. So that is so it will > notify > > you > > > > if > > > > > > your > > > > > > > > > > > > choice is invalid. Nice lil tidbit of information > > there. > > > > > I'll > > > > > > be > > > > > > > > > > > > sure to use this. Oh and while your here, I'd like > to > > ask > > > > > about > > > > > > > > > > > > loops I guess they are. I want to have the program > go > > > back > > > > to > > > > > > the > > > > > > > > > > > > part where it asks for the user to select an option > > after > > > it > > > > > has > > > > > > > > > > > > run one of its if statements.Like, when the user > tells > > it, > > > > > > > > > > > > "circle," then "radius," then enters the radius: > here I > > > > would > > > > > > like > > > > > > > > > > > > the program to go back and ask the user if they want > to > > do > > > > > > > anything > > > > > > > > > > > > else, like find the area of a square, instead of the > > > circle. > > > > > > > Would > > > > > > > > > > > > I have to tell python to print all those selections > > again, > > > > or > > > > > > > would > > > > > > > > > > > > there be a way to just return to the > > beginning?Thanks,Au> > > > > > Date: > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > Hi Adam, > > > > > > > > > > > > > > > > > > > > > > Again, I cut the mess, but I expect that if you use > the > > > gmail > > > > > > > account > > > > > > > > > > > you just posted about here on in, that will be the end > of > > > it. > > > > > > > > > > > > > > > > > > > > > > I'm glad that you are starting to have the warm glow > of > > > > > > > understanding > > > > > > > > > :-) > > > > > > > > > > > > > > > > > > > > > > What you are asking about here is one reason why > functions > > > are > > > > > so > > > > > > > > > > > useful. They allow you (more or less) to give a name > to a > > > > chunk > > > > > of > > > > > > > > > > > code, and then you can rerun that chunk at will by > > invoking > > > > the > > > > > > > name. > > > > > > > > > > > > > > > > > > > > > > Given the problem you want to solve, I'd structure my > code > > > > > > something > > > > > > > > > > > like the following. Most of the details need to be > filled > > > in, > > > > > but > > > > > > > this > > > > > > > > > > > is the skeletal structure. > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > def welcome_message(): > > > > > > > > > > > # Some actions to invoke when the user starts the > > > program > > > > > > > > > > > print "Welcome to this program." > > > > > > > > > > > > > > > > > > > > > > def display_menu(): > > > > > > > > > > > # Insert code for showing the user the menu of > > options > > > > > > > > > > > pass > > > > > > > > > > > > > > > > > > > > > > def circle_area(): > > > > > > > > > > > # insert code here to ask user for the radius, > > compute > > > > the > > > > > > > area, > > > > > > > > > > > # and display the result. You might well want to > > divide > > > > > that > > > > > > up > > > > > > > > > > > # into other functions that this one calls. > > > > > > > > > > > pass > > > > > > > > > > > > > > > > > > > > > > def square_area(): > > > > > > > > > > > # Likewise > > > > > > > > > > > pass > > > > > > > > > > > > > > > > > > > > > > # And so on, for each shape that you wish to handle > > > > > > > > > > > > > > > > > > > > > > def exit_message(): > > > > > > > > > > > # Some actions to invoke when the user chooses to > > > > terminate > > > > > > > > > > > # the program. > > > > > > > > > > > print "Thank you for using this program. > Goodbye." > > > > > > > > > > > > > > > > > > > > > > def prompt_user(): > > > > > > > > > > > # Here is where the sort of code I showed you > before > > > > would > > > > > > go. > > > > > > > > > > > # I'd include an option, say 0, for exiting, > which, > > > when > > > > > the > > > > > > > > > > > # user picks it, you call exit_message() > > > > > > > > > > > > > > > > > > > > > > while True: > > > > > > > > > > > try: > > > > > > > > > > > choice = int(raw_input("Please make your > > choice > > > > ")) > > > > > > > > > > > if choice < 0 or choice > 2: # Adjust to > suit > > > > > options > > > > > > > > > > > raise ValueError > > > > > > > > > > > break > > > > > > > > > > > except ValueError: > > > > > > > > > > > print "Please make a choice from the > options > > > > > > offered." > > > > > > > > > > > > > > > > > > > > > > # sends the choice back to the code that called > > > > prompt_user > > > > > > > > > > > # We won't get here until a good choice has been > made > > > > > > > > > > > return choice > > > > > > > > > > > > > > > > > > > > > > def main(): > > > > > > > > > > > # The main function driving your program. It > might > > look > > > > > > > > > > > # something like this: > > > > > > > > > > > welcome_message() > > > > > > > > > > > > > > > > > > > > > > while True: # This will loop forever until you > > break > > > > out > > > > > > > > > > > display_menu() > > > > > > > > > > > choice = prompt_user() > > > > > > > > > > > > > > > > > > > > > > if choice == 0: > > > > > > > > > > > exit_message() > > > > > > > > > > > break # Terminate the while loop > > > > > > > > > > > elif choice == 1: # Assuming 1 was the > option > > for > > > > > circle > > > > > > > > > > > circle_area() > > > > > > > > > > > elif choice == 2: > > > > > > > > > > > square_area() > > > > > > > > > > > # And so on > > > > > > > > > > > > > > > > > > > > > > print "Please make another choice:" # Go > back > > to > > > > top > > > > > of > > > > > > > > loop > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > if __name__ == '__main__': > > > > > > > > > > > # This will run if you run the script, but not if > you > > > > > import > > > > > > > it. > > > > > > > > > > > main() > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > This has not been tested (it is only an outline) but > it > > does > > > > > pass > > > > > > > the > > > > > > > > > > > only so reliable eyeball check :-) > > > > > > > > > > > > > > > > > > > > > > I'd suggest you try filling this sketch out to be > useful, > > > and > > > > > post > > > > > > > if > > > > > > > > > > > you run into troubles. > > > > > > > > > > > > > > > > > > > > > > Best, > > > > > > > > > > > > > > > > > > > > > > Brian vdB > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/adf5b0da/attachment-0001.html From andreengels at gmail.com Wed May 30 08:53:04 2007 From: andreengels at gmail.com (Andre Engels) Date: Wed, 30 May 2007 08:53:04 +0200 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: <465CFE46.50900@cc.umanitoba.ca> References: <465CFE46.50900@cc.umanitoba.ca> Message-ID: <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> 2007/5/30, Brian van den Broek : > Another fwd, folks. > > Brian vdB > > -------- Original Message -------- > Subject: Re: [Tutor] trouble with "if" > Date: Tue, 29 May 2007 23:28:46 -0500 > From: Adam Urbas > To: Brian van den Broek > References: > <465C64A4.60602 at cc.umanitoba.ca> > > > I'm having trouble with the parentheses after the def thing(). IDLE > says that there is something wrong with it. If I type something > between them, it says that there is something wrong with the quotation > marks. If I just leave it like (), then it says that something is > wrong with what is after the parentheses. Unless my code is supposed > to go between the parentheses. I'll try that. Between the parentheses should go the variables you use (if any) when calling the function. For example: def sayhello(): print "Hello" You don't have any parameters here, so there's nothing between the brackets def say(word): print word Now there is one parameter, namely word. def sayboth(word1,word2): print word1 print word2 Here there are two parameters, word1 and word2. The number of parameters should be the same as the number of parameters you use when calling the function: sayhello() say("One text") sayboth("One text","Another text") There is a much used method to make some of the parameters optional, but we'll not go into that. To know what is going wrong with your program, I would have to see the program (or a simplified version of it that still goes wrong) and preferably also the exact error message you are getting. -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From jped.aru at gmail.com Wed May 30 17:01:28 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Wed, 30 May 2007 10:01:28 -0500 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> References: <465CFE46.50900@cc.umanitoba.ca> <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> Message-ID: I can't exactly show you the error message anymore, because the program is now screwed up in so many ways that I can't even get it to do the things it used to. It says things like ERROR: Inconsistent indentation detected! 1) Your indentation is outright incorrect (easy to fix), OR 2) Your indentation mixes tabs and spaces. Then it tells me to untabify everything, which i did and it still gives this message. I've started completely over with the exact same indentation and that one works. Oh my gosh this gmail is a fricken crack head... none of this stuff was here last night. I have no idea what was going on then, but everything you guys said is right here. The plain text is right next to the Check spelling, the reply to all is right above send and save now and in the corner near the little arrow. Well, it's working now. Ok, so if i have a section of code that is: answer=(2+3): print "answer", answer so for the code above I would put: (I think I would have to have the two numbers and the addition thing in there wouldn't I; I saw something like this on Alan's tutorial last night.) def answer(2,3): answer=(2+3) print "answer",answer That is obviously not right.: There's an error in your program: invalid syntax when it says that it highlights the 2: def answer(2+3): Ok I think I understand these now. Thanks for the advice. I have this now: def answer(): print("answer") answer() It works too, yay! Thanks, Au On 5/30/07, Andre Engels wrote: > > 2007/5/30, Brian van den Broek : > > Another fwd, folks. > > > > Brian vdB > > > > -------- Original Message -------- > > Subject: Re: [Tutor] trouble with "if" > > Date: Tue, 29 May 2007 23:28:46 -0500 > > From: Adam Urbas > > To: Brian van den Broek > > References: > > <465C64A4.60602 at cc.umanitoba.ca> > > > > > > I'm having trouble with the parentheses after the def thing(). IDLE > > says that there is something wrong with it. If I type something > > between them, it says that there is something wrong with the quotation > > marks. If I just leave it like (), then it says that something is > > wrong with what is after the parentheses. Unless my code is supposed > > to go between the parentheses. I'll try that. > > Between the parentheses should go the variables you use (if any) when > calling the function. For example: > > def sayhello(): > print "Hello" > > You don't have any parameters here, so there's nothing between the > brackets > > def say(word): > print word > > Now there is one parameter, namely word. > > def sayboth(word1,word2): > print word1 > print word2 > > Here there are two parameters, word1 and word2. > > The number of parameters should be the same as the number of > parameters you use when calling the function: > > sayhello() > say("One text") > sayboth("One text","Another text") > > There is a much used method to make some of the parameters optional, > but we'll not go into that. > > To know what is going wrong with your program, I would have to see the > program (or a simplified version of it that still goes wrong) and > preferably also the exact error message you are getting. > > > -- > Andre Engels, andreengels at gmail.com > ICQ: 6260644 -- Skype: a_engels > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/af433e73/attachment.html From jped.aru at gmail.com Wed May 30 17:07:04 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Wed, 30 May 2007 10:07:04 -0500 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: References: <465CFE46.50900@cc.umanitoba.ca> <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> Message-ID: Ahahahahaha... I have figured these out beyond comprehension and power. Wahhaha. It feels good to get something to work correctly. Thanks much Andre. I don't quite understand the putting of things inside the parentheses, but I've discovered that I don't really need to, because def text(): works just fine with everything I've done so far. On 5/30/07, Adam Urbas wrote: > > I can't exactly show you the error message anymore, because the program is > now screwed up in so many ways that I can't even get it to do the things it > used to. > > It says things like ERROR: Inconsistent indentation detected! > 1) Your indentation is outright incorrect (easy to fix), OR > 2) Your indentation mixes tabs and spaces. Then it tells me to untabify > everything, which i did and it still gives this message. I've started > completely over with the exact same indentation and that one works. > > Oh my gosh this gmail is a fricken crack head... none of this stuff was > here last night. I have no idea what was going on then, but everything you > guys said is right here. The plain text is right next to the Check > spelling, the reply to all is right above send and save now and in the > corner near the little arrow. Well, it's working now. > > Ok, so if i have a section of code that is: > > answer=(2+3): > print "answer", answer > > so for the code above I would put: (I think I would have to have the two > numbers and the addition thing in there wouldn't I; I saw something like > this on Alan's tutorial last night.) > > def answer(2,3): > answer=(2+3) > print "answer",answer > > That is obviously not right.: > > There's an error in your program: > invalid syntax > > when it says that it highlights the 2: def answer( 2+3): > > Ok I think I understand these now. Thanks for the advice. I have this > now: > > def answer(): > print("answer") > answer() > > It works too, yay! > Thanks, > > Au > > > > On 5/30/07, Andre Engels wrote: > > > > 2007/5/30, Brian van den Broek < broek at cc.umanitoba.ca>: > > > Another fwd, folks. > > > > > > Brian vdB > > > > > > -------- Original Message -------- > > > Subject: Re: [Tutor] trouble with "if" > > > Date: Tue, 29 May 2007 23:28:46 -0500 > > > From: Adam Urbas > > > To: Brian van den Broek > > > References: < BAY103-W11DE2E62FD41449A952D68B12F0 at phx.gbl> > > > <465C64A4.60602 at cc.umanitoba.ca> > > > < ef52818c0705292107n1ee0c105k54c02ccf4d85f7c6 at mail.gmail.com> > > > > > > I'm having trouble with the parentheses after the def thing(). IDLE > > > says that there is something wrong with it. If I type something > > > between them, it says that there is something wrong with the quotation > > > marks. If I just leave it like (), then it says that something is > > > wrong with what is after the parentheses. Unless my code is supposed > > > to go between the parentheses. I'll try that. > > > > Between the parentheses should go the variables you use (if any) when > > calling the function. For example: > > > > def sayhello(): > > print "Hello" > > > > You don't have any parameters here, so there's nothing between the > > brackets > > > > def say(word): > > print word > > > > Now there is one parameter, namely word. > > > > def sayboth(word1,word2): > > print word1 > > print word2 > > > > Here there are two parameters, word1 and word2. > > > > The number of parameters should be the same as the number of > > parameters you use when calling the function: > > > > sayhello() > > say("One text") > > sayboth("One text","Another text") > > > > There is a much used method to make some of the parameters optional, > > but we'll not go into that. > > > > To know what is going wrong with your program, I would have to see the > > program (or a simplified version of it that still goes wrong) and > > preferably also the exact error message you are getting. > > > > > > -- > > Andre Engels, andreengels at gmail.com > > ICQ: 6260644 -- Skype: a_engels > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/df68b652/attachment.htm From broek at cc.umanitoba.ca Wed May 30 17:21:48 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 30 May 2007 11:21:48 -0400 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: References: <465CFE46.50900@cc.umanitoba.ca> <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> Message-ID: <465D968C.5060205@cc.umanitoba.ca> Adam Urbas said unto the world upon 05/30/2007 11:01 AM: > I can't exactly show you the error message anymore, because the program is > now screwed up in so many ways that I can't even get it to do the things it > used to. > > It says things like ERROR: Inconsistent indentation detected! > 1) Your indentation is outright incorrect (easy to fix), OR > 2) Your indentation mixes tabs and spaces. Then it tells me to untabify > everything, which i did and it still gives this message. I've started > completely over with the exact same indentation and that one works. > > Oh my gosh this gmail is a fricken crack head... none of this stuff was > here > last night. I have no idea what was going on then, but everything you guys > said is right here. The plain text is right next to the Check spelling, > the > reply to all is right above send and save now and in the corner near the > little arrow. Well, it's working now. > > Ok, so if i have a section of code that is: > > answer=(2+3): > print "answer", answer > > so for the code above I would put: (I think I would have to have the two > numbers and the addition thing in there wouldn't I; I saw something like > this on Alan's tutorial last night.) > > def answer(2,3): > answer=(2+3) > print "answer",answer > > That is obviously not right.: > > There's an error in your program: > invalid syntax > > when it says that it highlights the 2: def answer(2+3): > > Ok I think I understand these now. Thanks for the advice. I have this > now: > > def answer(): > print("answer") > answer() > > It works too, yay! > Thanks, > > Au > Adam, Glad you are sorting out the gmail---in the long run, plain text will make this all much easier than what you had before :-) Your answer function definition above is saying something like this: make answer the name of a function that takes no parameters, and, when called, have it execute a print. This: > def answer(2,3): > answer=(2+3) > print "answer",answer doesn't work, as you are trying to set the values of the two parameters to 2 and 3 in the function definition itself. That's not how parameters work. The definition of a function sets the parameters up as named `slots' that function calls will give values to. (There are, as Andre pointed out, more details, but let those aside for now and focus on the simplest cases.) This: def answer(): answer=(2+3) print "answer",answer would work, but it isn't much different than the code that did work. Try this: def answer(my_first_parameter, my_second_parameter): value = my_first_parameter + my_second_parameter print "Answer:\t", value (I wouldn't use the cumbersome names `my_first_parameter', etc. in real code, but perhaps they help keeping track of what is going on in early stages.) That says, in effect, let answer be a function which takes two positional parameters, adds them, and prints the result in an informative way. >>> answer(40, 2) Answer: 42 >>> answer("A string", " and another string") Answer: A string and another string >>> These work because the function definition ensures that the first parameter (40, in the first case above) will, as far as the function is concerned, be called my_first_parameter. (Likewise for 2 and my_second_parameter.) Does that help? Brian vdB From mikerev at gmail.com Wed May 30 18:19:39 2007 From: mikerev at gmail.com (Michael Revelle) Date: Wed, 30 May 2007 11:19:39 -0500 Subject: [Tutor] python exercises Message-ID: <226db29e0705300919o57bc4760w2ef0467a8028e571@mail.gmail.com> Anyone know where I can get some python excercises, like labs/someone's old homework assignments? I'm learning python without any prior experience in programming except for fundamental bash scripting and a lot of the terms and functionality doesn't make sense to me. I'm using Python Programming for the Absolute Beginner by Michael Dawson . -- Michael Revelle From Mike.Hansen at atmel.com Wed May 30 18:40:20 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Wed, 30 May 2007 10:40:20 -0600 Subject: [Tutor] python exercises In-Reply-To: <226db29e0705300919o57bc4760w2ef0467a8028e571@mail.gmail.com> References: <226db29e0705300919o57bc4760w2ef0467a8028e571@mail.gmail.com> Message-ID: <57B026980605A64F9B23484C5659E32E7D536D@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Michael Revelle > > Anyone know where I can get some python excercises, like > labs/someone's old homework assignments? There are some ideas at http://effbot.org/pyfaq/tutor-im-learning-python-what-should-i-program.h tm or http://tinyurl.com/yalvar Mike From jped.aru at gmail.com Wed May 30 19:38:56 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Wed, 30 May 2007 12:38:56 -0500 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: <465D968C.5060205@cc.umanitoba.ca> References: <465CFE46.50900@cc.umanitoba.ca> <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> <465D968C.5060205@cc.umanitoba.ca> Message-ID: I can't seem to get the type with the parameters to work. I can get def answer(): to work, but not def answer(my_first_parameter,my_second_parameter):. I'm not too concerned, as I haven't yet needed to use that. But, when I use the parameter type, it runs without error messages, but doesn't display anything. That's when I'm using your example with my_first_parameter. But when I use: def answer(40,2): answer=40+2 print "Answer:\t", value answer() it says: There's an error in your program: invalid syntax and then it highlights the first number between the parentheses, like last time. OK. New topic temporarily... I just completed a portion of my radiacir.py program, after much debugging. I still want to add that error message thing that we discussed eariler, but that's a whole nother can of worms. So I'm going to attach it. This is very exciting. Except, I renamed it and now it doesn't work. This frustrates me. How could something work one second and then not the next. Oh well, I'll still attach it and if you could help me find the problem, that would be nice. Thanks, Au On 5/30/07, Brian van den Broek wrote: > Adam Urbas said unto the world upon 05/30/2007 11:01 AM: > > I can't exactly show you the error message anymore, because the program is > > now screwed up in so many ways that I can't even get it to do the things it > > used to. > > > > It says things like ERROR: Inconsistent indentation detected! > > 1) Your indentation is outright incorrect (easy to fix), OR > > 2) Your indentation mixes tabs and spaces. Then it tells me to untabify > > everything, which i did and it still gives this message. I've started > > completely over with the exact same indentation and that one works. > > > > Oh my gosh this gmail is a fricken crack head... none of this stuff was > > here > > last night. I have no idea what was going on then, but everything you guys > > said is right here. The plain text is right next to the Check spelling, > > the > > reply to all is right above send and save now and in the corner near the > > little arrow. Well, it's working now. > > > > Ok, so if i have a section of code that is: > > > > answer=(2+3): > > print "answer", answer > > > > so for the code above I would put: (I think I would have to have the two > > numbers and the addition thing in there wouldn't I; I saw something like > > this on Alan's tutorial last night.) > > > > def answer(2,3): > > answer=(2+3) > > print "answer",answer > > > > That is obviously not right.: > > > > There's an error in your program: > > invalid syntax > > > > when it says that it highlights the 2: def answer(2+3): > > > > Ok I think I understand these now. Thanks for the advice. I have this > > now: > > > > def answer(): > > print("answer") > > answer() > > > > It works too, yay! > > Thanks, > > > > Au > > > > > Adam, > > Glad you are sorting out the gmail---in the long run, plain text will > make this all much easier than what you had before :-) > > Your answer function definition above is saying something like this: > make answer the name of a function that takes no parameters, and, when > called, have it execute a print. > > This: > > > def answer(2,3): > > answer=(2+3) > > print "answer",answer > > doesn't work, as you are trying to set the values of the two > parameters to 2 and 3 in the function definition itself. That's not > how parameters work. The definition of a function sets the parameters > up as named `slots' that function calls will give values to. (There > are, as Andre pointed out, more details, but let those aside for now > and focus on the simplest cases.) > > This: > > def answer(): > answer=(2+3) > print "answer",answer > > would work, but it isn't much different than the code that did work. > > Try this: > > def answer(my_first_parameter, my_second_parameter): > value = my_first_parameter + my_second_parameter > print "Answer:\t", value > > (I wouldn't use the cumbersome names `my_first_parameter', etc. in > real code, but perhaps they help keeping track of what is going on in > early stages.) > > That says, in effect, let answer be a function which takes two > positional parameters, adds them, and prints the result in an > informative way. > > >>> answer(40, 2) > Answer: 42 > >>> answer("A string", " and another string") > Answer: A string and another string > >>> > > These work because the function definition ensures that the first > parameter (40, in the first case above) will, as far as the function > is concerned, be called my_first_parameter. (Likewise for 2 and > my_second_parameter.) > > Does that help? > > Brian vdB > From jped.aru at gmail.com Wed May 30 19:45:23 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Wed, 30 May 2007 12:45:23 -0500 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: References: <465CFE46.50900@cc.umanitoba.ca> <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> <465D968C.5060205@cc.umanitoba.ca> Message-ID: I think I may have figured it out. I just switched some things around. On 5/30/07, Adam Urbas wrote: > I can't seem to get the type with the parameters to work. I can get > def answer(): to work, but not def > answer(my_first_parameter,my_second_parameter):. I'm not too > concerned, as I haven't yet needed to use that. But, when I use the > parameter type, it runs without error messages, but doesn't display > anything. That's when I'm using your example with my_first_parameter. > But when I use: > > def answer(40,2): > answer=40+2 > print "Answer:\t", value > answer() > > it says: > > There's an error in your program: > invalid syntax > > and then it highlights the first number between the parentheses, like last time. > > OK. New topic temporarily... I just completed a portion of my > radiacir.py program, after much debugging. I still want to add that > error message thing that we discussed eariler, but that's a whole > nother can of worms. So I'm going to attach it. This is very > exciting. Except, I renamed it and now it doesn't work. This > frustrates me. How could something work one second and then not the > next. Oh well, I'll still attach it and if you could help me find the > problem, that would be nice. > > Thanks, > Au > On 5/30/07, Brian van den Broek wrote: > > Adam Urbas said unto the world upon 05/30/2007 11:01 AM: > > > I can't exactly show you the error message anymore, because the program is > > > now screwed up in so many ways that I can't even get it to do the things it > > > used to. > > > > > > It says things like ERROR: Inconsistent indentation detected! > > > 1) Your indentation is outright incorrect (easy to fix), OR > > > 2) Your indentation mixes tabs and spaces. Then it tells me to untabify > > > everything, which i did and it still gives this message. I've started > > > completely over with the exact same indentation and that one works. > > > > > > Oh my gosh this gmail is a fricken crack head... none of this stuff was > > > here > > > last night. I have no idea what was going on then, but everything you guys > > > said is right here. The plain text is right next to the Check spelling, > > > the > > > reply to all is right above send and save now and in the corner near the > > > little arrow. Well, it's working now. > > > > > > Ok, so if i have a section of code that is: > > > > > > answer=(2+3): > > > print "answer", answer > > > > > > so for the code above I would put: (I think I would have to have the two > > > numbers and the addition thing in there wouldn't I; I saw something like > > > this on Alan's tutorial last night.) > > > > > > def answer(2,3): > > > answer=(2+3) > > > print "answer",answer > > > > > > That is obviously not right.: > > > > > > There's an error in your program: > > > invalid syntax > > > > > > when it says that it highlights the 2: def answer(2+3): > > > > > > Ok I think I understand these now. Thanks for the advice. I have this > > > now: > > > > > > def answer(): > > > print("answer") > > > answer() > > > > > > It works too, yay! > > > Thanks, > > > > > > Au > > > > > > > > > Adam, > > > > Glad you are sorting out the gmail---in the long run, plain text will > > make this all much easier than what you had before :-) > > > > Your answer function definition above is saying something like this: > > make answer the name of a function that takes no parameters, and, when > > called, have it execute a print. > > > > This: > > > > > def answer(2,3): > > > answer=(2+3) > > > print "answer",answer > > > > doesn't work, as you are trying to set the values of the two > > parameters to 2 and 3 in the function definition itself. That's not > > how parameters work. The definition of a function sets the parameters > > up as named `slots' that function calls will give values to. (There > > are, as Andre pointed out, more details, but let those aside for now > > and focus on the simplest cases.) > > > > This: > > > > def answer(): > > answer=(2+3) > > print "answer",answer > > > > would work, but it isn't much different than the code that did work. > > > > Try this: > > > > def answer(my_first_parameter, my_second_parameter): > > value = my_first_parameter + my_second_parameter > > print "Answer:\t", value > > > > (I wouldn't use the cumbersome names `my_first_parameter', etc. in > > real code, but perhaps they help keeping track of what is going on in > > early stages.) > > > > That says, in effect, let answer be a function which takes two > > positional parameters, adds them, and prints the result in an > > informative way. > > > > >>> answer(40, 2) > > Answer: 42 > > >>> answer("A string", " and another string") > > Answer: A string and another string > > >>> > > > > These work because the function definition ensures that the first > > parameter (40, in the first case above) will, as far as the function > > is concerned, be called my_first_parameter. (Likewise for 2 and > > my_second_parameter.) > > > > Does that help? > > > > Brian vdB > > > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: acp.py Url: http://mail.python.org/pipermail/tutor/attachments/20070530/8d3126fa/attachment.asc From john.ertl at navy.mil Wed May 30 19:35:57 2007 From: john.ertl at navy.mil (Ertl, John C CIV 63134) Date: Wed, 30 May 2007 10:35:57 -0700 Subject: [Tutor] problem with mmap References: Message-ID: <2B3C3C2EA721A04191268CE74039414101814F8D@NAWEMUGUEX02VA.nadsuswe.nads.navy.mil> All, I am trying to work an example that I found at http://bitworking.org/news/132/REST-Tips-URI-space-is-infinite When I try the code below I get an error and I am not able to figure it out. Thanks for any and all help. I have two png and a text file (sortzip.txt) in the same dir as this code but I do not even get to that part...the mmap call is bad. I have never used mmap before so this is new to me. I am running python 2.4 John ############# code from mmap import mmap import os from bisect import bisect_left import sys class Zipcodes(object): """Use mmap to treat the sorted file of zipcodes as an array""" def __init__(self): self.f = open("sortzips.txt", "r+") self.size = os.path.getsize("sortzips.txt") self.m = mmap(self.f.fileno(), self.size) def __getitem__(self, i): self.m.seek(6*i) return self.m.read(5) def __del__(self): self.m.close() self.f.close() def __len__(self): return self.size / 6 zipcodes = Zipcodes() target = os.environ.get('PATH_INFO', '/')[1:] found = ( zipcodes[bisect_left(zipcodes, target)] == target ) print "Status: " + ( found and "200 Ok" or "404 Not Found" ) print "Cache-control: max-age=172800" print "Content-type: image/png" print "" file = open(found and "good.png" or "bad.png", "r") png = file.read() file.close() sys.stdout.write(png) ########################## error message when I try to run this. Traceback (most recent call last): File "./zipcode.cgi", line 23, in ? zipcodes = Zipcodes() File "./zipcode.cgi", line 14, in __init__ self.m = mmap(self.f.fileno(), self.size) EnvironmentError: [Errno 22] Invalid argument Exception exceptions.AttributeError: "'Zipcodes' object has no attribute 'm'" in > ignored ########################### John Ertl Meteorologist FNMOC 7 Grace Hopper Ave. Monterey, CA 93943 (831) 656-5704 john.ertl at navy.mil -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 6578 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070530/3479d7ff/attachment-0001.bin From jped.aru at gmail.com Wed May 30 19:49:42 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Wed, 30 May 2007 12:49:42 -0500 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: References: <465CFE46.50900@cc.umanitoba.ca> <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> <465D968C.5060205@cc.umanitoba.ca> Message-ID: Ok I forgot to put some things on the previous one. I discovered a flaw in my loop. It is not infinite. If you select circle, radius, enter the radius, circle, radius, enter the radius, then the program stops. I want it to be able to keep going as many times as needed, infinitely. So that the user could keep using that segment of the program over and over again, without having to restart the program. Is it possible to do that? On 5/30/07, Adam Urbas wrote: > I think I may have figured it out. I just switched some things around. > > On 5/30/07, Adam Urbas wrote: > > I can't seem to get the type with the parameters to work. I can get > > def answer(): to work, but not def > > answer(my_first_parameter,my_second_parameter):. I'm not too > > concerned, as I haven't yet needed to use that. But, when I use the > > parameter type, it runs without error messages, but doesn't display > > anything. That's when I'm using your example with my_first_parameter. > > But when I use: > > > > def answer(40,2): > > answer=40+2 > > print "Answer:\t", value > > answer() > > > > it says: > > > > There's an error in your program: > > invalid syntax > > > > and then it highlights the first number between the parentheses, like last time. > > > > OK. New topic temporarily... I just completed a portion of my > > radiacir.py program, after much debugging. I still want to add that > > error message thing that we discussed eariler, but that's a whole > > nother can of worms. So I'm going to attach it. This is very > > exciting. Except, I renamed it and now it doesn't work. This > > frustrates me. How could something work one second and then not the > > next. Oh well, I'll still attach it and if you could help me find the > > problem, that would be nice. > > > > Thanks, > > Au > > On 5/30/07, Brian van den Broek wrote: > > > Adam Urbas said unto the world upon 05/30/2007 11:01 AM: > > > > I can't exactly show you the error message anymore, because the program is > > > > now screwed up in so many ways that I can't even get it to do the things it > > > > used to. > > > > > > > > It says things like ERROR: Inconsistent indentation detected! > > > > 1) Your indentation is outright incorrect (easy to fix), OR > > > > 2) Your indentation mixes tabs and spaces. Then it tells me to untabify > > > > everything, which i did and it still gives this message. I've started > > > > completely over with the exact same indentation and that one works. > > > > > > > > Oh my gosh this gmail is a fricken crack head... none of this stuff was > > > > here > > > > last night. I have no idea what was going on then, but everything you guys > > > > said is right here. The plain text is right next to the Check spelling, > > > > the > > > > reply to all is right above send and save now and in the corner near the > > > > little arrow. Well, it's working now. > > > > > > > > Ok, so if i have a section of code that is: > > > > > > > > answer=(2+3): > > > > print "answer", answer > > > > > > > > so for the code above I would put: (I think I would have to have the two > > > > numbers and the addition thing in there wouldn't I; I saw something like > > > > this on Alan's tutorial last night.) > > > > > > > > def answer(2,3): > > > > answer=(2+3) > > > > print "answer",answer > > > > > > > > That is obviously not right.: > > > > > > > > There's an error in your program: > > > > invalid syntax > > > > > > > > when it says that it highlights the 2: def answer(2+3): > > > > > > > > Ok I think I understand these now. Thanks for the advice. I have this > > > > now: > > > > > > > > def answer(): > > > > print("answer") > > > > answer() > > > > > > > > It works too, yay! > > > > Thanks, > > > > > > > > Au > > > > > > > > > > > > > Adam, > > > > > > Glad you are sorting out the gmail---in the long run, plain text will > > > make this all much easier than what you had before :-) > > > > > > Your answer function definition above is saying something like this: > > > make answer the name of a function that takes no parameters, and, when > > > called, have it execute a print. > > > > > > This: > > > > > > > def answer(2,3): > > > > answer=(2+3) > > > > print "answer",answer > > > > > > doesn't work, as you are trying to set the values of the two > > > parameters to 2 and 3 in the function definition itself. That's not > > > how parameters work. The definition of a function sets the parameters > > > up as named `slots' that function calls will give values to. (There > > > are, as Andre pointed out, more details, but let those aside for now > > > and focus on the simplest cases.) > > > > > > This: > > > > > > def answer(): > > > answer=(2+3) > > > print "answer",answer > > > > > > would work, but it isn't much different than the code that did work. > > > > > > Try this: > > > > > > def answer(my_first_parameter, my_second_parameter): > > > value = my_first_parameter + my_second_parameter > > > print "Answer:\t", value > > > > > > (I wouldn't use the cumbersome names `my_first_parameter', etc. in > > > real code, but perhaps they help keeping track of what is going on in > > > early stages.) > > > > > > That says, in effect, let answer be a function which takes two > > > positional parameters, adds them, and prints the result in an > > > informative way. > > > > > > >>> answer(40, 2) > > > Answer: 42 > > > >>> answer("A string", " and another string") > > > Answer: A string and another string > > > >>> > > > > > > These work because the function definition ensures that the first > > > parameter (40, in the first case above) will, as far as the function > > > is concerned, be called my_first_parameter. (Likewise for 2 and > > > my_second_parameter.) > > > > > > Does that help? > > > > > > Brian vdB > > > > > > > -------------- next part -------------- #Welcome screen: def welcome(): print "Welcome to the Area Calculation Program." print welcome() #Shape choice: def shape(): print "Choose a Shape:" print "1 Circle" print "2 Square" print "3 Triangle" print "4 Exit" print shape() #If circle: def circle(): shape=raw_input(">") if shape in["1","circle"]: print "1 Radius" print "2 Diameter" print "3 Circumference" print "4 Area" print circle() #If radius: def radius(): radius=int(raw_input("Enter Radius:")) diameter=(radius*2) circumference=(diameter*3.14) area=(radius**2*3.14) print "Diameter",diameter print "Circumference",circumference print "Area",area print print def choice(): given=raw_input(">") if given in["1","radius"]: radius() choice() shape() choice() From pine508 at hotmail.com Wed May 30 19:51:54 2007 From: pine508 at hotmail.com (Che M) Date: Wed, 30 May 2007 13:51:54 -0400 Subject: [Tutor] monitor other running applications with Py In-Reply-To: Message-ID: Thanks for the pointers, Alan. It seems perhaps a bit beyond my abilities for now, but something to keep in mind for the future if I get that far. And yes, the legal aspects are worth noting, though rest assured my wish for such a thing is for self-monitoring rather than other-monitoring, though I can see how it could get used nefariously if not cautious. Best, Che >Date: Sun, 27 May 2007 15:54:11 +0100 >From: "Alan Gauld" >Subject: Re: [Tutor] monitor other running applications with Python? >To: tutor at python.org >Message-ID: >Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > >"Che M" wrote > > > Hi, searched a bit for this but haven't found much. > > Is it possible to use Python to monitor the use of > > other applications? > >Yes, definitely. > > > At minimum, I wan't to know that the application was running > >Thats fairly easy using OS tools such as ps on Unix. >You can dig a little deeper and use the system APIs such >as the proc fiilesystem or the equivalent in the windows >registry. > > > better would be some sense of the use or content, such > > as whether the app was idle or the user was using it, > > or, for a web browser, what URLs were visited and for > > how long, etc. > >Thats possible but gets very OS specific and very low level too. >On Windows you can catch Windows events and messages >using some of the raw Win32 API calls from the ctypes module. >(I've never used ctypes for anything this low level but it >should be possible, I''ve certainly done it in C++ and Delphi >on Win 9X). But its messy and fairly deep Windows magic >and you will need to spend a fair bit of time experimenting >and reading the docs on MSDN as well as the Win32 API >help file. > > > Ideally I'd like a cross-platforms approach > >I doubt if that's possible except at the process monitoring >level. For the kind of detail you want the bgestb you can >do is have a common UI and pluggable modules based >on the OS. > >Also beware legal implications. There are issues around >personal privacy, data proptection etc and these vary between >countries (and even states in the US). People are increasingly >wary of Big Brother style monitoring. Detecting inappropriate >use of the internet across a corporate firwall is generally >considered OK but silently monitoring individuals brings you >into murky legal waters. > >Finally, take a look at the stuff in the os package and the >syslog module for Unix. > >HTH, > >-- >Alan Gauld >Author of the Learn to Program web site >http://www.freenetpages.co.uk/hp/alan.gauld > > > >------------------------------ > >Message: 2 >Date: Sun, 27 May 2007 12:25:17 -0500 >From: adam urbas >Subject: [Tutor] error message questions >To: python tutor >Message-ID: >Content-Type: text/plain; charset="windows-1252" > >Hello all,I was wondering if there would be someone who would be able to >give me a list of error messages and their meanings. I've attached this >test.py to illustrate my problem. When I run the program, I am able to >enter all the data, yet it will not calculate.It says:can't multiply >sequence by non-int of type 'str'I really would like to know how to fix >this.I get a similar message with my other one, radiacir.py:can't multiply >sequence by non-int of type 'float'Please help!Thanks in advance,Adam >_________________________________________________________________ >Change is good. See what?s different about Windows Live Hotmail. >http://www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=RMT_TAGLM_HMWL_reten_changegood_0507 >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: >http://mail.python.org/pipermail/tutor/attachments/20070527/167120aa/attachment.html >-------------- next part -------------- >An embedded and charset-unspecified text was scrubbed... >Name: test.py >Url: >http://mail.python.org/pipermail/tutor/attachments/20070527/167120aa/attachment-0001.pot >-------------- next part -------------- >An embedded and charset-unspecified text was scrubbed... >Name: radiacir.py >Url: >http://mail.python.org/pipermail/tutor/attachments/20070527/167120aa/attachment-0001.asc > >------------------------------ > >Message: 3 >Date: Sun, 27 May 2007 12:49:04 -0500 >From: adam urbas >Subject: Re: [Tutor] trouble with "if" >To: Brian van den Broek >Cc: python tutor >Message-ID: >Content-Type: text/plain; charset="windows-1252" > >Thank you for the help Brian. I would like to ask you about these things. >Which one of the examples you gave would be most fool proof.> Date: Wed, 23 >May 2007 13:40:09 -0400> From: broek at cc.umanitoba.ca> To: >adamurbas at hotmail.com> CC: tutor at python.org> Subject: Re: [Tutor] trouble >with "if"> > adam urbas said unto the world upon 05/23/2007 01:04 PM:> > >Sorry, I don't think Hotmail has turn off HTML. If it does I> > havn't >been able to find it. I think you're going to have to> > explain your >little bit of text stuff down there at the bottom. I> > have no idea what >most of that means. All my choice things are> > working now though. I >think that is what you were trying to help> > me with. What I used wasif >shape in["1","circle"]:and if shape ==> > "1" or shape =="circle":It works >perfectly fine now.Ya that little> > bit o' code is really puzzling. I >wish I knew more about this> > python deal. I understand the concept, but >not the rules or the> > techniques and things ! > of that sort. OK... I've got it... the> > data=raw_input('Feed Me!'). >Ok I now understand that bit. Then it> > says Feed Me! and you put 42 >(the ultimate answer to life the> > universe, everything). OK, it won't >accept the bit.> > it doesn't like the "<". Well, I just >removed that bit and it> > said:Feed Me! and I put 42, and it said >>> (I >guess it's> > satisfied now, with the whole feeding). Well if I understood >what> > 'str' meant, then I could probably figure the rest out. Well I> > >have to go do other things so I'll save the rest of this figuring> > out >till later.I shall return,Adam> Date: Wed, 23 May 2007 12:12:16> > -0400> >From: broek at cc.umanitoba.ca> To: adamurbas at hotmail.com> CC:> > >tutor at python.org> Subject: Re: [Tutor] trouble with "if"> > adam> > urbas >said unto the world upon 05/23/2007 11:57 AM:> > > > Hi all,>> > > > > I've >been working with this new program that I wrote. I> > started out > > with >it on a Ti-83, which is much easier to! > program> > than python. Now > > I'm trying to transfer the program t >o python> > but its proving to be quite > > difficult. I'm not sure what >the> > whole indentation thing is for. And > > now I'm having trouble> > >with the if statement things. > > > > #"Circle Data Calculation> > >Program:"> > print "Welcome to the Circle Data Calcuation> > Program."> > >print> > > > #"Menu 1:"> > print "Pick a shape:">> > > print "(NOTE: >You must select the number of the shape and not the> > shape > > itself)"> > > print "1 Circle"> > print "2 Square"> > print> > "3 Triangle"> > > > >#"User's Choice:"> > shape=raw_input("> ")>> > > > > #"Select >Given:"> > if shape == 1:> > print> > "Choose the given value:"> > > print "1 radius"> >> > print "2 diameter"> > print "3 >circumference"> >> > print "4 area"> > > > #"User's Choice:"> > >given=raw_input("> ")> >> > > > if given == 1:> > >radius=raw_input("Enter Radius:")> >> > diameter=(radius*2)> > >circumference=(diameter*3.14)> >> > area=(radius**2*3.14)> > ! > print "Diameter:", diameter> >> > print "Circumference:", circumference> > > print "Area:",> > area> > > > if given == 2:> > >diameter=raw_input("Enter> > Diameter:")> > radius=(diameter/2)> >> > > circumference=(diameter*3.14)> > area=(radius**2*3.14)> >> > >print "Radius:", radius> > print "Circumference:",> > >circumference> > print "Area:", area> > > > if given == 3:>> > > > circumference=raw_input("Enter Circumference:")> >> > >radius=(circumference/3.14/2)> > diameter=(radius*2)> >> > >area=(radius**2*3.14)> > print "Radius:", radius> >> > print >"Diameter:", diameter> > print "Area:", area> > > >> > if given == >4:> > area=raw_input("Enter Area:")> >> > radius=(area/3.14)> > > > > This is the whole program so> > far, because I haven't quite >finished it > > yet. But I tried to> > get it to display another list of >options after you > > select a> > shape but it just does this.> > > > Pick! > a shape:> > 1 Circle> > 2> > Square> > 3 Triangle> > >1> > >1> > > > >>> > > > I'm not sure why> > it does that but I do know that it is >skipping the > > second list> > of options.> > > > Another of my problems >is that I can't figure> > out how to get it to > > accept two different >inputs for a> > selection. Like I want it to accept > > both the number 1 >and> > circle as circle then list the options for > > circle. It won't> > >even accept words. I can only get it to accept > > numbers. It's> > quite >frustrating actually.> > > > Any advice would be greatly> > appreciated.> > >Thanks in advance,> > Adam> > > > > > > Adam,> >> > Could you send plain >text email rather than html, please? At least> > for > me, your code's >indentation is all messed up unless I take> > some steps > to rectify it.> > > The problem is that raw_input> > returns a string, and you are testing > >whether given is equal to> > integers. See if this helps make things >clear:> > >>> data => > raw_input('Feed me!')> Feed me!42> >>> >type(data)> >> > >>> data == 42> ! > False> >>> int(data) == 42> True> >>>> > Best,> >> > Brian vdB > > > >Adam,> > As you can see from the above, the way hotmail is formatting >things > makes the conversation a bit tricky :-) I'm only willing to spend >so > much time trying to sort through it, so I hope what follows helps.> > > >>> data = raw_input("Feed me!")> Feed me!42> > This calls the builtin >function raw_input with a parameter setting the > prompt to "Feed me!" and >assigns the result to data. Since I hit 42 > and then enter,> > >>> data> >'42'> > Notice the quotes around 42. They indicate that the value of data >is a > string. That's what this tells us:> > >>> type(data)> > > > The string '42' is not the same as the integer 42:> > >>> type(42)> >> >>> '42' == 42> False> > So, when you had an if test that >was something like:> > if given == 1:> # Do stuff here> > the equality >comparison was never going to work---given was a string > returned by >raw_input and no string is ever equa! > l to an integer.> > What I suggested was taking the string returned by > raw_input and > feeding it to int() to transform it from a string to an >integer, and > allow your if test to stand a chance:> > >>> data = >raw_input("Feed me!")> Feed me!42> >>> if data == 42:> ... print >"Matches!"> ...> >>> data = int(raw_input("Feed me!"))> Feed me!42> >>> >if data == 42:> ... print "Matches!"> ...> Matches!> >>>> > There are >other ways, for instance:> > >>> data = raw_input("Feed me!")> Feed me!42> > >>> if data == '42':> ... print "Matches!"> ...> Matches!> >>>> > >Here, instead of transforming data to an int and then testing for > >equality with 42, I left data as a string and tested for equality with > >the string '42'.> > The way calling int() is a bit better, I think. If the >user enters a > few spaces, then 42 then a few more spaces, that way will >still work:> > >>> data = int(raw_input("Feed me!"))> Feed me! 42> >>> >if data == 42:> ... print "Matches!"> ...> Matches!> >>>> > because> > > >>> int(' 42 ')> 42> >>>> > whereas> > ! > >>> ' 42 ' == '42'> False> > > I hope there is some help in there >somewhere :-)> > Brian vdB >_________________________________________________________________ >Change is good. See what?s different about Windows Live Hotmail. >www.windowslive-hotmail.com/learnmore/default.html?locale=en-us&ocid=TXT_TAGLM_HMWL_reten_changegood_0507 >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: >http://mail.python.org/pipermail/tutor/attachments/20070527/81f34a70/attachment.htm > >------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > >End of Tutor Digest, Vol 39, Issue 70 >************************************* _________________________________________________________________ Catch suspicious messages before you open them?with Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_protection_0507 From jped.aru at gmail.com Wed May 30 20:59:02 2007 From: jped.aru at gmail.com (Adam Urbas) Date: Wed, 30 May 2007 13:59:02 -0500 Subject: [Tutor] [Fwd: Re: trouble with "if"] In-Reply-To: References: <465CFE46.50900@cc.umanitoba.ca> <6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com> <465D968C.5060205@cc.umanitoba.ca> Message-ID: Once again this is my latest version. I know of several problems, such as the previously posted infinite looping problem. Also, if sends you to the wrong place sometimes. Ex: a second ago, I pressed 4 to exit (which does not work either) and it took me to triangle. I'm not sure how to end the program. It takes you to the def goodbye(): part, but then if you press enter again, it starts the program over. I was hoping that if I just left it blank, then it would just automatically end, like it does with simpler programs, but that was not the case, because apparently there has to be something after the def goodbye(): So If someone wouldn't mind taking a look at it, then I would be very grateful. Thanks, Au On 5/30/07, Adam Urbas wrote: > Ok I forgot to put some things on the previous one. I discovered a > flaw in my loop. It is not infinite. If you select circle, radius, > enter the radius, circle, radius, enter the radius, then the program > stops. I want it to be able to keep going as many times as needed, > infinitely. So that the user could keep using that segment of the > program over and over again, without having to restart the program. > Is it possible to do that? > > On 5/30/07, Adam Urbas wrote: > > I think I may have figured it out. I just switched some things around. > > > > On 5/30/07, Adam Urbas wrote: > > > I can't seem to get the type with the parameters to work. I can get > > > def answer(): to work, but not def > > > answer(my_first_parameter,my_second_parameter):. I'm not too > > > concerned, as I haven't yet needed to use that. But, when I use the > > > parameter type, it runs without error messages, but doesn't display > > > anything. That's when I'm using your example with my_first_parameter. > > > But when I use: > > > > > > def answer(40,2): > > > answer=40+2 > > > print "Answer:\t", value > > > answer() > > > > > > it says: > > > > > > There's an error in your program: > > > invalid syntax > > > > > > and then it highlights the first number between the parentheses, like last time. > > > > > > OK. New topic temporarily... I just completed a portion of my > > > radiacir.py program, after much debugging. I still want to add that > > > error message thing that we discussed eariler, but that's a whole > > > nother can of worms. So I'm going to attach it. This is very > > > exciting. Except, I renamed it and now it doesn't work. This > > > frustrates me. How could something work one second and then not the > > > next. Oh well, I'll still attach it and if you could help me find the > > > problem, that would be nice. > > > > > > Thanks, > > > Au > > > On 5/30/07, Brian van den Broek wrote: > > > > Adam Urbas said unto the world upon 05/30/2007 11:01 AM: > > > > > I can't exactly show you the error message anymore, because the program is > > > > > now screwed up in so many ways that I can't even get it to do the things it > > > > > used to. > > > > > > > > > > It says things like ERROR: Inconsistent indentation detected! > > > > > 1) Your indentation is outright incorrect (easy to fix), OR > > > > > 2) Your indentation mixes tabs and spaces. Then it tells me to untabify > > > > > everything, which i did and it still gives this message. I've started > > > > > completely over with the exact same indentation and that one works. > > > > > > > > > > Oh my gosh this gmail is a fricken crack head... none of this stuff was > > > > > here > > > > > last night. I have no idea what was going on then, but everything you guys > > > > > said is right here. The plain text is right next to the Check spelling, > > > > > the > > > > > reply to all is right above send and save now and in the corner near the > > > > > little arrow. Well, it's working now. > > > > > > > > > > Ok, so if i have a section of code that is: > > > > > > > > > > answer=(2+3): > > > > > print "answer", answer > > > > > > > > > > so for the code above I would put: (I think I would have to have the two > > > > > numbers and the addition thing in there wouldn't I; I saw something like > > > > > this on Alan's tutorial last night.) > > > > > > > > > > def answer(2,3): > > > > > answer=(2+3) > > > > > print "answer",answer > > > > > > > > > > That is obviously not right.: > > > > > > > > > > There's an error in your program: > > > > > invalid syntax > > > > > > > > > > when it says that it highlights the 2: def answer(2+3): > > > > > > > > > > Ok I think I understand these now. Thanks for the advice. I have this > > > > > now: > > > > > > > > > > def answer(): > > > > > print("answer") > > > > > answer() > > > > > > > > > > It works too, yay! > > > > > Thanks, > > > > > > > > > > Au > > > > > > > > > > > > > > > > > Adam, > > > > > > > > Glad you are sorting out the gmail---in the long run, plain text will > > > > make this all much easier than what you had before :-) > > > > > > > > Your answer function definition above is saying something like this: > > > > make answer the name of a function that takes no parameters, and, when > > > > called, have it execute a print. > > > > > > > > This: > > > > > > > > > def answer(2,3): > > > > > answer=(2+3) > > > > > print "answer",answer > > > > > > > > doesn't work, as you are trying to set the values of the two > > > > parameters to 2 and 3 in the function definition itself. That's not > > > > how parameters work. The definition of a function sets the parameters > > > > up as named `slots' that function calls will give values to. (There > > > > are, as Andre pointed out, more details, but let those aside for now > > > > and focus on the simplest cases.) > > > > > > > > This: > > > > > > > > def answer(): > > > > answer=(2+3) > > > > print "answer",answer > > > > > > > > would work, but it isn't much different than the code that did work. > > > > > > > > Try this: > > > > > > > > def answer(my_first_parameter, my_second_parameter): > > > > value = my_first_parameter + my_second_parameter > > > > print "Answer:\t", value > > > > > > > > (I wouldn't use the cumbersome names `my_first_parameter', etc. in > > > > real code, but perhaps they help keeping track of what is going on in > > > > early stages.) > > > > > > > > That says, in effect, let answer be a function which takes two > > > > positional parameters, adds them, and prints the result in an > > > > informative way. > > > > > > > > >>> answer(40, 2) > > > > Answer: 42 > > > > >>> answer("A string", " and another string") > > > > Answer: A string and another string > > > > >>> > > > > > > > > These work because the function definition ensures that the first > > > > parameter (40, in the first case above) will, as far as the function > > > > is concerned, be called my_first_parameter. (Likewise for 2 and > > > > my_second_parameter.) > > > > > > > > Does that help? > > > > > > > > Brian vdB > > > > > > > > > > > > > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: acp.py Url: http://mail.python.org/pipermail/tutor/attachments/20070530/d1999cbd/attachment.pot From grantahagstrom at gmail.com Wed May 30 21:01:35 2007 From: grantahagstrom at gmail.com (Grant Hagstrom) Date: Wed, 30 May 2007 14:01:35 -0500 Subject: [Tutor] python exercises In-Reply-To: <57B026980605A64F9B23484C5659E32E7D536D@poccso.US.ad.atmel.com> References: <226db29e0705300919o57bc4760w2ef0467a8028e571@mail.gmail.com> <57B026980605A64F9B23484C5659E32E7D536D@poccso.US.ad.atmel.com> Message-ID: <4257d6370705301201m57f6134ev893106c6ff09273d@mail.gmail.com> the daniweb forum has a beginners project sticky: http://www.daniweb.com/techtalkforums/thread32007.html On 5/30/07, Mike Hansen wrote: > > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Michael Revelle > > > > Anyone know where I can get some python excercises, like > > labs/someone's old homework assignments? > > There are some ideas at > > http://effbot.org/pyfaq/tutor-im-learning-python-what-should-i-program.h > tm > > or http://tinyurl.com/yalvar > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/b168e2b1/attachment.html From kriti_satija at yahoo.co.in Wed May 30 21:36:12 2007 From: kriti_satija at yahoo.co.in (Kriti Satija) Date: Wed, 30 May 2007 20:36:12 +0100 (BST) Subject: [Tutor] leave tutorial Message-ID: <49592.54519.qm@web8511.mail.in.yahoo.com> i want to leave the tutorial Looking for people who are YOUR TYPE? Find them at in.groups.yahoo.com From wescpy at gmail.com Wed May 30 21:48:40 2007 From: wescpy at gmail.com (wesley chun) Date: Wed, 30 May 2007 12:48:40 -0700 Subject: [Tutor] python exercises In-Reply-To: <226db29e0705300919o57bc4760w2ef0467a8028e571@mail.gmail.com> References: <226db29e0705300919o57bc4760w2ef0467a8028e571@mail.gmail.com> Message-ID: <78b3a9580705301248y6dc55325hb9612a8202b20cc1@mail.gmail.com> > Anyone know where I can get some python excercises, like > labs/someone's old homework assignments? I'm learning python without > any prior experience in programming except for fundamental bash > scripting and a lot of the terms and functionality doesn't make sense > to me. michael, i put a *lot* of exercises into Core Python (see link below). there are exercises at the end of every chapter. the book, however, targets those with prior programming experience. since you've done shell scripting before, you aren't exactly a complete newbie. i think what would also be valuable to you would be the numerous interactive interpreter examples... you can follow along with or without a computer in front of you. seeing all those examples will hopefully clear up some of the confusion you have now. if you go to the book's website, there should be a link to download a free chapter to see if it's right for you. also, if you have any particular areas of trouble/understanding, and/or have code snippets, including errors, feel free to post them here for the tutors to look at. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From tktucker at gmail.com Wed May 30 21:48:45 2007 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 30 May 2007 15:48:45 -0400 Subject: [Tutor] leave tutorial In-Reply-To: <49592.54519.qm@web8511.mail.in.yahoo.com> References: <49592.54519.qm@web8511.mail.in.yahoo.com> Message-ID: <2a278ffe0705301248w74962d27p2721ab0cc72f8613@mail.gmail.com> http://mail.python.org/mailman/listinfo/tutor On 5/30/07, Kriti Satija wrote: > > i want to leave the tutorial > > > Looking for people who are YOUR TYPE? Find them at > in.groups.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/405370e0/attachment.html From grantahagstrom at gmail.com Wed May 30 21:50:25 2007 From: grantahagstrom at gmail.com (Grant Hagstrom) Date: Wed, 30 May 2007 14:50:25 -0500 Subject: [Tutor] leave tutorial In-Reply-To: <49592.54519.qm@web8511.mail.in.yahoo.com> References: <49592.54519.qm@web8511.mail.in.yahoo.com> Message-ID: <4257d6370705301250g1e663c3er202693a0e0f184a@mail.gmail.com> Nobody leaves the tutorial. http://mail.python.org/mailman/listinfo/tutor (at the bottom of the page) On 5/30/07, Kriti Satija wrote: > > i want to leave the tutorial > > > Looking for people who are YOUR TYPE? Find them at > in.groups.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/b1a25b7d/attachment.htm From alan.gauld at btinternet.com Wed May 30 23:05:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 May 2007 22:05:48 +0100 Subject: [Tutor] [Fwd: Re: trouble with "if"] References: <465CFE46.50900@cc.umanitoba.ca><6faf39c90705292353g9c66286qa4e723cd33d64fb8@mail.gmail.com><465D968C.5060205@cc.umanitoba.ca> Message-ID: Hi Adam > flaw in my loop. It is not infinite. In fact you don't have a loop, your program is really just a simple sequence. #Welcome screen: def welcome(): print "Welcome to the Area Calculation Program." print welcome() AG:Since you only call this once there is no point in putting AG: it in a functuion #Shape choice: def shape(): print "Choose a Shape:" print "1 Circle" print "2 Square" print "3 Triangle" print "4 Exit" print shape() AG: And you call this here and again at the end of the code. AG: But its not in a loop, its just two calls to the same function. #If circle: def circle(): shape=raw_input(">") if shape in["1","circle"]: print "1 Radius" print "2 Diameter" print "3 Circumference" print "4 Area" print circle() AG: And this gets a string fom the user and prints one of the AG: values but doesn't do anything with it. Functions should AG: normally do more than just print some values. AG: You never use the menu you print. #If radius: def radius(): radius=int(raw_input("Enter Radius:")) diameter=(radius*2) circumference=(diameter*3.14) area=(radius**2*3.14) print "Diameter",diameter print "Circumference",circumference print "Area",area print print def choice(): given=raw_input(">") if given in["1","radius"]: radius() choice() AG: Now you call radius which actually does some work shape() choice() AG: Then you call shape but don't use the result then call AG: choice which only works for circles. AG:If we use the more conventional approach of defining the AG: functins first then calling them at the end your code AG: looks like this: welcome() shape() circle() choice() #--> which calls radius() shape() choice() As you see there is no loop just a sequence of function calls. Now if I rename your functions to reflect what theyactually do: printWelcomeMessage() printShapeMenu() getShapeAndIfCirclePrintCircleParameterNames() getParameterAndIfRadiuscallRadius() -----> getRadiusCalculateResultsAndPrintThem() printShapeMenu() getParameterAndIfRadiuscallRadius() -----> getRadiusCalculateResultsAndPrintThem() Hopefully this illustrates several things: 1) Naming your functions to reflect what they actually do helps see what the code does 2) Especially if you group the function calls together at the end of your program 3) Your functions are mixing up the presentation of menus and the getting of values. A better structure might be to do something like: shape = 0 # a variable to store the shape printWelcomeMessage() printShapeMenuAndGetValue() #---store he result in the shape variable if shape in['1','circle']: doAllCircleStuff() else: print "Only circles supported for now!" And then its easy to wrap that in a real loop shape = 0 # a variable to store the shape printWelcomeMessage() while shape == 0: printShapeMenuAndGetValue() #---store he result in the shape variable if shape in['1','circle']: doAllCircleStuff() shape = 0 # reset shape back to zero else: print "Only circles supported for now!" Can you rewrite your functions to match that? You need to change the shape() function so that it sets the shape global variable to the value input by the user. You will need to include the statement global shape at the top of the function for that to work. The other (and better) way is to use the return statement to return the value. BTW I'm not really suggesting you use those long names, they were just to point out what the functions were really doing! HTH, Alan G. From Linda.Landry at nuance.com Wed May 30 22:55:42 2007 From: Linda.Landry at nuance.com (Linda Landry) Date: Wed, 30 May 2007 16:55:42 -0400 Subject: [Tutor] Web-based Python Training Message-ID: <2AB5541EB33172459EE430FFB66B1EE9060A279A@BN-EXCH01.nuance.com> Hello, I work as a Learning & Development Director in a mid-size technology company outside of Boston, Massachusetts. Our engineers are looking for either a web-based Python course, or an online instructor-led Python course. They already work with and know other programming languages. Do you know of any companies that offer Python via the web? Thank you, Linda Landry Linda Landry Director, Learning and Development Nuance Communications, Inc. Phone: 781/565-4950 nuance.com The experience speaks for itself (tm) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070530/87a032d6/attachment.html From alan.gauld at btinternet.com Thu May 31 00:03:06 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 May 2007 23:03:06 +0100 Subject: [Tutor] Web-based Python Training References: <2AB5541EB33172459EE430FFB66B1EE9060A279A@BN-EXCH01.nuance.com> Message-ID: "Linda Landry" wrote > I work as a Learning & Development Director in a mid-size technology > company outside of Boston, Massachusetts. Our engineers are looking > for > either a web-based Python course, or an online instructor-led Python > course. They already work with and know other programming languages. There are a wealth of Web resources for learning Python including the official tutorial on the python.org web site. Another good resource is the online book Dive into Python. If they are expertienced those should do to start them off and the Python mailing lists and wikis cover most areas of interest. And during the learning period this list is suited to both total novices and language switchers. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jackup at gmail.com Thu May 31 08:24:34 2007 From: jackup at gmail.com (Young-gyu Park) Date: Thu, 31 May 2007 15:24:34 +0900 Subject: [Tutor] How can I see properly my korean. Message-ID: I input the data which is from the database into array. and then I print out the array to the file but the letter I can not figure out. > fileHandle = open ( '/var/chroot/www/htdocs/django/js/model.js', > 'w' ) > fileHandle.write( codecs.BOM_UTF8 ) > print >> fileHandle, 'var blog = ' > print >> fileHandle, blog > fileHandle.close() this is the file model.js > var blog = > {'description': '\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad > \xed\x91\xb8\xeb\xa6\x84\xed\x84\xb0', 'links': [{'link': ' > www.hideout.com.br', 'title': 'ggum'}, {'link': 'www.hideout.com.br', > 'title': 'hideout'}, {'link': 'www.hideout.com.br', 'title': 'hideout'}, > {'link': 'www.hideout.com.br', 'title': 'hideout'}], 'title': > u'\uce74\ud1a8\ub9ad \ud478\ub984\ud130', 'items': [{'body': > '\xeb\xaf\xbc\xec\x95\x84\xeb\x9e\x80\xe3\x85\x81\xec\x95\x8c\r\n\r\n\xed\x85\x8c\xec\x8a\xa4\xed\x8a\xb8\xec\x9e\x85\xeb\x8b\x88\xe3\x85\x8f.', > 'permalink': 'perma link', 'author': 'ggum', 'title': > '\xec\xb2\xab\xeb\xb2\x88 \xec\xa7\xb8 > \xea\xb3\xb5\xec\xa7\x80\xec\x82\xac\xed\x95\xad', 'comments': [{'comment': > 'blah', 'author': 'ygp', 'dateTime': '10:43 7/20/2004'}], 'time': '13234 > 23423423'}, {'body': '\xec\x98\xa4\xeb\x8a\x98\xec\x9d\x80 > \xec\xa0\x95\xeb\xa7\x90 > \xec\x9e\xac\xeb\xb0\x8c\xec\x97\x88\xeb\x8b\xa4.\r\n\r\n\xeb\x98\x90 > \xed\x95\x9c\xeb\xb2\x88 \xeb\x8d\x94.......', 'permalink': 'perma link', > 'author': 'ggum', 'title': '\xec\x98\xa4\xeb\x8a\x98\xec\x9d\x98 > \xec\x9d\xb4\xec\x95\xbc\xea\xb8\xb0', 'comments': [{'comment': 'blah', > 'author': 'ygp', 'dateTime': '10:43 7/20/2004'}], 'time': '13234 > 23423423'}], 'currentPost': {'dateIndex': 0, 'postIndex': 0}, 'sections': > [{'link': 'www.hideout.com.br', 'title': > '\xea\xb3\xb5\xec\xa7\x80\xec\x82\xac\xed\x95\xad'}, {'link': ' > www.hideout.com.br', 'title': > '\xec\x9a\xb0\xeb\xa6\xac\xeb\x93\xa4\xec\x9d\x98 > \xec\x9d\xb4\xec\x95\xbc\xea\xb8\xb0'}, {'link': 'www.hideout.com.br', > 'title': '\xed\x9b\x84\xec\x9b\x90'}]} > What I want to do is to see properly the letter not this letter '\xec\x9d' Can anyone who know solution let me know how to do kindly? Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070531/96f68b7d/attachment.htm From alan.gauld at btinternet.com Thu May 31 09:41:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 May 2007 08:41:46 +0100 Subject: [Tutor] How can I see properly my korean. References: Message-ID: >I input the data which is from the database into array. > and then I print out the array to the file > but the letter I can not figure out. > >> fileHandle = open ( >> '/var/chroot/www/htdocs/django/js/model.js', >> 'w' ) >> fileHandle.write( codecs.BOM_UTF8 ) >> print >> fileHandle, 'var blog = ' >> print >> fileHandle, blog >> fileHandle.close() > > > What I want to do is to see properly the letter not this letter > '\xec\x9d' > > Can anyone who know solution let me know how to do kindly? I think you need to set the locale at the top of your python code. I have no idea what you need to do in your JavaScript however. Alan G. From jackup at gmail.com Thu May 31 12:20:19 2007 From: jackup at gmail.com (Young-gyu Park) Date: Thu, 31 May 2007 19:20:19 +0900 Subject: [Tutor] How can I see properly my korean. In-Reply-To: References: Message-ID: Yes I did I added the locale code at the top of my python code. What I want to do is that I want to convert to python dict to javascript associative array. and I will get the javascript array to display in the html page. But the korean letter which is in the python dict is displayed raw format ( I can't find any appropriate expression ) such as \x0e\xed\xff I want to see the korean letters like ?? ?? how I convert the python dict to javascript array? On 5/31/07, Alan Gauld wrote: > > >I input the data which is from the database into array. > > and then I print out the array to the file > > but the letter I can not figure out. > > > >> fileHandle = open ( > >> '/var/chroot/www/htdocs/django/js/model.js', > >> 'w' ) > >> fileHandle.write( codecs.BOM_UTF8 ) > >> print >> fileHandle, 'var blog = ' > >> print >> fileHandle, blog > >> fileHandle.close() > > > > > > What I want to do is to see properly the letter not this letter > > '\xec\x9d' > > > > Can anyone who know solution let me know how to do kindly? > > I think you need to set the locale at the top of your python code. > I have no idea what you need to do in your JavaScript however. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070531/cb9dd977/attachment.htm From kent37 at tds.net Wed May 30 21:53:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 May 2007 15:53:20 -0400 Subject: [Tutor] leave tutorial In-Reply-To: <49592.54519.qm@web8511.mail.in.yahoo.com> References: <49592.54519.qm@web8511.mail.in.yahoo.com> Message-ID: <465DD630.9020601@tds.net> Kriti Satija wrote: > i want to leave the tutorial If you mean you want to unsubscribe to the tutor list, click the link at the bottom of each posting and you will get to a form that lets you unsubscribe. Kent From kent37 at tds.net Thu May 31 12:38:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 May 2007 06:38:16 -0400 Subject: [Tutor] How can I see properly my korean. In-Reply-To: References: Message-ID: <465EA598.80300@tds.net> Young-gyu Park wrote: > fileHandle = open ( > '/var/chroot/www/htdocs/django/js/model.js', 'w' ) > fileHandle.write( codecs.BOM_UTF8 ) > print >> fileHandle, 'var blog = ' > print >> fileHandle, blog > fileHandle.close() > > > this is the file model.js > > > var blog = > {'description': '\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad .... > ', 'title': '\xed\x9b\x84\xec\x9b\x90'}]} > > > What I want to do is to see properly the letter not this letter '\xec\x9d' > > Can anyone who know solution let me know how to do kindly? You haven't shown us enough code. Where does the variable blog come from? This is a hard question to answer because there are so many ways to get confused. How did you display the file? It is possible that it contains the correct characters but the method you are using to display them shows them as \x escapes. For example the Python interpreter will do this. It looks like you are using a JSON encoder to create the data. Which one? Here is an example using the version of SimpleJSON that is bundled with Django. It does what you want but it's a little tricky to be sure: In [3]: from django.utils.simplejson import dumps This is Python so I can use \x escapes to define the string; the actual string is UTF-8: In [4]: data = {'description': '\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad \xed\x91\xb8\xeb\xa6\x84\xed\x84\xb0'} If I ask the interpreter for the value directly, it shows it with escapes. (Technically, the interpreter prints repr(value) for any value it is asked to display; for strings, repr() inserts \x escapes so the result is printable ASCII text.) In [7]: data['description'] Out[7]: '\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad \xed\x91\xb8\xeb\xa6\x84\xed\x84\xb0' On the other hand, if I ask the interpreter explicitly to print the value, the \x escapes are not inserted and the correct characters are shown: In [8]: print data['description'] ??? ??? The parameter ensure_ascii=False prevents the JSON serializer from converting the individual bytes of UTF-8 to \u escapes. Here again, showing the converted data directly uses repr() and shows \x escapes: In [6]: dumps(data, ensure_ascii=False) Out[6]: '{"description": "\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad If I print the result, I can see that it contains the correct characters: In [17]: print dumps(data, ensure_ascii=False) {"description": "??? ???"} Kent From jackup at gmail.com Thu May 31 13:44:32 2007 From: jackup at gmail.com (Young-gyu Park) Date: Thu, 31 May 2007 20:44:32 +0900 Subject: [Tutor] How can I see properly my korean. In-Reply-To: <465EA598.80300@tds.net> References: <465EA598.80300@tds.net> Message-ID: > user = User.objects.get(userID__exact=user_id) > user.blog_set.all() > blogData = user.blog_set.get(id__exact=user.id) > section_list = blogData.section_set.all() > latest_content_list = blogData.content_set.all > ().order_by('-pub_date')[:5] > > blog = dict() > blog['currentPost'] = {"dateIndex":0, "postIndex":0} > > blog['title'] = blogData.name.encode('utf-8') > blog['description'] = blogData.description.encode('utf-8') > > sections = list() > for section in section_list: > sections.append({"title":section.name.strip(), "link":" > www.hideout.com.br"}) > blog['sections'] = sections > > links = list() > link = dict() > links.append({"title":user_id, "link":"www.hideout.com.br"}) > links.append({"title":"hideout", "link":"www.hideout.com.br"}) > links.append({"title":"hideout", "link":"www.hideout.com.br"}) > links.append({"title":"hideout", "link":"www.hideout.com.br"}) > > blog['links'] = links > > comments = list() > comment = dict() > comment['dateTime'] = "10:43 7/20/2004" > comment['author'] = "ygp" > comment['comment'] = "blah" > comments.append(comment) > > items = list() > for content in latest_content_list: > item = dict() > item['title'] = content.subject > item['body'] = content.content > item['author'] = user.name > item['permalink'] = "perma link" > item['time'] = "13234 23423423" > item['comments'] = comments > items.append(item) > > > blog['items'] = items > > fileHandle = open ( '/var/chroot/www/htdocs/django/js/model.js', > 'w' ) > fileHandle.write( codecs.BOM_UTF8 ) > print >> fileHandle, 'var blog = ' > print >> fileHandle, blog > fileHandle.close() > This is the part of my whole source code. I try to convert the python dict into javascript array. Because they have same syntax. So when I print out the the dict, this is valid javascript array. And then I parsed the javascript array to display html page. But when I print out the python dict. the __str__ function don't have any encode routine. so I guess this problem is caused. The below is my wonder. Do I need to make my own fuction which to convert the dict value to utf-8? Or Is there any other way to display dict's korean letter properly? On 5/31/07, Kent Johnson wrote: > > Young-gyu Park wrote: > > > fileHandle = open ( > > '/var/chroot/www/htdocs/django/js/model.js', 'w' ) > > fileHandle.write( codecs.BOM_UTF8 ) > > print >> fileHandle, 'var blog = ' > > print >> fileHandle, blog > > fileHandle.close() > > > > > > this is the file model.js > > > > > > var blog = > > {'description': '\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad > .... > > ', 'title': '\xed\x9b\x84\xec\x9b\x90'}]} > > > > > > What I want to do is to see properly the letter not this letter > '\xec\x9d' > > > > Can anyone who know solution let me know how to do kindly? > > You haven't shown us enough code. Where does the variable blog come from? > > This is a hard question to answer because there are so many ways to get > confused. How did you display the file? It is possible that it contains > the correct characters but the method you are using to display them > shows them as \x escapes. For example the Python interpreter will do this. > > It looks like you are using a JSON encoder to create the data. Which > one? Here is an example using the version of SimpleJSON that is bundled > with Django. It does what you want but it's a little tricky to be sure: > > In [3]: from django.utils.simplejson import dumps > > This is Python so I can use \x escapes to define the string; the actual > string is UTF-8: > > In [4]: data = {'description': '\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad > \xed\x91\xb8\xeb\xa6\x84\xed\x84\xb0'} > > If I ask the interpreter for the value directly, it shows it with > escapes. (Technically, the interpreter prints repr(value) for any value > it is asked to display; for strings, repr() inserts \x escapes so the > result is printable ASCII text.) > > In [7]: data['description'] > Out[7]: '\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad > \xed\x91\xb8\xeb\xa6\x84\xed\x84\xb0' > > On the other hand, if I ask the interpreter explicitly to print the > value, the \x escapes are not inserted and the correct characters are > shown: > > In [8]: print data['description'] > ??? ??? > > The parameter ensure_ascii=False prevents the JSON serializer from > converting the individual bytes of UTF-8 to \u escapes. > > Here again, showing the converted data directly uses repr() and shows \x > escapes: > > In [6]: dumps(data, ensure_ascii=False) > Out[6]: '{"description": "\xec\xb9\xb4\xed\x86\xa8\xeb\xa6\xad > > If I print the result, I can see that it contains the correct characters: > > In [17]: print dumps(data, ensure_ascii=False) > {"description": "??? ???"} > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070531/9a7797a9/attachment-0001.html From kent37 at tds.net Thu May 31 15:09:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 May 2007 09:09:04 -0400 Subject: [Tutor] How can I see properly my korean. In-Reply-To: References: <465EA598.80300@tds.net> Message-ID: <465EC8F0.4000900@tds.net> Young-gyu Park wrote: > fileHandle = open ( > '/var/chroot/www/htdocs/django/js/model.js', 'w' ) > fileHandle.write( codecs.BOM_UTF8 ) > print >> fileHandle, 'var blog = ' > print >> fileHandle, blog > fileHandle.close() > > This is the part of my whole source code. OK, blog is a dict containing nested dicts. The problem is that printing a dict prints the repr() of the contents of the dict, which gives you the \x escapes for your strings. > > I try to convert the python dict into javascript array. Since you are clearly using Django, I suggest you use the simplejson module to do the serialization as I showed in my previous email. Instead of print >> fileHandle, blog try print >> fileHandle, dumps(blog, ensure_ascii=False) where dumps is imported from django.utils.simplejson Kent From maseriyer at yahoo.com Thu May 31 16:08:35 2007 From: maseriyer at yahoo.com (Iyer) Date: Thu, 31 May 2007 07:08:35 -0700 (PDT) Subject: [Tutor] creating a buffer object from a file ? In-Reply-To: <123790.88738.qm@web50708.mail.re2.yahoo.com> Message-ID: <949181.73964.qm@web50703.mail.re2.yahoo.com> I think this got lost among the threads: in reality what is a buffer object used for ? reading a file itself creates a string as in itself, file_handle = file ("path_to_file") file_data = file_handle.read() # file_data is a string, so why is a buffer object is needed ? the data in the binary file is just raw binary. I apologize for replying to the existing subject. Thanks for letting me know. I shall make sure this doesn't happen again. thanks iyer --- Alan Gauld wrote: > "Iyer" wrote > > > How do I go about creating a buffer object from > > a file containing binary data ? I have a function > > that accepts only buffer objects for it's > parameters > > Can you define what you mean by a buffer object? > Python uses duck typing so, unless the function has > been badly coded with an explicit type check, it > should accept any object that supports the methods > used. > > If you really do need a buffer the docs say: > > ----- > Buffer objects are not directly supported by Python > syntax, but can be created by calling the builtin > function buffer(). They don't support concatenation > or repetition. > ----- > > Which was new to me. But some experimentation > with the interpreter shows: > ---- > class buffer(object) > | buffer(object [, offset[, size]]) > | > | Create a new buffer object which references the > given object. > | The buffer will reference a slice of the target > object from the > | start of the object (or at the specified > offset). The slice will > | extend to the end of the target object (or with > the specified > size). > --- > and > ---- > >>> b = buffer('fredrica', 2,4) > >>> b[:] > 'edri' > ---- > > So we can see how to create a buffer object. > You want to do it with a binary file. You can read > the content > of a binary file using the struct module. But you > need to know > what kind of data is in your file. To create a > buffer you need > a string. So do you want your buffer to process the > raw binary > bytes as if they were a string? Or do you want to > convert the > binary data and then convert it again into a string > representation? > > Either is possible but you need to decide which you > need. > > BTW Please don't post new subjects to the list by > replying > to an existing subject. For those using threaded > readers it > buries your post insife another thread, in this case > 3 levels > deep in one about MSSQL! I only just noticed it. Its > better > to start a fresh message. After all its not exactly > difficult to > type tutor at python.org in the to line! :-) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started. http://mobile.yahoo.com/mail From jackup at gmail.com Thu May 31 16:15:06 2007 From: jackup at gmail.com (Young-gyu Park) Date: Thu, 31 May 2007 23:15:06 +0900 Subject: [Tutor] How can I see properly my korean. In-Reply-To: <465EC8F0.4000900@tds.net> References: <465EA598.80300@tds.net> <465EC8F0.4000900@tds.net> Message-ID: Yes, It works. Thank you so much kent. you make the time when I spent two days for solving this problem useless. you are genious ^^ Why I didn't know that *"from django.utils.simplejson import dumps" !!!* Do you have anything which you want to let me know, when I develop the ajax application by Django? Best regards. On 5/31/07, Kent Johnson wrote: > > Young-gyu Park wrote: > > fileHandle = open ( > > '/var/chroot/www/htdocs/django/js/model.js', 'w' ) > > fileHandle.write( codecs.BOM_UTF8 ) > > print >> fileHandle, 'var blog = ' > > print >> fileHandle, blog > > fileHandle.close() > > > > This is the part of my whole source code. > > OK, blog is a dict containing nested dicts. The problem is that printing > a dict prints the repr() of the contents of the dict, which gives you > the \x escapes for your strings. > > > > I try to convert the python dict into javascript array. > > Since you are clearly using Django, I suggest you use the simplejson > module to do the serialization as I showed in my previous email. Instead > of > print >> fileHandle, blog > try > print >> fileHandle, dumps(blog, ensure_ascii=False) > > where dumps is imported from django.utils.simplejson > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070531/a550fc2e/attachment.htm From kent37 at tds.net Thu May 31 16:33:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 May 2007 10:33:58 -0400 Subject: [Tutor] How can I see properly my korean. In-Reply-To: References: <465EA598.80300@tds.net> <465EC8F0.4000900@tds.net> Message-ID: <465EDCD6.5030708@tds.net> Young-gyu Park wrote: > Do you have anything which you want to let me know, when I develop the > ajax application by Django? Well, it's off topic for this list, and I don't really want to be a JavaScript / AJAX tutor, but I will say that it is easy to serve JSON directly from a Django view and using jQuery on the client side makes it easy to fetch the data with XmlHttpRequest. Here are some starting points: http://wolfram.kriesing.de/blog/index.php/2007/json-serialization-for-django http://www.djangosnippets.org/snippets/154/ http://docs.jquery.com/Ajax#.24.getJSON.28_url.2C_params.2C_callback_.29 Kent From maseriyer at yahoo.com Thu May 31 17:25:46 2007 From: maseriyer at yahoo.com (Iyer) Date: Thu, 31 May 2007 08:25:46 -0700 (PDT) Subject: [Tutor] configparser -- suggestions on when "name: value" entries are incomplete Message-ID: <36932.94178.qm@web50705.mail.re2.yahoo.com> Regarding the configparser module, if there is a configuration file to be read that has incomplete "name: value" entries, what would be the best way to handle this situation ? I was thinking of catching the exemption parsingerror and deleting the sections that have incomplete "name:value" entries, to delete the sections, the configfile has to be read, right and that raises the parsing error. any suggestions on how to best handle this situation? iyer ____________________________________________________________________________________ Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From kent37 at tds.net Thu May 31 17:36:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 May 2007 11:36:35 -0400 Subject: [Tutor] configparser -- suggestions on when "name: value" entries are incomplete In-Reply-To: <36932.94178.qm@web50705.mail.re2.yahoo.com> References: <36932.94178.qm@web50705.mail.re2.yahoo.com> Message-ID: <465EEB83.2010406@tds.net> Iyer wrote: > Regarding the configparser module, if there is a > configuration file to be read that has incomplete > "name: value" entries, what would be the best way to > handle this situation ? Do you mean incomplete as in not syntactically correct? I would tell the user to fix it. If you mean missing some values, you could provide defaults. > > I was thinking of catching the exemption parsingerror > and deleting the sections that have incomplete > "name:value" entries, to delete the sections, the > configfile has to be read, right and that raises the > parsing error. > > any suggestions on how to best handle this situation? Don't accept garbage data. Kent From malaclypse2 at gmail.com Thu May 31 17:36:43 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 31 May 2007 11:36:43 -0400 Subject: [Tutor] creating a buffer object from a file ? In-Reply-To: <949181.73964.qm@web50703.mail.re2.yahoo.com> References: <123790.88738.qm@web50708.mail.re2.yahoo.com> <949181.73964.qm@web50703.mail.re2.yahoo.com> Message-ID: <16651e80705310836p1d2768a5o2becce36acf27b82@mail.gmail.com> On 5/31/07, Iyer wrote: > I think this got lost among the threads: I think it got lost because you haven't given us enough information to answer your question. > in reality what is a buffer object used for ? reading > a file itself creates a string as in itself, We don't know. Your original email said you needed a buffer object, but didn't tell us why. As a consequence, the only one who knows why you need one is you. Perhaps if you actually showed us some code, or mentioned what library you were using that required a buffer object? -- Jerry From maseriyer at yahoo.com Thu May 31 18:28:06 2007 From: maseriyer at yahoo.com (Iyer) Date: Thu, 31 May 2007 09:28:06 -0700 (PDT) Subject: [Tutor] configparser -- suggestions on when "name: value" entries are incomplete In-Reply-To: <465EEB83.2010406@tds.net> Message-ID: <639409.24315.qm@web50705.mail.re2.yahoo.com> --- Kent Johnson wrote: > Iyer wrote: > > Regarding the configparser module, if there is a > > configuration file to be read that has incomplete > > "name: value" entries, what would be the best way > to > > handle this situation ? > > Do you mean incomplete as in not syntactically > correct? I would tell the > user to fix it. yes, it is not syntactically correct - for one section there are no corresponding names for the values; the values show up in the config file. This config file is actually generated by another program not under my control and breaks my python script trying to read it. > > If you mean missing some values, you could provide > defaults. > > > > > I was thinking of catching the exemption > parsingerror > > and deleting the sections that have incomplete > > "name:value" entries, to delete the sections, the > > configfile has to be read, right and that raises > the > > parsing error. > > > > any suggestions on how to best handle this > situation? > > Don't accept garbage data. > > Kent > ____________________________________________________________________________________ Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ From alan.gauld at btinternet.com Thu May 31 18:49:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 May 2007 17:49:44 +0100 Subject: [Tutor] creating a buffer object from a file ? References: <123790.88738.qm@web50708.mail.re2.yahoo.com><949181.73964.qm@web50703.mail.re2.yahoo.com> <16651e80705310836p1d2768a5o2becce36acf27b82@mail.gmail.com> Message-ID: "Jerry Hill" wrote >> I think this got lost among the threads: > > I think it got lost because you haven't given us enough information > to > answer your question. > >> in reality what is a buffer object used for ? reading >> a file itself creates a string as in itself, > > We don't know. Your original email said you needed a buffer object, The problem is that the Python docs refer to "a buffer object" but are not very forthcoming about exactly what it is or when/why you should use one. I confess that until Iyer asked his question I didn't even know they existed and still don't know when or why I'd need one. They appear to be some kind of string based object used in the internals of Python but with some operations blocked. But the only halfway useful info is what you get when you do help(buffer). Sorry Iyer, I can't really tell you anymore than I did already. As Jerry says, maybe if you could remind us of the context where you were told you needed to use a buffer object? I've never seen such a demand in Python myself. Alan G. From Barry.Carroll at datalogic.com Thu May 31 01:11:56 2007 From: Barry.Carroll at datalogic.com (Carroll, Barry) Date: Wed, 30 May 2007 16:11:56 -0700 Subject: [Tutor] leave tutorial In-Reply-To: Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595BA2@eugsrv400.psc.pscnet.com> > -----Original Message----- > Date: Wed, 30 May 2007 14:50:25 -0500 > From: "Grant Hagstrom" > Subject: Re: [Tutor] leave tutorial > To: "Kriti Satija" > Cc: Tutor at python.org > Message-ID: > <4257d6370705301250g1e663c3er202693a0e0f184a at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Nobody leaves the tutorial. > > http://mail.python.org/mailman/listinfo/tutor > (at the bottom of the page) > > On 5/30/07, Kriti Satija wrote: > > > > i want to leave the tutorial <> 'relax,' said the night man, 'We are programmed to receive. You can checkout any time you like, But you can never leave!' (Hotel California: Don Henley, Glenn Frey and Don Felder; 1977) Off-topic, I know, but I couldn't resist. Sorry. Regards, Barry barry.carroll at datalogic.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed